context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Threading;
using System.Collections.Generic;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// This class implements a Finite State Machine (FSM) to control the remote connection on the client side.
/// There is a similar but not identical FSM on the server side for this connection.
///
/// The FSM's states and events are defined to be the same for both the client FSM and the server FSM.
/// This design allows the client and server FSM's to
/// be as similar as possible, so that the complexity of maintaining them is minimized.
///
/// This FSM only controls the remote connection state. States related to runspace and pipeline are managed by runspace
/// pipeline themselves.
///
/// This FSM defines an event handling matrix, which is filled by the event handlers.
/// The state transitions can only be performed by these event handlers, which are private
/// to this class. The event handling is done by a single thread, which makes this
/// implementation solid and thread safe.
///
/// This implementation of the FSM does not allow the remote session to be reused for a connection
/// after it is been closed. This design decision is made to simplify the implementation.
/// However, the design can be easily modified to allow the reuse of the remote session
/// to reconnect after the connection is closed.
/// </summary>
internal class ClientRemoteSessionDSHandlerStateMachine
{
[TraceSourceAttribute("CRSessionFSM", "CRSessionFSM")]
private static PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionFSM", "CRSessionFSM");
/// <summary>
/// Event handling matrix. It defines what action to take when an event occur.
/// [State,Event]=>Action
/// </summary>
private EventHandler<RemoteSessionStateMachineEventArgs>[,] _stateMachineHandle;
private Queue<RemoteSessionStateEventArgs> _clientRemoteSessionStateChangeQueue;
/// <summary>
/// Current state of session
/// </summary>
private RemoteSessionState _state;
private Queue<RemoteSessionStateMachineEventArgs> _processPendingEventsQueue
= new Queue<RemoteSessionStateMachineEventArgs>();
// all events raised through the state machine
// will be queued in this
private object _syncObject = new object();
// object for synchronizing access to the above
// queue
private bool _eventsInProcess = false;
// whether some thread is actively processing events
// in a loop. If this is set then other threads
// should simply add to the queue and not attempt
// at processing the events in the queue. This will
// guarantee that events will always be serialized
// and processed
/// <summary>
/// Timer to be used for key exchange
/// </summary>
private Timer _keyExchangeTimer;
/// <summary>
/// indicates that the client has previously completed the session key exchange
/// </summary>
private bool _keyExchanged = false;
/// <summary>
/// this is to queue up a disconnect request when a key exchange is in process
/// the session will be disconnect once the exchange is complete
/// intermediate disconnect requests are tracked by this flag
/// </summary>
private bool _pendingDisconnect = false;
/// <summary>
/// processes events in the queue. If there are no
/// more events to process, then sets eventsInProcess
/// variable to false. This will ensure that another
/// thread which raises an event can then take control
/// of processing the events
/// </summary>
private void ProcessEvents()
{
RemoteSessionStateMachineEventArgs eventArgs = null;
do
{
lock (_syncObject)
{
if (_processPendingEventsQueue.Count == 0)
{
_eventsInProcess = false;
break;
}
eventArgs = _processPendingEventsQueue.Dequeue();
}
try
{
RaiseEventPrivate(eventArgs);
}
catch (Exception ex)
{
HandleFatalError(ex);
}
try
{
RaiseStateMachineEvents();
}
catch (Exception ex)
{
HandleFatalError(ex);
}
} while (_eventsInProcess);
}
private void HandleFatalError(Exception ex)
{
// Event handlers should not throw exceptions. But if they do we need to
// handle them here to prevent the state machine from hanging when there are pending
// events to process.
// Enqueue a fatal error event if such an exception occurs; clear all existing events.. we are going to terminate the session
PSRemotingDataStructureException fatalError = new PSRemotingDataStructureException(ex,
RemotingErrorIdStrings.FatalErrorCausingClose);
RemoteSessionStateMachineEventArgs closeEvent =
new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, fatalError);
RaiseEvent(closeEvent, true);
}
/// <summary>
/// Raises the StateChanged events which are queued
/// All StateChanged events will be raised once the
/// processing of the State Machine events are
/// complete
/// </summary>
private void RaiseStateMachineEvents()
{
RemoteSessionStateEventArgs queuedEventArg = null;
while (_clientRemoteSessionStateChangeQueue.Count > 0)
{
queuedEventArg = _clientRemoteSessionStateChangeQueue.Dequeue();
StateChanged.SafeInvoke(this, queuedEventArg);
}
}
/// <summary>
/// Unique identifier for this state machine. Used
/// in tracing
/// </summary>
private Guid _id;
/// <summary>
/// Handler to be used in cases, where setting the state is the
/// only task being performed. This method also asserts
/// if the specified event is valid for the current state of
/// the state machine
/// </summary>
/// <param name="sender">sender of this event</param>
/// <param name="eventArgs">event args</param>
private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs eventArgs)
{
switch (eventArgs.StateEvent)
{
case RemoteSessionEvent.NegotiationCompleted:
{
Dbg.Assert(_state == RemoteSessionState.NegotiationReceived,
"State can be set to Established only when current state is NegotiationReceived");
SetState(RemoteSessionState.Established, null);
}
break;
case RemoteSessionEvent.NegotiationReceived:
{
Dbg.Assert(eventArgs.RemoteSessionCapability != null,
"State can be set to NegotiationReceived only when RemoteSessionCapability is not null");
if (eventArgs.RemoteSessionCapability == null)
{
throw PSTraceSource.NewArgumentException("eventArgs");
}
SetState(RemoteSessionState.NegotiationReceived, null);
}
break;
case RemoteSessionEvent.NegotiationSendCompleted:
{
Dbg.Assert((_state == RemoteSessionState.NegotiationSending) || (_state == RemoteSessionState.NegotiationSendingOnConnect),
"Negotiating send can be completed only when current state is NegotiationSending");
SetState(RemoteSessionState.NegotiationSent, null);
}
break;
case RemoteSessionEvent.ConnectFailed:
{
Dbg.Assert(_state == RemoteSessionState.Connecting,
"A ConnectFailed event can be raised only when the current state is Connecting");
SetState(RemoteSessionState.ClosingConnection, eventArgs.Reason);
}
break;
case RemoteSessionEvent.CloseFailed:
{
SetState(RemoteSessionState.Closed, eventArgs.Reason);
}
break;
case RemoteSessionEvent.CloseCompleted:
{
SetState(RemoteSessionState.Closed, eventArgs.Reason);
}
break;
case RemoteSessionEvent.KeyRequested:
{
Dbg.Assert(_state == RemoteSessionState.Established,
"Server can request a key only after the client reaches the Established state");
if (_state == RemoteSessionState.Established)
{
SetState(RemoteSessionState.EstablishedAndKeyRequested, eventArgs.Reason);
}
}
break;
case RemoteSessionEvent.KeyReceived:
{
Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeySent,
"Key Receiving can only be raised after reaching the Established state");
if (_state == RemoteSessionState.EstablishedAndKeySent)
{
Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null);
if (tmp != null)
{
tmp.Dispose();
}
_keyExchanged = true;
SetState(RemoteSessionState.Established, eventArgs.Reason);
if (_pendingDisconnect)
{
//session key exchange is complete, if there is a disconnect pending, process it now
_pendingDisconnect = false;
DoDisconnect(sender, eventArgs);
}
}
}
break;
case RemoteSessionEvent.KeySent:
{
Dbg.Assert(_state >= RemoteSessionState.Established,
"Client can send a public key only after reaching the Established state");
Dbg.Assert(_keyExchanged == false, "Client should do key exchange only once");
if (_state == RemoteSessionState.Established ||
_state == RemoteSessionState.EstablishedAndKeyRequested)
{
SetState(RemoteSessionState.EstablishedAndKeySent, eventArgs.Reason);
// start the timer and wait
_keyExchangeTimer = new Timer(HandleKeyExchangeTimeout, null, BaseTransportManager.ClientDefaultOperationTimeoutMs, Timeout.Infinite);
}
}
break;
case RemoteSessionEvent.DisconnectCompleted:
{
Dbg.Assert(_state == RemoteSessionState.Disconnecting || _state == RemoteSessionState.RCDisconnecting,
"DisconnectCompleted event received while state machine is in wrong state");
if (_state == RemoteSessionState.Disconnecting || _state == RemoteSessionState.RCDisconnecting)
{
SetState(RemoteSessionState.Disconnected, eventArgs.Reason);
}
}
break;
case RemoteSessionEvent.DisconnectFailed:
{
Dbg.Assert(_state == RemoteSessionState.Disconnecting,
"DisconnectCompleted event received while state machine is in wrong state");
if (_state == RemoteSessionState.Disconnecting)
{
SetState(RemoteSessionState.Disconnected, eventArgs.Reason); //set state to disconnected even TODO. Put some ETW event describing the disconnect process failure
}
}
break;
case RemoteSessionEvent.ReconnectCompleted:
{
Dbg.Assert(_state == RemoteSessionState.Reconnecting,
"ReconnectCompleted event received while state machine is in wrong state");
if (_state == RemoteSessionState.Reconnecting)
{
SetState(RemoteSessionState.Established, eventArgs.Reason);
}
}
break;
} // switch...
}
/// <summary>
/// Handles the timeout for key exchange
/// </summary>
/// <param name="sender">sender of this event</param>
private void HandleKeyExchangeTimeout(object sender)
{
Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeySent, "timeout should only happen when waiting for a key");
Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null);
if (tmp != null)
{
tmp.Dispose();
}
PSRemotingDataStructureException exception =
new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientKeyExchangeFailed);
RaiseEvent(new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceiveFailed, exception));
} // SetStateHandler
/// <summary>
/// Handler to be used in cases, where raising an event to
/// the state needs to be performed. This method also
/// asserts if the specified event is valid for
/// the current state of the state machine
/// </summary>
/// <param name="sender">sender of this event</param>
/// <param name="eventArgs">event args</param>
private void SetStateToClosedHandler(object sender, RemoteSessionStateMachineEventArgs eventArgs)
{
Dbg.Assert(_state == RemoteSessionState.NegotiationReceived &&
eventArgs.StateEvent == RemoteSessionEvent.NegotiationFailed ||
eventArgs.StateEvent == RemoteSessionEvent.SendFailed ||
eventArgs.StateEvent == RemoteSessionEvent.ReceiveFailed ||
eventArgs.StateEvent == RemoteSessionEvent.NegotiationTimeout ||
eventArgs.StateEvent == RemoteSessionEvent.KeySendFailed ||
eventArgs.StateEvent == RemoteSessionEvent.KeyReceiveFailed ||
eventArgs.StateEvent == RemoteSessionEvent.KeyRequestFailed ||
eventArgs.StateEvent == RemoteSessionEvent.ReconnectFailed,
"An event to close the state machine can be raised only on the following conditions: " +
"1. Negotiation failed 2. Send failed 3. Receive failed 4. Negotiation timedout 5. Key send failed 6. key receive failed 7. key exchange failed 8. Reconnection failed");
// if there is a NegotiationTimeout event raised, it
// shouldn't matter if we are currently in the
// Established state
if (eventArgs.StateEvent == RemoteSessionEvent.NegotiationTimeout &&
State == RemoteSessionState.Established)
{
return;
}
// raise an event to close the state machine
RaiseEvent(new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close,
eventArgs.Reason));
} //SetStateToClosedHandler
#region constructor
/// <summary>
/// Creates an instance of ClientRemoteSessionDSHandlerStateMachine
/// </summary>
internal ClientRemoteSessionDSHandlerStateMachine()
{
_clientRemoteSessionStateChangeQueue = new Queue<RemoteSessionStateEventArgs>();
//Initialize the state machine event handling matrix
_stateMachineHandle = new EventHandler<RemoteSessionStateMachineEventArgs>[(int)RemoteSessionState.MaxState, (int)RemoteSessionEvent.MaxEvent];
for (int i = 0; i < _stateMachineHandle.GetLength(0); i++)
{
_stateMachineHandle[i, (int)RemoteSessionEvent.FatalError] += DoFatal;
_stateMachineHandle[i, (int)RemoteSessionEvent.Close] += DoClose;
_stateMachineHandle[i, (int)RemoteSessionEvent.CloseFailed] += SetStateHandler;
_stateMachineHandle[i, (int)RemoteSessionEvent.CloseCompleted] += SetStateHandler;
_stateMachineHandle[i, (int)RemoteSessionEvent.NegotiationTimeout] += SetStateToClosedHandler;
_stateMachineHandle[i, (int)RemoteSessionEvent.SendFailed] += SetStateToClosedHandler;
_stateMachineHandle[i, (int)RemoteSessionEvent.ReceiveFailed] += SetStateToClosedHandler;
_stateMachineHandle[i, (int)RemoteSessionEvent.CreateSession] += DoCreateSession;
_stateMachineHandle[i, (int)RemoteSessionEvent.ConnectSession] += DoConnectSession;
}
_stateMachineHandle[(int)RemoteSessionState.Idle, (int)RemoteSessionEvent.NegotiationSending] += DoNegotiationSending;
_stateMachineHandle[(int)RemoteSessionState.Idle, (int)RemoteSessionEvent.NegotiationSendingOnConnect] += DoNegotiationSending;
_stateMachineHandle[(int)RemoteSessionState.NegotiationSending, (int)RemoteSessionEvent.NegotiationSendCompleted] += SetStateHandler;
_stateMachineHandle[(int)RemoteSessionState.NegotiationSendingOnConnect, (int)RemoteSessionEvent.NegotiationSendCompleted] += SetStateHandler;
_stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationReceived] += SetStateHandler;
_stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationCompleted] += SetStateHandler;
_stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationFailed] += SetStateToClosedHandler;
_stateMachineHandle[(int)RemoteSessionState.Connecting, (int)RemoteSessionEvent.ConnectFailed] += SetStateHandler;
_stateMachineHandle[(int)RemoteSessionState.ClosingConnection, (int)RemoteSessionEvent.CloseCompleted] += SetStateHandler;
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.DisconnectStart] += DoDisconnect;
_stateMachineHandle[(int)RemoteSessionState.Disconnecting, (int)RemoteSessionEvent.DisconnectCompleted] += SetStateHandler;
_stateMachineHandle[(int)RemoteSessionState.Disconnecting, (int)RemoteSessionEvent.DisconnectFailed] += SetStateHandler; //dont close
_stateMachineHandle[(int)RemoteSessionState.Disconnected, (int)RemoteSessionEvent.ReconnectStart] += DoReconnect;
_stateMachineHandle[(int)RemoteSessionState.Reconnecting, (int)RemoteSessionEvent.ReconnectCompleted] += SetStateHandler;
_stateMachineHandle[(int)RemoteSessionState.Reconnecting, (int)RemoteSessionEvent.ReconnectFailed] += SetStateToClosedHandler;
_stateMachineHandle[(int)RemoteSessionState.Disconnecting, (int)RemoteSessionEvent.RCDisconnectStarted] += DoRCDisconnectStarted;
_stateMachineHandle[(int)RemoteSessionState.Disconnected, (int)RemoteSessionEvent.RCDisconnectStarted] += DoRCDisconnectStarted;
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.RCDisconnectStarted] += DoRCDisconnectStarted;
_stateMachineHandle[(int)RemoteSessionState.RCDisconnecting, (int)RemoteSessionEvent.DisconnectCompleted] += SetStateHandler;
//Disconnect during key exchange process
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeySent, (int)RemoteSessionEvent.DisconnectStart] += DoDisconnectDuringKeyExchange;
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.DisconnectStart] += DoDisconnectDuringKeyExchange;
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyRequested] += SetStateHandler; //
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeySent] += SetStateHandler; //
_stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeySendFailed] += SetStateToClosedHandler; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeySent, (int)RemoteSessionEvent.KeyReceived] += SetStateHandler; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeySent] += SetStateHandler; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeySent, (int)RemoteSessionEvent.KeyReceiveFailed] += SetStateToClosedHandler; //
_stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeySendFailed] += SetStateToClosedHandler;
//TODO: All these are potential unexpected state transitions.. should have a way to track these calls..
// should atleast put a dbg assert in this handler
for (int i = 0; i < _stateMachineHandle.GetLength(0); i++)
{
for (int j = 0; j < _stateMachineHandle.GetLength(1); j++)
{
if (_stateMachineHandle[i, j] == null)
{
_stateMachineHandle[i, j] += DoClose;
}
}
}
_id = Guid.NewGuid();
// initialize the state to be Idle: this means it is ready to start connecting.
SetState(RemoteSessionState.Idle, null);
}
#endregion constructor
/// <summary>
/// Helper method used by dependents to figure out if the RaiseEvent
/// method can be short-circuited. This will be useful in cases where
/// the dependent code wants to take action immediately instead of
/// going through state machine.
/// </summary>
/// <param name="arg"></param>
internal bool CanByPassRaiseEvent(RemoteSessionStateMachineEventArgs arg)
{
if (arg.StateEvent == RemoteSessionEvent.MessageReceived)
{
if (_state == RemoteSessionState.Established ||
_state == RemoteSessionState.EstablishedAndKeyReceived || // TODO - Client session would never get into this state... to be removed
_state == RemoteSessionState.EstablishedAndKeySent ||
_state == RemoteSessionState.Disconnecting || // There can be input data until disconnect has been completed
_state == RemoteSessionState.Disconnected) // Data can arrive while state machine is transitioning to disconnected, in a race.
{
return true;
}
}
return false;
}
/// <summary>
/// This method is used by all classes to raise a FSM event.
/// The method will queue the event. The event queue will be handled in
/// a thread safe manner by a single dedicated thread.
/// </summary>
/// <param name="arg">
/// This parameter contains the event to be raised.
/// </param>
/// <param name="clearQueuedEvents">
/// optional bool indicating whether to clear currently queued events
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter is null.
/// </exception>
internal void RaiseEvent(RemoteSessionStateMachineEventArgs arg, bool clearQueuedEvents = false)
{
lock (_syncObject)
{
s_trace.WriteLine("Event received : {0} for {1}", arg.StateEvent, _id);
if (clearQueuedEvents)
{
_processPendingEventsQueue.Clear();
}
_processPendingEventsQueue.Enqueue(arg);
if (!_eventsInProcess)
{
_eventsInProcess = true;
}
else
{
return;
}
}
ProcessEvents();
}
/// <summary>
/// This is the private version of raising a FSM event.
/// It can only be called by the dedicated thread that processes the event queue.
/// It calls the event handler
/// in the right position of the event handling matrix.
/// </summary>
/// <param name="arg">
/// The parameter contains the actual FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter is null.
/// </exception>
private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs arg)
{
if (arg == null)
{
throw PSTraceSource.NewArgumentNullException("arg");
}
EventHandler<RemoteSessionStateMachineEventArgs> handler = _stateMachineHandle[(int)State, (int)arg.StateEvent];
if (handler != null)
{
s_trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}, id = {2}", State, arg.StateEvent, _id);
handler(this, arg);
s_trace.WriteLine("After calling state machine event handler: state = {0}, event = {1}, id = {2}", State, arg.StateEvent, _id);
}
}
/// <summary>
/// This is a readonly property available to all other classes. It gives the FSM state.
/// Other classes can query for this state. Only the FSM itself can change the state.
/// </summary>
internal RemoteSessionState State
{
get
{
return _state;
}
}
/// <summary>
/// This event indicates that the FSM state changed.
/// </summary>
internal event EventHandler<RemoteSessionStateEventArgs> StateChanged;
#region Event Handlers
/// <summary>
/// This is the handler for CreateSession event of the FSM. This is the beginning of everything
/// else. From this moment on, the FSM will proceeds step by step to eventually reach
/// Established state or Closed state.
/// </summary>
/// <param name="sender"></param>
/// <param name="arg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="PSArgumentNullException">
/// If the parameter <paramref name="arg"/> is null.
/// </exception>
private void DoCreateSession(object sender, RemoteSessionStateMachineEventArgs arg)
{
using (s_trace.TraceEventHandlers())
{
Dbg.Assert(_state == RemoteSessionState.Idle,
"State needs to be idle to start connection");
Dbg.Assert(_state != RemoteSessionState.ClosingConnection ||
_state != RemoteSessionState.Closed,
"Reconnect after connection is closing or closed is not allowed");
if (State == RemoteSessionState.Idle)
{
// we are short-circuiting the state by going directly to NegotiationSending..
// This will save 1 network trip just to establish a connection.
// Raise the event for sending the negotiation
RemoteSessionStateMachineEventArgs sendingArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSending);
RaiseEvent(sendingArg);
}
}
}
/// <summary>
/// This is the handler for ConnectSession event of the FSM. This is the beginning of everything
/// else. From this moment on, the FSM will proceeds step by step to eventually reach
/// Established state or Closed state.
/// </summary>
/// <param name="sender"></param>
/// <param name="arg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="PSArgumentNullException">
/// If the parameter <paramref name="arg"/> is null.
/// </exception>
private void DoConnectSession(object sender, RemoteSessionStateMachineEventArgs arg)
{
using (s_trace.TraceEventHandlers())
{
Dbg.Assert(_state == RemoteSessionState.Idle,
"State needs to be idle to start connection");
if (State == RemoteSessionState.Idle)
{
//We need to send negotiation and connect algorithm related info
//Change state to let other DSHandlers add appropriate messages to be piggybacked on transport's Create payload
RemoteSessionStateMachineEventArgs sendingArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSendingOnConnect);
RaiseEvent(sendingArg);
}
}
}
/// <summary>
/// This is the handler for NegotiationSending event.
/// It sets the new state to be NegotiationSending and
/// calls data structure handler to send the negotiation packet.
/// </summary>
/// <param name="sender"></param>
/// <param name="arg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="arg"/> is null.
/// </exception>
private void DoNegotiationSending(object sender, RemoteSessionStateMachineEventArgs arg)
{
if (arg.StateEvent == RemoteSessionEvent.NegotiationSending)
{
SetState(RemoteSessionState.NegotiationSending, null);
}
else if (arg.StateEvent == RemoteSessionEvent.NegotiationSendingOnConnect)
{
SetState(RemoteSessionState.NegotiationSendingOnConnect, null);
}
else
{
Dbg.Assert(false, "NegotiationSending called on wrong event");
}
}
private void DoDisconnectDuringKeyExchange(object sender, RemoteSessionStateMachineEventArgs arg)
{
//set flag to indicate Disconnect request queue up
_pendingDisconnect = true;
}
private void DoDisconnect(object sender, RemoteSessionStateMachineEventArgs arg)
{
SetState(RemoteSessionState.Disconnecting, null);
}
private void DoReconnect(object sender, RemoteSessionStateMachineEventArgs arg)
{
SetState(RemoteSessionState.Reconnecting, null);
}
private void DoRCDisconnectStarted(object sender, RemoteSessionStateMachineEventArgs arg)
{
if (State != RemoteSessionState.Disconnecting &&
State != RemoteSessionState.Disconnected)
{
SetState(RemoteSessionState.RCDisconnecting, null);
}
}
/// <summary>
/// This is the handler for Close event.
/// </summary>
/// <param name="sender"></param>
/// <param name="arg">
/// This parameter contains the FSM event.
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If the parameter <paramref name="arg"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the parameter <paramref name="arg"/> does not contain remote data.
/// </exception>
private void DoClose(object sender, RemoteSessionStateMachineEventArgs arg)
{
using (s_trace.TraceEventHandlers())
{
RemoteSessionState oldState = _state;
switch (oldState)
{
case RemoteSessionState.ClosingConnection:
case RemoteSessionState.Closed:
// do nothing
break;
case RemoteSessionState.Connecting:
case RemoteSessionState.Connected:
case RemoteSessionState.Established:
case RemoteSessionState.EstablishedAndKeyReceived: //TODO - Client session would never get into this state... to be removed
case RemoteSessionState.EstablishedAndKeySent:
case RemoteSessionState.NegotiationReceived:
case RemoteSessionState.NegotiationSent:
case RemoteSessionState.NegotiationSending:
case RemoteSessionState.Disconnected:
case RemoteSessionState.Disconnecting:
case RemoteSessionState.Reconnecting:
case RemoteSessionState.RCDisconnecting:
SetState(RemoteSessionState.ClosingConnection, arg.Reason);
break;
case RemoteSessionState.Idle:
case RemoteSessionState.UndefinedState:
default:
PSRemotingTransportException forceClosedException = new PSRemotingTransportException(arg.Reason, RemotingErrorIdStrings.ForceClosed);
SetState(RemoteSessionState.Closed, forceClosedException);
break;
}
CleanAll();
}
}
/// <summary>
/// Handles a fatal error message. Throws a well defined error message,
/// which contains the reason for the fatal error as an inner exception.
/// This way the internal details are not surfaced to the user
/// </summary>
/// <param name="sender">sender of this event, unused</param>
/// <param name="eventArgs">arguments describing this event</param>
private void DoFatal(object sender, RemoteSessionStateMachineEventArgs eventArgs)
{
PSRemotingDataStructureException fatalError =
new PSRemotingDataStructureException(eventArgs.Reason, RemotingErrorIdStrings.FatalErrorCausingClose);
RemoteSessionStateMachineEventArgs closeEvent =
new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, fatalError);
RaiseEvent(closeEvent);
}
#endregion Event Handlers
private void CleanAll()
{
}
/// <summary>
/// Sets the state of the state machine. Since only
/// one thread can be manipulating the state at a time
/// the state is not synchronized
/// </summary>
/// <param name="newState">new state of the state machine</param>
/// <param name="reason">reason why the state machine is set
/// to the new state</param>
private void SetState(RemoteSessionState newState, Exception reason)
{
RemoteSessionState oldState = _state;
if (newState != oldState)
{
_state = newState;
s_trace.WriteLine("state machine state transition: from state {0} to state {1}", oldState, _state);
RemoteSessionStateInfo stateInfo = new RemoteSessionStateInfo(_state, reason);
RemoteSessionStateEventArgs sessionStateEventArg = new RemoteSessionStateEventArgs(stateInfo);
_clientRemoteSessionStateChangeQueue.Enqueue(sessionStateEventArg);
}
}
}
}
| |
using System;
using System.Drawing;
using System.Threading;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Forms;
using System.Data.Odbc;
using AWIComponentLib.Database;
using System.Data;
using System.Text;
using System.IO;
namespace AWI.SmartTracker
{
/// <summary>
/// Summary description for AssetForm.
/// </summary>
public class AssetForm : System.Windows.Forms.Form
{
private System.Windows.Forms.ToolBar toolBar1;
private System.Windows.Forms.ToolBarButton NewToolBarButton;
private System.Windows.Forms.ToolBarButton EditToolBarButton;
private System.Windows.Forms.ToolBarButton CancelToolBarButton;
private System.Windows.Forms.ToolBarButton SaveToolBarButton;
private System.Windows.Forms.ToolBarButton DeleteToolBarButton;
private System.Windows.Forms.ToolBarButton RefreshToolBarButton;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.Label DBStatusLabel;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox NameTextBox;
private System.Windows.Forms.TextBox TagIDTextBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button OpenImageButton;
private System.Windows.Forms.Button PreButton;
private System.Windows.Forms.Button NextButton;
private System.Windows.Forms.Button LastButton;
private System.Windows.Forms.Button FirstButton;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.PictureBox AstPictureBox;
private System.Windows.Forms.CheckBox MobileCheckBox;
private System.Windows.Forms.TextBox ModelTextBox;
private System.Windows.Forms.TextBox SKUTextBox;
private System.Windows.Forms.TextBox DateTimeTextBox;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader4;
private System.Windows.Forms.ColumnHeader columnHeader5;
private System.Windows.Forms.ColumnHeader columnHeader6;
private System.Windows.Forms.TextBox DescriptionTextBox;
private System.Windows.Forms.ListView listView;
private System.ComponentModel.IContainer components;
private OdbcDbClass odbcDB = new OdbcDbClass();
public AWIHelperClass awiHelper;
private Bitmap astImage ;
private bool newRec = false;
private string oldAssetID = "";
private string m_imageName = "";
private System.Windows.Forms.OpenFileDialog OpenFileDlg;
private System.Windows.Forms.ColumnHeader columnHeader7;
private System.Windows.Forms.Label label8;
private OdbcConnection m_connection = null;
private System.Timers.Timer timer1;
private MainForm mForm;
public AssetForm()
{
InitializeComponent();
//changes made to support MYSQL Server v5.0 and later
CultureInfo ci = new CultureInfo("sv-SE", true);
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
ci.DateTimeFormat.DateSeparator = "-";
}
private void DBConnectionStatusHandler(status stat, OdbcConnection connect)
{
if (stat == status.open)
{
m_connection = connect;
RefreshListView();
//MainForm.reconnectCounter = -1;
//timer1.Enabled = false;
//DBStatusLabel.ForeColor = System.Drawing.Color.Blue;
//DBStatusLabel.Text = "Connected";
//toolBar1.Enabled = true;
}
else if (stat == status.broken)
{
m_connection = null;
DBStatusLabel.ForeColor = System.Drawing.Color.Red;
DBStatusLabel.Text = "Disconnected";
toolBar1.Enabled = false;
}
else if (stat == status.close)
{
m_connection = null;
DBStatusLabel.ForeColor = System.Drawing.Color.Red;
DBStatusLabel.Text = "Disconnected";
toolBar1.Enabled = false;
}
}
public AssetForm(MainForm form)
{
mForm = form;
//changes made to support MYSQL Server v5.0 and later
CultureInfo ci = new CultureInfo("sv-SE", true);
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
ci.DateTimeFormat.DateSeparator = "-";
InitializeComponent();
OdbcDbClass.NotifyDBConnectionStatusHandler += new NotifyDBConnectionStatus(DBConnectionStatusHandler);
awiHelper = new AWIHelperClass(form);
if (MainForm.m_connection == null)
{
DBStatusLabel.ForeColor = System.Drawing.Color.Red;
DBStatusLabel.Text = "Disconnected";
toolBar1.Enabled = false;
FirstButton.Enabled = false;
LastButton.Enabled = false;
NextButton.Enabled = false;
PreButton.Enabled = false;
return;
}
else
{
DBStatusLabel.ForeColor = System.Drawing.Color.Blue;
DBStatusLabel.Text = "Connected";
m_connection = MainForm.m_connection;
}
RefreshListView();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.toolBar1 = new System.Windows.Forms.ToolBar();
this.NewToolBarButton = new System.Windows.Forms.ToolBarButton();
this.EditToolBarButton = new System.Windows.Forms.ToolBarButton();
this.CancelToolBarButton = new System.Windows.Forms.ToolBarButton();
this.SaveToolBarButton = new System.Windows.Forms.ToolBarButton();
this.DeleteToolBarButton = new System.Windows.Forms.ToolBarButton();
this.RefreshToolBarButton = new System.Windows.Forms.ToolBarButton();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.DBStatusLabel = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.NameTextBox = new System.Windows.Forms.TextBox();
this.TagIDTextBox = new System.Windows.Forms.TextBox();
this.AstPictureBox = new System.Windows.Forms.PictureBox();
this.label1 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.OpenImageButton = new System.Windows.Forms.Button();
this.MobileCheckBox = new System.Windows.Forms.CheckBox();
this.PreButton = new System.Windows.Forms.Button();
this.NextButton = new System.Windows.Forms.Button();
this.LastButton = new System.Windows.Forms.Button();
this.FirstButton = new System.Windows.Forms.Button();
this.DescriptionTextBox = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.ModelTextBox = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.SKUTextBox = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.DateTimeTextBox = new System.Windows.Forms.TextBox();
this.listView = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader7 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
this.columnHeader5 = new System.Windows.Forms.ColumnHeader();
this.columnHeader6 = new System.Windows.Forms.ColumnHeader();
this.OpenFileDlg = new System.Windows.Forms.OpenFileDialog();
this.label8 = new System.Windows.Forms.Label();
this.timer1 = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)(this.AstPictureBox)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
this.SuspendLayout();
//
// toolBar1
//
this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.toolBar1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.NewToolBarButton,
this.EditToolBarButton,
this.CancelToolBarButton,
this.SaveToolBarButton,
this.DeleteToolBarButton,
this.RefreshToolBarButton});
this.toolBar1.ButtonSize = new System.Drawing.Size(75, 28);
this.toolBar1.Cursor = System.Windows.Forms.Cursors.Hand;
this.toolBar1.DropDownArrows = true;
this.toolBar1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.toolBar1.ImageList = this.imageList1;
this.toolBar1.Location = new System.Drawing.Point(0, 0);
this.toolBar1.Name = "toolBar1";
this.toolBar1.ShowToolTips = true;
this.toolBar1.Size = new System.Drawing.Size(576, 32);
this.toolBar1.TabIndex = 42;
this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
//
// NewToolBarButton
//
this.NewToolBarButton.Name = "NewToolBarButton";
this.NewToolBarButton.Text = "New";
//
// EditToolBarButton
//
this.EditToolBarButton.Name = "EditToolBarButton";
this.EditToolBarButton.Text = "Edit";
//
// CancelToolBarButton
//
this.CancelToolBarButton.Name = "CancelToolBarButton";
this.CancelToolBarButton.Text = "Cancel";
//
// SaveToolBarButton
//
this.SaveToolBarButton.Name = "SaveToolBarButton";
this.SaveToolBarButton.Text = "Save";
//
// DeleteToolBarButton
//
this.DeleteToolBarButton.Name = "DeleteToolBarButton";
this.DeleteToolBarButton.Text = "Delete";
//
// RefreshToolBarButton
//
this.RefreshToolBarButton.Name = "RefreshToolBarButton";
this.RefreshToolBarButton.Text = "Refresh";
//
// imageList1
//
this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
this.imageList1.ImageSize = new System.Drawing.Size(52, 2);
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// DBStatusLabel
//
this.DBStatusLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.DBStatusLabel.ForeColor = System.Drawing.Color.Red;
this.DBStatusLabel.Location = new System.Drawing.Point(110, 236);
this.DBStatusLabel.Name = "DBStatusLabel";
this.DBStatusLabel.Size = new System.Drawing.Size(90, 18);
this.DBStatusLabel.TabIndex = 53;
this.DBStatusLabel.Text = "Disconnected";
//
// label2
//
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.ForeColor = System.Drawing.Color.Black;
this.label2.Location = new System.Drawing.Point(8, 236);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(100, 18);
this.label2.TabIndex = 52;
this.label2.Text = "Database Status: ";
this.label2.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// NameTextBox
//
this.NameTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.NameTextBox.Location = new System.Drawing.Point(110, 84);
this.NameTextBox.Name = "NameTextBox";
this.NameTextBox.ReadOnly = true;
this.NameTextBox.Size = new System.Drawing.Size(246, 21);
this.NameTextBox.TabIndex = 46;
//
// TagIDTextBox
//
this.TagIDTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.TagIDTextBox.Location = new System.Drawing.Point(110, 54);
this.TagIDTextBox.Name = "TagIDTextBox";
this.TagIDTextBox.ReadOnly = true;
this.TagIDTextBox.Size = new System.Drawing.Size(120, 21);
this.TagIDTextBox.TabIndex = 45;
//
// AstPictureBox
//
this.AstPictureBox.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.AstPictureBox.Location = new System.Drawing.Point(424, 84);
this.AstPictureBox.Name = "AstPictureBox";
this.AstPictureBox.Size = new System.Drawing.Size(136, 124);
this.AstPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.AstPictureBox.TabIndex = 51;
this.AstPictureBox.TabStop = false;
//
// label1
//
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.Color.Black;
this.label1.Location = new System.Drawing.Point(8, 56);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(100, 18);
this.label1.TabIndex = 44;
this.label1.Text = "Asset Tag ID: ";
this.label1.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label3
//
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.Color.Black;
this.label3.Location = new System.Drawing.Point(8, 86);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(100, 18);
this.label3.TabIndex = 48;
this.label3.Text = "Asset Name : ";
this.label3.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// OpenImageButton
//
this.OpenImageButton.Enabled = false;
this.OpenImageButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.OpenImageButton.ForeColor = System.Drawing.Color.Black;
this.OpenImageButton.Location = new System.Drawing.Point(466, 210);
this.OpenImageButton.Name = "OpenImageButton";
this.OpenImageButton.Size = new System.Drawing.Size(54, 23);
this.OpenImageButton.TabIndex = 47;
this.OpenImageButton.Text = "Open";
this.OpenImageButton.Click += new System.EventHandler(this.OpenImageButton_Click);
//
// MobileCheckBox
//
this.MobileCheckBox.Enabled = false;
this.MobileCheckBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.MobileCheckBox.Location = new System.Drawing.Point(252, 52);
this.MobileCheckBox.Name = "MobileCheckBox";
this.MobileCheckBox.Size = new System.Drawing.Size(14, 24);
this.MobileCheckBox.TabIndex = 54;
//
// PreButton
//
this.PreButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.PreButton.ForeColor = System.Drawing.Color.Black;
this.PreButton.Location = new System.Drawing.Point(362, 518);
this.PreButton.Name = "PreButton";
this.PreButton.Size = new System.Drawing.Size(75, 27);
this.PreButton.TabIndex = 59;
this.PreButton.Text = "Previous";
this.PreButton.Click += new System.EventHandler(this.PreButton_Click);
//
// NextButton
//
this.NextButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.NextButton.ForeColor = System.Drawing.Color.Black;
this.NextButton.Location = new System.Drawing.Point(286, 518);
this.NextButton.Name = "NextButton";
this.NextButton.Size = new System.Drawing.Size(75, 27);
this.NextButton.TabIndex = 58;
this.NextButton.Text = "Next";
this.NextButton.Click += new System.EventHandler(this.NextButton_Click);
//
// LastButton
//
this.LastButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LastButton.ForeColor = System.Drawing.Color.Black;
this.LastButton.Location = new System.Drawing.Point(210, 518);
this.LastButton.Name = "LastButton";
this.LastButton.Size = new System.Drawing.Size(75, 27);
this.LastButton.TabIndex = 57;
this.LastButton.Text = "Last";
this.LastButton.Click += new System.EventHandler(this.LastButton_Click);
//
// FirstButton
//
this.FirstButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.FirstButton.ForeColor = System.Drawing.Color.Black;
this.FirstButton.Location = new System.Drawing.Point(134, 518);
this.FirstButton.Name = "FirstButton";
this.FirstButton.Size = new System.Drawing.Size(75, 27);
this.FirstButton.TabIndex = 56;
this.FirstButton.Text = "First";
this.FirstButton.Click += new System.EventHandler(this.FirstButton_Click);
//
// DescriptionTextBox
//
this.DescriptionTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.DescriptionTextBox.Location = new System.Drawing.Point(110, 174);
this.DescriptionTextBox.Name = "DescriptionTextBox";
this.DescriptionTextBox.ReadOnly = true;
this.DescriptionTextBox.Size = new System.Drawing.Size(244, 21);
this.DescriptionTextBox.TabIndex = 60;
//
// label4
//
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.ForeColor = System.Drawing.Color.Black;
this.label4.Location = new System.Drawing.Point(8, 206);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(100, 18);
this.label4.TabIndex = 61;
this.label4.Text = "Date && Time: ";
this.label4.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// ModelTextBox
//
this.ModelTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ModelTextBox.Location = new System.Drawing.Point(110, 114);
this.ModelTextBox.Name = "ModelTextBox";
this.ModelTextBox.ReadOnly = true;
this.ModelTextBox.Size = new System.Drawing.Size(118, 21);
this.ModelTextBox.TabIndex = 62;
//
// label5
//
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.ForeColor = System.Drawing.Color.Black;
this.label5.Location = new System.Drawing.Point(8, 116);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(100, 18);
this.label5.TabIndex = 63;
this.label5.Text = "Model #:";
this.label5.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// SKUTextBox
//
this.SKUTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.SKUTextBox.Location = new System.Drawing.Point(110, 144);
this.SKUTextBox.Name = "SKUTextBox";
this.SKUTextBox.ReadOnly = true;
this.SKUTextBox.Size = new System.Drawing.Size(120, 21);
this.SKUTextBox.TabIndex = 65;
//
// label6
//
this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.ForeColor = System.Drawing.Color.Black;
this.label6.Location = new System.Drawing.Point(8, 146);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(100, 18);
this.label6.TabIndex = 64;
this.label6.Text = "SKU #: ";
this.label6.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// label7
//
this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.ForeColor = System.Drawing.Color.Black;
this.label7.Location = new System.Drawing.Point(8, 176);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(100, 18);
this.label7.TabIndex = 66;
this.label7.Text = "Description:";
this.label7.TextAlign = System.Drawing.ContentAlignment.TopRight;
//
// DateTimeTextBox
//
this.DateTimeTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.DateTimeTextBox.Location = new System.Drawing.Point(110, 204);
this.DateTimeTextBox.Name = "DateTimeTextBox";
this.DateTimeTextBox.ReadOnly = true;
this.DateTimeTextBox.Size = new System.Drawing.Size(126, 21);
this.DateTimeTextBox.TabIndex = 67;
//
// listView
//
this.listView.BackColor = System.Drawing.SystemColors.Info;
this.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader7,
this.columnHeader2,
this.columnHeader3,
this.columnHeader4,
this.columnHeader5,
this.columnHeader6});
this.listView.FullRowSelect = true;
this.listView.GridLines = true;
this.listView.HideSelection = false;
this.listView.Location = new System.Drawing.Point(8, 278);
this.listView.MultiSelect = false;
this.listView.Name = "listView";
this.listView.Size = new System.Drawing.Size(558, 232);
this.listView.TabIndex = 68;
this.listView.UseCompatibleStateImageBehavior = false;
this.listView.View = System.Windows.Forms.View.Details;
this.listView.SelectedIndexChanged += new System.EventHandler(this.listView_SelectedIndexChanged);
this.listView.Click += new System.EventHandler(this.listView_Click);
//
// columnHeader1
//
this.columnHeader1.Text = "ID";
this.columnHeader1.Width = 80;
//
// columnHeader7
//
this.columnHeader7.Text = "Mobile";
this.columnHeader7.Width = 70;
//
// columnHeader2
//
this.columnHeader2.Text = "Name";
this.columnHeader2.Width = 120;
//
// columnHeader3
//
this.columnHeader3.Text = "Model #";
this.columnHeader3.Width = 90;
//
// columnHeader4
//
this.columnHeader4.Text = "SKU #";
this.columnHeader4.Width = 90;
//
// columnHeader5
//
this.columnHeader5.Text = "Description";
this.columnHeader5.Width = 150;
//
// columnHeader6
//
this.columnHeader6.Text = "Date & Time";
this.columnHeader6.Width = 130;
//
// label8
//
this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label8.ForeColor = System.Drawing.Color.Black;
this.label8.Location = new System.Drawing.Point(268, 56);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(50, 18);
this.label8.TabIndex = 69;
this.label8.Text = "Mobile";
this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// timer1
//
this.timer1.Interval = 1000;
this.timer1.SynchronizingObject = this;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
//
// AssetForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(576, 551);
this.Controls.Add(this.label8);
this.Controls.Add(this.listView);
this.Controls.Add(this.DateTimeTextBox);
this.Controls.Add(this.SKUTextBox);
this.Controls.Add(this.ModelTextBox);
this.Controls.Add(this.DescriptionTextBox);
this.Controls.Add(this.NameTextBox);
this.Controls.Add(this.TagIDTextBox);
this.Controls.Add(this.toolBar1);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.PreButton);
this.Controls.Add(this.NextButton);
this.Controls.Add(this.LastButton);
this.Controls.Add(this.FirstButton);
this.Controls.Add(this.MobileCheckBox);
this.Controls.Add(this.DBStatusLabel);
this.Controls.Add(this.label2);
this.Controls.Add(this.AstPictureBox);
this.Controls.Add(this.label1);
this.Controls.Add(this.label3);
this.Controls.Add(this.OpenImageButton);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AssetForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Asset Tag Registration Form";
this.Load += new System.EventHandler(this.AssetForm_Load);
((System.ComponentModel.ISupportInitialize)(this.AstPictureBox)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void AssetForm_Load(object sender, System.EventArgs e)
{
}
private void ShowErrorMessage(string msg)
{
MessageBox.Show(this, msg, "Smart Tracker", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
if (m_connection == null) //added Dec 06, 06
return;
//changes made to support MYSQL Server v5.0 and later
CultureInfo ci = new CultureInfo("sv-SE", true);
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
ci.DateTimeFormat.DateSeparator = "-";
if (e.Button.Text == "New")
{
MobileCheckBox.Checked = false;
MobileCheckBox.Enabled = true;
TagIDTextBox.Text = "";
NameTextBox.Text = "";
ModelTextBox.Text = "";
SKUTextBox.Text = "";
DescriptionTextBox.Text = "";
DateTimeTextBox.Text = "";
DateTimeTextBox.Text = "";
AstPictureBox.Image = null;
OpenImageButton.Enabled = true;
TagIDTextBox.Focus();
TagIDTextBox.ReadOnly = false;
NameTextBox.ReadOnly = false;
ModelTextBox.ReadOnly = false;
SKUTextBox.ReadOnly = false;
DescriptionTextBox.ReadOnly = false;
newRec = true;
}
else if (e.Button.Text == "Edit")
{
TagIDTextBox.Focus();
MobileCheckBox.Enabled = true;
oldAssetID = TagIDTextBox.Text;
TagIDTextBox.ReadOnly = false;
NameTextBox.ReadOnly = false;
ModelTextBox.ReadOnly = false;
SKUTextBox.ReadOnly = false;
DescriptionTextBox.ReadOnly = false;
OpenImageButton.Enabled = true;
newRec = false;
}
else if (e.Button.Text == "Cancel")
{
TagIDTextBox.ReadOnly = true;
NameTextBox.ReadOnly = true;
ModelTextBox.ReadOnly = true;
SKUTextBox.ReadOnly = true;
DescriptionTextBox.ReadOnly = true;
DateTimeTextBox.ReadOnly = true;
MobileCheckBox.Enabled = false;
OpenImageButton.Enabled = false;
if(this.listView.SelectedIndices.Count <= 0)
{
//MobileCheckBox.Checked = false;
TagIDTextBox.Text = "";
NameTextBox.Text = "";
ModelTextBox.Text = "";
SKUTextBox.Text = "";
DescriptionTextBox.Text = "";
DateTimeTextBox.Text = "";
OpenImageButton.Enabled = true;
AstPictureBox.Image = null;
return;
}
ListViewItem selItem = listView.SelectedItems[0];
TagIDTextBox.Text = selItem.SubItems[0].Text;
if (selItem.SubItems[1].Text == "True")
MobileCheckBox.Checked = true;
else
MobileCheckBox.Checked = false;
NameTextBox.Text = selItem.SubItems[2].Text;
ModelTextBox.Text = selItem.SubItems[3].Text;
SKUTextBox.Text = selItem.SubItems[4].Text;
DescriptionTextBox.Text = selItem.SubItems[5].Text;
DateTimeTextBox.Text = selItem.SubItems[6].Text;
if (TagIDTextBox.Text.Length > 0)
AstPictureBox.Image = awiHelper.GetTagImage(TagIDTextBox.Text, "asset"); //GetTagImage(TagIDTextBox.Text, m_connection);
}
else if (e.Button.Text == "Save")
{
if (TagIDTextBox.Text.Equals(""))
{
ShowErrorMessage("Need Tag ID");
TagIDTextBox.Focus();
return;
}
TagIDTextBox.ReadOnly = true;
MobileCheckBox.Enabled = false;
NameTextBox.ReadOnly = true;
ModelTextBox.ReadOnly = true;
SKUTextBox.ReadOnly = true;
DescriptionTextBox.ReadOnly = true;
DateTimeTextBox.ReadOnly = true;
OpenImageButton.Enabled = true;
int FileSize;
byte[] rawData = null;
//FileStream fs;
//string SQL = "";
if (AstPictureBox.Image != null)
{
MemoryStream stream = new MemoryStream();
AstPictureBox.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
FileSize = Convert.ToInt32(stream.Length);
rawData = new byte[FileSize];
stream.Position = 0;
stream.Read(rawData, 0, FileSize);
stream.Close();
}
else
{
rawData = new byte[1];
rawData[0] = Convert.ToByte(0);
}
DateTime time = DateTime.Now;
string timeStr = time.ToString("MM-dd-yyyy HH:mm:ss");
if (!awiHelper.SaveAssetTag(newRec, TagIDTextBox.Text, MobileCheckBox.Checked, NameTextBox.Text, ModelTextBox.Text, SKUTextBox.Text, DescriptionTextBox.Text, DateTime.Now, rawData, oldAssetID)) //oldEmployeeID))
return;
if (!newRec)
{
ListViewItem selItem = listView.SelectedItems[0];
int index = selItem.Index;
if (index >= 0)
selItem.Remove();
}
ListViewItem listItem = new ListViewItem(TagIDTextBox.Text);
if (MobileCheckBox.Checked)
listItem.SubItems.Add("True");
else
listItem.SubItems.Add("False");
listItem.SubItems.Add(NameTextBox.Text);
listItem.SubItems.Add(ModelTextBox.Text);
listItem.SubItems.Add(SKUTextBox.Text);
listItem.SubItems.Add(DescriptionTextBox.Text);
listItem.SubItems.Add(timeStr);
listView.Items.Add(listItem);
listItem.EnsureVisible();
listItem.Selected = true;
}
else if (e.Button.Text == "Delete")
{
if (listView.Items.Count == 0)
return;
if (TagIDTextBox.Text.Equals(""))
{
ShowErrorMessage("No Tag ID");
return;
}
if (MessageBox.Show(this, "Delete the record?", "Smart Tracker", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
return;
TagIDTextBox.ReadOnly = true;
NameTextBox.ReadOnly = true;
ModelTextBox.ReadOnly = true;
SKUTextBox.ReadOnly = true;
MobileCheckBox.Enabled = false;
DescriptionTextBox.ReadOnly = true;
OpenImageButton.Enabled = false;
//SaveButton.Enabled = false;
StringBuilder sql = new StringBuilder();
sql.Append("DELETE FROM asset WHERE ID = ");
sql.AppendFormat("'{0}'", TagIDTextBox.Text);
OdbcCommand myCommand = new OdbcCommand(sql.ToString(), m_connection);
/*try
{
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
ShowErrorMessage(ex.Message);
return;
}*/
lock (m_connection)
{
try
{
myCommand.ExecuteNonQuery();
//MainForm.reconnectCounter = -1;
//timer1.Enabled = false;
}
catch (Exception ex)
{
int ret = 0, ret1 = 0, ret2 = 0;
if (((ret=ex.Message.IndexOf("Lost connection")) >= 0) ||
((ret1=ex.Message.IndexOf("MySQL server has gone away")) >= 0) ||
((ret2=ex.Message.IndexOf("(10061)")) >= 0)) //can not connect
{
//error code 2013
DBStatusLabel.ForeColor = System.Drawing.Color.Red;
DBStatusLabel.Text = "Disconnected";
toolBar1.Enabled = false;
//if process of reconnecting started skip
if (MainForm.reconnectCounter < 0)
{
MainForm.reconnectCounter = 0;
//timer1.Enabled = true;
}
MainForm.dbDisconnectedFlag = true;
}
return;
}//catch .. try
}//lock
awiHelper.DeleteTag(TagIDTextBox.Text, "AST");
ListViewItem selItem = listView.SelectedItems[0];
int index = selItem.Index;
selItem.Remove();
if (index > 0)
{
listView.Items[index-1].Selected = true;
listView.Select();
}
else if ((index == 0) && (listView.Items.Count > 0))
{
listView.Items[0].Selected = true;
listView.Select();
}
else if (listView.Items.Count == 0)
{
TagIDTextBox.Text = "";
NameTextBox.Text = "";
ModelTextBox.Text = "";
SKUTextBox.Text = "";
DescriptionTextBox.Text = "";
DateTimeTextBox.Text = "";
DateTimeTextBox.Text = "";
AstPictureBox.Image = null;
}
}
else if (e.Button.Text == "Refresh")
{
listView.Items.Clear();
TagIDTextBox.Text = "";
NameTextBox.Text = "";
ModelTextBox.Text = "";
SKUTextBox.Text = "";
DescriptionTextBox.Text = "";
DateTimeTextBox.Text = "";
AstPictureBox.Image = null;
MobileCheckBox.Enabled = false;
TagIDTextBox.ReadOnly = true;
NameTextBox.ReadOnly = true;
ModelTextBox.ReadOnly = true;
SKUTextBox.ReadOnly = true;
DescriptionTextBox.ReadOnly = true;
RefreshListView();
/*newRec = false;
string mySelectQuery = "SELECT ID, Mobile, Name, Model, SKU, Description, Timestamp FROM asset"; // WHERE Type = 'AST' AND AccType = '1'";
OdbcCommand myCommand = new OdbcCommand(mySelectQuery, m_connection);
OdbcDataReader myReader = null;
try
{
myReader = myCommand.ExecuteReader();
}
catch (Exception ex)
{
ShowErrorMessage(ex.Message);
if (myReader != null)
{
if (!myReader.IsClosed)
myReader.Close();
}
return;
}
bool firstRec = true;
int myRec = 0;
while (myReader.Read())
{
myRec += 1;
//if (myRec > MAX_DEMO_RECORDS)
//break;
ListViewItem listItem = new ListViewItem(myReader.GetString(0)); //ID
if (myReader.GetBoolean(1))
listItem.SubItems.Add("True"); //mobile
else
listItem.SubItems.Add("False"); //mobile
listItem.SubItems.Add(myReader.GetString(2)); //name
listItem.SubItems.Add(myReader.GetString(3)); //model
listItem.SubItems.Add(myReader.GetString(4)); //sku
listItem.SubItems.Add(myReader.GetString(5)); //description
listItem.SubItems.Add(myReader.GetString(6)); //dateTime
listView.Items.Add(listItem);
if (firstRec)
{
//listItem.Selected = true;
firstRec = false;
TagIDTextBox.Text = myReader.GetString(0); //id
if (myReader.GetBoolean(1))
listItem.SubItems.Add("True"); //mobile
else
listItem.SubItems.Add("False"); //mobile
NameTextBox.Text = myReader.GetString(2); //name
ModelTextBox.Text = myReader.GetString(3); //model
SKUTextBox.Text = myReader.GetString(4); //sku
DescriptionTextBox.Text = myReader.GetString(5); //description
DateTimeTextBox.Text = myReader.GetString(6); //datetime
}
}//while
myReader.Close();
if (listView.Items.Count > 0)
listView.Items[0].Selected = true;*/
}
}
private void RefreshListView()
{
bool firstRec = true;
int myRec = 0;
if (m_connection == null) //added Dec 06, 06
return;
lock (MainForm.m_connection)
{
string mySelectQuery = "SELECT ID, Mobile, Name, Model, SKU, Description, Timestamp FROM asset"; // WHERE Type = 'AST' AND AccType = '1'";
OdbcCommand myCommand = new OdbcCommand(mySelectQuery, m_connection);
OdbcDataReader myReader = null;
/*try
{
myReader = myCommand.ExecuteReader();
}
catch (Exception ex)
{
ShowErrorMessage(ex.Message);
if (myReader != null)
{
if (!myReader.IsClosed)
myReader.Close();
}
return;
}*/
//lock (MainForm.m_connection)
//{
try
{
myReader = myCommand.ExecuteReader();
//MainForm.reconnectCounter = -1;
//timer1.Enabled = false;
}
catch (Exception ex)
{
int ret = 0, ret1 = 0, ret2 = 0;
if (((ret=ex.Message.IndexOf("Lost connection")) >= 0) ||
((ret1=ex.Message.IndexOf("MySQL server has gone away")) >= 0) ||
((ret2=ex.Message.IndexOf("(10061)")) >= 0)) //can not connect
{
//error code 2013
DBStatusLabel.ForeColor = System.Drawing.Color.Red;
DBStatusLabel.Text = "Disconnected";
toolBar1.Enabled = false;
//if process of reconnecting started skip
if (MainForm.reconnectCounter < 0)
{
MainForm.reconnectCounter = 0;
//timer1.Enabled = true;
}
}
if (myReader != null)
{
if (!myReader.IsClosed)
myReader.Close();
}
return;
}//try .. catch
//}//lock
DBStatusLabel.ForeColor = System.Drawing.Color.Green;
DBStatusLabel.Text = "Connected";
toolBar1.Enabled = true;
while (myReader.Read())
{
myRec += 1;
//if (myRec > MAX_DEMO_RECORDS)
//break;
ListViewItem listItem = new ListViewItem(myReader.GetString(0)); //ID
if (myReader.GetBoolean(1))
listItem.SubItems.Add("True"); //mobile
else
listItem.SubItems.Add("False"); //mobile
listItem.SubItems.Add(myReader.GetString(2)); //name
listItem.SubItems.Add(myReader.GetString(3)); //model
listItem.SubItems.Add(myReader.GetString(4)); //sku
listItem.SubItems.Add(myReader.GetString(5)); //description
listItem.SubItems.Add(myReader.GetString(6)); //dateTime
listView.Items.Add(listItem);
if (firstRec)
{
//listItem.Selected = true;
firstRec = false;
TagIDTextBox.Text = myReader.GetString(0); //id
if (myReader.GetBoolean(1))
listItem.SubItems.Add("True"); //mobile
else
listItem.SubItems.Add("False"); //mobile
NameTextBox.Text = myReader.GetString(2); //name
ModelTextBox.Text = myReader.GetString(3); //model
SKUTextBox.Text = myReader.GetString(4); //sku
DescriptionTextBox.Text = myReader.GetString(5); //description
try
{
DateTimeTextBox.Text = myReader.GetDateTime(6).ToString("MM-dd-yyyy HH:mm:ss"); //dateTime
}
catch (System.InvalidCastException)
{
}
}
}//while
myReader.Close();
if (listView.Items.Count > 0)
listView.Items[0].Selected = true;
if (TagIDTextBox.Text.Length > 0)
AstPictureBox.Image = awiHelper.GetTagImage(TagIDTextBox.Text, "asset");
}//lock m_connection
}
private void OpenImageButton_Click(object sender, System.EventArgs e)
{
Stream myStream;
//OpenFileDialog openFileDlg = new OpenFileDialog();
//OpenFileDlg.InitialDirectory = "c:\\" ;
OpenFileDlg.Filter = "JPEG files (*.jpg)|*.jpg|Bitmap (*.bmp)|*.bmp" ;
OpenFileDlg.FilterIndex = 2 ;
//OpenFileDlg.RestoreDirectory = true ;
m_imageName = "";
if(OpenFileDlg.ShowDialog() == DialogResult.OK)
{
if((myStream = OpenFileDlg.OpenFile())!= null)
{
m_imageName = OpenFileDlg.FileName;
myStream.Close();
}
}
if (m_imageName.Length > 0)
{
// Sets up an image object to be displayed.
if (astImage != null)
{
astImage.Dispose();
}
// Stretches the image to fit the pictureBox.
AstPictureBox.SizeMode = PictureBoxSizeMode.StretchImage ;
astImage = new Bitmap(m_imageName);
AstPictureBox.Image = (Image)astImage ;
}
}
private void listView_Click(object sender, System.EventArgs e)
{
ListViewItem selItem = listView.SelectedItems[0];
int index = selItem.Index;
TagIDTextBox.Text = selItem.SubItems[0].Text; //ID
if (selItem.SubItems[1].Text == "True") //mobile
MobileCheckBox.Checked = true;
else
MobileCheckBox.Checked = false;
NameTextBox.Text = selItem.SubItems[2].Text; //name
ModelTextBox.Text = selItem.SubItems[3].Text; //model
SKUTextBox.Text = selItem.SubItems[4].Text; //sku
DescriptionTextBox.Text = selItem.SubItems[5].Text; //description
DateTimeTextBox.Text = selItem.SubItems[6].Text; //time
if (TagIDTextBox.Text.Length > 0)
AstPictureBox.Image = awiHelper.GetTagImage(TagIDTextBox.Text, "asset");
}
private void listView_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(this.listView.SelectedIndices.Count <= 0)
return;
ListViewItem selItem = listView.SelectedItems[0];
TagIDTextBox.Text = selItem.SubItems[0].Text;
if (selItem.SubItems[1].Text == "True") //mobile
MobileCheckBox.Checked = true;
else
MobileCheckBox.Checked = false;
NameTextBox.Text = selItem.SubItems[2].Text; //name
ModelTextBox.Text = selItem.SubItems[3].Text; //model
SKUTextBox.Text = selItem.SubItems[4].Text; //sku
DescriptionTextBox.Text = selItem.SubItems[5].Text; //description
DateTimeTextBox.Text = selItem.SubItems[6].Text; //time
if (TagIDTextBox.Text.Length > 0)
AstPictureBox.Image = awiHelper.GetTagImage(TagIDTextBox.Text, "asset"); //GetTagImage(TagIDTextBox.Text, m_connection);
}
private void FirstButton_Click(object sender, System.EventArgs e)
{
if (listView.Items.Count > 0)
{
listView.Items[0].Selected = true;
listView.Select();
}
}
private void LastButton_Click(object sender, System.EventArgs e)
{
if (listView.Items.Count > 0)
{
listView.Items[listView.Items.Count-1].Selected = true;
listView.Select();
}
}
private void NextButton_Click(object sender, System.EventArgs e)
{
if (listView.Items.Count > 0)
{
ListViewItem selItem = listView.SelectedItems[0];
int index = selItem.Index;
if ((index >= 0)&& (index < listView.Items.Count-1))
{
listView.Items[index+1].Selected = true;
listView.Select();
}
}
}
private void PreButton_Click(object sender, System.EventArgs e)
{
if (listView.Items.Count > 0)
{
ListViewItem selItem = listView.SelectedItems[0];
int index = selItem.Index;
if (index >= 1)
{
listView.Items[index-1].Selected = true;
listView.Select();
}
}
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
/*if (MainForm.reconnectCounter > 3)
{
timer1.Enabled = false;
//DBStatusBarPanel.Text = "DB Server : MYSQL Database : Disconnected";
MessageBox.Show(this, "Connection to DB Server lost and reconnect failed.", "Bank", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
MainForm.reconnectCounter += 1;
//lock (MainForm.m_connection) //dec06-06
{
if(mForm.ReconnectToDBServer())
{
timer1.Enabled = false;
DBStatusLabel.ForeColor = System.Drawing.Color.Blue;
DBStatusLabel.Text = "Connected";
toolBar1.Enabled = true;
}
}
}*/
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you
/// currently do not have developer preview access, please contact help@twilio.com.
///
/// SyncMapResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Preview.Sync.Service
{
public class SyncMapResource : Resource
{
private static Request BuildFetchRequest(FetchSyncMapOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Preview,
"/Sync/Services/" + options.PathServiceSid + "/Maps/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch SyncMap parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMap </returns>
public static SyncMapResource Fetch(FetchSyncMapOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch SyncMap parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMap </returns>
public static async System.Threading.Tasks.Task<SyncMapResource> FetchAsync(FetchSyncMapOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMap </returns>
public static SyncMapResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchSyncMapOptions(pathServiceSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMap </returns>
public static async System.Threading.Tasks.Task<SyncMapResource> FetchAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchSyncMapOptions(pathServiceSid, pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildDeleteRequest(DeleteSyncMapOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Preview,
"/Sync/Services/" + options.PathServiceSid + "/Maps/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete SyncMap parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMap </returns>
public static bool Delete(DeleteSyncMapOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="options"> Delete SyncMap parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMap </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteSyncMapOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMap </returns>
public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteSyncMapOptions(pathServiceSid, pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// delete
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMap </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new DeleteSyncMapOptions(pathServiceSid, pathSid);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateSyncMapOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Preview,
"/Sync/Services/" + options.PathServiceSid + "/Maps",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create SyncMap parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMap </returns>
public static SyncMapResource Create(CreateSyncMapOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create SyncMap parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMap </returns>
public static async System.Threading.Tasks.Task<SyncMapResource> CreateAsync(CreateSyncMapOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="uniqueName"> The unique_name </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMap </returns>
public static SyncMapResource Create(string pathServiceSid,
string uniqueName = null,
ITwilioRestClient client = null)
{
var options = new CreateSyncMapOptions(pathServiceSid){UniqueName = uniqueName};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="uniqueName"> The unique_name </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMap </returns>
public static async System.Threading.Tasks.Task<SyncMapResource> CreateAsync(string pathServiceSid,
string uniqueName = null,
ITwilioRestClient client = null)
{
var options = new CreateSyncMapOptions(pathServiceSid){UniqueName = uniqueName};
return await CreateAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadSyncMapOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Preview,
"/Sync/Services/" + options.PathServiceSid + "/Maps",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read SyncMap parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMap </returns>
public static ResourceSet<SyncMapResource> Read(ReadSyncMapOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<SyncMapResource>.FromJson("maps", response.Content);
return new ResourceSet<SyncMapResource>(page, options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="options"> Read SyncMap parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMap </returns>
public static async System.Threading.Tasks.Task<ResourceSet<SyncMapResource>> ReadAsync(ReadSyncMapOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<SyncMapResource>.FromJson("maps", response.Content);
return new ResourceSet<SyncMapResource>(page, options, client);
}
#endif
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of SyncMap </returns>
public static ResourceSet<SyncMapResource> Read(string pathServiceSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadSyncMapOptions(pathServiceSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// read
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of SyncMap </returns>
public static async System.Threading.Tasks.Task<ResourceSet<SyncMapResource>> ReadAsync(string pathServiceSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadSyncMapOptions(pathServiceSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<SyncMapResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<SyncMapResource>.FromJson("maps", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<SyncMapResource> NextPage(Page<SyncMapResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Preview)
);
var response = client.Request(request);
return Page<SyncMapResource>.FromJson("maps", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<SyncMapResource> PreviousPage(Page<SyncMapResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Preview)
);
var response = client.Request(request);
return Page<SyncMapResource>.FromJson("maps", response.Content);
}
/// <summary>
/// Converts a JSON string into a SyncMapResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> SyncMapResource object represented by the provided JSON </returns>
public static SyncMapResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<SyncMapResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The sid
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The unique_name
/// </summary>
[JsonProperty("unique_name")]
public string UniqueName { get; private set; }
/// <summary>
/// The account_sid
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The service_sid
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The url
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The links
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
/// <summary>
/// The revision
/// </summary>
[JsonProperty("revision")]
public string Revision { get; private set; }
/// <summary>
/// The date_created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The date_updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The created_by
/// </summary>
[JsonProperty("created_by")]
public string CreatedBy { get; private set; }
private SyncMapResource()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ApprovalTests.Reporters;
using ConsoleToolkit.ConsoleIO;
using ConsoleToolkit.ConsoleIO.Internal;
using ConsoleToolkitTests.TestingUtilities;
using NUnit.Framework;
using Approvals = ApprovalTests.Approvals;
namespace ConsoleToolkitTests.ConsoleIO.Internal
{
[TestFixture]
[UseReporter(typeof (CustomReporter))]
public class TestColumnWrapper
{
[Test]
public void StringIsWrappedAtWordBreaks()
{
var c = new ColumnFormat("h", typeof (string));
const string value = "One two three four five six seven eight nine ten eleven.";
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void NoTrailingSpacesAreIncludedOnLineWrap()
{
var c = new ColumnFormat("h", typeof (string));
const string value = "One two three four\t\t\t\t\t\t\t\t five\tsix seven eight nine ten eleven.";
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void WordsLongerThanOneLineAreBroken()
{
var c = new ColumnFormat("h", typeof (string));
const string value = "One two three four fivesixseveneightnineteneleven.";
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void VeryLongInitialWordisBroken()
{
var c = new ColumnFormat("h", typeof (string));
const string value = "Onetwothreefourfivesixseveneightnineten eleven.";
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void LineBreaksArePreserved()
{
var c = new ColumnFormat("h", typeof (string));
const string value = "One two three\r\nfour five six seven eight\r\n\r\n\r\nnine\r\nten\r\neleven.";
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void ColourInstructionsAreIncluded()
{
var c = new ColumnFormat("h", typeof (string));
var value = "One".Red() +" " + "two".Blue() + " three\r\nfour five six seven eight\r\n\r\n\r\nnine\r\nten\r\neleven.";
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void LineBreaksWithinColouredTextAreFormatted()
{
var c = new ColumnFormat("h", typeof (string));
var value = "One\r\ntwo\r\nthree".Red().BGBlue();
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void ColouredSpacesAreSkippedAtTheEndOfTheLineButInstructionsArePreserved()
{
var c = new ColumnFormat("h", typeof (string));
var value = "four five six seven" + " ".Red() + " ".White() + " ".Blue() + "eight";
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void ColourInstructionsForLastWordAreIncluded()
{
var c = new ColumnFormat("h", typeof (string));
var value = "four five six seven " + "eight".Red();
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void WordBreaksAreCounted()
{
var c = new ColumnFormat("h", typeof (string));
const string value = "One two three four five six seven eight nine ten eleven.";
var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20);
Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20)));
Assert.That(addedBreaks, Is.EqualTo(2));
}
[Test]
public void TrailingSpacesDoNotCauseAdditionalLineBreaks()
{
var c = new ColumnFormat("h", typeof (string));
const string value = "One two three four\t\t\t\t\t\t\t\t five\tsix seven eight nine ten eleven.";
var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20);
Console.WriteLine("----+----|----+----|");
Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20)));
Assert.That(addedBreaks, Is.EqualTo(3));
}
[Test]
public void BreaksInVeryLongWordsAreCounted()
{
var c = new ColumnFormat("h", typeof (string));
const string value = "One two three four fivesixseveneightnineteneleven.";
var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20);
Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20)));
Assert.That(addedBreaks, Is.EqualTo(2));
}
[Test]
public void BreaksInVeryLongInitialWordAreCounted()
{
var c = new ColumnFormat("h", typeof (string));
const string value = "Onetwothreefourfivesixseveneightnineten eleven.";
var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20);
Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20)));
Assert.That(addedBreaks, Is.EqualTo(2));
}
[Test]
public void DataLineBreaksAreNotCounted()
{
var c = new ColumnFormat("h", typeof (string));
const string value = "One two three\r\nfour five six seven eight\r\n\r\n\r\nnine\r\nten\r\neleven.";
var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20);
Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20)));
Assert.That(addedBreaks, Is.EqualTo(1));
}
[Test]
public void SingleLineDataAddsNoLineBreaks()
{
var c = new ColumnFormat("h", typeof (string));
const string value = "One two three.";
var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20);
Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20)));
Assert.That(addedBreaks, Is.EqualTo(0));
}
[Test]
public void NestedColourChangesArePreserved()
{
var c = new ColumnFormat("h", typeof (string));
var value = (("Red" + Environment.NewLine + "Lines").Cyan() + Environment.NewLine + "lines").BGDarkRed() + "Clear";
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void LinesWithColourAreExpandedToCorrectLength()
{
var c = new ColumnFormat("h", typeof (string));
c.SetActualWidth(20);
var value = (("Red" + Environment.NewLine + "Lines").Cyan() + Environment.NewLine + "lines").BGDarkRed() + "Clear";
var wrapped = ColumnWrapper.WrapValue(value, c, 20).Select(l => "-->" + l + "<--");
var result = FormatResult(value, wrapped, 20, 3);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void LinesAreExpandedToCorrectLength()
{
var c = new ColumnFormat("h", typeof (string));
c.SetActualWidth(20);
var value = "Line" + Environment.NewLine + "Data" + Environment.NewLine + "More";
var wrapped = ColumnWrapper.WrapValue(value, c, 20).Select(l => "-->" + l + "<--");
var result = FormatResult(value, wrapped, 20, 3);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void RightAlignedLinesAreExpandedToCorrectLength()
{
var c = new ColumnFormat("h", typeof (string), ColumnAlign.Right);
c.SetActualWidth(20);
var value = "Line" + Environment.NewLine + "Data" + Environment.NewLine + "More";
var wrapped = ColumnWrapper.WrapValue(value, c, 20).Select(l => "-->" + l + "<--");
var result = FormatResult(value, wrapped, 20, 3);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void RightAlignedLinesWithColourAreExpandedToCorrectLength()
{
var c = new ColumnFormat("h", typeof (string), ColumnAlign.Right);
c.SetActualWidth(20);
var value = (("Red" + Environment.NewLine + "Lines").Cyan() + Environment.NewLine + "lines").BGDarkRed() + "Clear";
var wrapped = ColumnWrapper.WrapValue(value, c, 20).Select(l => "-->" + l + "<--");
var result = FormatResult(value, wrapped, 20, 3);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void RightAlignedLinesWithExcessiveColumnWidthAreExpandedToCorrectLength()
{
var c = new ColumnFormat("h", typeof (string), ColumnAlign.Right);
c.SetActualWidth(20);
var value = (("Red" + Environment.NewLine + "Lines").Cyan() + Environment.NewLine + "lines").BGDarkRed() + "Clear";
var wrapped = ColumnWrapper.WrapValue(value, c, 10).Select(l => "-->" + l + "<--");
var result = FormatResult(value, wrapped, 10, 3);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void ColouredWordsTooLongForALineAreCorrectlyChunked()
{
var c = new ColumnFormat("h", typeof (string));
var value = "toomuchdataforeventwolines".Red();
var wrapped = ColumnWrapper.WrapValue(value, c, 9);
var result = FormatResult(value, wrapped, 10);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void FirstLineIndentShortensFirstLine()
{
var c = new ColumnFormat("h", typeof(string));
const string value = "One two three four five six seven eight nine ten eleven.";
var wrapped = ColumnWrapper.WrapValue(value, c, 20, firstLineHangingIndent: 10);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void LeadingSpacesArePreserved()
{
var c = new ColumnFormat("h", typeof(string));
const string value = " One two three.";
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void TrailingSpacesArePreserved()
{
var c = new ColumnFormat("h", typeof(string));
const string value = "One two three. ";
var wrapped = ColumnWrapper.WrapValue(value, c, 20);
var result = FormatResult(value, wrapped, 20);
Console.WriteLine(result);
Approvals.Verify(result);
}
[Test]
public void WrapAndMeasureWordsCanWorkWithSplitData()
{
//Arrange
var c = new ColumnFormat("h", typeof(string));
const string value = "One two three four five six seven eight nine ten eleven.";
var words = WordSplitter.SplitToList(value, 4);
//Act
int wrappedLines;
var wrapped = ColumnWrapper.WrapAndMeasureWords(words, c, 20, 0, out wrappedLines);
//Assert
var result = FormatResult(value, wrapped, 20)
+ Environment.NewLine
+ string.Format("Added line breaks = {0}", wrappedLines);
Console.WriteLine(result);
Approvals.Verify(result);
}
private string FormatResult(string value, IEnumerable<string> wrapped, int guideWidth, int indent = 0)
{
var indentString = new string(' ', indent);
var sb = new StringBuilder();
sb.AppendLine(TestContext.CurrentContext.Test.Name);
sb.AppendLine();
sb.AppendLine("Original:");
sb.AppendLine(value);
sb.AppendLine();
sb.AppendLine("Wrapped:");
var guide = Enumerable.Range(0, guideWidth)
.Select(i => ((i + 1)%10).ToString())
.Aggregate((t, i) => t + i);
var divide = Enumerable.Range(0, guideWidth)
.Select(i => ((i + 1) % 10) == 0 ? "+" : "-")
.Aggregate((t, i) => t + i);
sb.AppendLine(indentString + guide);
sb.AppendLine(indentString + divide);
foreach (var line in wrapped)
{
sb.AppendLine(line);
}
return sb.ToString();
}
}
}
| |
namespace SharpCompress.Common.Zip.Headers
{
using SharpCompress.Common;
using SharpCompress.Common.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
internal abstract class ZipFileEntry : ZipHeader
{
[CompilerGenerated]
private uint _CompressedSize_k__BackingField;
[CompilerGenerated]
private ZipCompressionMethod _CompressionMethod_k__BackingField;
[CompilerGenerated]
private uint _Crc_k__BackingField;
[CompilerGenerated]
private long? _DataStartPosition_k__BackingField;
[CompilerGenerated]
private List<ExtraData> _Extra_k__BackingField;
[CompilerGenerated]
private HeaderFlags _Flags_k__BackingField;
[CompilerGenerated]
private ushort _LastModifiedDate_k__BackingField;
[CompilerGenerated]
private ushort _LastModifiedTime_k__BackingField;
[CompilerGenerated]
private string _Name_k__BackingField;
[CompilerGenerated]
private Stream _PackedStream_k__BackingField;
[CompilerGenerated]
private ZipFilePart _Part_k__BackingField;
[CompilerGenerated]
private SharpCompress.Common.Zip.PkwareTraditionalEncryptionData _PkwareTraditionalEncryptionData_k__BackingField;
[CompilerGenerated]
private uint _UncompressedSize_k__BackingField;
protected ZipFileEntry(ZipHeaderType type) : base(type)
{
this.Extra = new List<ExtraData>();
}
protected string DecodeString(byte[] str)
{
if (FlagUtility.HasFlag<HeaderFlags>(this.Flags, HeaderFlags.UTF8))
{
return Encoding.UTF8.GetString(str, 0, str.Length);
}
return ArchiveEncoding.Default.GetString(str, 0, str.Length);
}
protected byte[] EncodeString(string str)
{
if (FlagUtility.HasFlag<HeaderFlags>(this.Flags, HeaderFlags.UTF8))
{
return Encoding.UTF8.GetBytes(str);
}
return ArchiveEncoding.Default.GetBytes(str);
}
protected void LoadExtra(byte[] extra)
{
ushort num2;
for (int i = 0; i < (extra.Length - 4); i += num2 + 4)
{
ExtraDataType notImplementedExtraData = (ExtraDataType) BitConverter.ToUInt16(extra, i);
if (!Enum.IsDefined(typeof(ExtraDataType), notImplementedExtraData))
{
notImplementedExtraData = ExtraDataType.NotImplementedExtraData;
}
num2 = BitConverter.ToUInt16(extra, i + 2);
byte[] dst = new byte[num2];
Buffer.BlockCopy(extra, i + 4, dst, 0, num2);
this.Extra.Add(LocalEntryHeaderExtraFactory.Create(notImplementedExtraData, num2, dst));
}
}
internal uint CompressedSize
{
[CompilerGenerated]
get
{
return this._CompressedSize_k__BackingField;
}
[CompilerGenerated]
set
{
this._CompressedSize_k__BackingField = value;
}
}
internal ZipCompressionMethod CompressionMethod
{
[CompilerGenerated]
get
{
return this._CompressionMethod_k__BackingField;
}
[CompilerGenerated]
set
{
this._CompressionMethod_k__BackingField = value;
}
}
internal uint Crc
{
[CompilerGenerated]
get
{
return this._Crc_k__BackingField;
}
[CompilerGenerated]
set
{
this._Crc_k__BackingField = value;
}
}
internal long? DataStartPosition
{
[CompilerGenerated]
get
{
return this._DataStartPosition_k__BackingField;
}
[CompilerGenerated]
set
{
this._DataStartPosition_k__BackingField = value;
}
}
internal List<ExtraData> Extra
{
[CompilerGenerated]
get
{
return this._Extra_k__BackingField;
}
[CompilerGenerated]
set
{
this._Extra_k__BackingField = value;
}
}
internal HeaderFlags Flags
{
[CompilerGenerated]
get
{
return this._Flags_k__BackingField;
}
[CompilerGenerated]
set
{
this._Flags_k__BackingField = value;
}
}
internal bool IsDirectory
{
get
{
return this.Name.EndsWith("/");
}
}
internal ushort LastModifiedDate
{
[CompilerGenerated]
get
{
return this._LastModifiedDate_k__BackingField;
}
[CompilerGenerated]
set
{
this._LastModifiedDate_k__BackingField = value;
}
}
internal ushort LastModifiedTime
{
[CompilerGenerated]
get
{
return this._LastModifiedTime_k__BackingField;
}
[CompilerGenerated]
set
{
this._LastModifiedTime_k__BackingField = value;
}
}
internal string Name
{
[CompilerGenerated]
get
{
return this._Name_k__BackingField;
}
[CompilerGenerated]
set
{
this._Name_k__BackingField = value;
}
}
internal Stream PackedStream
{
[CompilerGenerated]
get
{
return this._PackedStream_k__BackingField;
}
[CompilerGenerated]
set
{
this._PackedStream_k__BackingField = value;
}
}
internal ZipFilePart Part
{
[CompilerGenerated]
get
{
return this._Part_k__BackingField;
}
[CompilerGenerated]
set
{
this._Part_k__BackingField = value;
}
}
internal SharpCompress.Common.Zip.PkwareTraditionalEncryptionData PkwareTraditionalEncryptionData
{
[CompilerGenerated]
get
{
return this._PkwareTraditionalEncryptionData_k__BackingField;
}
[CompilerGenerated]
set
{
this._PkwareTraditionalEncryptionData_k__BackingField = value;
}
}
internal uint UncompressedSize
{
[CompilerGenerated]
get
{
return this._UncompressedSize_k__BackingField;
}
[CompilerGenerated]
set
{
this._UncompressedSize_k__BackingField = value;
}
}
}
}
| |
using System;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Services;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
namespace Umbraco.Tests.Services
{
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)]
[TestFixture, RequiresSTA]
public class MemberServiceTests : BaseServiceTest
{
[SetUp]
public override void Initialize()
{
base.Initialize();
}
[TearDown]
public override void TearDown()
{
base.TearDown();
}
[Test]
public void Can_Create_Role()
{
ServiceContext.MemberService.AddRole("MyTestRole");
var found = ServiceContext.MemberService.GetAllRoles();
Assert.AreEqual(1, found.Count());
Assert.AreEqual("MyTestRole", found.Single());
}
[Test]
public void Can_Create_Duplicate_Role()
{
ServiceContext.MemberService.AddRole("MyTestRole");
ServiceContext.MemberService.AddRole("MyTestRole");
var found = ServiceContext.MemberService.GetAllRoles();
Assert.AreEqual(1, found.Count());
Assert.AreEqual("MyTestRole", found.Single());
}
[Test]
public void Can_Get_All_Roles()
{
ServiceContext.MemberService.AddRole("MyTestRole1");
ServiceContext.MemberService.AddRole("MyTestRole2");
ServiceContext.MemberService.AddRole("MyTestRole3");
var found = ServiceContext.MemberService.GetAllRoles();
Assert.AreEqual(3, found.Count());
}
[Test]
public void Can_Get_All_Roles_By_Member_Id()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test");
ServiceContext.MemberService.Save(member);
ServiceContext.MemberService.AddRole("MyTestRole1");
ServiceContext.MemberService.AddRole("MyTestRole2");
ServiceContext.MemberService.AddRole("MyTestRole3");
ServiceContext.MemberService.AssignRoles(new[] { member.Id }, new[] { "MyTestRole1", "MyTestRole2" });
var memberRoles = ServiceContext.MemberService.GetAllRoles(member.Id);
Assert.AreEqual(2, memberRoles.Count());
}
[Test]
public void Can_Get_All_Roles_By_Member_Username()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test");
ServiceContext.MemberService.Save(member);
ServiceContext.MemberService.AddRole("MyTestRole1");
ServiceContext.MemberService.AddRole("MyTestRole2");
ServiceContext.MemberService.AddRole("MyTestRole3");
ServiceContext.MemberService.AssignRoles(new[] { member.Id }, new[] { "MyTestRole1", "MyTestRole2" });
var memberRoles = ServiceContext.MemberService.GetAllRoles("test");
Assert.AreEqual(2, memberRoles.Count());
}
[Test]
public void Can_Delete_Role()
{
ServiceContext.MemberService.AddRole("MyTestRole1");
ServiceContext.MemberService.DeleteRole("MyTestRole1", false);
var memberRoles = ServiceContext.MemberService.GetAllRoles();
Assert.AreEqual(0, memberRoles.Count());
}
[Test]
public void Throws_When_Deleting_Assigned_Role()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test");
ServiceContext.MemberService.Save(member);
ServiceContext.MemberService.AddRole("MyTestRole1");
ServiceContext.MemberService.AssignRoles(new[] { member.Id }, new[] { "MyTestRole1", "MyTestRole2" });
Assert.Throws<InvalidOperationException>(() => ServiceContext.MemberService.DeleteRole("MyTestRole1", true));
}
[Test]
public void Can_Get_Members_In_Role()
{
ServiceContext.MemberService.AddRole("MyTestRole1");
var roleId = DatabaseContext.Database.ExecuteScalar<int>("SELECT id from umbracoNode where [text] = 'MyTestRole1'");
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1");
ServiceContext.MemberService.Save(member1);
var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2");
ServiceContext.MemberService.Save(member2);
DatabaseContext.Database.Insert(new Member2MemberGroupDto {MemberGroup = roleId, Member = member1.Id});
DatabaseContext.Database.Insert(new Member2MemberGroupDto { MemberGroup = roleId, Member = member2.Id });
var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1");
Assert.AreEqual(2, membersInRole.Count());
}
[TestCase("MyTestRole1", "test1", StringPropertyMatchType.StartsWith, 1)]
[TestCase("MyTestRole1", "test", StringPropertyMatchType.StartsWith, 3)]
[TestCase("MyTestRole1", "test1", StringPropertyMatchType.Exact, 1)]
[TestCase("MyTestRole1", "test", StringPropertyMatchType.Exact, 0)]
[TestCase("MyTestRole1", "st2", StringPropertyMatchType.EndsWith, 1)]
[TestCase("MyTestRole1", "test%", StringPropertyMatchType.Wildcard, 3)]
public void Find_Members_In_Role(string roleName1, string usernameToMatch, StringPropertyMatchType matchType, int resultCount)
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1");
ServiceContext.MemberService.Save(member1);
var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2");
ServiceContext.MemberService.Save(member2);
var member3 = MockedMember.CreateSimpleMember(memberType, "test3", "test3@test.com", "pass", "test3");
ServiceContext.MemberService.Save(member3);
ServiceContext.MemberService.AssignRoles(new[] { member1.Id, member2.Id, member3.Id }, new[] { roleName1 });
var result = ServiceContext.MemberService.FindMembersInRole(roleName1, usernameToMatch, matchType);
Assert.AreEqual(resultCount, result.Count());
}
[Test]
public void Associate_Members_To_Roles_With_Member_Id()
{
ServiceContext.MemberService.AddRole("MyTestRole1");
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1");
ServiceContext.MemberService.Save(member1);
var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2");
ServiceContext.MemberService.Save(member2);
ServiceContext.MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole1" });
var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1");
Assert.AreEqual(2, membersInRole.Count());
}
[Test]
public void Associate_Members_To_Roles_With_Member_Username()
{
ServiceContext.MemberService.AddRole("MyTestRole1");
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1");
ServiceContext.MemberService.Save(member1);
var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2");
ServiceContext.MemberService.Save(member2);
ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" });
var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1");
Assert.AreEqual(2, membersInRole.Count());
}
[Test]
public void Associate_Members_To_Roles_With_Member_Username_Containing_At_Symbols()
{
ServiceContext.MemberService.AddRole("MyTestRole1");
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1@test.com");
ServiceContext.MemberService.Save(member1);
var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2@test.com");
ServiceContext.MemberService.Save(member2);
ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" });
var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1");
Assert.AreEqual(2, membersInRole.Count());
}
[Test]
public void Associate_Members_To_Roles_With_New_Role()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1");
ServiceContext.MemberService.Save(member1);
var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2");
ServiceContext.MemberService.Save(member2);
//implicitly create the role
ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" });
var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1");
Assert.AreEqual(2, membersInRole.Count());
}
[Test]
public void Remove_Members_From_Roles_With_Member_Id()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1");
ServiceContext.MemberService.Save(member1);
var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2");
ServiceContext.MemberService.Save(member2);
ServiceContext.MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole1", "MyTestRole2" });
ServiceContext.MemberService.DissociateRoles(new[] {member1.Id }, new[] {"MyTestRole1"});
ServiceContext.MemberService.DissociateRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole2" });
var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1");
Assert.AreEqual(1, membersInRole.Count());
membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole2");
Assert.AreEqual(0, membersInRole.Count());
}
[Test]
public void Remove_Members_From_Roles_With_Member_Username()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1");
ServiceContext.MemberService.Save(member1);
var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2");
ServiceContext.MemberService.Save(member2);
ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1", "MyTestRole2" });
ServiceContext.MemberService.DissociateRoles(new[] { member1.Username }, new[] { "MyTestRole1" });
ServiceContext.MemberService.DissociateRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole2" });
var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1");
Assert.AreEqual(1, membersInRole.Count());
membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole2");
Assert.AreEqual(0, membersInRole.Count());
}
[Test]
public void Can_Delete_member()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test");
ServiceContext.MemberService.Save(member);
ServiceContext.MemberService.Delete(member);
var deleted = ServiceContext.MemberService.GetById(member.Id);
// Assert
Assert.That(deleted, Is.Null);
}
[Test]
public void ContentXml_Created_When_Saved()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test");
ServiceContext.MemberService.Save(member);
var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = member.Id });
Assert.IsNotNull(xml);
}
[Test]
public void Exists_By_Username()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test");
ServiceContext.MemberService.Save(member);
Assert.IsTrue(ServiceContext.MemberService.Exists("test"));
Assert.IsFalse(ServiceContext.MemberService.Exists("notFound"));
}
[Test]
public void Exists_By_Id()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test");
ServiceContext.MemberService.Save(member);
Assert.IsTrue(ServiceContext.MemberService.Exists(member.Id));
Assert.IsFalse(ServiceContext.MemberService.Exists(9876));
}
[Test]
public void Get_By_Email()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test");
ServiceContext.MemberService.Save(member);
Assert.IsNotNull(ServiceContext.MemberService.GetByEmail(member.Email));
Assert.IsNull(ServiceContext.MemberService.GetByEmail("do@not.find"));
}
[Test]
public void Get_By_Username()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test");
ServiceContext.MemberService.Save(member);
Assert.IsNotNull(ServiceContext.MemberService.GetByUsername(member.Username));
Assert.IsNull(ServiceContext.MemberService.GetByUsername("notFound"));
}
[Test]
public void Get_By_Object_Id()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test");
ServiceContext.MemberService.Save(member);
Assert.IsNotNull(ServiceContext.MemberService.GetById(member.Id));
Assert.IsNull(ServiceContext.MemberService.GetById(9876));
}
[Test]
public void Get_All_Paged_Members()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
int totalRecs;
var found = ServiceContext.MemberService.GetAll(0, 2, out totalRecs);
Assert.AreEqual(2, found.Count());
Assert.AreEqual(10, totalRecs);
Assert.AreEqual("test0", found.First().Username);
Assert.AreEqual("test1", found.Last().Username);
}
[Test]
public void Find_By_Email_Starts_With()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
//don't find this
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello","hello");
ServiceContext.MemberService.Save(customMember);
int totalRecs;
var found = ServiceContext.MemberService.FindByEmail("tes", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith);
Assert.AreEqual(10, found.Count());
}
[Test]
public void Find_By_Email_Ends_With()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
//include this
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
int totalRecs;
var found = ServiceContext.MemberService.FindByEmail("test.com", 0, 100, out totalRecs, StringPropertyMatchType.EndsWith);
Assert.AreEqual(11, found.Count());
}
[Test]
public void Find_By_Email_Contains()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
//include this
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
int totalRecs;
var found = ServiceContext.MemberService.FindByEmail("test", 0, 100, out totalRecs, StringPropertyMatchType.Contains);
Assert.AreEqual(11, found.Count());
}
[Test]
public void Find_By_Email_Exact()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
//include this
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
int totalRecs;
var found = ServiceContext.MemberService.FindByEmail("hello@test.com", 0, 100, out totalRecs, StringPropertyMatchType.Exact);
Assert.AreEqual(1, found.Count());
}
[Test]
public void Find_By_Login_Starts_With()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
//don't find this
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
int totalRecs;
var found = ServiceContext.MemberService.FindByUsername("tes", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith);
Assert.AreEqual(10, found.Count());
}
[Test]
public void Find_By_Login_Ends_With()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
//include this
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
int totalRecs;
var found = ServiceContext.MemberService.FindByUsername("llo", 0, 100, out totalRecs, StringPropertyMatchType.EndsWith);
Assert.AreEqual(1, found.Count());
}
[Test]
public void Find_By_Login_Contains()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
//include this
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hellotest");
ServiceContext.MemberService.Save(customMember);
int totalRecs;
var found = ServiceContext.MemberService.FindByUsername("test", 0, 100, out totalRecs, StringPropertyMatchType.Contains);
Assert.AreEqual(11, found.Count());
}
[Test]
public void Find_By_Login_Exact()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
//include this
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
int totalRecs;
var found = ServiceContext.MemberService.FindByUsername("hello", 0, 100, out totalRecs, StringPropertyMatchType.Exact);
Assert.AreEqual(1, found.Count());
}
[Test]
public void Get_By_Property_String_Value_Exact()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"title", "hello member", StringPropertyMatchType.Exact);
Assert.AreEqual(1, found.Count());
}
[Test]
public void Get_By_Property_String_Value_Contains()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"title", " member", StringPropertyMatchType.Contains);
Assert.AreEqual(11, found.Count());
}
[Test]
public void Get_By_Property_String_Value_Starts_With()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"title", "Member No", StringPropertyMatchType.StartsWith);
Assert.AreEqual(10, found.Count());
}
[Test]
public void Get_By_Property_String_Value_Ends_With()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue("title", "title of mine");
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"title", "mine", StringPropertyMatchType.EndsWith);
Assert.AreEqual(1, found.Count());
}
[Test]
public void Get_By_Property_Int_Value_Exact()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer)
{
Alias = "number",
Name = "Number",
//NOTE: This is what really determines the db type - the above definition doesn't really do anything
DataTypeDefinitionId = -51
}, "Content");
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i));
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue("number", 2);
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"number", 2, ValuePropertyMatchType.Exact);
Assert.AreEqual(2, found.Count());
}
[Test]
public void Get_By_Property_Int_Value_Greater_Than()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer)
{
Alias = "number",
Name = "Number",
//NOTE: This is what really determines the db type - the above definition doesn't really do anything
DataTypeDefinitionId = -51
}, "Content");
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i));
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue("number", 10);
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"number", 3, ValuePropertyMatchType.GreaterThan);
Assert.AreEqual(7, found.Count());
}
[Test]
public void Get_By_Property_Int_Value_Greater_Than_Equal_To()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer)
{
Alias = "number",
Name = "Number",
//NOTE: This is what really determines the db type - the above definition doesn't really do anything
DataTypeDefinitionId = -51
}, "Content");
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i));
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue("number", 10);
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"number", 3, ValuePropertyMatchType.GreaterThanOrEqualTo);
Assert.AreEqual(8, found.Count());
}
[Test]
public void Get_By_Property_Int_Value_Less_Than()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.DateAlias, DataTypeDatabaseType.Date)
{
Alias = "number",
Name = "Number",
//NOTE: This is what really determines the db type - the above definition doesn't really do anything
DataTypeDefinitionId = -51
}, "Content");
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i));
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue("number", 1);
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"number", 5, ValuePropertyMatchType.LessThan);
Assert.AreEqual(6, found.Count());
}
[Test]
public void Get_By_Property_Int_Value_Less_Than_Or_Equal()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer)
{
Alias = "number",
Name = "Number",
//NOTE: This is what really determines the db type - the above definition doesn't really do anything
DataTypeDefinitionId = -51
}, "Content");
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i));
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue("number", 1);
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"number", 5, ValuePropertyMatchType.LessThanOrEqualTo);
Assert.AreEqual(7, found.Count());
}
[Test]
public void Get_By_Property_Date_Value_Exact()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer)
{
Alias = "date",
Name = "Date",
//NOTE: This is what really determines the db type - the above definition doesn't really do anything
DataTypeDefinitionId = -36
}, "Content");
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0)));
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 2, 0));
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"date", new DateTime(2013, 12, 20, 1, 2, 0), ValuePropertyMatchType.Exact);
Assert.AreEqual(2, found.Count());
}
[Test]
public void Get_By_Property_Date_Value_Greater_Than()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer)
{
Alias = "date",
Name = "Date",
//NOTE: This is what really determines the db type - the above definition doesn't really do anything
DataTypeDefinitionId = -36
}, "Content");
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0)));
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 10, 0));
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"date", new DateTime(2013, 12, 20, 1, 3, 0), ValuePropertyMatchType.GreaterThan);
Assert.AreEqual(7, found.Count());
}
[Test]
public void Get_By_Property_Date_Value_Greater_Than_Equal_To()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer)
{
Alias = "date",
Name = "Date",
//NOTE: This is what really determines the db type - the above definition doesn't really do anything
DataTypeDefinitionId = -36
}, "Content");
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0)));
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 10, 0));
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"date", new DateTime(2013, 12, 20, 1, 3, 0), ValuePropertyMatchType.GreaterThanOrEqualTo);
Assert.AreEqual(8, found.Count());
}
[Test]
public void Get_By_Property_Date_Value_Less_Than()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer)
{
Alias = "date",
Name = "Date",
//NOTE: This is what really determines the db type - the above definition doesn't really do anything
DataTypeDefinitionId = -36
}, "Content");
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0)));
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 1, 0));
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"date", new DateTime(2013, 12, 20, 1, 5, 0), ValuePropertyMatchType.LessThan);
Assert.AreEqual(6, found.Count());
}
[Test]
public void Get_By_Property_Date_Value_Less_Than_Or_Equal()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer)
{
Alias = "date",
Name = "Date",
//NOTE: This is what really determines the db type - the above definition doesn't really do anything
DataTypeDefinitionId = -36
}, "Content");
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0)));
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 1, 0));
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetMembersByPropertyValue(
"date", new DateTime(2013, 12, 20, 1, 5, 0), ValuePropertyMatchType.LessThanOrEqualTo);
Assert.AreEqual(7, found.Count());
}
[Test]
public void Count_All_Members()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10);
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetCount(MemberCountType.All);
Assert.AreEqual(11, found);
}
[Test]
public void Count_All_Online_Members()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.LastLoginDate = DateTime.Now.AddMinutes(i * -2));
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue(Constants.Conventions.Member.LastLoginDate, DateTime.Now);
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetCount(MemberCountType.Online);
Assert.AreEqual(9, found);
}
[Test]
public void Count_All_Locked_Members()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.IsLockedOut = i % 2 == 0);
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue(Constants.Conventions.Member.IsLockedOut, true);
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetCount(MemberCountType.LockedOut);
Assert.AreEqual(6, found);
}
[Test]
public void Count_All_Approved_Members()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.IsApproved = i % 2 == 0);
ServiceContext.MemberService.Save(members);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
customMember.SetValue(Constants.Conventions.Member.IsApproved, false);
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetCount(MemberCountType.Approved);
Assert.AreEqual(5, found);
}
[Test]
public void Setting_Property_On_Built_In_Member_Property_When_Property_Doesnt_Exist_On_Type_Is_Ok()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
memberType.RemovePropertyType(Constants.Conventions.Member.Comments);
ServiceContext.MemberTypeService.Save(memberType);
Assert.IsFalse(memberType.PropertyTypes.Any(x => x.Alias == Constants.Conventions.Member.Comments));
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
//this should not throw an exception
customMember.Comments = "hello world";
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetById(customMember.Id);
Assert.IsTrue(found.Comments.IsNullOrWhiteSpace());
}
/// <summary>
/// Because we are forcing some of the built-ins to be Labels which have an underlying db type as nvarchar but we need
/// to ensure that the dates/int get saved to the correct column anyways.
/// </summary>
[Test]
public void Setting_DateTime_Property_On_Built_In_Member_Property_Saves_To_Correct_Column()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "test", "test");
var date = DateTime.Now;
member.LastLoginDate = DateTime.Now;
ServiceContext.MemberService.Save(member);
var result = ServiceContext.MemberService.GetById(member.Id);
Assert.AreEqual(
date.TruncateTo(DateTimeExtensions.DateTruncate.Second),
result.LastLoginDate.TruncateTo(DateTimeExtensions.DateTruncate.Second));
//now ensure the col is correct
var sql = new Sql().Select("cmsPropertyData.*")
.From<PropertyDataDto>()
.InnerJoin<PropertyTypeDto>()
.On<PropertyDataDto, PropertyTypeDto>(dto => dto.PropertyTypeId, dto => dto.Id)
.Where<PropertyDataDto>(dto => dto.NodeId == member.Id)
.Where<PropertyTypeDto>(dto => dto.Alias == Constants.Conventions.Member.LastLoginDate);
var colResult = DatabaseContext.Database.Fetch<PropertyDataDto>(sql);
Assert.AreEqual(1, colResult.Count);
Assert.IsTrue(colResult.First().Date.HasValue);
Assert.IsFalse(colResult.First().Integer.HasValue);
Assert.IsNull(colResult.First().Text);
Assert.IsNull(colResult.First().VarChar);
}
[Test]
public void New_Member_Approved_By_Default()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
var found = ServiceContext.MemberService.GetById(customMember.Id);
Assert.IsTrue(found.IsApproved);
}
[Test]
public void Ensure_Content_Xml_Created()
{
IMemberType memberType = MockedContentTypes.CreateSimpleMemberType();
ServiceContext.MemberTypeService.Save(memberType);
var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello");
ServiceContext.MemberService.Save(customMember);
var provider = new PetaPocoUnitOfWorkProvider();
var uow = provider.GetUnitOfWork();
using (RepositoryResolver.Current.ResolveByType<IMemberRepository>(uow))
{
Assert.IsTrue(uow.Database.Exists<ContentXmlDto>(customMember.Id));
}
}
}
}
| |
using System;
using System.Collections;
using Fonet.Fo.Properties;
namespace Fonet.Fo
{
internal class PropertyList : Hashtable
{
private byte[] wmtable = null;
public const int LEFT = 0;
public const int RIGHT = 1;
public const int TOP = 2;
public const int BOTTOM = 3;
public const int HEIGHT = 4;
public const int WIDTH = 5;
public const int START = 0;
public const int END = 1;
public const int BEFORE = 2;
public const int AFTER = 3;
public const int BLOCKPROGDIM = 4;
public const int INLINEPROGDIM = 5;
private static readonly string[] sAbsNames = new string[] {
"left", "right", "top", "bottom", "height", "width"
};
private static readonly string[] sRelNames = new string[] {
"start", "end", "before", "after", "block-progression-dimension",
"inline-progression-dimension"
};
private static readonly Hashtable wmtables = new Hashtable(4);
private PropertyListBuilder builder;
private PropertyList parentPropertyList = null;
private string nmspace = "";
private string element = "";
private FObj fobj = null;
static PropertyList()
{
wmtables.Add(
WritingMode.LR_TB, /* lr-tb */
new byte[] {
START, END, BEFORE, AFTER, BLOCKPROGDIM, INLINEPROGDIM
});
wmtables.Add(
WritingMode.RL_TB, /* rl-tb */
new byte[] {
END, START, BEFORE, AFTER, BLOCKPROGDIM, INLINEPROGDIM
});
wmtables.Add(
WritingMode.TB_RL, /* tb-rl */
new byte[] {
AFTER, BEFORE, START, END, INLINEPROGDIM, BLOCKPROGDIM
});
}
public PropertyList(
PropertyList parentPropertyList, string space, string el)
{
this.parentPropertyList = parentPropertyList;
this.nmspace = space;
this.element = el;
}
public FObj FObj
{
get { return fobj; }
set { fobj = value; }
}
public FObj getParentFObj()
{
if (parentPropertyList != null)
{
return parentPropertyList.FObj;
}
else
{
return null;
}
}
public Property GetExplicitOrShorthandProperty(string propertyName)
{
int sepchar = propertyName.IndexOf('.');
string baseName;
if (sepchar > -1)
{
baseName = propertyName.Substring(0, sepchar);
}
else
{
baseName = propertyName;
}
Property p = GetExplicitBaseProperty(baseName);
if (p == null)
{
p = builder.GetShorthand(this, baseName);
}
if (p != null && sepchar > -1)
{
return builder.GetSubpropValue(baseName, p,
propertyName.Substring(sepchar
+ 1));
}
return p;
}
public Property GetExplicitProperty(string propertyName)
{
int sepchar = propertyName.IndexOf('.');
if (sepchar > -1)
{
string baseName = propertyName.Substring(0, sepchar);
Property p = GetExplicitBaseProperty(baseName);
if (p != null)
{
return builder.GetSubpropValue(
baseName, p,
propertyName.Substring(sepchar
+ 1));
}
else
{
return null;
}
}
return (Property)this[propertyName];
}
public Property GetExplicitBaseProperty(string propertyName)
{
return (Property)this[propertyName];
}
public Property GetInheritedProperty(string propertyName)
{
if (builder != null)
{
if (parentPropertyList != null && IsInherited(propertyName))
{
return parentPropertyList.GetProperty(propertyName);
}
else
{
try
{
return builder.MakeProperty(this, propertyName);
}
catch (FonetException e)
{
FonetDriver.ActiveDriver.FireFonetError(
"Exception in getInherited(): property=" + propertyName + " : " + e);
}
}
}
return null;
}
private bool IsInherited(string propertyName)
{
PropertyMaker propertyMaker = builder.FindMaker(propertyName);
if (propertyMaker != null)
{
return propertyMaker.IsInherited();
}
else
{
FonetDriver.ActiveDriver.FireFonetError("Unknown property : " + propertyName);
return true;
}
}
private Property FindProperty(string propertyName, bool bTryInherit)
{
PropertyMaker maker = builder.FindMaker(propertyName);
Property p = null;
if (maker.IsCorrespondingForced(this))
{
p = ComputeProperty(this, maker);
}
else
{
p = GetExplicitBaseProperty(propertyName);
if (p == null)
{
p = ComputeProperty(this, maker);
}
if (p == null)
{
p = maker.GetShorthand(this);
}
if (p == null && bTryInherit)
{
if (this.parentPropertyList != null && maker.IsInherited())
{
p = parentPropertyList.FindProperty(propertyName, true);
}
}
}
return p;
}
private Property ComputeProperty(
PropertyList propertyList, PropertyMaker propertyMaker)
{
Property p = null;
try
{
p = propertyMaker.Compute(propertyList);
}
catch (FonetException e)
{
FonetDriver.ActiveDriver.FireFonetError(e.Message);
}
return p;
}
public Property GetSpecifiedProperty(string propertyName)
{
return GetProperty(propertyName, false, false);
}
public Property GetProperty(string propertyName)
{
return GetProperty(propertyName, true, true);
}
private Property GetProperty(string propertyName, bool bTryInherit, bool bTryDefault)
{
if (builder == null)
{
FonetDriver.ActiveDriver.FireFonetError("builder not set in PropertyList");
}
int sepchar = propertyName.IndexOf('.');
string subpropName = null;
if (sepchar > -1)
{
subpropName = propertyName.Substring(sepchar + 1);
propertyName = propertyName.Substring(0, sepchar);
}
Property p = FindProperty(propertyName, bTryInherit);
if (p == null && bTryDefault)
{
try
{
p = this.builder.MakeProperty(this, propertyName);
}
catch (FonetException e)
{
FonetDriver.ActiveDriver.FireFonetError(e.ToString());
}
}
if (subpropName != null && p != null)
{
return this.builder.GetSubpropValue(propertyName, p, subpropName);
}
else
{
return p;
}
}
public void SetBuilder(PropertyListBuilder builder)
{
this.builder = builder;
}
public string GetNameSpace()
{
return nmspace;
}
public string GetElement()
{
return element;
}
public Property GetNearestSpecifiedProperty(string propertyName)
{
Property p = null;
for (PropertyList plist = this; p == null && plist != null;
plist = plist.parentPropertyList)
{
p = plist.GetExplicitProperty(propertyName);
}
if (p == null)
{
try
{
p = this.builder.MakeProperty(this, propertyName);
}
catch (FonetException e)
{
FonetDriver.ActiveDriver.FireFonetError(
"Exception in getNearestSpecified(): property=" + propertyName + " : " + e);
}
}
return p;
}
public Property GetFromParentProperty(string propertyName)
{
if (parentPropertyList != null)
{
return parentPropertyList.GetProperty(propertyName);
}
else if (builder != null)
{
try
{
return builder.MakeProperty(this, propertyName);
}
catch (FonetException e)
{
FonetDriver.ActiveDriver.FireFonetError(
"Exception in getFromParent(): property=" + propertyName + " : " + e);
}
}
return null;
}
public string wmAbsToRel(int absdir)
{
if (wmtable != null)
{
return sRelNames[wmtable[absdir]];
}
else
{
return String.Empty;
}
}
public string wmRelToAbs(int reldir)
{
if (wmtable != null)
{
for (int i = 0; i < wmtable.Length; i++)
{
if (wmtable[i] == reldir)
{
return sAbsNames[i];
}
}
}
return String.Empty;
}
public void SetWritingMode(int writingMode)
{
this.wmtable = (byte[])wmtables[writingMode];
}
}
}
| |
/**
* Logger
*
* Copyright (c) 2016 Osamu Takahashi
* Copyright (c) 2016 Rusty Raven Inc.
*
* This software is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
*
* @author Osamu Takahashi
*/
using System;
using System.Collections.Generic;
using Codebook.Runtime.Actors;
namespace Codebook.Runtime {
public enum LogLevel {
Debug,
Info,
Warning,
Error
}
public class LogEvent {
public DateTime Time {
get;
set;
}
public LogLevel Level {
get;
set;
}
public string Message {
get;
set;
}
public LogEvent(LogLevel level,string msg) {
Time = DateTime.Now;
Level = level;
Message = msg;
}
}
public interface LogAppender {
string Signature { get; }
void DispatchEvent(LogEvent ev);
}
public class ConsoleLogAppender : LogAppender {
public string Signature => "Console";
public void DispatchEvent(LogEvent ev) {
try {
Console.WriteLine("[{0}] {1} {2}", ev.Level, ev.Time, ev.Message);
} catch (System.Threading.ThreadAbortException e) {
}
}
}
public static class Logger {
private static LogLevel _logLevel = LogLevel.Info;
private static List<LogAppender> _appenders = new List<LogAppender>();
private static Option<ActorRef> _worker = Option<ActorRef>.None;
private static bool _isTerminated = false;
private static int _loggerCount = 0;
internal class LogWorker : Actor {
private List<LogAppender> _appenders = new List<LogAppender>();
public override Matcher Receive(ActorRef sender,object msg) {
var ev = msg as LogEvent;
if (ev != null) {
foreach(LogAppender appender in _appenders) {
appender.DispatchEvent(ev);
}
}
return Matched.Success;
}
public LogWorker(List<LogAppender> appenders) {
_appenders = appenders;
}
}
public static LogLevel Level {
get { return _logLevel; }
set { _logLevel = value; }
}
private static Option<ActorRef> Worker {
get {
if (!_isTerminated && _worker.IsEmpty) {
Start();
}
return _worker;
}
}
public static void AddAppender(LogAppender appender) {
_appenders.RemoveAll(e => e.Signature == appender.Signature);
_appenders.Add(appender);
}
private static void OnExit(object sender, EventArgs e) {
Stop();
}
public static void Start() {
if (!_isTerminated && _worker.IsEmpty) {
if (_appenders.Count == 0) {
AddAppender(new ConsoleLogAppender());
}
var worker = ActorSystem.ActorOf(new LogWorker(_appenders),new ControlAwareMailbox<InnerMessage>());
_worker = Option<ActorRef>.Some(worker);
AppDomain.CurrentDomain.ProcessExit += OnExit;
Info("Codebook.Logger Starting...");
}
}
public static void Stop() {
_isTerminated = true;
Info("Codebook.Logger Shutting down...");
_worker.ForEach((worker) => { worker.Tell(null,ActorControlMessage.PoisonPill); });
_worker = Option<ActorRef>.None;
}
private static void _dispatchEvent(LogEvent ev) {
if (_worker.IsEmpty) {
if (_appenders.Count == 0) {
AddAppender(new ConsoleLogAppender());
}
foreach(LogAppender appender in _appenders) {
appender.DispatchEvent(ev);
}
} else {
_worker.ForEach((worker) => { worker.Tell(null,ev); });
}
}
public static void Debug(string msg) {
if (_logLevel == LogLevel.Debug) {
try {
_dispatchEvent(new LogEvent(LogLevel.Debug,msg));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Debug(string msg,Object obj) {
if (_logLevel == LogLevel.Debug) {
try {
_dispatchEvent(new LogEvent(LogLevel.Debug,String.Format(msg,obj)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Debug(string msg,Object obj,Object obj2) {
if (_logLevel == LogLevel.Debug) {
try {
_dispatchEvent(new LogEvent(LogLevel.Debug,String.Format(msg,obj,obj2)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Debug(string msg,Object obj,Object obj2,Object obj3) {
if (_logLevel == LogLevel.Debug) {
try {
_dispatchEvent(new LogEvent(LogLevel.Debug,String.Format(msg,obj,obj2,obj3)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Debug(string msg,Object[] objects) {
if (_logLevel == LogLevel.Debug) {
try {
_dispatchEvent(new LogEvent(LogLevel.Debug,String.Format(msg,objects)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Info(string msg) {
if (_logLevel <= LogLevel.Info) {
try {
_dispatchEvent(new LogEvent(LogLevel.Info,msg));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Info(string msg,Object obj) {
if (_logLevel <= LogLevel.Info) {
try {
_dispatchEvent(new LogEvent(LogLevel.Info,String.Format(msg,obj)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Info(string msg,Object obj,Object obj2) {
if (_logLevel <= LogLevel.Info) {
try {
_dispatchEvent(new LogEvent(LogLevel.Info,String.Format(msg,obj,obj2)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Info(string msg,Object obj,Object obj2,Object obj3) {
if (_logLevel <= LogLevel.Info) {
try {
_dispatchEvent(new LogEvent(LogLevel.Info,String.Format(msg,obj,obj2,obj3)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Info(string msg,Object[] objects) {
if (_logLevel <= LogLevel.Info) {
try {
_dispatchEvent(new LogEvent(LogLevel.Info,String.Format(msg,objects)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Warn(string msg) {
if (_logLevel <= LogLevel.Warning) {
try {
_dispatchEvent(new LogEvent(LogLevel.Warning,msg));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Warn(string msg,Object obj) {
if (_logLevel <= LogLevel.Warning) {
try {
_dispatchEvent(new LogEvent(LogLevel.Warning,String.Format(msg,obj)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Warn(string msg,Object obj,Object obj2) {
if (_logLevel <= LogLevel.Warning) {
try {
_dispatchEvent(new LogEvent(LogLevel.Warning,String.Format(msg,obj,obj2)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Warn(string msg,Object obj,Object obj2,Object obj3) {
if (_logLevel <= LogLevel.Warning) {
try {
_dispatchEvent(new LogEvent(LogLevel.Warning,String.Format(msg,obj,obj2,obj3)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Warn(string msg,Object[] objects) {
if (_logLevel <= LogLevel.Warning) {
try {
_dispatchEvent(new LogEvent(LogLevel.Warning,String.Format(msg,objects)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Error(string msg) {
if (_logLevel <= LogLevel.Error) {
try {
_dispatchEvent(new LogEvent(LogLevel.Error,msg));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Error(string msg,Object obj) {
if (_logLevel <= LogLevel.Error) {
try {
_dispatchEvent(new LogEvent(LogLevel.Error,String.Format(msg,obj)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Error(string msg,Object obj,Object obj2) {
if (_logLevel <= LogLevel.Error) {
try {
_dispatchEvent(new LogEvent(LogLevel.Error,String.Format(msg,obj,obj2)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Error(string msg,Object obj,Object obj2,Object obj3) {
if (_logLevel <= LogLevel.Error) {
try {
_dispatchEvent(new LogEvent(LogLevel.Error,String.Format(msg,obj,obj2,obj3)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
public static void Error(string msg,Object[] objects) {
if (_logLevel <= LogLevel.Error) {
try {
_dispatchEvent(new LogEvent(LogLevel.Error,String.Format(msg,objects)));
} catch(Exception e) {
Error(e.ToString());
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
private SafePipeHandle _handle;
private bool _canRead;
private bool _canWrite;
private bool _isAsync;
private bool _isMessageComplete;
private bool _isFromExistingHandle;
private bool _isHandleExposed;
private PipeTransmissionMode _readMode;
private PipeTransmissionMode _transmissionMode;
private PipeDirection _pipeDirection;
private int _outBufferSize;
private PipeState _state;
private StreamAsyncHelper _streamAsyncHelper;
protected PipeStream(PipeDirection direction, int bufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException("direction", SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, PipeTransmissionMode.Byte, bufferSize);
}
protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException("direction", SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (transmissionMode < PipeTransmissionMode.Byte || transmissionMode > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException("transmissionMode", SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (outBufferSize < 0)
{
throw new ArgumentOutOfRangeException("outBufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, transmissionMode, outBufferSize);
}
private void Init(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
// always defaults to this until overridden
_readMode = transmissionMode;
_transmissionMode = transmissionMode;
_pipeDirection = direction;
if ((_pipeDirection & PipeDirection.In) != 0)
{
_canRead = true;
}
if ((_pipeDirection & PipeDirection.Out) != 0)
{
_canWrite = true;
}
_outBufferSize = outBufferSize;
// This should always default to true
_isMessageComplete = true;
_state = PipeState.WaitingToConnect;
_streamAsyncHelper = new StreamAsyncHelper(this);
}
// Once a PipeStream has a handle ready, it should call this method to set up the PipeStream. If
// the pipe is in a connected state already, it should also set the IsConnected (protected) property.
// This method may also be called to uninitialize a handle, setting it to null.
[SecuritySafeCritical]
internal void InitializeHandle(SafePipeHandle handle, bool isExposed, bool isAsync)
{
if (isAsync && handle != null)
{
InitializeAsyncHandle(handle);
}
_handle = handle;
_isAsync = isAsync;
// track these separately; _isHandleExposed will get updated if accessed though the property
_isHandleExposed = isExposed;
_isFromExistingHandle = isExposed;
}
[SecurityCritical]
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!CanRead)
{
throw __Error.GetReadNotSupported();
}
CheckReadOperations();
return ReadCore(buffer, offset, count);
}
[SecurityCritical]
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
CheckWriteOperations();
WriteCore(buffer, offset, count);
return;
}
[ThreadStatic]
private static byte[] t_singleByteArray;
private static byte[] SingleByteArray
{
get { return t_singleByteArray ?? (t_singleByteArray = new byte[1]); }
}
// Reads a byte from the pipe stream. Returns the byte cast to an int
// or -1 if the connection has been broken.
[SecurityCritical]
public override int ReadByte()
{
CheckReadOperations();
if (!CanRead)
{
throw __Error.GetReadNotSupported();
}
byte[] buffer = SingleByteArray;
int n = ReadCore(buffer, 0, 1);
if (n == 0) { return -1; }
else return (int)buffer[0];
}
[SecurityCritical]
public override void WriteByte(byte value)
{
CheckWriteOperations();
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
byte[] buffer = SingleByteArray;
buffer[0] = value;
WriteCore(buffer, 0, 1);
}
// Does nothing on PipeStreams. We cannot call Interop.FlushFileBuffers here because we can deadlock
// if the other end of the pipe is no longer interested in reading from the pipe.
[SecurityCritical]
public override void Flush()
{
CheckWriteOperations();
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
}
[SecurityCritical]
protected override void Dispose(bool disposing)
{
try
{
// Nothing will be done differently based on whether we are
// disposing vs. finalizing.
if (_handle != null && !_handle.IsClosed)
{
_handle.Dispose();
}
UninitializeAsyncHandle();
}
finally
{
base.Dispose(disposing);
}
_state = PipeState.Closed;
}
// ********************** Public Properties *********************** //
// APIs use coarser definition of connected, but these map to internal
// Connected/Disconnected states. Note that setter is protected; only
// intended to be called by custom PipeStream concrete children
public bool IsConnected
{
get
{
return State == PipeState.Connected;
}
protected set
{
_state = (value) ? PipeState.Connected : PipeState.Disconnected;
}
}
public bool IsAsync
{
get { return _isAsync; }
}
// Set by the most recent call to Read or EndRead. Will be false if there are more buffer in the
// message, otherwise it is set to true.
public bool IsMessageComplete
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
// omitting pipe broken exception to allow reader to finish getting message
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (_handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if (_state == PipeState.Closed)
{
throw __Error.GetPipeNotOpen();
}
if (_handle.IsClosed)
{
throw __Error.GetPipeNotOpen();
}
// don't need to check transmission mode; just care about read mode. Always use
// cached mode; otherwise could throw for valid message when other side is shutting down
if (_readMode != PipeTransmissionMode.Message)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeReadModeNotMessage);
}
return _isMessageComplete;
}
}
public SafePipeHandle SafePipeHandle
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
if (_handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if (_handle.IsClosed)
{
throw __Error.GetPipeNotOpen();
}
_isHandleExposed = true;
return _handle;
}
}
internal SafePipeHandle InternalHandle
{
[SecurityCritical]
get
{
return _handle;
}
}
internal bool IsHandleExposed
{
get
{
return _isHandleExposed;
}
}
public override bool CanRead
{
[Pure]
get
{
return _canRead;
}
}
public override bool CanWrite
{
[Pure]
get
{
return _canWrite;
}
}
public override bool CanSeek
{
[Pure]
get
{
return false;
}
}
public override long Length
{
get
{
throw __Error.GetSeekNotSupported();
}
}
public override long Position
{
get
{
throw __Error.GetSeekNotSupported();
}
set
{
throw __Error.GetSeekNotSupported();
}
}
public override void SetLength(long value)
{
throw __Error.GetSeekNotSupported();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw __Error.GetSeekNotSupported();
}
// anonymous pipe ends and named pipe server can get/set properties when broken
// or connected. Named client overrides
[SecurityCritical]
internal virtual void CheckPipePropertyOperations()
{
if (_handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if (_state == PipeState.Closed)
{
throw __Error.GetPipeNotOpen();
}
if (_handle.IsClosed)
{
throw __Error.GetPipeNotOpen();
}
}
// Reads can be done in Connected and Broken. In the latter,
// read returns 0 bytes
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Consistent with security model")]
internal void CheckReadOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (_handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if (_state == PipeState.Closed)
{
throw __Error.GetPipeNotOpen();
}
if (_handle.IsClosed)
{
throw __Error.GetPipeNotOpen();
}
}
// Writes can only be done in connected state
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Consistent with security model")]
internal void CheckWriteOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (_handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// IOException
if (_state == PipeState.Broken)
{
throw new IOException(SR.IO_PipeBroken);
}
// these throw object disposed
if (_state == PipeState.Closed)
{
throw __Error.GetPipeNotOpen();
}
if (_handle.IsClosed)
{
throw __Error.GetPipeNotOpen();
}
}
internal PipeState State
{
get
{
return _state;
}
set
{
_state = value;
}
}
}
}
| |
namespace Fonet
{
using System.Collections;
using Fonet.Apps;
using Fonet.DataTypes;
using Fonet.Fo.Flow;
using Fonet.Fo.Pagination;
using Fonet.Layout;
using Fonet.Render.Pdf;
/// <summary>
/// This class acts as a bridge between the XML:FO parser and the
/// formatting/rendering classes. It will queue PageSequences up until
/// all the IDs required by them are satisfied, at which time it will
/// render the pages.
/// StreamRenderer is created by Driver and called from FOTreeBuilder
/// when a PageSequence is created, and AreaTree when a Page is formatted.
/// </summary>
internal class StreamRenderer
{
/// <summary>
/// Keep track of the number of pages rendered.
/// </summary>
private int pageCount = 0;
/// <summary>
/// The renderer being used.
/// </summary>
private PdfRenderer renderer;
/// <summary>
/// The formatting results to be handed back to the caller.
/// </summary>
private FormattingResults results = new FormattingResults();
/// <summary>
/// The FontInfo for this renderer.
/// </summary>
private FontInfo fontInfo = new FontInfo();
/// <summary>
/// The list of pages waiting to be renderered.
/// </summary>
private ArrayList renderQueue = new ArrayList();
/// <summary>
/// The current set of IDReferences, passed to the areatrees
/// and pages. This is used by the AreaTree as a single map of
/// all IDs.
/// </summary>
private IDReferences idReferences = new IDReferences();
/// <summary>
/// The list of markers.
/// </summary>
private ArrayList documentMarkers;
private ArrayList currentPageSequenceMarkers;
private PageSequence currentPageSequence;
public StreamRenderer(PdfRenderer renderer)
{
this.renderer = renderer;
}
public IDReferences GetIDReferences()
{
return idReferences;
}
public FormattingResults getResults()
{
return this.results;
}
public void StartRenderer()
{
pageCount = 0;
renderer.SetupFontInfo(fontInfo);
renderer.StartRenderer();
}
public void StopRenderer()
{
// Force the processing of any more queue elements, even if they
// are not resolved.
ProcessQueue(true);
renderer.StopRenderer();
}
/// <summary>
/// Format the PageSequence. The PageSequence formats Pages and adds
/// them to the AreaTree, which subsequently calls the StreamRenderer
/// instance (this) again to render the page. At this time the page
/// might be printed or it might be queued. A page might not be
/// renderable immediately if the IDReferences are not all valid. In
/// this case we defer the rendering until they are all valid.
/// </summary>
/// <param name="pageSequence"></param>
public void Render(PageSequence pageSequence)
{
AreaTree a = new AreaTree(this);
a.setFontInfo(fontInfo);
pageSequence.Format(a);
this.results.HaveFormattedPageSequence(pageSequence);
FonetDriver.ActiveDriver.FireFonetInfo(
"Last page-sequence produced " + pageSequence.PageCount + " page(s).");
}
public void QueuePage(Page page)
{
// Process markers
PageSequence pageSequence = page.getPageSequence();
if (pageSequence != currentPageSequence)
{
currentPageSequence = pageSequence;
currentPageSequenceMarkers = null;
}
ArrayList markers = page.getMarkers();
if (markers != null)
{
if (documentMarkers == null)
{
documentMarkers = new ArrayList();
}
if (currentPageSequenceMarkers == null)
{
currentPageSequenceMarkers = new ArrayList();
}
for (int i = 0; i < markers.Count; i++)
{
Marker marker = (Marker)markers[i];
marker.releaseRegistryArea();
currentPageSequenceMarkers.Add(marker);
documentMarkers.Add(marker);
}
}
// Try to optimise on the common case that there are no pages pending
// and that all ID references are valid on the current pages. This
// short-cuts the pipeline and renders the area immediately.
if ((renderQueue.Count == 0) && idReferences.IsEveryIdValid())
{
renderer.Render(page);
}
else
{
AddToRenderQueue(page);
}
pageCount++;
}
private void AddToRenderQueue(Page page)
{
RenderQueueEntry entry = new RenderQueueEntry(this, page);
renderQueue.Add(entry);
// The just-added entry could (possibly) resolve the waiting entries,
// so we try to process the queue now to see.
ProcessQueue(false);
}
/// <summary>
/// Try to process the queue from the first entry forward. If an
/// entry can't be processed, then the queue can't move forward,
/// so return.
/// </summary>
/// <param name="force"></param>
private void ProcessQueue(bool force)
{
while (renderQueue.Count > 0)
{
RenderQueueEntry entry = (RenderQueueEntry)renderQueue[0];
if ((!force) && (!entry.isResolved()))
{
break;
}
renderer.Render(entry.getPage());
renderQueue.RemoveAt(0);
}
}
/// <summary>
/// A RenderQueueEntry consists of the Page to be queued, plus a list
/// of outstanding ID references that need to be resolved before the
/// Page can be renderered.
/// </summary>
private class RenderQueueEntry
{
/// <summary>
/// The Page that has outstanding ID references.
/// </summary>
private Page page;
private StreamRenderer outer;
/// <summary>
/// A list of ID references (names).
/// </summary>
private ArrayList unresolvedIdReferences = new ArrayList();
public RenderQueueEntry(StreamRenderer outer, Page page)
{
this.outer = outer;
this.page = page;
foreach (object o in outer.idReferences.getInvalidElements())
{
unresolvedIdReferences.Add(o);
}
}
public Page getPage()
{
return page;
}
/// <summary>
/// See if the outstanding references are resolved in the current
/// copy of IDReferences.
/// </summary>
/// <returns></returns>
public bool isResolved()
{
if ((unresolvedIdReferences.Count == 0) || outer.idReferences.IsEveryIdValid())
{
return true;
}
// See if any of the unresolved references are still unresolved.
foreach (string s in unresolvedIdReferences)
{
if (!outer.idReferences.doesIDExist(s))
{
return false;
}
}
unresolvedIdReferences.RemoveRange(0, unresolvedIdReferences.Count);
return true;
}
}
/// <summary>
/// Auxillary function for retrieving markers.
/// </summary>
/// <returns></returns>
public ArrayList GetDocumentMarkers()
{
return documentMarkers;
}
/// <summary>
/// Auxillary function for retrieving markers.
/// </summary>
/// <returns></returns>
public PageSequence GetCurrentPageSequence()
{
return currentPageSequence;
}
/// <summary>
/// Auxillary function for retrieving markers.
/// </summary>
/// <returns></returns>
public ArrayList GetCurrentPageSequenceMarkers()
{
return currentPageSequenceMarkers;
}
}
}
| |
/*
<copyright file="SettingsManagerTest.cs">
Copyright 2015 MadDonkey Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
</copyright>
*/
using System;
using System.IO;
using System.Threading;
using DonkeySuite.DesktopMonitor.Domain.Model.Repositories;
using DonkeySuite.DesktopMonitor.Domain.Model.Settings;
using log4net;
using MadDonkeySoftware.SystemWrappers.Threading;
using Moq;
using NUnit.Framework;
namespace DonkeySuite.Tests.DesktopMonitor.Domain.Model.Settings
{
[TestFixture]
public class SettingsManagerTest
{
private class SettingsManagerTestBundle
{
public Mock<ILog> MockLog { get; private set; }
public Mock<ISemaphore> MockSemaphore { get; private set; }
public Mock<ISettingsRepository> MockSettingsRepository { get; private set; }
public SettingsManager SettingsManager { get; private set; }
public SettingsManagerTestBundle()
{
MockLog = new Mock<ILog>();
MockSemaphore = new Mock<ISemaphore>();
MockSettingsRepository = new Mock<ISettingsRepository>();
SettingsManager = new SettingsManager(MockLog.Object, MockSemaphore.Object, MockSettingsRepository.Object);
}
}
[Test]
public void GetSettings_Returns_Settings_Object()
{
// Arrange
var testBundle = new SettingsManagerTestBundle();
var mockSettingsRoot = new Mock<SettingsRoot>();
testBundle.MockSettingsRepository.Setup(x => x.Load()).Returns(mockSettingsRoot.Object);
// Act
var settings = testBundle.SettingsManager.GetSettings();
// Assert
Assert.IsNotNull(settings);
Assert.AreSame(mockSettingsRoot.Object, settings);
}
[Test]
public void GetSettings_Returns_New_Settings_Object_After_Save_Fails()
{
// Arrange
var testBundle = new SettingsManagerTestBundle();
var mockSettingsRoot = new Mock<SettingsRoot>();
testBundle.MockSettingsRepository.Setup(x => x.Load()).Returns((SettingsRoot)null);
testBundle.MockSettingsRepository.Setup(x => x.CreateNewSettings()).Returns(mockSettingsRoot.Object);
testBundle.MockSettingsRepository.Setup(x => x.Save(mockSettingsRoot.Object)).Throws(new IOException("Test Exception"));
// Act
var settings = testBundle.SettingsManager.GetSettings();
// Assert
Assert.AreSame(mockSettingsRoot.Object, settings);
testBundle.MockSemaphore.Verify(x => x.WaitOne(), Times.Once);
testBundle.MockSemaphore.Verify(x => x.Release(), Times.Once);
}
[Test]
public void GetSettings_Returns_New_Settings_Object_After_Save_Succeeds()
{
// Arrange
var testBundle = new SettingsManagerTestBundle();
var mockSettingsRoot = new Mock<SettingsRoot>();
testBundle.MockSettingsRepository.Setup(x => x.Load()).Returns((SettingsRoot)null);
testBundle.MockSettingsRepository.Setup(x => x.CreateNewSettings()).Returns(mockSettingsRoot.Object);
// Act
var settings = testBundle.SettingsManager.GetSettings();
// Assert
Assert.AreSame(mockSettingsRoot.Object, settings);
testBundle.MockSemaphore.Verify(x => x.WaitOne(), Times.Once);
testBundle.MockSemaphore.Verify(x => x.Release(), Times.Once);
}
[Test]
public void GetSettings_Returns_Null_When_Semaphore_Interrupted()
{
// Arrange
var testBundle = new SettingsManagerTestBundle();
testBundle.MockSemaphore.Setup(x => x.WaitOne()).Throws(new AbandonedMutexException());
// Act
var settings = testBundle.SettingsManager.GetSettings();
// Assert
Assert.IsNull(settings);
}
[Test]
public void GetSettings_Rethrows_Exception()
{
var testBundle = new SettingsManagerTestBundle();
var testException = new NullReferenceException();
Exception caughtException = null;
testBundle.MockSettingsRepository.Setup(x => x.Load()).Throws(testException);
// Act
try
{
testBundle.SettingsManager.GetSettings();
}
catch (Exception ex)
{
caughtException = ex;
}
// Assert
Assert.AreSame(testException, caughtException);
}
[Test]
public void SettingsManagerReturnsSameSettingsObjectAfterMultipleCalls()
{
// Arrange
var testBundle = new SettingsManagerTestBundle();
var mockSettingsRoot = new Mock<SettingsRoot>();
testBundle.MockSettingsRepository.Setup(x => x.Load()).Returns(mockSettingsRoot.Object);
// Act
var s1 = testBundle.SettingsManager.GetSettings();
var s2 = testBundle.SettingsManager.GetSettings();
// Assert
Assert.AreSame(mockSettingsRoot.Object, s1);
Assert.AreSame(mockSettingsRoot.Object, s2);
Assert.AreSame(s1, s2);
}
[Test]
public void SaveSettings_Locks_And_Unlocks_When_Save_Successful()
{
// Arrange
var testBundle = new SettingsManagerTestBundle();
// Act
testBundle.SettingsManager.SaveSettings();
// Assert
testBundle.MockSemaphore.Verify(x => x.WaitOne(), Times.Once);
testBundle.MockSemaphore.Verify(x => x.Release(), Times.Once);
}
[Test]
public void SaveSettings_Throws_Exception_When_Semaphore_Fails()
{
// Arrange
var testException = new ThreadInterruptedException();
var testBundle = new SettingsManagerTestBundle();
Exception thrownException = null;
testBundle.MockSemaphore.Setup(x => x.WaitOne()).Throws(testException);
// Act
try
{
testBundle.SettingsManager.SaveSettings();
}
catch (Exception ex)
{
thrownException = ex;
}
// Assert
testBundle.MockSemaphore.Verify(x => x.WaitOne(), Times.Once);
testBundle.MockSemaphore.Verify(x => x.Release(), Times.Once);
Assert.IsNotNull(thrownException);
}
[Test]
public void SaveSettings_Throws_Exception_When_Serialization_Fails()
{
// Arrange
var testException = new ThreadInterruptedException();
var testBundle = new SettingsManagerTestBundle();
Exception thrownException = null;
testBundle.MockSettingsRepository.Setup(x => x.Save(It.IsAny<SettingsRoot>())).Throws(testException);
// Act
try
{
testBundle.SettingsManager.SaveSettings();
}
catch (Exception ex)
{
thrownException = ex;
}
// Assert
testBundle.MockSemaphore.Verify(x => x.WaitOne(), Times.Once);
testBundle.MockSemaphore.Verify(x => x.Release(), Times.Once);
Assert.IsNotNull(thrownException);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace NSimulate
{
/// <summary>
/// Context containing state information for a simulation
/// </summary>
public class SimulationContext : IDisposable
{
private static SimulationContext _current;
[ThreadStatic]
private static SimulationContext _currentForThread;
private Dictionary<Type, Dictionary<object, SimulationElement>> _registeredElements = new Dictionary<Type, Dictionary<object, SimulationElement>>();
/// <summary>
/// Gets the current SimulationContext. A new SimulationContext is created if one does not already exist.
/// </summary>
/// <value>
/// The current simulation context
/// </value>
public static SimulationContext Current
{
get
{
return _currentForThread ?? _current;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="NSimulate.SimulationContext"/> class.
/// </summary>
public SimulationContext ()
: this(false)
{
}
/// <summary>
/// Gets or sets the time period.
/// </summary>
/// <value>
/// The time period.
/// </value>
public long TimePeriod {
get;
private set;
}
/// <summary>
/// Gets or sets a value indicating whether the simulation is terminating.
/// </summary>
/// <value>
/// <c>true</c> if the simulation terminating; otherwise, <c>false</c>.
/// </value>
public bool IsSimulationTerminating{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether the simulation is stopping.
/// </summary>
/// <value>
/// <c>true</c> if the simulation is stopping; otherwise, <c>false</c>.
/// </value>
public bool IsSimulationStopping{
get;
set;
}
/// <summary>
/// Gets the active processes.
/// </summary>
/// <value>
/// The active processes.
/// </value>
public HashSet<Process> ActiveProcesses{
get;
private set;
}
/// <summary>
/// Gets the processes remaining this time period.
/// </summary>
/// <value>
/// The processes remaining this time period.
/// </value>
public Queue<Process> ProcessesRemainingThisTimePeriod{
get;
private set;
}
/// <summary>
/// Gets the processed processes.
/// </summary>
/// <value>
/// The processed processes.
/// </value>
public HashSet<Process> ProcessedProcesses{
get;
private set;
}
/// <summary>
/// Moves to time period.
/// </summary>
/// <param name='timePeriod'>
/// Time period.
/// </param>
public void MoveToTimePeriod(long timePeriod){
TimePeriod = timePeriod;
if (ActiveProcesses == null){
ActiveProcesses = new HashSet<Process>();
var processes = GetByType<Process>();
foreach(var process in processes){
if (process.SimulationState == null){
process.SimulationState = new ProcessSimulationState();
}
if (process.SimulationState.IsActive){
ActiveProcesses.Add(process);
}
}
}
// order processes by process priority, instruction priority, insruction raise time, and then process instance
var processesInPriorityOrder = ActiveProcesses
.OrderBy(p=>p.Priority)
.ThenBy(p=>(p.SimulationState != null && p.SimulationState.InstructionEnumerator != null && p.SimulationState.InstructionEnumerator.Current != null)
?p.SimulationState.InstructionEnumerator.Current.Priority
:Priority.Medium)
.ThenBy(p=>(p.SimulationState != null && p.SimulationState.InstructionEnumerator != null && p.SimulationState.InstructionEnumerator.Current != null)
?p.SimulationState.InstructionEnumerator.Current.RaisedInTimePeriod
:timePeriod)
.ThenBy(p=>p.InstanceIndex);
ProcessesRemainingThisTimePeriod = new Queue<Process>();
foreach(var process in processesInPriorityOrder){
ProcessesRemainingThisTimePeriod.Enqueue(process);
}
ProcessedProcesses = new HashSet<Process>();
}
/// <summary>
/// Initializes a new instance of the <see cref="NSimulate.SimulationContext"/> class.
/// </summary>
/// <param name="isDefaultContextForProcess">if true, this context will become the default for the process</param>
/// <param name="isDefaultContextForThread">if true, this context will become the default for the current thread</param>
public SimulationContext (bool isDefaultContextForProcess, bool isDefaultContextForThread = false)
{
if (isDefaultContextForProcess)
{
_current = this;
}
if (isDefaultContextForThread)
{
_currentForThread = this;
}
}
/// <summary>
/// Register an object with this context
/// </summary>
public void Register<TType>(TType objectToRegister)
where TType : SimulationElement
{
Register(typeof(TType), objectToRegister);
}
/// <summary>
/// Register an object with this context
/// </summary>
public void Register(Type typeToRegister, object objectToRegister)
{
if (!IsTypeEqualOrSubclass(typeToRegister, typeof(SimulationElement)))
{
throw new ArgumentException("typeToRegister");
}
SimulationElement element = objectToRegister as SimulationElement;
Dictionary<object, SimulationElement> elementsByKey = null;
if (!_registeredElements.TryGetValue(typeToRegister, out elementsByKey))
{
elementsByKey = new Dictionary<object, SimulationElement>();
_registeredElements[typeToRegister] = elementsByKey;
}
elementsByKey[element.Key] = element;
}
/// <summary>
/// Gets a previously registered object by key.
/// </summary>
/// <returns>
/// The matching object if any
/// </returns>
/// <param name='key'>
/// Key identifying object
/// </param>
/// <typeparam name='TType'>
/// The type of object to retrieve
/// </typeparam>
public TType GetByKey<TType>(object key)
where TType : SimulationElement
{
SimulationElement objectToRetrieve = null;
foreach(var entry in _registeredElements) {
if (IsTypeEqualOrSubclass(entry.Key, typeof(TType))) {
if (entry.Value.TryGetValue(key, out objectToRetrieve)){
break;
}
}
}
return objectToRetrieve as TType;
}
/// <summary>
/// Get a list of objects registered
/// </summary>
/// <returns>
/// A list of matching objects
/// </returns>
/// <typeparam name='TType'>
/// The type of objects to retrieve
/// </typeparam>
public IEnumerable<TType> GetByType<TType>()
{
List<TType> enumerableToReturn = new List<TType>();
foreach(var entry in _registeredElements) {
if (IsTypeEqualOrSubclass(entry.Key, typeof(TType))){
enumerableToReturn.AddRange(entry.Value.Values.Cast<TType>());
}
}
return enumerableToReturn;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>
/// 2
/// </filterpriority>
/// <remarks>
/// Call <see cref="Dispose"/> when you are finished using the <see cref="NSimulate.SimulationContext"/>. The
/// <see cref="Dispose"/> method leaves the <see cref="NSimulate.SimulationContext"/> in an unusable state. After
/// calling <see cref="Dispose"/>, you must release all references to the <see cref="NSimulate.SimulationContext"/> so
/// the garbage collector can reclaim the memory that the <see cref="NSimulate.SimulationContext"/> was occupying.
/// </remarks>
public void Dispose()
{
if (_current == this)
{
_current = null;
}
if (_currentForThread == this)
{
_currentForThread = null;
}
}
/// <summary>
/// Tests whether a Type is the same as another, or the subclass of another
/// </summary>
/// <param name='typeToCheck'>
/// The type to be checked
/// </param>
/// <param name='typeToCompare'>
/// The type to match, either exactly or as an ancestor
/// </param>
/// <returns>True if the typeToCheck is the same or a subclass of the typeToCompare</returns>
private bool IsTypeEqualOrSubclass(Type typeToCheck, Type typeToCompare){
bool match = false;
Type currentType = typeToCheck;
while (currentType != null){
if (currentType == typeToCompare){
match = true;
break;
}
currentType = currentType.GetTypeInfo().BaseType;
}
return match;
}
}
}
| |
using System;
using System.Collections.Generic;
using Umbraco.Cms.Core.Models.Membership;
using Umbraco.Cms.Core.Persistence.Querying;
namespace Umbraco.Cms.Core.Services
{
/// <summary>
/// Defines the UserService, which is an easy access to operations involving <see cref="IProfile"/> and eventually Users.
/// </summary>
public interface IUserService : IMembershipUserService
{
/// <summary>
/// Creates a database entry for starting a new login session for a user
/// </summary>
/// <param name="userId"></param>
/// <param name="requestingIpAddress"></param>
/// <returns></returns>
Guid CreateLoginSession(int userId, string requestingIpAddress);
/// <summary>
/// Validates that a user login session is valid/current and hasn't been closed
/// </summary>
/// <param name="userId"></param>
/// <param name="sessionId"></param>
/// <returns></returns>
bool ValidateLoginSession(int userId, Guid sessionId);
/// <summary>
/// Removes the session's validity
/// </summary>
/// <param name="sessionId"></param>
void ClearLoginSession(Guid sessionId);
/// <summary>
/// Removes all valid sessions for the user
/// </summary>
/// <param name="userId"></param>
int ClearLoginSessions(int userId);
/// <summary>
/// This is basically facets of UserStates key = state, value = count
/// </summary>
IDictionary<UserState, int> GetUserStates();
/// <summary>
/// Get paged users
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecords"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="userState"></param>
/// <param name="includeUserGroups">
/// A filter to only include user that belong to these user groups
/// </param>
/// <param name="excludeUserGroups">
/// A filter to only include users that do not belong to these user groups
/// </param>
/// <param name="filter"></param>
/// <returns></returns>
IEnumerable<IUser> GetAll(long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection,
UserState[] userState = null,
string[] includeUserGroups = null,
string[] excludeUserGroups = null,
IQuery<IUser> filter = null);
/// <summary>
/// Get paged users
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecords"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="userState"></param>
/// <param name="userGroups">
/// A filter to only include user that belong to these user groups
/// </param>
/// <param name="filter"></param>
/// <returns></returns>
IEnumerable<IUser> GetAll(long pageIndex, int pageSize, out long totalRecords,
string orderBy, Direction orderDirection,
UserState[] userState = null,
string[] userGroups = null,
string filter = null);
/// <summary>
/// Deletes or disables a User
/// </summary>
/// <param name="user"><see cref="IUser"/> to delete</param>
/// <param name="deletePermanently"><c>True</c> to permanently delete the user, <c>False</c> to disable the user</param>
void Delete(IUser user, bool deletePermanently);
/// <summary>
/// Gets an IProfile by User Id.
/// </summary>
/// <param name="id">Id of the User to retrieve</param>
/// <returns><see cref="IProfile"/></returns>
IProfile GetProfileById(int id);
/// <summary>
/// Gets a profile by username
/// </summary>
/// <param name="username">Username</param>
/// <returns><see cref="IProfile"/></returns>
IProfile GetProfileByUserName(string username);
/// <summary>
/// Gets a user by Id
/// </summary>
/// <param name="id">Id of the user to retrieve</param>
/// <returns><see cref="IUser"/></returns>
IUser GetUserById(int id);
/// <summary>
/// Gets a users by Id
/// </summary>
/// <param name="ids">Ids of the users to retrieve</param>
/// <returns><see cref="IUser"/></returns>
IEnumerable<IUser> GetUsersById(params int[] ids);
/// <summary>
/// Removes a specific section from all user groups
/// </summary>
/// <remarks>This is useful when an entire section is removed from config</remarks>
/// <param name="sectionAlias">Alias of the section to remove</param>
void DeleteSectionFromAllUserGroups(string sectionAlias);
/// <summary>
/// Get explicitly assigned permissions for a user and optional node ids
/// </summary>
/// <remarks>If no permissions are found for a particular entity then the user's default permissions will be applied</remarks>
/// <param name="user">User to retrieve permissions for</param>
/// <param name="nodeIds">Specifying nothing will return all user permissions for all nodes that have explicit permissions defined</param>
/// <returns>An enumerable list of <see cref="EntityPermission"/></returns>
/// <remarks>
/// This will return the default permissions for the user's groups for node ids that don't have explicitly defined permissions
/// </remarks>
EntityPermissionCollection GetPermissions(IUser user, params int[] nodeIds);
/// <summary>
/// Get explicitly assigned permissions for groups and optional node Ids
/// </summary>
/// <param name="groups"></param>
/// <param name="fallbackToDefaultPermissions">
/// Flag indicating if we want to include the default group permissions for each result if there are not explicit permissions set
/// </param>
/// <param name="nodeIds">Specifying nothing will return all permissions for all nodes</param>
/// <returns>An enumerable list of <see cref="EntityPermission"/></returns>
EntityPermissionCollection GetPermissions(IUserGroup[] groups, bool fallbackToDefaultPermissions, params int[] nodeIds);
/// <summary>
/// Gets the implicit/inherited permissions for the user for the given path
/// </summary>
/// <param name="user">User to check permissions for</param>
/// <param name="path">Path to check permissions for</param>
EntityPermissionSet GetPermissionsForPath(IUser user, string path);
/// <summary>
/// Gets the permissions for the provided groups and path
/// </summary>
/// <param name="groups"></param>
/// <param name="path">Path to check permissions for</param>
/// <param name="fallbackToDefaultPermissions">
/// Flag indicating if we want to include the default group permissions for each result if there are not explicit permissions set
/// </param>
EntityPermissionSet GetPermissionsForPath(IUserGroup[] groups, string path, bool fallbackToDefaultPermissions = false);
/// <summary>
/// Replaces the same permission set for a single group to any number of entities
/// </summary>
/// <param name="groupId">Id of the group</param>
/// <param name="permissions">
/// Permissions as enumerable list of <see cref="char"/>,
/// if no permissions are specified then all permissions for this node are removed for this group
/// </param>
/// <param name="entityIds">Specify the nodes to replace permissions for. If nothing is specified all permissions are removed.</param>
/// <remarks>If no 'entityIds' are specified all permissions will be removed for the specified group.</remarks>
void ReplaceUserGroupPermissions(int groupId, IEnumerable<char> permissions, params int[] entityIds);
/// <summary>
/// Assigns the same permission set for a single user group to any number of entities
/// </summary>
/// <param name="groupId">Id of the group</param>
/// <param name="permission"></param>
/// <param name="entityIds">Specify the nodes to replace permissions for</param>
void AssignUserGroupPermission(int groupId, char permission, params int[] entityIds);
/// <summary>
/// Gets a list of <see cref="IUser"/> objects associated with a given group
/// </summary>
/// <param name="groupId">Id of group</param>
/// <returns><see cref="IEnumerable{IUser}"/></returns>
IEnumerable<IUser> GetAllInGroup(int groupId);
/// <summary>
/// Gets a list of <see cref="IUser"/> objects not associated with a given group
/// </summary>
/// <param name="groupId">Id of group</param>
/// <returns><see cref="IEnumerable{IUser}"/></returns>
IEnumerable<IUser> GetAllNotInGroup(int groupId);
IEnumerable<IUser> GetNextUsers(int id, int count);
#region User groups
/// <summary>
/// Gets all UserGroups or those specified as parameters
/// </summary>
/// <param name="ids">Optional Ids of UserGroups to retrieve</param>
/// <returns>An enumerable list of <see cref="IUserGroup"/></returns>
IEnumerable<IUserGroup> GetAllUserGroups(params int[] ids);
/// <summary>
/// Gets a UserGroup by its Alias
/// </summary>
/// <param name="alias">Alias of the UserGroup to retrieve</param>
/// <returns><see cref="IUserGroup"/></returns>
IEnumerable<IUserGroup> GetUserGroupsByAlias(params string[] alias);
/// <summary>
/// Gets a UserGroup by its Alias
/// </summary>
/// <param name="name">Name of the UserGroup to retrieve</param>
/// <returns><see cref="IUserGroup"/></returns>
IUserGroup GetUserGroupByAlias(string name);
/// <summary>
/// Gets a UserGroup by its Id
/// </summary>
/// <param name="id">Id of the UserGroup to retrieve</param>
/// <returns><see cref="IUserGroup"/></returns>
IUserGroup GetUserGroupById(int id);
/// <summary>
/// Saves a UserGroup
/// </summary>
/// <param name="userGroup">UserGroup to save</param>
/// <param name="userIds">
/// If null than no changes are made to the users who are assigned to this group, however if a value is passed in
/// than all users will be removed from this group and only these users will be added
/// </param>
void Save(IUserGroup userGroup, int[] userIds = null);
/// <summary>
/// Deletes a UserGroup
/// </summary>
/// <param name="userGroup">UserGroup to delete</param>
void DeleteUserGroup(IUserGroup userGroup);
#endregion
}
}
| |
using System.Collections.Generic;
using NFluent;
using WireMock.Matchers;
using Xunit;
using WireMock.RequestBuilders;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.Util;
namespace WireMock.Net.Tests
{
public class RequestWithPathTests
{
private const string ClientIp = "::1";
[Fact]
public void Request_WithPath_Spaces()
{
// Assign
var spec = Request.Create().WithPath("/path/a b").UsingAnyMethod();
// when
var body = new BodyData();
var request = new RequestMessage(new UrlDetails("http://localhost/path/a b"), "GET", ClientIp, body);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Request_WithPath_WithHeader_Match()
{
// given
var spec = Request.Create().WithPath("/foo").UsingAnyMethod().WithHeader("X-toto", "tata");
// when
var body = new BodyData
{
BodyAsString = "abc"
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp, body, new Dictionary<string, string[]> { { "X-toto", new[] { "tata" } } });
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Request_WithPath()
{
// given
var spec = Request.Create().WithPath("/foo");
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "blabla", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Request_WithPaths()
{
var requestBuilder = Request.Create().WithPath("/x1", "/x2");
var request1 = new RequestMessage(new UrlDetails("http://localhost/x1"), "blabla", ClientIp);
var request2 = new RequestMessage(new UrlDetails("http://localhost/x2"), "blabla", ClientIp);
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request1, requestMatchResult)).IsEqualTo(1.0);
Check.That(requestBuilder.GetMatchingScore(request2, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Request_WithPathFunc()
{
// given
var spec = Request.Create().WithPath(url => url.EndsWith("/foo"));
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "blabla", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Request_WithPathRegexMatcher_HasMatch()
{
// given
var spec = Request.Create().WithPath(new RegexMatcher("^/foo"));
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo/bar"), "blabla", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Request_WithPathRegexMatcher_HasNoMatch()
{
// given
var spec = Request.Create().WithPath("/foo");
// when
var request = new RequestMessage(new UrlDetails("http://localhost/bar"), "blabla", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0);
}
[Fact]
public void Request_WithPathRegexMatcher_WithPatternAsFile_HasMatch()
{
// Arrange
var pattern = new StringPattern
{
Pattern = "^/foo",
PatternAsFile = "c:\\x.txt"
};
var spec = Request.Create().WithPath(new RegexMatcher(pattern));
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo/bar"), "blabla", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Should_specify_requests_matching_given_path_and_method_delete()
{
// given
var spec = Request.Create().WithPath("/foo").UsingDelete();
// when
var body = new BodyData
{
BodyAsString = "whatever"
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "Delete", ClientIp, body);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Should_specify_requests_matching_given_path_and_method_get()
{
// given
var spec = Request.Create().WithPath("/foo").UsingGet();
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Should_specify_requests_matching_given_path_and_method_head()
{
// given
var spec = Request.Create().WithPath("/foo").UsingHead();
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "HEAD", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Should_specify_requests_matching_given_path_and_method_post()
{
// given
var spec = Request.Create().WithPath("/foo").UsingPost();
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Should_specify_requests_matching_given_path_and_method_put()
{
// given
var spec = Request.Create().WithPath("/foo").UsingPut();
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PUT", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Should_specify_requests_matching_given_path_and_method_patch()
{
// given
var spec = Request.Create().WithPath("/foo").UsingPatch();
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "PATCH", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Should_exclude_requests_matching_given_path_but_not_http_method()
{
// given
var spec = Request.Create().WithPath("/foo").UsingPut();
// when
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "HEAD", ClientIp);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
namespace System.Reflection.Emit
{
using System.Text;
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_SignatureHelper))]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SignatureHelper : _SignatureHelper
{
#region Consts Fields
private const int NO_SIZE_IN_SIG = -1;
#endregion
#region Static Members
public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes)
{
return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null);
}
internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType, int cGenericParam)
{
return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null);
}
public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType)
{
return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null);
}
internal static SignatureHelper GetMethodSpecSigHelper(Module scope, Type[] inst)
{
SignatureHelper sigHelp = new SignatureHelper(scope, MdSigCallingConvention.GenericInst);
sigHelp.AddData(inst.Length);
foreach(Type t in inst)
sigHelp.AddArgument(t);
return sigHelp;
}
internal static SignatureHelper GetMethodSigHelper(
Module scope, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
return GetMethodSigHelper(scope, callingConvention, 0, returnType, requiredReturnTypeCustomModifiers,
optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
internal static SignatureHelper GetMethodSigHelper(
Module scope, CallingConventions callingConvention, int cGenericParam,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
if (returnType == null)
{
returnType = typeof(void);
}
intCall = MdSigCallingConvention.Default;
if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
intCall = MdSigCallingConvention.Vararg;
if (cGenericParam > 0)
{
intCall |= MdSigCallingConvention.Generic;
}
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
intCall |= MdSigCallingConvention.HasThis;
sigHelp = new SignatureHelper(scope, intCall, cGenericParam, returnType,
requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers);
sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
return sigHelp;
}
public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType)
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
if (returnType == null)
returnType = typeof(void);
if (unmanagedCallConv == CallingConvention.Cdecl)
{
intCall = MdSigCallingConvention.C;
}
else if (unmanagedCallConv == CallingConvention.StdCall || unmanagedCallConv == CallingConvention.Winapi)
{
intCall = MdSigCallingConvention.StdCall;
}
else if (unmanagedCallConv == CallingConvention.ThisCall)
{
intCall = MdSigCallingConvention.ThisCall;
}
else if (unmanagedCallConv == CallingConvention.FastCall)
{
intCall = MdSigCallingConvention.FastCall;
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_UnknownUnmanagedCallConv"), nameof(unmanagedCallConv));
}
sigHelp = new SignatureHelper(mod, intCall, returnType, null, null);
return sigHelp;
}
public static SignatureHelper GetLocalVarSigHelper()
{
return GetLocalVarSigHelper(null);
}
public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type returnType)
{
return GetMethodSigHelper(null, callingConvention, returnType);
}
public static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type returnType)
{
return GetMethodSigHelper(null, unmanagedCallingConvention, returnType);
}
public static SignatureHelper GetLocalVarSigHelper(Module mod)
{
return new SignatureHelper(mod, MdSigCallingConvention.LocalSig);
}
public static SignatureHelper GetFieldSigHelper(Module mod)
{
return new SignatureHelper(mod, MdSigCallingConvention.Field);
}
public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] parameterTypes)
{
return GetPropertySigHelper(mod, returnType, null, null, parameterTypes, null, null);
}
public static SignatureHelper GetPropertySigHelper(Module mod,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
SignatureHelper sigHelp;
if (returnType == null)
{
returnType = typeof(void);
}
MdSigCallingConvention intCall = MdSigCallingConvention.Property;
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
intCall |= MdSigCallingConvention.HasThis;
sigHelp = new SignatureHelper(mod, intCall,
returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers);
sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
return sigHelp;
}
internal static SignatureHelper GetTypeSigToken(Module module, Type type)
{
if (module == null)
throw new ArgumentNullException(nameof(module));
if (type == null)
throw new ArgumentNullException(nameof(type));
return new SignatureHelper(module, type);
}
#endregion
#region Private Data Members
private byte[] m_signature;
private int m_currSig; // index into m_signature buffer for next available byte
private int m_sizeLoc; // index into m_signature buffer to put m_argCount (will be NO_SIZE_IN_SIG if no arg count is needed)
private ModuleBuilder m_module;
private bool m_sigDone;
private int m_argCount; // tracking number of arguments in the signature
#endregion
#region Constructor
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention)
{
// Use this constructor to instantiate a local var sig or Field where return type is not applied.
Init(mod, callingConvention);
}
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters,
Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
// Use this constructor to instantiate a any signatures that will require a return type.
Init(mod, callingConvention, cGenericParameters);
if (callingConvention == MdSigCallingConvention.Field)
throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldSig"));
AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers);
}
private SignatureHelper(Module mod, MdSigCallingConvention callingConvention,
Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
: this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers)
{
}
private SignatureHelper(Module mod, Type type)
{
Init(mod);
AddOneArgTypeHelper(type);
}
private void Init(Module mod)
{
m_signature = new byte[32];
m_currSig = 0;
m_module = mod as ModuleBuilder;
m_argCount = 0;
m_sigDone = false;
m_sizeLoc = NO_SIZE_IN_SIG;
if (m_module == null && mod != null)
throw new ArgumentException(Environment.GetResourceString("NotSupported_MustBeModuleBuilder"));
}
private void Init(Module mod, MdSigCallingConvention callingConvention)
{
Init(mod, callingConvention, 0);
}
private void Init(Module mod, MdSigCallingConvention callingConvention, int cGenericParam)
{
Init(mod);
AddData((byte)callingConvention);
if (callingConvention == MdSigCallingConvention.Field ||
callingConvention == MdSigCallingConvention.GenericInst)
{
m_sizeLoc = NO_SIZE_IN_SIG;
}
else
{
if (cGenericParam > 0)
AddData(cGenericParam);
m_sizeLoc = m_currSig++;
}
}
#endregion
#region Private Members
private void AddOneArgTypeHelper(Type argument, bool pinned)
{
if (pinned)
AddElementType(CorElementType.Pinned);
AddOneArgTypeHelper(argument);
}
private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
// This function will not increase the argument count. It only fills in bytes
// in the signature based on clsArgument. This helper is called for return type.
Contract.Requires(clsArgument != null);
Contract.Requires((optionalCustomModifiers == null && requiredCustomModifiers == null) || !clsArgument.ContainsGenericParameters);
if (optionalCustomModifiers != null)
{
for (int i = 0; i < optionalCustomModifiers.Length; i++)
{
Type t = optionalCustomModifiers[i];
if (t == null)
throw new ArgumentNullException(nameof(optionalCustomModifiers));
if (t.HasElementType)
throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(optionalCustomModifiers));
if (t.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(optionalCustomModifiers));
AddElementType(CorElementType.CModOpt);
int token = m_module.GetTypeToken(t).Token;
Debug.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
if (requiredCustomModifiers != null)
{
for (int i = 0; i < requiredCustomModifiers.Length; i++)
{
Type t = requiredCustomModifiers[i];
if (t == null)
throw new ArgumentNullException(nameof(requiredCustomModifiers));
if (t.HasElementType)
throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(requiredCustomModifiers));
if (t.ContainsGenericParameters)
throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(requiredCustomModifiers));
AddElementType(CorElementType.CModReqd);
int token = m_module.GetTypeToken(t).Token;
Debug.Assert(!MetadataToken.IsNullToken(token));
AddToken(token);
}
}
AddOneArgTypeHelper(clsArgument);
}
private void AddOneArgTypeHelper(Type clsArgument) { AddOneArgTypeHelperWorker(clsArgument, false); }
private void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst)
{
if (clsArgument.IsGenericParameter)
{
if (clsArgument.DeclaringMethod != null)
AddElementType(CorElementType.MVar);
else
AddElementType(CorElementType.Var);
AddData(clsArgument.GenericParameterPosition);
}
else if (clsArgument.IsGenericType && (!clsArgument.IsGenericTypeDefinition || !lastWasGenericInst))
{
AddElementType(CorElementType.GenericInst);
AddOneArgTypeHelperWorker(clsArgument.GetGenericTypeDefinition(), true);
Type[] args = clsArgument.GetGenericArguments();
AddData(args.Length);
foreach (Type t in args)
AddOneArgTypeHelper(t);
}
else if (clsArgument is TypeBuilder)
{
TypeBuilder clsBuilder = (TypeBuilder)clsArgument;
TypeToken tkType;
if (clsBuilder.Module.Equals(m_module))
{
tkType = clsBuilder.TypeToken;
}
else
{
tkType = m_module.GetTypeToken(clsArgument);
}
if (clsArgument.IsValueType)
{
InternalAddTypeToken(tkType, CorElementType.ValueType);
}
else
{
InternalAddTypeToken(tkType, CorElementType.Class);
}
}
else if (clsArgument is EnumBuilder)
{
TypeBuilder clsBuilder = ((EnumBuilder)clsArgument).m_typeBuilder;
TypeToken tkType;
if (clsBuilder.Module.Equals(m_module))
{
tkType = clsBuilder.TypeToken;
}
else
{
tkType = m_module.GetTypeToken(clsArgument);
}
if (clsArgument.IsValueType)
{
InternalAddTypeToken(tkType, CorElementType.ValueType);
}
else
{
InternalAddTypeToken(tkType, CorElementType.Class);
}
}
else if (clsArgument.IsByRef)
{
AddElementType(CorElementType.ByRef);
clsArgument = clsArgument.GetElementType();
AddOneArgTypeHelper(clsArgument);
}
else if (clsArgument.IsPointer)
{
AddElementType(CorElementType.Ptr);
AddOneArgTypeHelper(clsArgument.GetElementType());
}
else if (clsArgument.IsArray)
{
if (clsArgument.IsSzArray)
{
AddElementType(CorElementType.SzArray);
AddOneArgTypeHelper(clsArgument.GetElementType());
}
else
{
AddElementType(CorElementType.Array);
AddOneArgTypeHelper(clsArgument.GetElementType());
// put the rank information
int rank = clsArgument.GetArrayRank();
AddData(rank); // rank
AddData(0); // upper bounds
AddData(rank); // lower bound
for (int i = 0; i < rank; i++)
AddData(0);
}
}
else
{
CorElementType type = CorElementType.Max;
if (clsArgument is RuntimeType)
{
type = RuntimeTypeHandle.GetCorElementType((RuntimeType)clsArgument);
//GetCorElementType returns CorElementType.Class for both object and string
if (type == CorElementType.Class)
{
if (clsArgument == typeof(object))
type = CorElementType.Object;
else if (clsArgument == typeof(string))
type = CorElementType.String;
}
}
if (IsSimpleType(type))
{
AddElementType(type);
}
else if (m_module == null)
{
InternalAddRuntimeType(clsArgument);
}
else if (clsArgument.IsValueType)
{
InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.ValueType);
}
else
{
InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.Class);
}
}
}
private void AddData(int data)
{
// A managed representation of CorSigCompressData;
if (m_currSig + 4 > m_signature.Length)
{
m_signature = ExpandArray(m_signature);
}
if (data <= 0x7F)
{
m_signature[m_currSig++] = (byte)(data & 0xFF);
}
else if (data <= 0x3FFF)
{
m_signature[m_currSig++] = (byte)((data >>8) | 0x80);
m_signature[m_currSig++] = (byte)(data & 0xFF);
}
else if (data <= 0x1FFFFFFF)
{
m_signature[m_currSig++] = (byte)((data >>24) | 0xC0);
m_signature[m_currSig++] = (byte)((data >>16) & 0xFF);
m_signature[m_currSig++] = (byte)((data >>8) & 0xFF);
m_signature[m_currSig++] = (byte)((data) & 0xFF);
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
}
}
private void AddData(uint data)
{
if (m_currSig + 4 > m_signature.Length)
{
m_signature = ExpandArray(m_signature);
}
m_signature[m_currSig++] = (byte)((data) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>8) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>16) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>24) & 0xFF);
}
private void AddData(ulong data)
{
if (m_currSig + 8 > m_signature.Length)
{
m_signature = ExpandArray(m_signature);
}
m_signature[m_currSig++] = (byte)((data) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>8) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>16) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>24) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>32) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>40) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>48) & 0xFF);
m_signature[m_currSig++] = (byte)((data>>56) & 0xFF);
}
private void AddElementType(CorElementType cvt)
{
// Adds an element to the signature. A managed represenation of CorSigCompressElement
if (m_currSig + 1 > m_signature.Length)
m_signature = ExpandArray(m_signature);
m_signature[m_currSig++] = (byte)cvt;
}
private void AddToken(int token)
{
// A managed represenation of CompressToken
// Pulls the token appart to get a rid, adds some appropriate bits
// to the token and then adds this to the signature.
int rid = (token & 0x00FFFFFF); //This is RidFromToken;
MetadataTokenType type = (MetadataTokenType)(token & unchecked((int)0xFF000000)); //This is TypeFromToken;
if (rid > 0x3FFFFFF)
{
// token is too big to be compressed
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
}
rid = (rid << 2);
// TypeDef is encoded with low bits 00
// TypeRef is encoded with low bits 01
// TypeSpec is encoded with low bits 10
if (type == MetadataTokenType.TypeRef)
{
//if type is mdtTypeRef
rid|=0x1;
}
else if (type == MetadataTokenType.TypeSpec)
{
//if type is mdtTypeSpec
rid|=0x2;
}
AddData(rid);
}
private void InternalAddTypeToken(TypeToken clsToken, CorElementType CorType)
{
// Add a type token into signature. CorType will be either CorElementType.Class or CorElementType.ValueType
AddElementType(CorType);
AddToken(clsToken.Token);
}
private unsafe void InternalAddRuntimeType(Type type)
{
// Add a runtime type into the signature.
AddElementType(CorElementType.Internal);
IntPtr handle = type.GetTypeHandleInternal().Value;
// Internal types must have their pointer written into the signature directly (we don't
// want to convert to little-endian format on big-endian machines because the value is
// going to be extracted and used directly as a pointer (and only within this process)).
if (m_currSig + sizeof(void*) > m_signature.Length)
m_signature = ExpandArray(m_signature);
byte *phandle = (byte*)&handle;
for (int i = 0; i < sizeof(void*); i++)
m_signature[m_currSig++] = phandle[i];
}
private byte[] ExpandArray(byte[] inArray)
{
// Expand the signature buffer size
return ExpandArray(inArray, inArray.Length * 2);
}
private byte[] ExpandArray(byte[] inArray, int requiredLength)
{
// Expand the signature buffer size
if (requiredLength < inArray.Length)
requiredLength = inArray.Length*2;
byte[] outArray = new byte[requiredLength];
Buffer.BlockCopy(inArray, 0, outArray, 0, inArray.Length);
return outArray;
}
private void IncrementArgCounts()
{
if (m_sizeLoc == NO_SIZE_IN_SIG)
{
//We don't have a size if this is a field.
return;
}
m_argCount++;
}
private void SetNumberOfSignatureElements(bool forceCopy)
{
// For most signatures, this will set the number of elements in a byte which we have reserved for it.
// However, if we have a field signature, we don't set the length and return.
// If we have a signature with more than 128 arguments, we can't just set the number of elements,
// we actually have to allocate more space (e.g. shift everything in the array one or more spaces to the
// right. We do this by making a copy of the array and leaving the correct number of blanks. This new
// array is now set to be m_signature and we use the AddData method to set the number of elements properly.
// The forceCopy argument can be used to force SetNumberOfSignatureElements to make a copy of
// the array. This is useful for GetSignature which promises to trim the array to be the correct size anyway.
byte[] temp;
int newSigSize;
int currSigHolder = m_currSig;
if (m_sizeLoc == NO_SIZE_IN_SIG)
return;
//If we have fewer than 128 arguments and we haven't been told to copy the
//array, we can just set the appropriate bit and return.
if (m_argCount < 0x80 && !forceCopy)
{
m_signature[m_sizeLoc] = (byte)m_argCount;
return;
}
//We need to have more bytes for the size. Figure out how many bytes here.
//Since we need to copy anyway, we're just going to take the cost of doing a
//new allocation.
if (m_argCount < 0x80)
{
newSigSize = 1;
}
else if (m_argCount < 0x4000)
{
newSigSize = 2;
}
else
{
newSigSize = 4;
}
//Allocate the new array.
temp = new byte[m_currSig + newSigSize - 1];
//Copy the calling convention. The calling convention is always just one byte
//so we just copy that byte. Then copy the rest of the array, shifting everything
//to make room for the new number of elements.
temp[0] = m_signature[0];
Buffer.BlockCopy(m_signature, m_sizeLoc + 1, temp, m_sizeLoc + newSigSize, currSigHolder - (m_sizeLoc + 1));
m_signature = temp;
//Use the AddData method to add the number of elements appropriately compressed.
m_currSig = m_sizeLoc;
AddData(m_argCount);
m_currSig = currSigHolder + (newSigSize - 1);
}
#endregion
#region Internal Members
internal int ArgumentCount
{
get
{
return m_argCount;
}
}
internal static bool IsSimpleType(CorElementType type)
{
if (type <= CorElementType.String)
return true;
if (type == CorElementType.TypedByRef || type == CorElementType.I || type == CorElementType.U || type == CorElementType.Object)
return true;
return false;
}
internal byte[] InternalGetSignature(out int length)
{
// An internal method to return the signature. Does not trim the
// array, but passes out the length of the array in an out parameter.
// This is the actual array -- not a copy -- so the callee must agree
// to not copy it.
//
// param length : an out param indicating the length of the array.
// return : A reference to the internal ubyte array.
if (!m_sigDone)
{
m_sigDone = true;
// If we have more than 128 variables, we can't just set the length, we need
// to compress it. Unfortunately, this means that we need to copy the entire
// array. Bummer, eh?
SetNumberOfSignatureElements(false);
}
length = m_currSig;
return m_signature;
}
internal byte[] InternalGetSignatureArray()
{
int argCount = m_argCount;
int currSigLength = m_currSig;
int newSigSize = currSigLength;
//Allocate the new array.
if (argCount < 0x7F)
newSigSize += 1;
else if (argCount < 0x3FFF)
newSigSize += 2;
else
newSigSize += 4;
byte[] temp = new byte[newSigSize];
// copy the sig
int sigCopyIndex = 0;
// calling convention
temp[sigCopyIndex++] = m_signature[0];
// arg size
if (argCount <= 0x7F)
temp[sigCopyIndex++] = (byte)(argCount & 0xFF);
else if (argCount <= 0x3FFF)
{
temp[sigCopyIndex++] = (byte)((argCount >>8) | 0x80);
temp[sigCopyIndex++] = (byte)(argCount & 0xFF);
}
else if (argCount <= 0x1FFFFFFF)
{
temp[sigCopyIndex++] = (byte)((argCount >>24) | 0xC0);
temp[sigCopyIndex++] = (byte)((argCount >>16) & 0xFF);
temp[sigCopyIndex++] = (byte)((argCount >>8) & 0xFF);
temp[sigCopyIndex++] = (byte)((argCount) & 0xFF);
}
else
throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
// copy the sig part of the sig
Buffer.BlockCopy(m_signature, 2, temp, sigCopyIndex, currSigLength - 2);
// mark the end of sig
temp[newSigSize - 1] = (byte)CorElementType.End;
return temp;
}
#endregion
#region Public Methods
public void AddArgument(Type clsArgument)
{
AddArgument(clsArgument, null, null);
}
public void AddArgument(Type argument, bool pinned)
{
if (argument == null)
throw new ArgumentNullException(nameof(argument));
IncrementArgCounts();
AddOneArgTypeHelper(argument, pinned);
}
public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
{
if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(requiredCustomModifiers), nameof(arguments)));
if (optionalCustomModifiers != null && (arguments == null || optionalCustomModifiers.Length != arguments.Length))
throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(optionalCustomModifiers), nameof(arguments)));
if (arguments != null)
{
for (int i =0; i < arguments.Length; i++)
{
AddArgument(arguments[i],
requiredCustomModifiers == null ? null : requiredCustomModifiers[i],
optionalCustomModifiers == null ? null : optionalCustomModifiers[i]);
}
}
}
public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
if (m_sigDone)
throw new ArgumentException(Environment.GetResourceString("Argument_SigIsFinalized"));
if (argument == null)
throw new ArgumentNullException(nameof(argument));
IncrementArgCounts();
// Add an argument to the signature. Takes a Type and determines whether it
// is one of the primitive types of which we have special knowledge or a more
// general class. In the former case, we only add the appropriate short cut encoding,
// otherwise we will calculate proper description for the type.
AddOneArgTypeHelper(argument, requiredCustomModifiers, optionalCustomModifiers);
}
public void AddSentinel()
{
AddElementType(CorElementType.Sentinel);
}
public override bool Equals(Object obj)
{
if (!(obj is SignatureHelper))
{
return false;
}
SignatureHelper temp = (SignatureHelper)obj;
if ( !temp.m_module.Equals(m_module) || temp.m_currSig!=m_currSig || temp.m_sizeLoc!=m_sizeLoc || temp.m_sigDone !=m_sigDone )
{
return false;
}
for (int i=0; i<m_currSig; i++)
{
if (m_signature[i]!=temp.m_signature[i])
return false;
}
return true;
}
public override int GetHashCode()
{
// Start the hash code with the hash code of the module and the values of the member variables.
int HashCode = m_module.GetHashCode() + m_currSig + m_sizeLoc;
// Add one if the sig is done.
if (m_sigDone)
HashCode += 1;
// Then add the hash code of all the arguments.
for (int i=0; i < m_currSig; i++)
HashCode += m_signature[i].GetHashCode();
return HashCode;
}
public byte[] GetSignature()
{
return GetSignature(false);
}
internal byte[] GetSignature(bool appendEndOfSig)
{
// Chops the internal signature to the appropriate length. Adds the
// end token to the signature and marks the signature as finished so that
// no further tokens can be added. Return the full signature in a trimmed array.
if (!m_sigDone)
{
if (appendEndOfSig)
AddElementType(CorElementType.End);
SetNumberOfSignatureElements(true);
m_sigDone = true;
}
// This case will only happen if the user got the signature through
// InternalGetSignature first and then called GetSignature.
if (m_signature.Length > m_currSig)
{
byte[] temp = new byte[m_currSig];
Array.Copy(m_signature, 0, temp, 0, m_currSig);
m_signature = temp;
}
return m_signature;
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("Length: " + m_currSig + Environment.NewLine);
if (m_sizeLoc != -1)
{
sb.Append("Arguments: " + m_signature[m_sizeLoc] + Environment.NewLine);
}
else
{
sb.Append("Field Signature" + Environment.NewLine);
}
sb.Append("Signature: " + Environment.NewLine);
for (int i=0; i<=m_currSig; i++)
{
sb.Append(m_signature[i] + " ");
}
sb.Append(Environment.NewLine);
return sb.ToString();
}
#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;
/// <summary>
/// ToInt16(System.Int32)
/// </summary>
public class ConvertToInt16_7
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify methos ToInt16(random).");
try
{
Int16 random = TestLibrary.Generator.GetInt16(-55);
Int16 actual = Convert.ToInt16((Int32)random);
Int16 expected = random;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("001.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method ToInt16(0)");
try
{
Int32 i = 0;
Int16 actual = Convert.ToInt16(i);
Int16 expected = 0;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("002.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method ToInt16(int16.max)");
try
{
Int32 i = Int16.MaxValue;
Int16 actual = Convert.ToInt16(i);
Int16 expected = Int16.MaxValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("003.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify method ToInt16(int16.min)");
try
{
Int32 i = Int16.MinValue;
Int16 actual = Convert.ToInt16(i);
Int16 expected = Int16.MinValue;
if (actual != expected)
{
TestLibrary.TestFramework.LogError("004.1", "Method ToInt16 Err.");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actual = " + actual + ", expected = " + expected);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException is not thrown.");
try
{
Int32 i = Int16.MaxValue + 1;
Int16 r = Convert.ToInt16(i);
TestLibrary.TestFramework.LogError("101.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: OverflowException is not thrown.");
try
{
Int32 i = Int16.MinValue - 1;
Int16 r = Convert.ToInt16(i);
TestLibrary.TestFramework.LogError("102.1", "OverflowException is not thrown.");
retVal = false;
}
catch (OverflowException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
ConvertToInt16_7 test = new ConvertToInt16_7();
TestLibrary.TestFramework.BeginTestCase("ConvertToInt16_7");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Microsoft.CodeAnalysis.Scripting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Interactive
{
internal partial class InteractiveHost
{
/// <summary>
/// A remote singleton server-activated object that lives in the interactive host process and controls it.
/// </summary>
internal sealed class Service : MarshalByRefObject, IDisposable
{
private static readonly ManualResetEventSlim s_clientExited = new ManualResetEventSlim(false);
// Signaled when UI thread is ready to process messages.
private static readonly ManualResetEventSlim s_uiReady = new ManualResetEventSlim(false);
// A WinForms control that enables us to execute code on UI thread.
// TODO (tomat): consider removing dependency on WinForms.
private static Control s_ui;
internal static readonly ImmutableArray<string> DefaultSourceSearchPaths =
ImmutableArray.Create(FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)));
internal static readonly ImmutableArray<string> DefaultReferenceSearchPaths =
ImmutableArray.Create(FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()));
private readonly InteractiveAssemblyLoader _assemblyLoader;
private readonly MetadataShadowCopyProvider _metadataFileProvider;
// the search paths - updated from the hostObject
private ImmutableArray<string> _sourceSearchPaths;
private ObjectFormatter _objectFormatter;
private IRepl _repl;
private InteractiveHostObject _hostObject;
private ObjectFormattingOptions _formattingOptions;
// Session is not thread-safe by itself,
// so we need to lock whenever we compile a submission or add a reference:
private readonly object _sessionGuard = new object();
private ScriptOptions _options;
private ScriptState _lastResult;
private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create(
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)),
FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()));
#region Setup
public Service()
{
// TODO (tomat): we should share the copied files with the host
_metadataFileProvider = new MetadataShadowCopyProvider(
Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"),
noShadowCopyDirectories: s_systemNoShadowCopyDirectories);
_options = ScriptOptions.Default.WithSearchPaths(DefaultReferenceSearchPaths);
_assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider);
_sourceSearchPaths = DefaultSourceSearchPaths;
_formattingOptions = new ObjectFormattingOptions(
memberFormat: MemberDisplayFormat.Inline,
quoteStrings: true,
useHexadecimalNumbers: false,
maxOutputLength: 200,
memberIndentation: " ");
// We want to be sure to delete the shadow-copied files when the process goes away. Frankly
// there's nothing we can do if the process is forcefully quit or goes down in a completely
// uncontrolled manner (like a stack overflow). When the process goes down in a controlled
// manned, we should generally expect this event to be called.
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
}
private void HandleProcessExit(object sender, EventArgs e)
{
Dispose();
AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit;
}
public void Dispose()
{
_metadataFileProvider.Dispose();
}
public override object InitializeLifetimeService()
{
return null;
}
public void Initialize(Type replType)
{
Contract.ThrowIfNull(replType);
_repl = (IRepl)Activator.CreateInstance(replType);
_objectFormatter = _repl.CreateObjectFormatter();
_hostObject = new InteractiveHostObject();
_options = _options
.WithBaseDirectory(Directory.GetCurrentDirectory())
.AddReferences(_hostObject.GetType().Assembly);
_hostObject.ReferencePaths.AddRange(_options.SearchPaths);
_hostObject.SourcePaths.AddRange(_sourceSearchPaths);
Console.OutputEncoding = Encoding.UTF8;
}
private static bool AttachToClientProcess(int clientProcessId)
{
Process clientProcess;
try
{
clientProcess = Process.GetProcessById(clientProcessId);
}
catch (ArgumentException)
{
return false;
}
clientProcess.EnableRaisingEvents = true;
clientProcess.Exited += new EventHandler((_, __) =>
{
s_clientExited.Set();
});
return clientProcess.IsAlive();
}
// for testing purposes
public void EmulateClientExit()
{
s_clientExited.Set();
}
internal static void RunServer(string[] args)
{
if (args.Length != 3)
{
throw new ArgumentException("Expecting arguments: <server port> <semaphore name> <client process id>");
}
RunServer(args[0], args[1], int.Parse(args[2], CultureInfo.InvariantCulture));
}
/// <summary>
/// Implements remote server.
/// </summary>
private static void RunServer(string serverPort, string semaphoreName, int clientProcessId)
{
if (!AttachToClientProcess(clientProcessId))
{
return;
}
// Disables Windows Error Reporting for the process, so that the process fails fast.
// Unfortunately, this doesn't work on Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1)
// Note that GetErrorMode is not available on XP at all.
if (Environment.OSVersion.Version >= new Version(6, 1, 0, 0))
{
SetErrorMode(GetErrorMode() | ErrorMode.SEM_FAILCRITICALERRORS | ErrorMode.SEM_NOOPENFILEERRORBOX | ErrorMode.SEM_NOGPFAULTERRORBOX);
}
IpcServerChannel serverChannel = null;
IpcClientChannel clientChannel = null;
try
{
using (var semaphore = Semaphore.OpenExisting(semaphoreName))
{
// DEBUG: semaphore.WaitOne();
var serverProvider = new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
var clientProvider = new BinaryClientFormatterSinkProvider();
clientChannel = new IpcClientChannel(GenerateUniqueChannelLocalName(), clientProvider);
ChannelServices.RegisterChannel(clientChannel, ensureSecurity: false);
serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), serverPort, serverProvider);
ChannelServices.RegisterChannel(serverChannel, ensureSecurity: false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(Service),
ServiceName,
WellKnownObjectMode.Singleton);
var uiThread = new Thread(UIThread);
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.IsBackground = true;
uiThread.Start();
s_uiReady.Wait();
// the client can instantiate interactive host now:
semaphore.Release();
}
s_clientExited.Wait();
}
finally
{
if (serverChannel != null)
{
ChannelServices.UnregisterChannel(serverChannel);
}
if (clientChannel != null)
{
ChannelServices.UnregisterChannel(clientChannel);
}
}
// force exit even if there are foreground threads running:
Environment.Exit(0);
}
private static void UIThread()
{
s_ui = new Control();
s_ui.CreateControl();
s_uiReady.Set();
Application.Run();
}
internal static string ServiceName
{
get { return typeof(Service).Name; }
}
private static string GenerateUniqueChannelLocalName()
{
return typeof(Service).FullName + Guid.NewGuid();
}
#endregion
#region Remote Async Entry Points
// Used by ResetInteractive - consider improving (we should remember the parameters for auto-reset, e.g.)
[OneWay]
public void SetPathsAsync(
RemoteAsyncOperation<object> operation,
string[] referenceSearchPaths,
string[] sourceSearchPaths,
string baseDirectory)
{
Debug.Assert(operation != null);
Debug.Assert(referenceSearchPaths != null);
Debug.Assert(sourceSearchPaths != null);
Debug.Assert(baseDirectory != null);
lock (_sessionGuard)
{
_hostObject.ReferencePaths.Clear();
_hostObject.ReferencePaths.AddRange(referenceSearchPaths);
_options = _options.WithSearchPaths(referenceSearchPaths).WithBaseDirectory(baseDirectory);
_hostObject.SourcePaths.Clear();
_hostObject.SourcePaths.AddRange(sourceSearchPaths);
_sourceSearchPaths = sourceSearchPaths.AsImmutable();
Directory.SetCurrentDirectory(baseDirectory);
}
operation.Completed(null);
}
/// <summary>
/// Reads given initialization file (.rsp) and loads and executes all assembly references and files, respectively specified in it.
/// Execution is performed on the UI thread.
/// </summary>
[OneWay]
public void InitializeContextAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string initializationFile, bool isRestarting)
{
Debug.Assert(operation != null);
var success = false;
try
{
InitializeContext(initializationFile, isRestarting);
success = true;
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
CompleteExecution(operation, success);
}
}
private string ResolveReferencePath(string reference, string baseFilePath)
{
var references = _options.ReferenceResolver.ResolveReference(reference, baseFilePath: null, properties: MetadataReferenceProperties.Assembly);
if (references.IsDefaultOrEmpty)
{
return null;
}
return references.Single().FilePath;
}
/// <summary>
/// Adds an assembly reference to the current session.
/// </summary>
[OneWay]
public void AddReferenceAsync(RemoteAsyncOperation<bool> operation, string reference)
{
Debug.Assert(operation != null);
Debug.Assert(reference != null);
var success = false;
try
{
// TODO (tomat): This lock blocks all other session operations.
// We should be able to run multiple assembly resolutions and code execution in parallel.
string fullPath;
lock (_sessionGuard)
{
fullPath = ResolveReferencePath(reference, baseFilePath: null);
if (fullPath != null)
{
success = LoadReference(fullPath, suppressWarnings: false, addReference: true);
}
}
if (fullPath == null)
{
Console.Error.WriteLine(string.Format(FeaturesResources.CannotResolveReference, reference));
}
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
operation.Completed(success);
}
}
/// <summary>
/// Executes given script snippet on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string text)
{
Debug.Assert(operation != null);
Debug.Assert(text != null);
var success = false;
try
{
success = Execute(text);
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
CompleteExecution(operation, success);
}
}
/// <summary>
/// Executes given script file on the UI thread in the context of the current session.
/// </summary>
[OneWay]
public void ExecuteFileAsync(RemoteAsyncOperation<RemoteExecutionResult> operation, string path)
{
Debug.Assert(operation != null);
Debug.Assert(path != null);
string fullPath = null;
bool success = false;
try
{
fullPath = ResolveRelativePath(path, _options.BaseDirectory, displayPath: false);
success = fullPath != null && ExecuteFile(fullPath);
}
catch (Exception e)
{
ReportUnhandledException(e);
}
finally
{
CompleteExecution(operation, success, fullPath);
}
}
private void CompleteExecution(RemoteAsyncOperation<RemoteExecutionResult> operation, bool success, string resolvedPath = null)
{
// TODO (tomat): we should be resetting this info just before the execution to ensure that the services see the same
// as the next execution.
// send any updates to the host object and current directory back to the client:
var newSourcePaths = _hostObject.SourcePaths.List.GetNewContent();
var newReferencePaths = _hostObject.ReferencePaths.List.GetNewContent();
var currentDirectory = Directory.GetCurrentDirectory();
var oldWorkingDirectory = _options.BaseDirectory;
var newWorkingDirectory = (oldWorkingDirectory != currentDirectory) ? currentDirectory : null;
// update local search paths, the client updates theirs on operation completion:
if (newSourcePaths != null)
{
_sourceSearchPaths = newSourcePaths.AsImmutable();
}
if (newReferencePaths != null)
{
_options = _options.WithSearchPaths(newReferencePaths);
}
_options = _options.WithBaseDirectory(currentDirectory);
operation.Completed(new RemoteExecutionResult(success, newSourcePaths, newReferencePaths, newWorkingDirectory, resolvedPath));
}
private static void ReportUnhandledException(Exception e)
{
Console.Error.WriteLine("Unexpected error:");
Console.Error.WriteLine(e);
Debug.Fail("Unexpected error");
Debug.WriteLine(e);
}
#endregion
#region Operations
// TODO (tomat): testing only
public void SetTestObjectFormattingOptions()
{
_formattingOptions = new ObjectFormattingOptions(
memberFormat: MemberDisplayFormat.Inline,
quoteStrings: true,
useHexadecimalNumbers: false,
maxOutputLength: int.MaxValue,
memberIndentation: " ");
}
/// <summary>
/// Loads references, set options and execute files specified in the initialization file.
/// Also prints logo unless <paramref name="isRestarting"/> is true.
/// </summary>
private void InitializeContext(string initializationFileOpt, bool isRestarting)
{
Debug.Assert(initializationFileOpt == null || PathUtilities.IsAbsolute(initializationFileOpt));
// TODO (tomat): this is also done in CommonInteractiveEngine, perhaps we can pass the parsed command lines to here?
if (!isRestarting)
{
Console.Out.WriteLine(_repl.GetLogo());
}
if (File.Exists(initializationFileOpt))
{
Console.Out.WriteLine(string.Format(FeaturesResources.LoadingContextFrom, Path.GetFileName(initializationFileOpt)));
var parser = _repl.GetCommandLineParser();
// The base directory for relative paths is the directory that contains the .rsp file.
// Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc).
var args = parser.Parse(new[] { "@" + initializationFileOpt }, Path.GetDirectoryName(initializationFileOpt), RuntimeEnvironment.GetRuntimeDirectory(), null /* TODO: pass a valid value*/);
foreach (var error in args.Errors)
{
var writer = (error.Severity == DiagnosticSeverity.Error) ? Console.Error : Console.Out;
writer.WriteLine(error.GetMessage(CultureInfo.CurrentCulture));
}
if (args.Errors.Length == 0)
{
// TODO (tomat): other arguments
// TODO (tomat): parse options
lock (_sessionGuard)
{
// TODO (tomat): consolidate with other reference resolving
foreach (CommandLineReference cmdLineReference in args.MetadataReferences)
{
// interactive command line parser doesn't accept modules or linked assemblies
Debug.Assert(cmdLineReference.Properties.Kind == MetadataImageKind.Assembly && !cmdLineReference.Properties.EmbedInteropTypes);
string fullPath = ResolveReferencePath(cmdLineReference.Reference, baseFilePath: null);
LoadReference(fullPath, suppressWarnings: true, addReference: true);
}
}
var rspDirectory = Path.GetDirectoryName(initializationFileOpt);
foreach (CommandLineSourceFile file in args.SourceFiles)
{
// execute all files as scripts (matches csi/vbi semantics)
string fullPath = ResolveRelativePath(file.Path, rspDirectory, displayPath: true);
if (fullPath != null)
{
ExecuteFile(fullPath);
}
}
}
}
if (!isRestarting)
{
Console.Out.WriteLine(FeaturesResources.TypeHelpForMoreInformation);
}
}
private string ResolveRelativePath(string path, string baseDirectory, bool displayPath)
{
List<string> attempts = new List<string>();
Func<string, bool> fileExists = file =>
{
attempts.Add(file);
return File.Exists(file);
};
string fullPath = FileUtilities.ResolveRelativePath(path, null, baseDirectory, _sourceSearchPaths, fileExists);
if (fullPath == null)
{
if (displayPath)
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFoundFormat, path);
}
else
{
Console.Error.WriteLine(FeaturesResources.SpecifiedFileNotFound);
}
if (attempts.Count > 0)
{
DisplaySearchPaths(Console.Error, attempts);
}
}
return fullPath;
}
private bool LoadReference(string fullOriginalPath, bool suppressWarnings, bool addReference)
{
AssemblyLoadResult result;
try
{
result = LoadFromPathThrowing(fullOriginalPath, addReference);
}
catch (FileNotFoundException e)
{
Console.Error.WriteLine(e.Message);
return false;
}
catch (ArgumentException e)
{
Console.Error.WriteLine((e.InnerException ?? e).Message);
return false;
}
catch (TargetInvocationException e)
{
// The user might have hooked AssemblyResolve event, which might have thrown an exception.
// Display stack trace in this case.
Console.Error.WriteLine(e.InnerException.ToString());
return false;
}
if (!result.IsSuccessful && !suppressWarnings)
{
Console.Out.WriteLine(string.Format(CultureInfo.CurrentCulture, FeaturesResources.RequestedAssemblyAlreadyLoaded, result.OriginalPath));
}
return true;
}
// Testing utility.
// TODO (tomat): needed since MetadataReference is not serializable .
// Has to be public to be callable via remoting.
public SerializableAssemblyLoadResult LoadReferenceThrowing(string reference, bool addReference)
{
var fullPath = ResolveReferencePath(reference, baseFilePath: null);
if (fullPath == null)
{
throw new FileNotFoundException(message: null, fileName: reference);
}
return LoadFromPathThrowing(fullPath, addReference);
}
private AssemblyLoadResult LoadFromPathThrowing(string fullOriginalPath, bool addReference)
{
var result = _assemblyLoader.LoadFromPath(fullOriginalPath);
if (addReference && result.IsSuccessful)
{
var reference = _metadataFileProvider.GetReference(fullOriginalPath);
_options = _options.AddReferences(reference);
}
return result;
}
public ObjectHandle ExecuteAndWrap(string text)
{
return new ObjectHandle(ExecuteInner(Compile(text)));
}
private Script Compile(string text, string path = null)
{
// note that the actual submission execution runs on the UI thread, not under this lock:
lock (_sessionGuard)
{
Script script = _repl.CreateScript(text).WithOptions(_options);
if (_lastResult != null)
{
script = script.WithPrevious(_lastResult.Script);
}
else
{
script = script.WithGlobalsType(_hostObject.GetType());
}
if (path != null)
{
script = script.WithPath(path).WithOptions(script.Options.WithIsInteractive(false));
}
// force build so exception is thrown now if errors are found.
script.Build();
// load all references specified in #r's -- they will all be PE references (may be shadow copied):
foreach (PortableExecutableReference reference in script.GetCompilation().DirectiveReferences)
{
// FullPath refers to the original reference path, not the copy:
LoadReference(reference.FilePath, suppressWarnings: false, addReference: false);
}
return script;
}
}
/// <summary>
/// Executes specified script file as a submission.
/// </summary>
/// <param name="fullPath">Full source path.</param>
/// <returns>True if the code has been executed. False if the code doesn't compile.</returns>
/// <remarks>
/// All errors are written to the error output stream.
/// Uses source search paths to resolve unrooted paths.
/// </remarks>
private bool ExecuteFile(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
string content;
try
{
content = File.ReadAllText(fullPath);
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
return false;
}
// TODO (tomat): engine.CompileSubmission shouldn't throw
Script script;
try
{
script = Compile(content, fullPath);
}
catch (CompilationErrorException e)
{
DisplayInteractiveErrors(e.Diagnostics, Console.Error);
return false;
}
object result;
ExecuteOnUIThread(script, out result);
return true;
}
private void DisplaySearchPaths(TextWriter writer, List<string> attemptedFilePaths)
{
writer.WriteLine(attemptedFilePaths.Count == 1 ?
FeaturesResources.SearchedInDirectory :
FeaturesResources.SearchedInDirectories);
foreach (string path in attemptedFilePaths)
{
writer.Write(" ");
writer.WriteLine(Path.GetDirectoryName(path));
}
}
/// <summary>
/// Executes specified code.
/// </summary>
/// <param name="text">Source code.</param>
/// <returns>True if the code has been executed. False if the code doesn't compile.</returns>
/// <remarks>
/// All errors are written to the error output stream.
/// The resulting value (if any) is formatted and printed to the output stream.
/// </remarks>
private bool Execute(string text)
{
Script script;
try
{
script = Compile(text);
}
catch (CompilationErrorException e)
{
DisplayInteractiveErrors(e.Diagnostics, Console.Error);
return false;
}
object result;
if (!ExecuteOnUIThread(script, out result))
{
return true;
}
bool hasValue;
var resultType = script.GetCompilation().GetSubmissionResultType(out hasValue);
if (hasValue)
{
if (resultType != null && resultType.SpecialType == SpecialType.System_Void)
{
Console.Out.WriteLine(_objectFormatter.VoidDisplayString);
}
else
{
Console.Out.WriteLine(_objectFormatter.FormatObject(result, _formattingOptions));
}
}
return true;
}
private class ExecuteSubmissionError
{
public readonly Exception Exception;
public ExecuteSubmissionError(Exception exception)
{
this.Exception = exception;
}
}
private bool ExecuteOnUIThread(Script script, out object result)
{
result = s_ui.Invoke(new Func<object>(() =>
{
try
{
return ExecuteInner(script);
}
catch (Exception e)
{
return new ExecuteSubmissionError(e);
}
}));
var error = result as ExecuteSubmissionError;
if (error != null)
{
// TODO (tomat): format exception
Console.Error.WriteLine(error.Exception);
return false;
}
else
{
return true;
}
}
private object ExecuteInner(Script script)
{
var globals = _lastResult != null ? (object)_lastResult : (object)_hostObject;
var result = script.Run(globals);
_lastResult = result;
return result.ReturnValue;
}
private void DisplayInteractiveErrors(ImmutableArray<Diagnostic> diagnostics, TextWriter output)
{
var displayedDiagnostics = new List<Diagnostic>();
const int MaxErrorCount = 5;
for (int i = 0, n = Math.Min(diagnostics.Length, MaxErrorCount); i < n; i++)
{
displayedDiagnostics.Add(diagnostics[i]);
}
displayedDiagnostics.Sort((d1, d2) => d1.Location.SourceSpan.Start - d2.Location.SourceSpan.Start);
var formatter = _repl.GetDiagnosticFormatter();
foreach (var diagnostic in displayedDiagnostics)
{
output.WriteLine(formatter.Format(diagnostic, output.FormatProvider as CultureInfo));
}
if (diagnostics.Length > MaxErrorCount)
{
int notShown = diagnostics.Length - MaxErrorCount;
output.WriteLine(string.Format(output.FormatProvider, FeaturesResources.PlusAdditional, notShown, (notShown == 1) ? "error" : "errors"));
}
}
#endregion
#region Win32 API
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode SetErrorMode(ErrorMode mode);
[DllImport("kernel32", PreserveSig = true)]
internal static extern ErrorMode GetErrorMode();
[Flags]
internal enum ErrorMode : int
{
/// <summary>
/// Use the system default, which is to display all error dialog boxes.
/// </summary>
SEM_FAILCRITICALERRORS = 0x0001,
/// <summary>
/// The system does not display the critical-error-handler message box. Instead, the system sends the error to the calling process.
/// Best practice is that all applications call the process-wide SetErrorMode function with a parameter of SEM_FAILCRITICALERRORS at startup.
/// This is to prevent error mode dialogs from hanging the application.
/// </summary>
SEM_NOGPFAULTERRORBOX = 0x0002,
/// <summary>
/// The system automatically fixes memory alignment faults and makes them invisible to the application.
/// It does this for the calling process and any descendant processes. This feature is only supported by
/// certain processor architectures. For more information, see the Remarks section.
/// After this value is set for a process, subsequent attempts to clear the value are ignored.
/// </summary>
SEM_NOALIGNMENTFAULTEXCEPT = 0x0004,
/// <summary>
/// The system does not display a message box when it fails to find a file. Instead, the error is returned to the calling process.
/// </summary>
SEM_NOOPENFILEERRORBOX = 0x8000,
}
#endregion
#region Testing
// TODO(tomat): remove when the compiler supports events
// For testing purposes only!
public void HookMaliciousAssemblyResolve()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((_, __) =>
{
int i = 0;
while (true)
{
if (i < 10)
{
i = i + 1;
}
else if (i == 10)
{
Console.Error.WriteLine("in the loop");
i = i + 1;
}
}
});
}
public void RemoteConsoleWrite(byte[] data, bool isError)
{
using (var stream = isError ? Console.OpenStandardError() : Console.OpenStandardOutput())
{
stream.Write(data, 0, data.Length);
stream.Flush();
}
}
public bool IsShadowCopy(string path)
{
return _metadataFileProvider.IsShadowCopy(path);
}
#endregion
}
}
}
| |
using Lidgren.Network;
using SFML.System;
using System;
namespace Iris
{
public class ClientMailman
{
private NetClient client;
private Deathmatch dm;
public static string ip = "giga.krash.net";
public ClientMailman(Deathmatch dm)
{
this.dm = dm;
}
public void Disconnect()
{
try
{
client.Disconnect("Bye"); //Throws an exception when exiting from the menu
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public bool Connect()
{
NetPeerConfiguration config = new NetPeerConfiguration("bandit");
config.EnableMessageType(NetIncomingMessageType.ConnectionLatencyUpdated);
config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
int port = 5635;
client = new NetClient(config);
client.Start();
MainGame.dm.player.UID = MainGame.dm.Mailman.client.UniqueIdentifier;
//start processing messages
try
{
client.Connect(ip, port);
}
catch (Exception)
{
Console.WriteLine("Check your connection");
return false;
}
return true;
}
public bool FullyConnected
{
get
{
return client.ConnectionsCount == 1;
}
}
public void HandleMessages()
{
NetIncomingMessage msg;
while ((msg = client.ReadMessage()) != null)
{
switch (msg.MessageType)
{
case NetIncomingMessageType.ConnectionApproval:
case NetIncomingMessageType.ConnectionLatencyUpdated:
break;
case NetIncomingMessageType.VerboseDebugMessage:
case NetIncomingMessageType.DebugMessage:
case NetIncomingMessageType.WarningMessage:
case NetIncomingMessageType.ErrorMessage:
Console.WriteLine("[{0}]: {1}", msg.MessageType, msg.ReadString());
break;
case NetIncomingMessageType.StatusChanged:
NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
Console.WriteLine("[{0}]: {1}", msg.MessageType, status);
break;
case NetIncomingMessageType.Data:
//multiple game messages in a single packet
if (msg.PeekString() == "MULTI_ON")
{
//consume start marker
msg.ReadString();
//read until end marker is reached
while (msg.PeekString() != "MULTI_OFF")
{
HandleAGameMessage(msg);
}
}
else //regular single message
{
HandleAGameMessage(msg);
}
break;
default:
Console.WriteLine("Unrecognized Lidgren Message Recieved: {0}", msg.MessageType);
break;
}
client.Recycle(msg);
}
}
private void HandleAGameMessage(NetIncomingMessage msg)
{
string messageType = msg.ReadString();
switch (messageType)
{
case "LIFE":
long UID_LIFE = msg.ReadInt64();
int hp = msg.ReadInt32();
HandleLifeMessage(UID_LIFE, hp);
break;
case "NAME":
long UID_NAME = msg.ReadInt64();
string newName = msg.ReadString();
HandleNameMessage(UID_NAME, newName);
break;
case "POS": //Update a player's position
long UID_POS = msg.ReadInt64();
float xPos = msg.ReadFloat();
float yPos = msg.ReadFloat();
int facing = msg.ReadInt32();
float aimAngle = msg.ReadFloat();
HandlePosMessage(UID_POS, xPos, yPos, facing, aimAngle);
break;
case "JOIN": //Add a player
long UID_JOIN = msg.ReadInt64();
HandleJoinMessage(UID_JOIN);
break;
case "CHAT": //Add chat
long UID_CHAT = msg.ReadInt64();
string message = msg.ReadString();
HandleChatMessage(UID_CHAT, message);
break;
case "PART": //Remove a player
long UID_PART = msg.ReadInt64();
HandlePartMessage(UID_PART);
break;
case "INFO": //Recieved when server has completed sending all newbie initialization
break;
case "BULLET":
long UID_BULLET = msg.ReadInt64();
float xBULLET = msg.ReadFloat();
float yBULLET = msg.ReadFloat();
float BULLETangle = msg.ReadFloat();
Bullet b = new Bullet(UID_BULLET, BULLETangle, new Vector2f(xBULLET, yBULLET));
HandleBulletCreate(b, UID_BULLET);
break;
case "RESPAWN":
long UID_RESPAWN = msg.ReadInt64();
HandleRespawnMessage(UID_RESPAWN);
break;
case "COIN":
//long UID_COIN = msg.ReadInt64();
float xCOIN = msg.ReadFloat();
float yCOIN = msg.ReadFloat();
int countCOIN = msg.ReadInt32();
HandleCoinCreate(countCOIN, xCOIN, yCOIN);
break;
case "SWITCHWEAPON":
long UID_WEPSWITCH = msg.ReadInt64();
int WEAPONID = msg.ReadInt32();
HandleNetPlayerWeaponSwitch(UID_WEPSWITCH, WEAPONID);
break;
case "KILLER":
long UID_VICTIM = msg.ReadInt64();
long UID_KILLER = msg.ReadInt64();
HandleKillerMessage(UID_VICTIM, UID_KILLER);
break;
case "LOOT":
Console.WriteLine("LOOT Recieved");
int LOOTseed = msg.ReadInt32();
Console.WriteLine(LOOTseed);
Random rand = new Random(LOOTseed);
MainGame.dm.GameObjects.Add(new TreasureBox(new Vector2f(rand.Next(40, 1600), 180)));
break;
case "EMOTE":
long UID_EMOTE = msg.ReadInt64();
string EMOTE_TYPE = msg.ReadString();
MainGame.dm.GameObjects.Add(new EmoteBubble(EMOTE_TYPE, MainGame.dm.GetPlayerWithUID(UID_EMOTE))); ;
break;
case "BOMB":
long UID_EXPLOSIVE = msg.ReadInt64();
float xEXP = msg.ReadFloat();
float yEXP = msg.ReadFloat();
float EXPangle = msg.ReadFloat();
BombInstance bomb = new BombInstance(UID_EXPLOSIVE, EXPangle, new Vector2f(xEXP, yEXP));
HandleBombCreate(bomb, UID_EXPLOSIVE);
break;
case "TIME":
float TIME_MESSAGE = msg.ReadFloat();
HandleTimeMessage(TIME_MESSAGE);
break;
case "MODEL":
Console.WriteLine("Model");
long UID_MODEL = msg.ReadInt64();
string MODEL_STR = msg.ReadString();
Console.WriteLine(MODEL_STR);
HandleModel(UID_MODEL, MODEL_STR);
break;
case "GOLDCOUNT":
long UID_GOLDCOUNT = msg.ReadInt64();
int goldCount = msg.ReadInt32();
HandleGoldCountMessage(UID_GOLDCOUNT, goldCount);
break;
case "LANDMINE":
long UID_MINEOWNER = msg.ReadInt64();
float xMINE = msg.ReadFloat();
float yMINE = msg.ReadFloat();
int MINE_ID = msg.ReadInt32();
HandleLandMineMessage(UID_MINEOWNER, xMINE, yMINE, MINE_ID);
break;
case "LANDMINE_TRIGGER":
int LANDMINEID = msg.ReadInt32();
HandleLandMineTriggerMessage(LANDMINEID);
break;
case "GENERATOR":
long UID_GENOWNER = msg.ReadInt64();
float xGEN = msg.ReadFloat();
float yGEN = msg.ReadFloat();
int type = msg.ReadInt32();
DateTime when = new DateTime(msg.ReadInt64());
HandleGeneratorMessage(xGEN, yGEN, type, when);
break;
default:
Console.WriteLine("Unrecognized Game Message Recieved: {0}\n{1}", msg.ToString(), messageType);
break;
}
}
private void HandleLifeMessage(long uid, int health)
{
if (dm.GetPlayerWithUID(uid) != null)
dm.GetPlayerWithUID(uid).Health = health;
}
private void HandleLifeGOLDCOUNT(long uid, int gold)
{
if (dm.GetPlayerWithUID(uid) != null)
dm.GetPlayerWithUID(uid).gold = gold;
}
private void HandleGoldCountMessage(long uid, int gold)
{
if (dm.GetPlayerWithUID(uid) != null)
dm.GetPlayerWithUID(uid).gold = gold;
}
private void HandleLandMineTriggerMessage(int LANDMINE_ID)
{
MainGame.dm.GameObjects.ForEach((g) =>
{
if (g is Mine)
{
if (((Mine)g).ID == LANDMINE_ID)
{
((Mine)g).Destroy();
}
}
});
}
private void HandleLandMineMessage(long uid, float x, float y, int LANDMINE_ID)
{
MainGame.dm.GameObjects.Add(new Mine(new Vector2f(x, y), dm.GetPlayerWithUID(uid), LANDMINE_ID));
}
private void HandleGeneratorMessage(float x, float y, int type, DateTime when)
{
//TODO: datetime WHEN to place old
switch (type)
{
case 1:
MainGame.dm.GameObjects.Add(new HealthGenerator(new Vector2f(x, y)));
break;
case 2:
MainGame.dm.GameObjects.Add(new ShieldGenerator(new Vector2f(x, y)));
break;
}
}
private void HandleNameMessage(long uid, string newName)
{
Actor who = dm.GetPlayerWithUID(uid);
if (who != null)
{
string oldName = who.Name;
who.Name = newName;
Gui.Chats.Insert(0, oldName + " has changed their name to " + newName);
}
}
private void HandlePosMessage(long uid, float x, float y, int facing, float aimAngle)
{
Actor plr = dm.GetPlayerWithUID(uid);
if (plr != null) //stale POS message, player is already gone?
{
//Console.WriteLine(plr.Name);
plr.Pos = new Vector2f(x, y);
plr.Facing = facing;
plr.AimAngle = aimAngle;
plr.UpdateCollisionBox();
}
}
private void HandleBulletCreate(Bullet b, long uid)
{
Actor shooter = ((Actor)dm.GetPlayerWithUID(uid));
MainGame.dm.Projectiles.Add(b);
MainGame.dm.GameObjects.Add(new GunSmoke(shooter.Core + Helper.PolarToVector2(32, shooter.AimAngle, 1, 1) + (shooter.Velocity), shooter.AimAngle));
MainGame.dm.GameObjects.Add(new GunFlash(shooter.Core + Helper.PolarToVector2(32, shooter.AimAngle, 1, 1) + (shooter.Velocity), shooter.AimAngle));
}
private void HandleTimeMessage(float TIME_MESSAGE)
{
MainGame.dm.roundTimeLeft = 10 + (float)((int)((60 * 3) - (TIME_MESSAGE % (60 * 3))));
}
private void HandleBombCreate(BombInstance b, long uid)
{
Actor shooter = ((Actor)dm.GetPlayerWithUID(uid));
MainGame.dm.Projectiles.Add(b);
}
private void HandleCoinCreate(int countCOIN, float xCOIN, float yCOIN)
{
Random r = new Random(countCOIN);
for (int i = 0; i < countCOIN; i++)
{
Coin c = new Coin(new Vector2f(xCOIN, yCOIN), 2.5f + (float)r.NextDouble() * 1.5f, (float)
(-Math.PI / 2 + .35 * (r.NextDouble() - .5)));
dm.GameObjects.Add(c);
}
}
private void HandleChatMessage(long uid, string message)
{
Actor who = dm.GetPlayerWithUID(uid);
if (who != null)
{
Gui.Chats.Insert(0, who.Name + ": " + message);
Gui.ChatCloseDelay = 300;
}
}
private void HandleRespawnMessage(long uid)
{
dm.Players.Add(new NetPlayer(dm, uid));
}
private void HandleKillerMessage(long victimUID, long killerUID)
{
//Console.WriteLine("Killer UID: " + killerUID);
//Console.WriteLine("VICTIM UID: " + victimUID);
Actor killer = MainGame.dm.GetPlayerWithUID(killerUID);
Actor victim = MainGame.dm.GetPlayerWithUID(victimUID);
string killerName = killer != null ? killer.Name : "Universe";
string victimName = victim != null ? victim.Name : "Universe";
Gui.FragTexts.Add(new FragText(killerName, victimName,
Content.GetTexture("skullIcon.png")));
//Gui.Chats.Insert(0, "[Server] Killer UID: " + killerName);
//Gui.Chats.Insert(0, "[Server] Player UID: " + victimName);
}
private void HandleJoinMessage(long uid)
{
dm.Players.Add(new NetPlayer(dm, uid));
Gui.Chats.Insert(0, "[Server]: " + Math.Abs(uid).ToString().Substring(0, 4) + " has connected");
Gui.ChatCloseDelay = 200;
}
private void HandlePartMessage(long uid)
{
dm.Players.Remove(dm.GetPlayerWithUID(uid));
Gui.Chats.Insert(0, "[Server]: " + Math.Abs(uid).ToString().Substring(0, 4) + " has disconnected");
Gui.ChatCloseDelay = 200;
}
public void SendPlayerPosMessage(long uid, Vector2f pos, int facing, float aimAngle)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("POS");
outGoingMessage.Write(pos.X);
outGoingMessage.Write(pos.Y);
outGoingMessage.Write(facing);
outGoingMessage.Write(aimAngle);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
public void SendLandMineTrigger(int ID)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("LANDMINE_TRIGGER");
outGoingMessage.Write(ID);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
public void SendLandMineCreate(int ID, Vector2f position, long UID_OWNER)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("LANDMINE");
outGoingMessage.Write(position.X);
outGoingMessage.Write(position.Y);
outGoingMessage.Write(ID);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
public void SendGeneratorCreate(int type, Vector2f position)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("GENERATOR");
outGoingMessage.Write(position.X);
outGoingMessage.Write(position.Y);
outGoingMessage.Write(type);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
public void SendBulletCreate(Bullet b)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("BULLET");
outGoingMessage.Write(b.Pos.X);
outGoingMessage.Write(b.Pos.Y);
outGoingMessage.Write(b.Angle);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
public void SendBombCreate(BombInstance b)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("BOMB");
outGoingMessage.Write(b.Pos.X);
outGoingMessage.Write(b.Pos.Y);
outGoingMessage.Write(b.Angle);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
public void SendCoinCreate(Vector2f pos, int count)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("COIN");
outGoingMessage.Write(pos.X);
outGoingMessage.Write(pos.Y);
outGoingMessage.Write(count);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
public void SendHealth(int life)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("LIFE");
outGoingMessage.Write(life);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
public void SendRespawn(long uid)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("RESPAWN");
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
public void SendGoldCount(int gold)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("GOLDCOUNT");
outGoingMessage.Write(gold);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
public void SendKillerMessage(long killerUID)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("KILLER");
outGoingMessage.Write(killerUID);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
Console.WriteLine(killerUID);
Console.WriteLine(MainGame.dm.player.UID);
}
public void SendName(string name)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("NAME");
outGoingMessage.Write(name);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
public void SendModel(string modelName)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("MODEL");
outGoingMessage.Write(modelName);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
private void HandleModel(long uid, string modelName)
{
NetPlayer a = (NetPlayer)MainGame.dm.GetPlayerWithUID(uid);
Console.WriteLine(a.Name);
Console.WriteLine(modelName);
switch (modelName)
{
case "Character_1_Model":
a.model = MainGame.Char1Model;
a.UpdateToCurrentModel();
break;
case "Character_2_Model":
a.model = MainGame.Char2Model;
a.UpdateToCurrentModel();
break;
}
}
public void SendChat(string message)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("CHAT");
outGoingMessage.Write(message);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
internal void sendWeaponSwitch(int p)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("SWITCHWEAPON");
outGoingMessage.Write(p);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
internal void HandleNetPlayerWeaponSwitch(long UID, int index)
{
NetPlayer np = MainGame.dm.GetPlayerWithUID(UID) as NetPlayer;
np.weaponIndex = index;
}
internal void SendEmote(string e)
{
NetOutgoingMessage outGoingMessage = client.CreateMessage();
outGoingMessage.Write("EMOTE");
outGoingMessage.Write(e);
client.SendMessage(outGoingMessage, NetDeliveryMethod.ReliableOrdered);
}
}
}
| |
//
// System.Web.UI.WebControls.Xml.cs
//
// Authors:
// Gaurav Vaish (gvaish@iitk.ac.in)
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Andreas Nahr (ClassDevelopment@A-SoftTech.com)
//
// (c) 2002 Ximian, Inc. (http://www.ximian.com)
// (C) Gaurav Vaish (2002)
// (C) 2003 Andreas Nahr
//
//
// 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.ComponentModel;
using System.ComponentModel.Design;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Web;
using System.Web.UI;
namespace System.Web.UI.WebControls
{
[DefaultProperty("DocumentSource")]
[PersistChildren(false)]
[ControlBuilder (typeof (XmlBuilder))]
[Designer ("System.Web.UI.Design.WebControls.XmlDesigner, " + Consts.AssemblySystem_Design, typeof (IDesigner))]
public class Xml : Control
{
static XslTransform defaultTransform;
XmlDocument document;
string documentContent;
string documentSource;
XslTransform transform;
XsltArgumentList transformArgumentList;
string transformSource;
XPathDocument xpathDoc;
static Xml ()
{
XmlTextReader reader = new XmlTextReader (new StringReader("<xsl:stylesheet version='1.0' " +
"xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
"<xsl:template match=\"*\">" +
"<xsl:copy-of select=\".\"/>" +
"</xsl:template>" +
"</xsl:stylesheet>"));
defaultTransform = new XslTransform();
#if NET_1_0
defaultTransform.Load (reader);
#else
defaultTransform.Load (reader, null, null);
#endif
}
public Xml ()
{
}
[MonoTODO("security")]
private void LoadXmlDoc ()
{
if (documentContent != null && documentContent.Length > 0) {
document = new XmlDocument ();
document.LoadXml (documentContent);
return;
}
if (documentSource != null && documentSource.Length != 0) {
document = new XmlDocument ();
document.Load (documentSource);
}
}
#if NET_2_0
[Obsolete]
#endif
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription ("This is the XML document that is used for the XML Webcontrol.")]
public XmlDocument Document {
get {
if (document == null)
LoadXmlDoc ();
return document;
}
set {
documentSource = null;
documentContent = null;
xpathDoc = null;
document = value;
}
}
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription ("The XML content that is transformed for the XML Webcontrol.")]
public string DocumentContent {
get {
return documentContent;
}
set {
document = null;
xpathDoc = null;
documentContent = value;
}
}
#if NET_2_0
[Localizable (true)]
[UrlProperty]
#else
[Bindable (true)]
#endif
[DefaultValue (""), WebCategory ("Behavior")]
[Editor ("System.Web.UI.Design.XmlUrlEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
[WebSysDescription ("The URL or the source of the XML content that is transformed for the XML Webcontrol.")]
public string DocumentSource {
get {
if (documentSource != null)
return documentSource;
return String.Empty;
}
set {
document = null;
documentContent = null;
xpathDoc = null;
documentSource = value;
}
}
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription ("The XSL transform that is applied to this XML Webcontrol.")]
public XslTransform Transform {
get {
return transform;
}
set {
transformSource = null;
transform = value;
}
}
#if NET_2_0
[Localizable (true)]
#else
[Bindable (true)]
#endif
[DefaultValue (""), WebCategory ("Behavior")]
[Editor ("System.Web.UI.Design.XmlUrlEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
[WebSysDescription ("An URL specifying the source that is used for the XSL transformation.")]
public string TransformSource {
get {
if (transformSource != null)
return transformSource;
return String.Empty;
}
set {
transform = null;
transformSource = value;
}
}
[Browsable (false), DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
[WebSysDescription ("Arguments that are used by the XSL Transform.")]
public XsltArgumentList TransformArgumentList {
get { return transformArgumentList; }
set { transformArgumentList = value; }
}
protected override void AddParsedSubObject (object obj)
{
if (obj is LiteralControl) {
DocumentContent = ((LiteralControl) obj).Text;
return;
}
throw new HttpException (HttpRuntime.FormatResourceString (
"Cannot_Have_Children_of_Type",
"Xml",
GetType().Name));
}
private void LoadXpathDoc ()
{
if (documentContent != null && documentContent.Length > 0) {
xpathDoc = new XPathDocument (new StringReader (documentContent));
return;
}
if (documentSource != null && documentSource.Length != 0) {
xpathDoc = new XPathDocument (MapPathSecure (documentSource));
return;
}
}
private void LoadTransform ()
{
if (transform != null)
return;
if (transformSource != null && transformSource.Length != 0) {
transform = new XslTransform ();
transform.Load (MapPathSecure (transformSource));
}
}
protected override void Render(HtmlTextWriter output)
{
if (document == null) {
LoadXpathDoc();
}
LoadTransform();
if (document == null && xpathDoc == null) {
return;
}
if (transform == null) {
transform = defaultTransform;
}
if (document != null) {
#if NET_1_0
Transform.Transform(document, transformArgumentList, output);
#else
Transform.Transform(document, transformArgumentList, output, null);
#endif
return;
}
#if NET_1_0
Transform.Transform(xpathDoc, transformArgumentList, output);
#else
Transform.Transform(xpathDoc, transformArgumentList, output, null);
#endif
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal.ProviderControls {
public partial class SmarterMail60_EditAccount {
/// <summary>
/// passwordRow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlTableRow passwordRow;
/// <summary>
/// cbChangePassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbChangePassword;
/// <summary>
/// cbDomainAdmin control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbDomainAdmin;
/// <summary>
/// lblFirstName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFirstName;
/// <summary>
/// txtFirstName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtFirstName;
/// <summary>
/// lblLastName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblLastName;
/// <summary>
/// txtLastName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtLastName;
/// <summary>
/// lblReplyTo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblReplyTo;
/// <summary>
/// txtReplyTo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtReplyTo;
/// <summary>
/// lblSignature control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSignature;
/// <summary>
/// txtSignature control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSignature;
/// <summary>
/// secAutoresponder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secAutoresponder;
/// <summary>
/// AutoresponderPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel AutoresponderPanel;
/// <summary>
/// lblResponderEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblResponderEnabled;
/// <summary>
/// chkResponderEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkResponderEnabled;
/// <summary>
/// lblSubject control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSubject;
/// <summary>
/// txtSubject control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSubject;
/// <summary>
/// lblMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblMessage;
/// <summary>
/// txtMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtMessage;
/// <summary>
/// secForwarding control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secForwarding;
/// <summary>
/// ForwardingPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ForwardingPanel;
/// <summary>
/// lblForwardTo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblForwardTo;
/// <summary>
/// txtForward control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtForward;
/// <summary>
/// chkDeleteOnForward control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkDeleteOnForward;
}
}
| |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using MooGet;
namespace MooGet.Specs.Core {
[TestFixture]
public class NuspecSpec : Spec {
Nuspec minimum;
Nuspec maximum;
[SetUp]
public void Before() {
minimum = new Nuspec(PathToContent("nuspecs/MeetsMinimumSpecification.nuspec"));
maximum = new Nuspec(PathToContent("nuspecs/MeetsSpecification.nuspec"));
}
[Test]
public void can_create_blank_nuspec() {
var nuspec = new Nuspec();
nuspec.Xml.ShouldEqual(@"
<?xml version=""1.0"" encoding=""utf-8""?>
<package xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<metadata xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"">
</metadata>
</package>".TrimStart('\n'));
}
[Test]
public void can_add_metadata_to_blank_nuspec() {
var nuspec = new Nuspec();
nuspec.Id = "MyPackage";
nuspec.VersionText = "1.2.3";
nuspec.Xml.ShouldEqual(@"
<?xml version=""1.0"" encoding=""utf-8""?>
<package xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<metadata xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"">
<id>MyPackage</id>
<version>1.2.3</version>
</metadata>
</package>".TrimStart('\n'));
}
[Test]
public void can_add_dependencies_to_blank_nuspec() {
var nuspec = new Nuspec { Id = "MyPackage", VersionText = "1.2.3" };
// This API isn't ideal ... but it works. You can NOT manipulate Dependencies. You must set the whole property.
nuspec.Dependencies = new List<PackageDependency> { new PackageDependency("CoolPackage >= 1.5") };
nuspec.Xml.ShouldEqual(@"
<?xml version=""1.0"" encoding=""utf-8""?>
<package xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<metadata xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"">
<id>MyPackage</id>
<version>1.2.3</version>
<dependencies>
<dependency id=""CoolPackage"" version="">= 1.5"" />
</dependencies>
</metadata>
</package>".TrimStart('\n'));
}
[Test]
public void can_add_files_to_blank_nuspec() {
var nuspec = new Nuspec { Id = "MyPackage", VersionText = "1.2.3" };
nuspec.FileSources = new List<NuspecFileSource> {
new NuspecFileSource { Source = @"content\**" },
new NuspecFileSource { Source = @"bin\Release\*", Target = "lib" }
};
nuspec.Xml.ShouldEqual(@"
<?xml version=""1.0"" encoding=""utf-8""?>
<package xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<metadata xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"">
<id>MyPackage</id>
<version>1.2.3</version>
</metadata>
<files>
<file src=""content\**"" />
<file src=""bin\Release\*"" target=""lib"" />
</files>
</package>".TrimStart('\n'));
}
[Test]
public void can_add_lot_of_stuff_to_blank_nuspec() {
var nuspec = new Nuspec {
Id = "MyPackage",
VersionText = "1.2.3",
Description = "Cool package",
ProjectUrl = "https://github.com/me/whatever"
};
nuspec.Tags = new List<string> { "first", "second", "third" };
nuspec.Authors = new List<string> { "remi", "Lander", "Murdoch" };
nuspec.Dependencies = new List<PackageDependency> { new PackageDependency("CoolPackage") };
nuspec.FileSources = new List<NuspecFileSource> {
new NuspecFileSource { Source = @"README" },
new NuspecFileSource { Source = @"src\**" },
new NuspecFileSource { Source = @"bin\Release\*", Target = "tools" },
new NuspecFileSource { Source = @"bin\Release\*.dll", Target = "lib" }
};
nuspec.Xml.ShouldEqual(@"
<?xml version=""1.0"" encoding=""utf-8""?>
<package xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<metadata xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"">
<id>MyPackage</id>
<version>1.2.3</version>
<description>Cool package</description>
<projectUrl>https://github.com/me/whatever</projectUrl>
<tags>first second third</tags>
<authors>remi,Lander,Murdoch</authors>
<dependencies>
<dependency id=""CoolPackage"" />
</dependencies>
</metadata>
<files>
<file src=""README"" />
<file src=""src\**"" />
<file src=""bin\Release\*"" target=""tools"" />
<file src=""bin\Release\*.dll"" target=""lib"" />
</files>
</package>".TrimStart('\n'));
}
[Test]
public void Id() {
minimum.Id.ShouldEqual("Min.Id");
maximum.Id.ShouldEqual("Package-Id");
minimum.Id = "New Id";
minimum.Id.ShouldEqual("New Id");
}
[Test]
public void Version() {
minimum.VersionText.ShouldEqual("1.2.3.45678");
minimum.Version.ToString().ShouldEqual("1.2.3.45678");
maximum.VersionText.ShouldEqual("1.2.3.45678");
maximum.Version.ToString().ShouldEqual("1.2.3.45678");
minimum.Version = new PackageVersion("1.2.3");
minimum.VersionText.ShouldEqual("1.2.3");
minimum.VersionText = "4.5.6";
minimum.Version.ToString().ShouldEqual("4.5.6");
}
[Test]
public void Details_Title() {
minimum.Title.Should(Be.Null);
maximum.Title.ShouldEqual("Package ID");
minimum.Title = "Foo";
minimum.Title.ShouldEqual("Foo");
}
[Test]
public void Details_Description() {
minimum.Description.ShouldEqual("This is my minimum package");
maximum.Description.ShouldEqual("Description of Package-Id");
minimum.Description = "Hi";
minimum.Description.ShouldEqual("Hi");
}
[Test]
public void Details_Summary() {
minimum.Summary.Should(Be.Null);
maximum.Summary.ShouldEqual("Longer summary descripting Package-Id in detail");
minimum.Summary = "Hi";
minimum.Summary.ShouldEqual("Hi");
}
[Test]
public void Details_ProjectUrl() {
minimum.ProjectUrl.Should(Be.Null);
maximum.ProjectUrl.ShouldEqual("http://github.com/me/project");
minimum.ProjectUrl = "http://foo.com";
minimum.ProjectUrl.ShouldEqual("http://foo.com");
}
[Test]
public void Details_IconUrl() {
minimum.IconUrl.Should(Be.Null);
maximum.IconUrl.ShouldEqual("http://github.com/me/project/icon.png");
minimum.IconUrl = "http://foo.com";
minimum.IconUrl.ShouldEqual("http://foo.com");
}
[Test]
public void Details_LicenseUrl() {
minimum.LicenseUrl.Should(Be.Null);
maximum.LicenseUrl.ShouldEqual("http://github.com/me/project/LICENSE.txt");
minimum.LicenseUrl = "http://foo.com";
minimum.LicenseUrl.ShouldEqual("http://foo.com");
}
[Test]
public void Details_RequiredLicenseAcceptance() {
minimum.RequiresLicenseAcceptance.Should(Be.False);
maximum.RequiresLicenseAcceptance.Should(Be.False);
minimum.RequiresLicenseAcceptance = true;
minimum.RequiresLicenseAcceptance.Should(Be.True);
}
[Test]
public void Details_Authors() {
minimum.Authors.ShouldEqual(new List<string> { "remi", "bob" });
minimum.AuthorsText.ShouldEqual("remi,bob");
maximum.Authors.ShouldEqual(new List<string> { "Lander", "Murdoch" });
maximum.AuthorsText.ShouldEqual("Lander,Murdoch");
// Modifying Authors does nothing! you MUST edit AuthorsText or set Authors = new List<string>
minimum.Authors.Add("Rover");
minimum.Authors.ShouldEqual(new List<string>{ "remi", "bob" });
minimum.AuthorsText.ShouldEqual("remi,bob");
minimum.AuthorsText = "joe , sue";
minimum.Authors.ShouldEqual(new List<string>{ "joe", "sue" });
minimum.AuthorsText.ShouldEqual("joe,sue");
var authors = minimum.Authors;
authors.Add("foo");
minimum.Authors = authors;
minimum.Authors.ShouldEqual(new List<string>{ "joe", "sue", "foo" });
minimum.AuthorsText.ShouldEqual("joe,sue,foo");
}
[Test]
public void Details_Owners() {
minimum.Owners.Should(Be.Empty);
minimum.OwnersText.Should(Be.Empty);
maximum.Owners.ShouldEqual(new List<string> { "remi", "wanda" });
maximum.OwnersText.ShouldEqual("remi,wanda");
minimum.OwnersText = "joe , sue";
minimum.Owners.ShouldEqual(new List<string>{ "joe", "sue" });
minimum.OwnersText.ShouldEqual("joe,sue");
// Modifying Owners does nothing! you MUST edit OwnersText or set Owners = new List<string>
minimum.Owners.Add("Rover");
minimum.Owners.ShouldEqual(new List<string>{ "joe", "sue" });
minimum.OwnersText.ShouldEqual("joe,sue");
var owners = minimum.Owners;
owners.Add("Rover");
minimum.Owners = owners;
minimum.Owners.ShouldEqual(new List<string>{ "joe", "sue", "Rover" });
minimum.OwnersText.ShouldEqual("joe,sue,Rover");
}
[Test]
public void Details_Language() {
minimum.Language.Should(Be.Null);
minimum.Locale.Should(Be.Null);
maximum.Language.ShouldEqual("en-US");
maximum.Locale.DisplayName.ShouldEqual("English (United States)");
minimum.Language = "en-GB";
minimum.Language.ShouldEqual("en-GB");
minimum.Locale.DisplayName.ShouldEqual("English (United Kingdom)");
}
[Test]
public void Details_Tags() {
minimum.Tags.Should(Be.Empty);
minimum.TagsText.Should(Be.Empty);
maximum.Tags.ShouldEqual(new List<string>{ "foo", "bar", "foo.bar" });
maximum.TagsText.ShouldEqual("foo bar foo.bar");
minimum.TagsText = "hi there";
minimum.TagsText.ShouldEqual("hi there");
minimum.Tags.ShouldEqual(new List<string>{ "hi", "there" });
minimum.Tags = new List<string>{ "this" };
minimum.TagsText.ShouldEqual("this");
minimum.Tags.ShouldEqual(new List<string>{ "this" });
}
[Test]
public void Details_Dependencies() {
minimum.Dependencies.Should(Be.Empty);
maximum.Dependencies.Count.ShouldEqual(3);
maximum.Dependencies.ToStrings().ShouldEqual(new List<string> { "NUnit", "NHibernate.Core >= 2.1.2.4000", "FooBar = 1.0" });
// Just like Authors, Owners, Tags, and everything else ... you CANNOT modify the Dependencies List object if you
// want to change the xml. Instead you need to assign the whole List via the set {}
var dependencies = new List<PackageDependency>();
dependencies.Add(new PackageDependency("Foo"));
dependencies.Add(new PackageDependency("Bar 1.0"));
dependencies.Add(new PackageDependency("Neat >= 1.0 < 9.9"));
// can add dependencies if we didn't have any
minimum.Dependencies = dependencies;
minimum.Dependencies.ToStrings().ShouldEqual(new List<string> { "Foo", "Bar = 1.0", "Neat >= 1.0 < 9.9" });
// can override existing dependencies
maximum.Dependencies.ToStrings().ShouldEqual(new List<string> { "NUnit", "NHibernate.Core >= 2.1.2.4000", "FooBar = 1.0" });
maximum.Dependencies = dependencies;
maximum.Dependencies.ToStrings().ShouldEqual(new List<string> { "Foo", "Bar = 1.0", "Neat >= 1.0 < 9.9" });
}
[Test]
public void FilesSources() {
minimum.FileSources.Should(Be.Empty);
maximum.FileSources.Count.ShouldEqual(6);
maximum.FileSources.ToStrings().ShouldEqual(new List<string>{
@"<file src='README.markdown' />",
@"<file src='..\LICENSE.txt' />",
@"<file src='tools\**\*' />",
@"<file src='bin\**\*.dll' target='lib' />",
@"<file src='../../foo.exe' target='tools' />",
@"<file src='mystuff/*' target='content' />"
});
}
[Test][Ignore]
public void Reading_files_from_FilesSources() {
}
[Test][Ignore]
public void Can_Save_to_file__defaults_to_Path() {
}
/*
<package>
<metadata>
<id>elmah</id>
<version>1.1</version>
<description>ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.</description>
<authors>
<author>azizatif</author>
</authors>
<language>en-US</language>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<created>2010-10-25T22:55:23.3728+00:00</created>
<modified>2010-10-25T22:55:23.3738+00:00</modified>
</metadata>
</package>
*/
[Test]
public void Example_elmah() {
var spec = new Nuspec(PathToContent("nuspecs/elmah.nuspec"));
spec.ShouldHaveProperties(new {
Id = "elmah",
VersionText = "1.1",
Description = "ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.",
AuthorsText = "azizatif",
Language = "en-US",
RequireLicenseAcceptanceString = "false"
});
}
/*
<package>
<metadata>
<id>jQuery</id>
<version>1.4.1</version>
<description>jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development</description>
<authors>
<author>John Resig</author>
</authors>
<language>en-US</language>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<created>2010-10-25T22:55:32.1304+00:00</created>
<modified>2010-10-25T22:55:32.1314+00:00</modified>
</metadata>
</package>
*/
[Test]
public void Example_jQuery() {
var spec = new Nuspec(PathToContent("nuspecs/jQuery.nuspec"));
spec.ShouldHaveProperties(new {
Id = "jQuery",
VersionText = "1.4.1",
Description = "jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development",
AuthorsText = "John Resig",
Language = "en-US",
RequireLicenseAcceptanceString = "false"
});
}
/*
<package>
<metadata>
<id>IronPython</id>
<version>2.6.1</version>
<description>IronPython is an open-source implementation of the Python programming language which is tightly integrated with the .NET Framework. IronPython can use the .NET Framework and Python libraries, and other .NET languages can use Python code just as easily.</description>
<authors>
<author>Microsoft</author>
</authors>
<licenseUrl>http://ironpython.codeplex.com/license</licenseUrl>
<language>en-US</language>
<keywords>python DLR iron dynamic language</keywords>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<created>2010-10-25T22:55:30.9482+00:00</created>
<modified>2010-10-25T22:55:30.9492+00:00</modified>
</metadata>
</package>
*/
[Test]
public void Example_IronPython() {
var spec = new Nuspec(PathToContent("nuspecs/IronPython.nuspec"));
spec.ShouldHaveProperties(new {
Id = "IronPython",
VersionText = "2.6.1",
Description = "IronPython is an open-source implementation of the Python programming language which is tightly integrated with the .NET Framework. IronPython can use the .NET Framework and Python libraries, and other .NET languages can use Python code just as easily.",
AuthorsText = "Microsoft",
Language = "en-US",
RequireLicenseAcceptanceString = "false"
});
}
/*
<package>
<metadata>
<id>Ninject</id>
<version>2.0.1.0</version>
<description>Stop writing monolithic applications that make you feel like you have to move mountains to make the simplest of changes. Ninject helps you use the technique of dependency injection to break your applications into loosely-coupled, highly-cohesive components, and then glue them back together in a flexible manner.</description>
<authors>
<author>Nate Kohari</author>
<author>Ian Davis</author>
</authors>
<language>en-US</language>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<created>2010-10-25T22:55:38.4642+00:00</created>
<modified>2010-10-25T22:55:38.4642+00:00</modified>
</metadata>
</package>
*/
[Test]
public void Example_Ninject() {
var spec = new Nuspec(PathToContent("nuspecs/Ninject.nuspec"));
spec.ShouldHaveProperties(new {
Id = "Ninject",
VersionText = "2.0.1.0",
Description = "Stop writing monolithic applications that make you feel like you have to move mountains to make the simplest of changes. Ninject helps you use the technique of dependency injection to break your applications into loosely-coupled, highly-cohesive components, and then glue them back together in a flexible manner.",
AuthorsText = "Nate Kohari,Ian Davis",
Language = "en-US",
RequireLicenseAcceptanceString = "false"
});
// can update authors, even tho it has invalid <author> elements
spec.AuthorsText = "this, that";
spec.Authors.ShouldEqual(new List<string> { "this", "that" });
}
// If you can find a problem in the Nuspec parser for a particular nuspec, add an example here!
// The examples above are pretty arbitrary.
}
}
| |
using System;
using System.Diagnostics;
using BCurve=NS_GMath.I_BCurveD;
namespace NS_GMath
{
public class Param
{
/*
* CONSTS & ENUMS
*/
public const double Infinity=2.0e20;
public const double Degen=1.0e20;
public const double Invalid=1.5e20;
public enum TypeParam
{
Before=-2,
Start=-1,
Inner=0,
End=1,
After=2,
Invalid=100,
};
/*
* MEMBERS
*/
double val;
/*
* PROPERTIES
*/
public double Val
{
get { return this.val; }
set
{
if (Math.Abs(value)>Param.Infinity)
{
value=Param.Infinity*Math.Sign(value);
}
this.val=value;
}
}
public bool IsValid
{
get { return (this.val!=Param.Invalid); }
}
public bool IsFictive
{
get { return ((this.IsDegen)||(this.IsInfinite)||(!this.IsValid)); }
}
public bool IsDegen
{
get { return (this.val==Param.Degen); }
}
public bool IsInfinite
{
get { return (Math.Abs(this.val)==Param.Infinity); }
}
/*
* CONSTRUCTORS
*/
protected Param()
{
this.val=0.5;
}
public Param(double val)
{
this.Val=val;
}
/*
* METHODS
*/
virtual public void ClearRelease()
{
}
virtual public Param Copy()
{
return new Param(this.val);
}
public void Invalidate()
{
this.val=Param.Invalid;
}
public void Round(params double[] valRound)
{
for (int i=0; i<valRound.Length; i++)
{
if (Math.Abs(this.Val-valRound[i])<MConsts.EPS_DEC)
this.Val=valRound[i];
}
}
public void Reverse(double valRev)
{
if (this.val==Param.Degen)
return;
if (this.val==Param.Invalid)
return;
if (Math.Abs(this.val)==Param.Infinity)
{
this.val=-this.val;
return;
}
this.val=valRev-this.val;
this.Clip(-Param.Infinity,Param.Infinity);
}
public void Clip(double start, double end)
{
if (start>end)
{
throw new ExceptionGMath("Param","Clip",null);
}
if (this.val==Param.Degen)
return;
if (this.val==Param.Invalid)
return;
this.Round(start,end);
if (this.Val<start)
this.Val=start;
if (this.Val>end)
this.Val=end;
}
public void FromReduced(BCurve bcurve)
{
// parameter of the (reduced)curve may be invalidated if
// the curve intersects the self-intersecting Bezier
if (this.val==Param.Invalid)
return;
if (bcurve.IsDegen)
{
return;
}
if (bcurve is Bez2D)
{
Bez2D bez=bcurve as Bez2D;
Param parM;
if (bez.IsSeg(out parM))
{
bez.ParamFromSeg(this);
}
}
}
/*
* CONVERSIONS
*/
public static implicit operator double(Param par)
{
return par.val;
}
public static implicit operator Param(double val)
{
return new Param(val);
}
}
public class CParam : Param
{
Knot knot;
/*
* CONSTRUCTORS
*/
public CParam(double val, Knot knot)
{
this.Val=val;
this.knot=knot;
}
public CParam(Param par, Knot knot)
{
if (par.GetType()!=typeof(Param))
{
throw new ExceptionGMath("Param","CParam",null);
}
this.Val=par.Val;
this.knot=knot;
}
/*
* PROPERTIES
*/
public Knot Kn
{
get { return this.knot; }
}
public int IndKnot
{
get
{
if (this.knot==null)
return GConsts.IND_UNINITIALIZED;
return this.knot.IndexKnot;
}
}
/*
* METHODS
*/
override public void ClearRelease()
{
this.knot=null;
}
override public Param Copy()
{
throw new ExceptionGMath("Param","Copy","NOT IMPLEMENTED");
//return null;
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System.Collections;
using System.Threading;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Caching.Events;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.Util;
using Alachisoft.NCache.SocketServer.CallbackTasks;
using Alachisoft.NCache.SocketServer.EventTask;
using Alachisoft.NCache.Runtime.Exceptions;
using Alachisoft.NCache.SocketServer.Util;
using Alachisoft.NCache.Caching.Util;
using Alachisoft.NCache.Common.DataStructures;
using System.Collections.Generic;
using System.Text;
using Alachisoft.NCache.Common.Protobuf;
using EnumerationPointer = Alachisoft.NCache.Common.DataStructures.EnumerationPointer;
using Exception = System.Exception;
using Alachisoft.NCache.Runtime.Events;
using Alachisoft.NCache.Runtime.Caching;
using Alachisoft.NCache.Common.Enum;
using Alachisoft.NCache.Common.Caching;
namespace Alachisoft.NCache.SocketServer
{
internal sealed class NCache : ICommandExecuter
{
string _cacheserver="NCache";
private ClientManager _client;
private bool _isDotNetClient;
private Alachisoft.NCache.Caching.Cache _cache = null;
private string _cacheId = null;
private string _licenceCode = string.Empty;
private CustomUpdateCallback _onItemUpdatedCallback = null;
private Caching.PollRequestCallback _pollRequestCallback = null;
private CustomRemoveCallback _onItemRemoveCallback = null;
private AsyncOperationCompletedCallback _asyncOperationCallback = null;
private ItemAddedCallback _itemAdded = null;
private ItemUpdatedCallback _itemUpdated = null;
private ItemRemovedCallback _itemRemoved = null;
private CacheClearedCallback _cacheCleared = null;
private CustomNotificationCallback _customNotif = null;
private DataSourceUpdatedCallback _dsUpdatedCallback = null;
private ConfigurationModified _configModified = null;
private CompactTypeModifiedCallback _onCompactTypeModifiedCallback = null;
private short _addSeq = -1;
private short _removeSeq = -1;
private short _updateSeq = -1;
private object sync_lock_AddDataFilter = new object();
private object sync_lock_UpdateDataFilter = new object();
private object sync_lock_RemoveDataFilter = new object();
//muds:
private NodeJoinedCallback _nodeJoined = null;
private NodeLeftCallback _nodeLeft = null;
private CacheStoppedCallback _cacheStopped = null;
private CacheBecomeActiveCallback _cacheBecomeActive = null;
#if !DEVELOPMENT
private HashmapChangedCallback _hashmapChanged = null;
#endif
private OperationModeChangedCallback _operationModeChanged = null;
private BlockClientActivity _blockClientActivity = null;
private UnBlockClientActivity _unblockClientActivity = null;
/// <summary>flag to determine if client has registered to cache stopped event.
/// if so, client will be notified about cache stop.
/// We cannot unregister cache stopped event upon client request because it is
/// used to dispose client too.</summary>
private bool _cacheStoppedEventRegistered = false;
private bool _clientConnectivityChangeRegistered;
EventDataFilter _itemAddedFilter = EventDataFilter.None;
EventDataFilter _itemUpdatedFilter = EventDataFilter.None;
EventDataFilter _itemRemovedFilter = EventDataFilter.None;
/// <summary>
/// Initialize the cache instance.
/// </summary>
///
public EventDataFilter ItemAddedFilter
{
get { return _itemAddedFilter; }
set { _itemAddedFilter = value; }
}
public EventDataFilter ItemRemovedFilter
{
get { return _itemRemovedFilter; }
set { _itemRemovedFilter = value; }
}
public EventDataFilter ItemUpdatedFilter
{
get { return _itemUpdatedFilter; }
set { _itemUpdatedFilter = value; }
}
internal NCache(string cacheId, bool isDotNetClient, ClientManager client, string licenceInfo, string userId, string password, byte[] userIdBinary, byte[] paswordBinary, Runtime.Caching.ClientInfo clientInfo)
{
this._cacheId = cacheId;
this._isDotNetClient = isDotNetClient;
this._client = client;
this._licenceCode = licenceInfo;
_cache = CacheProvider.Provider.GetCacheInstanceIgnoreReplica(cacheId);
if (_cache == null) throw new Exception("Cache is not registered");
if (!_cache.IsRunning) throw new Exception("Cache is not running");
EventHelper.EventDataFormat = _cache.SocketServerDataService;
#if !CLIENT
if (_cache.CacheType.Equals("mirror-server") && !_cache.IsCoordinator)
throw new OperationNotSupportedException("Cannot connect to Passive Node in Mirror Cluster.");
#endif
_onItemUpdatedCallback = new CustomUpdateCallback(CustomUpdate);
_cache.CustomUpdateCallbackNotif += _onItemUpdatedCallback;
_onItemRemoveCallback = new CustomRemoveCallback(CustomRemove);
_cache.CustomRemoveCallbackNotif += _onItemRemoveCallback;
_pollRequestCallback = new Caching.PollRequestCallback(PollRequest);
_cache.PollRequestCallbackNotif += _pollRequestCallback;
if (SocketServer.Logger.IsErrorLogsEnabled)
{
SocketServer.Logger.NCacheLog.Error(_cacheserver+".ctor", "Registering cache stopped event for " + _client.ClientID);
}
_cacheStopped = new CacheStoppedCallback(OnCacheStopped);
_cache.CacheStopped += _cacheStopped;
if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error(_cacheserver+".ctor", "Cache stopped event registered for " + _client.ClientID);
_asyncOperationCallback = new AsyncOperationCompletedCallback(AsyncOperationCompleted);
_cache.AsyncOperationCompleted += _asyncOperationCallback;
_cacheBecomeActive = new CacheBecomeActiveCallback(OnCacheBecomeActive);
_cache.CacheBecomeActive += _cacheBecomeActive;
_configModified = new ConfigurationModified(OnConfigModified);
_cache.ConfigurationModified += _configModified;
_onCompactTypeModifiedCallback = new CompactTypeModifiedCallback(CompactTypesModified);
_cache.CompactTypeModified += _onCompactTypeModifiedCallback;
_blockClientActivity = new BlockClientActivity(BlockClientActivity);
_cache.BlockActivity += this._blockClientActivity;
_unblockClientActivity = new UnBlockClientActivity(UnBlockClientActivity);
_cache.UnBlockActivity += this._unblockClientActivity;
_operationModeChanged += new OperationModeChangedCallback(OperationModeChanged);
_cache.OperationModeChanged += _operationModeChanged;
}
private void InitAuthorizeCredentials(string userId, string password)
{
}
internal void MaxEventRequirement(EventDataFilter datafilter, NotificationsType eventType, short sequence)
{
switch (eventType)
{
case NotificationsType.RegAddNotif:
lock (sync_lock_AddDataFilter)
{
if (_addSeq < sequence)
{
ItemAddedFilter = datafilter;
_addSeq = sequence;
}
}
break;
case NotificationsType.RegRemoveNotif:
lock (sync_lock_RemoveDataFilter)
{
if (_removeSeq < sequence)
{
ItemRemovedFilter = datafilter;
_removeSeq = sequence;
}
}
break;
case NotificationsType.RegUpdateNotif:
lock (sync_lock_UpdateDataFilter)
{
if (_updateSeq < sequence)
{
ItemUpdatedFilter = datafilter;
_updateSeq = sequence;
}
}
break;
}
}
/// <summary>
/// Get the cacheId
/// </summary>
internal string CacheId
{
get { return _cacheId; }
}
/// <summary>Instance of cache</summary>
/// <remarks>You must obtain lock before using cache</remarks>
internal Alachisoft.NCache.Caching.Cache Cache
{
get { return _cache; }
}
internal AsyncOperationCompletedCallback AsyncOperationCallback
{
get { return _asyncOperationCallback; }
}
internal CustomRemoveCallback RemoveCallback
{
get { return _onItemRemoveCallback; }
}
internal CustomUpdateCallback UpdateCallback
{
get { return _onItemUpdatedCallback; }
}
/// <summary>
/// Determine whether the client connected is a .net client
/// </summary>
internal bool IsDotnetClient
{
get { return this._isDotNetClient; }
}
/// <summary>
/// This function is called by CacheStoppedCallback
/// </summary>
public void OnCacheStopped(string cacheId, EventContext eventContext)
{
//muds:
//first of all fire the CacheStoppedCallback for the remote client.
try
{
if (this._cacheStoppedEventRegistered)
{
CacheStopped();
}
}
catch (Exception e)
{
if (SocketServer.Logger.IsErrorLogsEnabled) SocketServer.Logger.NCacheLog.Error(_cacheserver+".OnCacheStopped", e.ToString());
}
//now break the connection of the socket server with the client.
if (_client != null) _client.OnCacheStopped(cacheId);
}
public void OnCacheBecomeActive(string cacheId, EventContext eventContext)
{
}
/// <summary>
/// Dispose the cahce and Unregister the callbacks being registered with that cache
/// </summary>
public void Dispose()
{
if (_cache != null)
{
UnRegisterNotifications();
}
}
public void DisposeEnumerator(EnumerationPointer pointer)
{
if (_cache != null)
{
//Just a dummy call to dispose enumerator
pointer.isDisposable = true;
pointer.IsSocketServerDispose = true;
_cache.GetNextChunk(pointer, new OperationContext());
}
}
/// <summary>
/// Unregister the callbacks registered with cache
/// </summary>
private void UnRegisterNotifications()
{
if (_onItemUpdatedCallback != null)
{
_cache.CustomUpdateCallbackNotif -= _onItemUpdatedCallback;
_onItemUpdatedCallback = null;
}
if (_onItemRemoveCallback != null)
{
_cache.CustomRemoveCallbackNotif -= _onItemRemoveCallback;
_onItemRemoveCallback = null;
}
if (_pollRequestCallback != null)
{
_cache.PollRequestCallbackNotif -= _pollRequestCallback;
_pollRequestCallback = null;
}
if (_cacheCleared != null)
{
_cache.CacheCleared -= _cacheCleared;
_cacheCleared = null;
}
if (_cacheStopped != null)
{
_cache.CacheStopped -= _cacheStopped;
_cacheStopped = null;
}
if(_onCompactTypeModifiedCallback !=null)
{
_cache.CompactTypeModified -= _onCompactTypeModifiedCallback;
_onCompactTypeModifiedCallback = null;
}
if (_asyncOperationCallback != null)
{
_cache.AsyncOperationCompleted -= _asyncOperationCallback;
_asyncOperationCallback = null;
}
if (_dsUpdatedCallback != null)
{
_cache.DataSourceUpdated -= _dsUpdatedCallback;
_dsUpdatedCallback = null;
}
if (_itemAdded != null)
{
_cache.ItemAdded -= _itemAdded;
_itemAdded = null;
lock (sync_lock_AddDataFilter)
{
ItemAddedFilter = EventDataFilter.None;
_addSeq = -1;
}
}
if (_itemUpdated != null)
{
_cache.ItemUpdated -= _itemUpdated;
_itemUpdated = null;
lock (sync_lock_UpdateDataFilter)
{
ItemUpdatedFilter = EventDataFilter.None;
_updateSeq = -1;
}
}
if (_itemRemoved != null)
{
_cache.ItemRemoved -= _itemRemoved;
_itemRemoved = null;
lock (sync_lock_RemoveDataFilter)
{
ItemRemovedFilter = EventDataFilter.None;
_removeSeq = -1;
}
}
if (_customNotif != null)
{
_cache.CustomNotif -= _customNotif;
_customNotif = null;
}
if (_nodeJoined != null)
{
_cache.MemberJoined -= _nodeJoined;
_nodeJoined = null;
}
if (_nodeLeft != null)
{
_cache.MemberLeft -= _nodeLeft;
_nodeLeft = null;
}
if (_cacheBecomeActive != null)
{
_cache.CacheBecomeActive -= _cacheBecomeActive;
_cacheBecomeActive = null;
}
if (_configModified != null)
{
_cache.ConfigurationModified -= _configModified;
_configModified = null;
}
#if !DEVELOPMENT
if (this._hashmapChanged != null)
{
this._cache.HashmapChanged -= this._hashmapChanged;
_hashmapChanged = null;
}
#endif
if (_operationModeChanged != null)
{
_cache.OperationModeChanged -= _operationModeChanged;
_operationModeChanged = null;
}
if (this._blockClientActivity != null)
{
this._cache.BlockActivity -= this._blockClientActivity;
_blockClientActivity = null;
}
if (this._unblockClientActivity != null)
{
this._cache.UnBlockActivity -= this._unblockClientActivity;
_unblockClientActivity = null;
}
}
/// <summary>
/// Called when an async operation is completed
/// </summary>
/// <param name="key">key being used for async operation</param>
/// <param name="callbackEntry">callback entry being used for async operation</param>
private void AsyncOperationCompleted(object opCode, object result, EventContext eventContext)
{
if (result is object[])
{
if (_client != null)
{
AsyncCallbackInfo cbInfo = ((object[])result)[1] as AsyncCallbackInfo;
if (cbInfo != null && cbInfo.Client != _client.ClientID) return;
//client older then 4.1 sp2 private patch 4 does not support bulk Events
if (_client.ClientVersion >= 4124)
{
object[] package = null;
package = (object[])SerializationUtil.CompactDeserialize(result, _cacheId);
string key = (string)package[0];
AsyncCallbackInfo cbInformation = (AsyncCallbackInfo)package[1];
object opResult = package[2];
Alachisoft.NCache.Common.Protobuf.AsyncOperationCompletedCallbackResponse asyncOperationCompleted = EventHelper.GetAsyncOpCompletedResponse(_client, cbInformation, opResult, opCode, key);
Alachisoft.NCache.Common.Protobuf.BulkEventItemResponse eventitem = new Common.Protobuf.BulkEventItemResponse();
eventitem.eventType = Common.Protobuf.BulkEventItemResponse.EventType.ASYNC_OP_COMPLETED_EVENT;
eventitem.asyncOperationCompletedCallback = asyncOperationCompleted;
//_client.EnqueueEvent(eventitem);
//To avoid NullReference problem if both evnt and NCache.Dispose are called simultaenously
ClientManager client = _client;
if(client != null) client.ConnectionManager.EnqueueEvent(eventitem, _client.SlaveId);
}
else
{
lock (ConnectionManager.CallbackQueue)
{
ConnectionManager.CallbackQueue.Enqueue(new AsyncOpCompletedCallback(/*notification.CallerID,*/ opCode, result, /*notification.ClientSocket,*/ _cacheId));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
}
}
/// <summary>
/// Called to find cache level events status
/// </summary>
public EventStatus GetEventsStatus()
{
EventStatus eventStatus = new EventStatus();
if (_cacheCleared != null)
{
eventStatus.IsCacheClearedEvent = true;
}
if (_itemUpdated != null)
{
eventStatus.IsItemUpdatedEvent = true;
}
if (_itemAdded != null)
{
eventStatus.IsItemAddedEvent = true;
}
if (_itemRemoved != null)
{
eventStatus.IsItemRemovedEvent = true;
}
return eventStatus;
}
/// <summary>
/// Called when item is updated
/// </summary>
/// <param name="key">key of the item being updated</param>
/// <param name="callbackEntry">callback entry that contains the updated value</param>
private void CustomUpdate(object key, object callbackInfo, EventContext eventContext)
{
if (_client != null)
{
CallbackInfo cbInfo = callbackInfo as CallbackInfo;
if (cbInfo != null && cbInfo.Client == _client.ClientID)
{
//client older then 4.1 sp2 private patch 4 does not support bulk Events
if (_client.ClientVersion >= 4124)
{
Alachisoft.NCache.Common.Protobuf.BulkEventItemResponse eventitem = new Common.Protobuf.BulkEventItemResponse();
eventitem.eventType = Common.Protobuf.BulkEventItemResponse.EventType.ITEM_UPDATED_CALLBACK;
eventitem.ItemUpdatedCallback = EventHelper.GetItemUpdatedCallbackResponse(eventContext, (string)key, (short)cbInfo.Callback, cbInfo.DataFilter);
//To avoid NullReference problem if both evnt and NCache.Dispose are called simultaenously
ClientManager client = _client;
if (client != null) client.ConnectionManager.EnqueueEvent(eventitem, _client.SlaveId);
}
else
{
lock (ConnectionManager.CallbackQueue)
{
ConnectionManager.CallbackQueue.Enqueue(new ItemUpdateCallback((short)cbInfo.Callback, (string)key, cbInfo.Client, eventContext, cbInfo.DataFilter));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="callbackEntry"></param>
/// <param name="reason"></param>
private void CustomRemove(object key, object value, ItemRemoveReason reason, BitSet Flag, EventContext eventContext)
{
if (_client != null)
{
object[] args = value as object[];
if (args != null)
{
object val = args[0];
CallbackInfo cbInfo = args[1] as CallbackInfo;
if (cbInfo != null && cbInfo.Client == _client.ClientID)
{
//client older then 4.1 sp2 private patch 4 does not support bulk Events
if (_client.ClientVersion >= 4124)
{
Alachisoft.NCache.Common.Protobuf.BulkEventItemResponse eventItem = new Common.Protobuf.BulkEventItemResponse();
eventItem.eventType = Common.Protobuf.BulkEventItemResponse.EventType.ITEM_REMOVED_CALLBACK;
eventItem.itemRemoveCallback = EventHelper.GetItemRemovedCallbackResponse(eventContext, (short)cbInfo.Callback, (string)key, (UserBinaryObject)val, Flag, reason,cbInfo.DataFilter);
// _client.EnqueueEvent(eventItem);
//To avoid NullReference problem if both evnt and NCache.Dispose are called simultaenously
ClientManager client = _client;
if (client != null) client.ConnectionManager.EnqueueEvent(eventItem, _client.SlaveId);
}
else
{
lock (ConnectionManager.CallbackQueue)
{
ConnectionManager.CallbackQueue.Enqueue(new ItemRemoveCallback((short)cbInfo.Callback, (string)key, val, reason, _client.ClientID, Flag, eventContext,cbInfo.DataFilter));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
}
}
}
private void PollRequest(string clientId, short callbackId, EventTypeInternal eventType)
{
if (_client != null)
{
//client older then 4.1 sp2 private patch 4 does not support bulk Events
if (_client.ClientVersion >= 4124)
{
Alachisoft.NCache.Common.Protobuf.BulkEventItemResponse eventItem = new Common.Protobuf.BulkEventItemResponse();
eventItem.eventType = Common.Protobuf.BulkEventItemResponse.EventType.POLL_NOTIFY_EVENT;
eventItem.pollNotifyEvent = EventHelper.GetPollNotifyEvent(callbackId, eventType);
//To avoid NullReference problem if both evnt and NCache.Dispose are called simultaenously
ClientManager client = _client;
if (client != null) client.ConnectionManager.EnqueueEvent(eventItem, _client.SlaveId);
}
else
{
lock (ConnectionManager.CallbackQueue)
{
ConnectionManager.CallbackQueue.Enqueue(new CallbackTasks.PollRequestCallback(_client.ClientID, callbackId, eventType));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="updatedCompactTypes"></param>
private void CompactTypesModified(Hashtable updatedCompactTypes, EventContext eventContext)
{
if (_client != null)
{
lock (ConnectionManager.CallbackQueue)
{
ConnectionManager.CallbackQueue.Enqueue(new CompactTypeRegisterCallback(updatedCompactTypes));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
/// <summary>
/// This function is called by ConfigurationModified callback
/// </summary>
/// <param name="hotConfig"></param>
private void OnConfigModified(HotConfig hotConfig)
{
lock (ConnectionManager.CallbackQueue)
{
if (_client != null)
{
ConnectionManager.CallbackQueue.Enqueue(new ConfigModifiedEvent(hotConfig, _cacheId, _client.ClientID));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
/// <summary>
/// Notify the connected client about logging information change
/// </summary>
/// <param name="enableErrorLogs"></param>
/// <param name="enableDetailedLogs"></param>
/// <param name="clientId"></param>
internal void OnLoggingInfoModified(bool enableErrorLogs, bool enableDetailedLogs, string clientId)
{
lock (ConnectionManager.CallbackQueue)
{
if (_client != null)
{
ConnectionManager.CallbackQueue.Enqueue(new LoggingInfoModifiedEvent(enableErrorLogs, enableDetailedLogs, clientId));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
/// <summary>
/// This function is called by ItemAddedCallback
/// </summary>
/// <param name="key"></param>
private void ItemAdded(object key, EventContext eventContext)
{
if (_client != null)
{
//client older then 4.1 sp2 private patch 4 does not support bulk Events
if (_client.ClientVersion >= 4124)
{
Alachisoft.NCache.Common.Protobuf.BulkEventItemResponse eventitem = new Common.Protobuf.BulkEventItemResponse();
eventitem.eventType = Common.Protobuf.BulkEventItemResponse.EventType.ITEM_ADDED_EVENT;
eventitem.itemAddedEvent = EventHelper.GetItemAddedEventResponse(eventContext, (string)key, this.ItemAddedFilter);
//_client.EnqueueEvent(eventitem);
//To avoid NullReference problem if both evnt and NCache.Dispose are called simultaenously
ClientManager client = _client;
if (client != null) client.ConnectionManager.EnqueueEvent(eventitem, _client.SlaveId);
}
else
{
lock (ConnectionManager.CallbackQueue)
{
if (_client != null)
{
ConnectionManager.CallbackQueue.Enqueue(new ItemAddedEvent((string)key, _cacheId, _client.ClientID, eventContext, this.ItemAddedFilter));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
}
}
/// <summary>
/// This function is called by ItemUpdatedCallback
/// </summary>
/// <param name="key"></param>
private void ItemUpdated(object key, EventContext eventContext)
{
if (_client != null)
{
//client older then 4.1 sp2 private patch 4 does not support bulk Events
if (_client.ClientVersion >= 4124)
{
Alachisoft.NCache.Common.Protobuf.BulkEventItemResponse eventItem = new Common.Protobuf.BulkEventItemResponse();
eventItem.eventType = Common.Protobuf.BulkEventItemResponse.EventType.ITEM_UPDATED_EVENT;
eventItem.itemUpdatedEvent = EventHelper.GetItemUpdatedEventResponse(eventContext, (string)key, this.ItemUpdatedFilter);
//To avoid NullReference problem if both evnt and NCache.Dispose are called simultaenously
ClientManager client = _client;
if (client != null) client.ConnectionManager.EnqueueEvent(eventItem, _client.SlaveId);
}
else
{
lock (ConnectionManager.CallbackQueue)
{
if (_client != null)
{
ConnectionManager.CallbackQueue.Enqueue(new ItemUpdatedEvent((string)key, _cacheId, _client.ClientID, eventContext));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
}
}
/// <summary>
/// This function is called by ItemRemovedCallback
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="reason"></param>
private void ItemRemoved(object key, object value, ItemRemoveReason reason, BitSet Flag, EventContext eventContext)
{
//value which arrives will be null
value = eventContext.Item.Value;
if (_client != null)
{
//client older then 4.1 sp2 private patch 4 does not support bulk Events
if (_client.ClientVersion >= 4124)
{
Alachisoft.NCache.Common.Protobuf.BulkEventItemResponse eventItem = new Common.Protobuf.BulkEventItemResponse();
eventItem.eventType = Common.Protobuf.BulkEventItemResponse.EventType.ITEM_REMOVED_EVENT;
eventItem.itemRemovedEvent = EventHelper.GetItemRemovedEventResponse(eventContext, (string)key, this.ItemRemovedFilter, Flag, reason, (UserBinaryObject)value);
// _client.EnqueueEvent(eventItem);
//To avoid NullReference problem if both evnt and NCache.Dispose are called simultaenously
ClientManager client = _client;
if (client != null) client.ConnectionManager.EnqueueEvent(eventItem, _client.SlaveId);
}
else
{
lock (ConnectionManager.CallbackQueue)
{
ConnectionManager.CallbackQueue.Enqueue(new ItemRemovedEvent((string)key, _cacheId, reason, (UserBinaryObject)value, _client.ClientID, Flag, eventContext));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
}
/// <summary>
/// This function is called by cacheClearedCallback
/// </summary>
private void CacheCleared(EventContext eventContext)
{
if (_client != null)
{
//client older then 4.1 sp2 private patch 4 does not support bulk Events
if (_client.ClientVersion >= 4124)
{
Alachisoft.NCache.Common.Protobuf.BulkEventItemResponse eventItem = new Common.Protobuf.BulkEventItemResponse();
eventItem.eventType = Common.Protobuf.BulkEventItemResponse.EventType.CACHE_CLEARED_EVENT;
eventItem.cacheClearedEvent = EventHelper.GetCacheClearedResponse(eventContext);
//_client.EnqueueEvent(eventItem);
//To avoid NullReference problem if both evnt and NCache.Dispose are called simultaenously
ClientManager client = _client;
if (client != null) client.ConnectionManager.EnqueueEvent(eventItem, _client.SlaveId);
}
else
{
lock (ConnectionManager.CallbackQueue)
{
ConnectionManager.CallbackQueue.Enqueue(new CacheClearedEvent(_cacheId, _client.ClientID, eventContext));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
}
/// <summary>
/// This function is called by CacheStopedCallback
/// </summary>
private void CacheStopped()
{
if (_client != null)
{
//client older then 4.1 sp2 private patch 4 does not support bulk Events
if (_client.ClientVersion >= 4124)
{
Alachisoft.NCache.Common.Protobuf.BulkEventItemResponse eventItem = new Common.Protobuf.BulkEventItemResponse();
eventItem.eventType = Common.Protobuf.BulkEventItemResponse.EventType.CACHE_STOPPED_EVENT;
eventItem.cacheStoppedEvent = EventHelper.GetCacheStoppedEventResponse(_cacheId);
//_client.EnqueueEvent(eventItem);
//To avoid NullReference problem if both evnt and NCache.Dispose are called simultaenously
ClientManager client = _client;
if (client != null) client.ConnectionManager.EnqueueEvent(eventItem, _client.SlaveId);
}
else
{
lock (ConnectionManager.CallbackQueue)
{
ConnectionManager.CallbackQueue.Enqueue(new CacheStoppedEvent(_cacheId, _client.ClientID));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="notifId"></param>
/// <param name="value"></param>
private void CustomNotification(object notifId, object value, EventContext eventContext)
{
if (_client != null)
{
//client older then 4.1 sp2 private patch 4 does not support bulk Events
if (_client.ClientVersion >= 4124)
{
Alachisoft.NCache.Common.Protobuf.BulkEventItemResponse eventItem = new Common.Protobuf.BulkEventItemResponse();
eventItem.eventType = Common.Protobuf.BulkEventItemResponse.EventType.RAISE_CUSTOM_EVENT;
eventItem.CustomEvent = EventHelper.GetCustomEventResponse((byte[])notifId, (byte[])value);
//_client.EnqueueEvent(eventItem);
//To avoid NullReference problem if both evnt and NCache.Dispose are called simultaenously
ClientManager client = _client;
if (client != null) client.ConnectionManager.EnqueueEvent(eventItem, _client.SlaveId);
}
else
{
lock (ConnectionManager.CallbackQueue)
{
if (_client == null) return;
ConnectionManager.CallbackQueue.Enqueue(new CustomEvent(_cacheId, (byte[])notifId, (byte[])value, _client.ClientID));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
}
/// <summary>
/// This function is called by NodeJoinedCallback
/// </summary>
/// <param name="notifId"></param>
/// <param name="value"></param>
private void NodeJoined(object clusterAddress, object serverAddress, bool reconnect, EventContext eventContext)
{
lock (ConnectionManager.CallbackQueue)
{
if (_client == null) return;
ConnectionManager.CallbackQueue.Enqueue(new NodeJoinedEvent(_cacheId, clusterAddress as Alachisoft.NCache.Common.Net.Address, serverAddress as Alachisoft.NCache.Common.Net.Address, _client.ClientID, reconnect));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
/// <summary>
/// This function is called by NodeLeftCallback
/// </summary>
/// <param name="notifId"></param>
/// <param name="value"></param>
private void NodeLeft(object clusterAddress, object serverAddress, EventContext eventContext)
{
lock (ConnectionManager.CallbackQueue)
{
if (_client == null) return;
ConnectionManager.CallbackQueue.Enqueue(new NodeLeftEvent(_cacheId, clusterAddress as Alachisoft.NCache.Common.Net.Address, serverAddress as Alachisoft.NCache.Common.Net.Address, _client.ClientID));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
private void OnCacheClientConnectivityChanged(string cacheId, Runtime.Caching.ClientInfo client)
{
if (_client != null)
{
if (_client.ClientVersion >= 4124)
{
BulkEventItemResponse eventItem = new BulkEventItemResponse();
eventItem.eventType = BulkEventItemResponse.EventType.CLIENT_CONNECTIVITY;
eventItem.clientConnectivityChangeEvent =
EventHelper.GetClientConnectivityChangeEventResponse(cacheId, client);
ClientManager clientReference = _client;
if (clientReference != null)
clientReference.ConnectionManager.EnqueueEvent(eventItem, clientReference.SlaveId);
}
}
}
#if !DEVELOPMENT
private void HashmapChanged(NewHashmap newmap, EventContext eventContext)
{
lock (ConnectionManager.CallbackQueue)
{
if (_client != null)
{
ConnectionManager.CallbackQueue.Enqueue(new HashmapChangedEvent(_cacheId, _client.ClientID, newmap, this._isDotNetClient));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
#endif
private void BlockClientActivity(string uniqueId, string serverIp, long timeoutInterval, int port)
{
lock (ConnectionManager.CallbackQueue)
{
if (_client != null)
{
ConnectionManager.CallbackQueue.Enqueue(new BlockActivityEvent(uniqueId, _cacheId, _client.ClientID, serverIp, timeoutInterval, port));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
private void UnBlockClientActivity(string uniqueId, string serverIp, int port)
{
lock (ConnectionManager.CallbackQueue)
{
if (_client != null)
{
ConnectionManager.CallbackQueue.Enqueue(new UnBlockActivityEvent(uniqueId, _cacheId, _client.ClientID, serverIp, port));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
private void OperationModeChanged(OperationMode mode)
{
if (mode == OperationMode.OFFLINE)
{
lock (ConnectionManager.CallbackQueue)
{
if (_client != null)
{
ConnectionManager.CallbackQueue.Enqueue(new OperationModeChangedEvent(_client.ClientID));
Monitor.Pulse(ConnectionManager.CallbackQueue);
}
}
}
}
#region ICommandExecuter Members
public string ID
{
get
{
return _cacheId;
}
}
public void OnClientConnected(string clientID, string cacheId, Runtime.Caching.ClientInfo clientInfo, long count)
{
if (_cache != null) _cache.OnClientConnected(clientID, cacheId, clientInfo, count);
}
/// <summary>
/// This function is called client is dis-connected
/// </summary>
/// <param name="clientID"></param>
/// <param name="cacheId"></param>
public void OnClientDisconnected(string clientID, string cacheId, Runtime.Caching.ClientInfo clientInfo, long count)
{
if (_cache != null) _cache.OnClientDisconnected(clientID, cacheId, clientInfo, count);
}
//fix for BroadAge 4.1 Sp2 patch 4
//forcefully disconnected when Socket is busy for more then configured interval
public void OnClientForceFullyDisconnected(string clientId)
{
if (_cache != null) _cache.OnClientForceFullyDisconnected(clientId);
}
public void UpdateSocketServerStats(SocketServerStats stats)
{
if (_cache != null) _cache.UpdateSocketServerStats(stats);
}
public bool IsCoordinator(string srcCacheID)
{
//we need not to implement this function here have implemented it in NBridge.cs. Just returning true in all cases.
return false;
}
/// <summary>
/// Register callbacks with cache.
/// </summary>
/// <param name="type"></param>
public void RegisterNotification(NotificationsType type)
{
switch (type)
{
case NotificationsType.RegAddNotif:
if (_itemAdded == null)
{
_itemAdded = new ItemAddedCallback(ItemAdded);
_cache.ItemAdded += _itemAdded;
}
break;
case NotificationsType.RegUpdateNotif:
if (_itemUpdated == null)
{
_itemUpdated = new ItemUpdatedCallback(ItemUpdated);
_cache.ItemUpdated += _itemUpdated;
}
break;
case NotificationsType.RegRemoveNotif:
if (_itemRemoved == null)
{
_itemRemoved = new ItemRemovedCallback(ItemRemoved);
_cache.ItemRemoved += _itemRemoved;
}
break;
case NotificationsType.RegClearNotif:
if (_cacheCleared == null)
{
_cacheCleared = new CacheClearedCallback(CacheCleared);
_cache.CacheCleared += _cacheCleared;
}
break;
case NotificationsType.RegCustomNotif:
if (_customNotif == null)
{
_customNotif = new CustomNotificationCallback(CustomNotification);
_cache.CustomNotif += _customNotif;
}
break;
case NotificationsType.RegNodeJoinedNotif:
if (_nodeJoined == null)
{
_nodeJoined = new NodeJoinedCallback(NodeJoined);
_cache.MemberJoined += _nodeJoined;
}
break;
case NotificationsType.RegNodeLeftNotif:
if (_nodeLeft == null)
{
_nodeLeft = new NodeLeftCallback(NodeLeft);
_cache.MemberLeft += _nodeLeft;
}
break;
case NotificationsType.RegCacheStoppedNotif:
_cacheStopped = new CacheStoppedCallback(OnCacheStopped);
_cache.CacheStopped += _cacheStopped;
this._cacheStoppedEventRegistered = true;
break;
#if !DEVELOPMENT
case NotificationsType.RegHashmapChangedNotif:
if (this._hashmapChanged == null)
{
this._hashmapChanged = new HashmapChangedCallback(HashmapChanged);
this._cache.HashmapChanged += this._hashmapChanged;
}
break;
#endif
case NotificationsType.UnregAddNotif:
if (_itemAdded != null)
{
_cache.ItemAdded -= _itemAdded;
_itemAdded = null;
lock (sync_lock_AddDataFilter)
{
ItemAddedFilter = EventDataFilter.None;
_addSeq = -1;
}
}
break;
case NotificationsType.UnregUpdateNotif:
if (_itemUpdated != null)
{
_cache.ItemUpdated -= _itemUpdated;
_itemUpdated = null;
lock (sync_lock_UpdateDataFilter = -1)
{
ItemUpdatedFilter = EventDataFilter.None;
_updateSeq = -1;
}
}
break;
case NotificationsType.UnregRemoveNotif:
if (_itemRemoved != null)
{
_cache.ItemRemoved -= _itemRemoved;
_itemRemoved = null;
lock (sync_lock_RemoveDataFilter)
{
ItemRemovedFilter = EventDataFilter.None;
_removeSeq = -1;
}
}
break;
case NotificationsType.UnregClearNotif:
if (_cacheCleared != null)
{
_cache.CacheCleared -= _cacheCleared;
_cacheCleared = null;
}
break;
case NotificationsType.UnregCustomNotif:
if (_customNotif != null)
{
_cache.CustomNotif -= _customNotif;
_customNotif = null;
}
break;
case NotificationsType.UnregNodeJoinedNotif:
if (_nodeJoined != null)
{
_cache.MemberJoined -= _nodeJoined;
_nodeJoined = null;
}
break;
case NotificationsType.UnregNodeLeftNotif:
if (_nodeLeft != null)
{
_cache.MemberLeft -= _nodeLeft;
_nodeLeft = null;
}
break;
case NotificationsType.UnregCacheStoppedNotif:
this._cacheStoppedEventRegistered = false;
break;
#if !DEVELOPMENT
case NotificationsType.UnregHashmapChangedNotif:
if (this._hashmapChanged != null)
{
this._cache.HashmapChanged -= this._hashmapChanged;
this._hashmapChanged = null;
}
break;
#endif
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MinSingle()
{
var test = new SimpleBinaryOpTest__MinSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MinSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<Single> _fld1;
public Vector256<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MinSingle testClass)
{
var result = Avx.Min(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinSingle testClass)
{
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
{
var result = Avx.Min(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MinSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
}
public SimpleBinaryOpTest__MinSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Min(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Min(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Min(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Min), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Min), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Min), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Min(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Single>* pClsVar1 = &_clsVar1)
fixed (Vector256<Single>* pClsVar2 = &_clsVar2)
{
var result = Avx.Min(
Avx.LoadVector256((Single*)(pClsVar1)),
Avx.LoadVector256((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var result = Avx.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Min(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MinSingle();
var result = Avx.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__MinSingle();
fixed (Vector256<Single>* pFld1 = &test._fld1)
fixed (Vector256<Single>* pFld2 = &test._fld2)
{
var result = Avx.Min(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Min(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Single>* pFld1 = &_fld1)
fixed (Vector256<Single>* pFld2 = &_fld2)
{
var result = Avx.Min(
Avx.LoadVector256((Single*)(pFld1)),
Avx.LoadVector256((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.Min(
Avx.LoadVector256((Single*)(&test._fld1)),
Avx.LoadVector256((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<Single> op1, Vector256<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(MathF.Min(left[0], right[0])) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(MathF.Min(left[i], right[i])) != BitConverter.SingleToInt32Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Min)}<Single>(Vector256<Single>, Vector256<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
#endregion // Namespaces
namespace FireRatingCloud
{
/// <summary>
/// Export all target element ids and their
/// FireRating parameter values to external database.
/// </summary>
[Transaction( TransactionMode.ReadOnly )]
public class Cmd_2a_ExportSharedParameterValues
: IExternalCommand
{
#region Project
#if NEED_PROJECT_DOCUMENT
/// <summary>
/// Retrieve the project identification information
/// to store in the external database and return it
/// as a dictionary in a JSON formatted string.
/// </summary>
string GetProjectDataJson(
//string project_id,
Document doc )
{
string path = doc.PathName.Replace( '\\', '/' );
BasicFileInfo file_info = BasicFileInfo.Extract( path );
DocumentVersion doc_version = file_info.GetDocumentVersion();
ModelPath model_path = doc.GetWorksharingCentralModelPath();
string central_server_path = null != model_path
? model_path.CentralServerPath
: string.Empty;
// Hand-written JSON formatting.
string s = string.Format(
//"\"_id\": \"{0}\","
"\"projectinfo_uid\": \"{0}\","
+ "\"versionguid\": \"{1}\","
+ "\"numberofsaves\": {2},"
+ "\"title\": \"{3}\","
+ "\"centralserverpath\": \"{4}\","
+ "\"path\": \"{5}\","
+ "\"computername\": \"{6}\","
+ "\"jid\": \"{7}\"",
//project_id,
doc.ProjectInformation.UniqueId,
doc_version.VersionGUID,
doc_version.NumberOfSaves,
doc.Title,
central_server_path,
path,
System.Environment.MachineName,
Util.GetProjectIdentifier( doc ) );
return "{" + s + "}";
#region Use JavaScriptSerializer
#if USE_JavaScriptSerializer
// Use JavaScriptSerializer to format JSON data.
ProjectData project_data = new ProjectData()
{
projectinfo_uid = doc.ProjectInformation.UniqueId,
versionguid = doc_version.VersionGUID.ToString(),
numberofsaves = doc_version.NumberOfSaves,
title = doc.Title,
centralserverpath = central_server_path,
path = path,
computername = System.Environment.MachineName
};
return new JavaScriptSerializer().Serialize(
project_data );
#endif // USE_JavaScriptSerializer
#endregion // Use JavaScriptSerializer
}
#endif // NEED_PROJECT_DOCUMENT
#endregion // Project
#region Obsolete code
/// <summary>
/// Retrieve the door instance data to store in
/// the external database and return it as a
/// dictionary-like object.
/// Obsolete, replaced by DoorData constructor.
/// </summary>
object GetDoorData(
Element door,
string project_id,
Guid paramGuid )
{
Document doc = door.Document;
string levelName = doc.GetElement(
door.LevelId ).Name;
string tagValue = door.get_Parameter(
BuiltInParameter.ALL_MODEL_MARK ).AsString();
double fireratingValue = door.get_Parameter(
paramGuid ).AsDouble();
object data = new
{
_id = door.UniqueId,
project_id = project_id,
level = levelName,
tag = tagValue,
firerating = fireratingValue
};
return data;
}
#endregion // Obsolete code
public static Result ExportOneByOne(
FilteredElementCollector doors,
Guid paramGuid,
string project_id,
uint timestamp,
ref string message )
{
#region Project
#if NEED_PROJECT_DOCUMENT
// Post project data.
string project_id = string.Empty;
object obj;
Hashtable d;
// curl -i -X POST -H 'Content-Type: application/json' -d '{
// "projectinfo_uid": "8764c510-57b7-44c3-bddf-266d86c26380-0000c160",
// "versionguid": "f498e8b1-7311-4409-a669-2fd290356bb4",
// "numberofsaves": 271,
// "title": "rac_basic_sample_project.rvt",
// "centralserverpath": "",
// "path": "C:/Program Files/Autodesk/Revit 2016/Samples/rac_basic_sample_project.rvt",
// "computername": "JEREMYTAMMIB1D2" }'
// http://localhost:3001/api/v1/projects
string json = GetProjectDataJson( doc );
Debug.Print( json );
string jsonResponse = string.Empty;
try
{
jsonResponse = Util.QueryOrUpsert(
"projects/jid/" + jid, string.Empty, "GET" );
}
catch( System.Net.WebException ex )
{
}
if( 0 == jsonResponse.Length )
{
jsonResponse = Util.QueryOrUpsert(
"projects", json, "POST" );
}
else
{
jsonResponse = Util.QueryOrUpsert(
"projects/" + project_id, json, "PUT" );
}
Debug.Print( jsonResponse );
obj = JsonParser.JsonDecode( jsonResponse );
if( null != obj )
{
d = obj as Hashtable;
project_id = d["_id"] as string;
}
//if( null != project_id )
//{
// jsonResponse = Util.QueryOrUpsert(
// "projects/" + project_id, json, "PUT" );
// Debug.Assert(
// jsonResponse.Equals( "Accepted" ),
// "expected successful db update response" );
// if( !jsonResponse.Equals( "Accepted" ) )
// {
// project_id = null;
// }
//}
//else
//{
// jsonResponse = Util.QueryOrUpsert(
// "projects", json, "POST" );
// Debug.Print( jsonResponse );
// obj = JsonParser.JsonDecode( jsonResponse );
// if( null != obj )
// {
// d = obj as Hashtable;
// project_id = d["_id"] as string;
// }
//}
if( !string.IsNullOrEmpty( project_id ) )
{
#endif // NEED_PROJECT_DOCUMENT
#endregion // Project
// Loop through the selected doors and export
// their shared parameter value one by one.
DoorData doorData;
HttpStatusCode sc;
string jsonResponse, errorMessage;
Result rc = Result.Succeeded;
//collector.Select<Element, string>(
// d => Util.Put( "doors/" + d.UniqueId,
// new DoorData( d, project_id, paramGuid ) ) );
foreach( Element e in doors )
{
//Debug.Print( e.Id.IntegerValue.ToString() );
doorData = new DoorData( e,
project_id, paramGuid, timestamp );
sc = Util.Put( out jsonResponse,
out errorMessage,
"doors/" + e.UniqueId, doorData );
if( 0 == (int) sc )
{
message = errorMessage;
rc = Result.Failed;
break;
}
//Util.Log( jsonResponse );
}
return rc;
}
public static Result ExportBatch(
FilteredElementCollector doors,
Guid paramGuid,
string project_id,
uint timestamp,
ref string message )
{
// Loop through the selected doors and export
// their shared parameter value in one single
// batch call.
int n = doors.Count<Element>();
List<FireRating.DoorData> doorData
= new List<FireRating.DoorData>( n );
HttpStatusCode sc;
string jsonResponse, errorMessage;
Result rc = Result.Succeeded;
foreach( Element e in doors )
{
//Util.Log( e.Id.IntegerValue.ToString() );
doorData.Add( new DoorData( e,
project_id, paramGuid, timestamp ) );
//Util.Log( jsonResponse );
}
string query = "doors/project/" + project_id;
string content = Util.Delete( query );
sc = Util.PostBatch( out jsonResponse,
out errorMessage, "doors", doorData );
if( 0 == (int) sc )
{
message = errorMessage;
rc = Result.Failed;
}
return rc;
}
public static Result ExportMain(
bool useBatch,
ExternalCommandData commandData,
ref string message )
{
UIApplication uiapp = commandData.Application;
Application app = uiapp.Application;
Document doc = uiapp.ActiveUIDocument.Document;
// Get shared parameter GUID.
Guid paramGuid;
if( !Util.GetSharedParamGuid( app, out paramGuid ) )
{
message = "Shared parameter GUID not found.";
return Result.Failed;
}
// Determine custom project identifier.
string project_id = Util.GetProjectIdentifier( doc );
// Determine timestamp.
uint timestamp = Util.UnixTimestamp();
// Loop through all elements of the given target
// category and export the shared parameter value
// specified by paramGuid for each.
//FilteredElementCollector collector
// = Util.GetTargetInstances( doc,
// Cmd_1_CreateAndBindSharedParameter.Target );
FilteredElementCollector collector
= new FilteredElementCollector( doc )
.OfClass( typeof( FamilyInstance ) )
.OfCategory( BuiltInCategory.OST_Doors );
int n = collector.Count<Element>();
Util.Log( string.Format(
"Exporting {0} element{1} {2}.",
n, Util.PluralSuffix( n ),
(useBatch ? "in batch" : "one by one" ) ) );
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Result rc = useBatch
? ExportBatch( collector, paramGuid,
project_id, timestamp, ref message )
: ExportOneByOne( collector, paramGuid,
project_id, timestamp, ref message );
stopwatch.Stop();
Util.Log( string.Format(
"{0} milliseconds to export {1} element{2}: {3}.",
stopwatch.ElapsedMilliseconds,
n, Util.PluralSuffix( n ), rc ) );
return rc;
}
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
return ExportMain( false, commandData,
ref message );
}
}
}
| |
using UnityEngine;
using System.Collections;
public class MeshCombineUtility {
public struct MeshInstance
{
public Mesh mesh;
public int subMeshIndex;
public Matrix4x4 transform;
}
public static Mesh Combine (MeshInstance[] combines, bool generateStrips)
{
int vertexCount = 0;
int triangleCount = 0;
int stripCount = 0;
foreach( MeshInstance combine in combines )
{
if (combine.mesh)
{
vertexCount += combine.mesh.vertexCount;
if (generateStrips)
{
// SUBOPTIMAL FOR PERFORMANCE
int curStripCount = combine.mesh.GetTriangles(combine.subMeshIndex).Length;
if (curStripCount != 0)
{
if( stripCount != 0 )
{
if ((stripCount & 1) == 1 )
stripCount += 3;
else
stripCount += 2;
}
stripCount += curStripCount;
}
else
{
generateStrips = false;
}
}
}
}
// Precomputed how many triangles we need instead
if (!generateStrips)
{
foreach( MeshInstance combine in combines )
{
if (combine.mesh)
{
triangleCount += combine.mesh.GetTriangles(combine.subMeshIndex).Length;
}
}
}
Vector3[] vertices = new Vector3[vertexCount] ;
Vector3[] normals = new Vector3[vertexCount] ;
Vector4[] tangents = new Vector4[vertexCount] ;
Vector2[] uv = new Vector2[vertexCount];
Vector2[] uv1 = new Vector2[vertexCount];
Color[] colors = new Color[vertexCount];
int[] triangles = new int[triangleCount];
int[] strip = new int[stripCount];
int offset;
offset=0;
foreach( MeshInstance combine in combines )
{
if (combine.mesh)
Copy(combine.mesh.vertexCount, combine.mesh.vertices, vertices, ref offset, combine.transform);
}
offset=0;
foreach( MeshInstance combine in combines )
{
if (combine.mesh)
{
Matrix4x4 invTranspose = combine.transform;
invTranspose = invTranspose.inverse.transpose;
CopyNormal(combine.mesh.vertexCount, combine.mesh.normals, normals, ref offset, invTranspose);
}
}
offset=0;
foreach( MeshInstance combine in combines )
{
if (combine.mesh)
{
Matrix4x4 invTranspose = combine.transform;
invTranspose = invTranspose.inverse.transpose;
CopyTangents(combine.mesh.vertexCount, combine.mesh.tangents, tangents, ref offset, invTranspose);
}
}
offset=0;
foreach( MeshInstance combine in combines )
{
if (combine.mesh)
Copy(combine.mesh.vertexCount, combine.mesh.uv, uv, ref offset);
}
offset=0;
foreach( MeshInstance combine in combines )
{
if (combine.mesh)
Copy(combine.mesh.vertexCount, combine.mesh.uv1, uv1, ref offset);
}
offset=0;
foreach( MeshInstance combine in combines )
{
if (combine.mesh)
CopyColors(combine.mesh.vertexCount, combine.mesh.colors, colors, ref offset);
}
int triangleOffset=0;
int stripOffset=0;
int vertexOffset=0;
foreach( MeshInstance combine in combines )
{
if (combine.mesh)
{
if (generateStrips)
{
int[] inputstrip = combine.mesh.GetTriangles(combine.subMeshIndex);
if (stripOffset != 0)
{
if ((stripOffset & 1) == 1)
{
strip[stripOffset+0] = strip[stripOffset-1];
strip[stripOffset+1] = inputstrip[0] + vertexOffset;
strip[stripOffset+2] = inputstrip[0] + vertexOffset;
stripOffset+=3;
}
else
{
strip[stripOffset+0] = strip[stripOffset-1];
strip[stripOffset+1] = inputstrip[0] + vertexOffset;
stripOffset+=2;
}
}
for (int i=0;i<inputstrip.Length;i++)
{
strip[i+stripOffset] = inputstrip[i] + vertexOffset;
}
stripOffset += inputstrip.Length;
}
else
{
int[] inputtriangles = combine.mesh.GetTriangles(combine.subMeshIndex);
for (int i=0;i<inputtriangles.Length;i++)
{
triangles[i+triangleOffset] = inputtriangles[i] + vertexOffset;
}
triangleOffset += inputtriangles.Length;
}
vertexOffset += combine.mesh.vertexCount;
}
}
Mesh mesh = new Mesh();
mesh.name = "Combined Mesh";
mesh.vertices = vertices;
mesh.normals = normals;
mesh.colors = colors;
mesh.uv = uv;
mesh.uv1 = uv1;
mesh.tangents = tangents;
// if (generateStrips)
// mesh.SetTriangles(strip, 0);
// else
mesh.triangles = triangles;
return mesh;
}
static void Copy (int vertexcount, Vector3[] src, Vector3[] dst, ref int offset, Matrix4x4 transform)
{
for (int i=0;i<src.Length;i++)
dst[i+offset] = transform.MultiplyPoint(src[i]);
offset += vertexcount;
}
static void CopyNormal (int vertexcount, Vector3[] src, Vector3[] dst, ref int offset, Matrix4x4 transform)
{
for (int i=0;i<src.Length;i++)
dst[i+offset] = transform.MultiplyVector(src[i]).normalized;
offset += vertexcount;
}
static void Copy (int vertexcount, Vector2[] src, Vector2[] dst, ref int offset)
{
for (int i=0;i<src.Length;i++)
dst[i+offset] = src[i];
offset += vertexcount;
}
static void CopyColors (int vertexcount, Color[] src, Color[] dst, ref int offset)
{
for (int i=0;i<src.Length;i++)
dst[i+offset] = src[i];
offset += vertexcount;
}
static void CopyTangents (int vertexcount, Vector4[] src, Vector4[] dst, ref int offset, Matrix4x4 transform)
{
for (int i=0;i<src.Length;i++)
{
Vector4 p4 = src[i];
Vector3 p = new Vector3(p4.x, p4.y, p4.z);
p = transform.MultiplyVector(p).normalized;
dst[i+offset] = new Vector4(p.x, p.y, p.z, p4.w);
}
offset += vertexcount;
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Redis.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using apis = Google.Cloud.Redis.V1;
using Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>Generated snippets</summary>
public class GeneratedCloudRedisClientSnippets
{
/// <summary>Snippet for ListInstancesAsync</summary>
public async Task ListInstancesAsync()
{
// Snippet: ListInstancesAsync(LocationName,string,int?,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = await CloudRedisClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = new LocationName("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListInstancesResponse, Instance> response =
cloudRedisClient.ListInstancesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Instance item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListInstancesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Instance item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Instance> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Instance item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListInstances</summary>
public void ListInstances()
{
// Snippet: ListInstances(LocationName,string,int?,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = CloudRedisClient.Create();
// Initialize request argument(s)
LocationName parent = new LocationName("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<ListInstancesResponse, Instance> response =
cloudRedisClient.ListInstances(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Instance item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListInstancesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Instance item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Instance> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Instance item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListInstancesAsync</summary>
public async Task ListInstancesAsync_RequestObject()
{
// Snippet: ListInstancesAsync(ListInstancesRequest,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = await CloudRedisClient.CreateAsync();
// Initialize request argument(s)
ListInstancesRequest request = new ListInstancesRequest
{
ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedAsyncEnumerable<ListInstancesResponse, Instance> response =
cloudRedisClient.ListInstancesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Instance item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListInstancesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Instance item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Instance> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Instance item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListInstances</summary>
public void ListInstances_RequestObject()
{
// Snippet: ListInstances(ListInstancesRequest,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = CloudRedisClient.Create();
// Initialize request argument(s)
ListInstancesRequest request = new ListInstancesRequest
{
ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
};
// Make the request
PagedEnumerable<ListInstancesResponse, Instance> response =
cloudRedisClient.ListInstances(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Instance item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListInstancesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Instance item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Instance> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Instance item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetInstanceAsync</summary>
public async Task GetInstanceAsync()
{
// Snippet: GetInstanceAsync(InstanceName,CallSettings)
// Additional: GetInstanceAsync(InstanceName,CancellationToken)
// Create client
CloudRedisClient cloudRedisClient = await CloudRedisClient.CreateAsync();
// Initialize request argument(s)
InstanceName name = new InstanceName("[PROJECT]", "[LOCATION]", "[INSTANCE]");
// Make the request
Instance response = await cloudRedisClient.GetInstanceAsync(name);
// End snippet
}
/// <summary>Snippet for GetInstance</summary>
public void GetInstance()
{
// Snippet: GetInstance(InstanceName,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = CloudRedisClient.Create();
// Initialize request argument(s)
InstanceName name = new InstanceName("[PROJECT]", "[LOCATION]", "[INSTANCE]");
// Make the request
Instance response = cloudRedisClient.GetInstance(name);
// End snippet
}
/// <summary>Snippet for GetInstanceAsync</summary>
public async Task GetInstanceAsync_RequestObject()
{
// Snippet: GetInstanceAsync(GetInstanceRequest,CallSettings)
// Additional: GetInstanceAsync(GetInstanceRequest,CancellationToken)
// Create client
CloudRedisClient cloudRedisClient = await CloudRedisClient.CreateAsync();
// Initialize request argument(s)
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
// Make the request
Instance response = await cloudRedisClient.GetInstanceAsync(request);
// End snippet
}
/// <summary>Snippet for GetInstance</summary>
public void GetInstance_RequestObject()
{
// Snippet: GetInstance(GetInstanceRequest,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = CloudRedisClient.Create();
// Initialize request argument(s)
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
// Make the request
Instance response = cloudRedisClient.GetInstance(request);
// End snippet
}
/// <summary>Snippet for CreateInstanceAsync</summary>
public async Task CreateInstanceAsync()
{
// Snippet: CreateInstanceAsync(LocationName,string,Instance,CallSettings)
// Additional: CreateInstanceAsync(LocationName,string,Instance,CancellationToken)
// Create client
CloudRedisClient cloudRedisClient = await CloudRedisClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = new LocationName("[PROJECT]", "[LOCATION]");
string instanceId = "test_instance";
Instance instance = new Instance
{
Tier = Instance.Types.Tier.Basic,
MemorySizeGb = 1,
};
// Make the request
Operation<Instance, OperationMetadata> response =
await cloudRedisClient.CreateInstanceAsync(parent, instanceId, instance);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse =
await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse =
await cloudRedisClient.PollOnceCreateInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateInstance</summary>
public void CreateInstance()
{
// Snippet: CreateInstance(LocationName,string,Instance,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = CloudRedisClient.Create();
// Initialize request argument(s)
LocationName parent = new LocationName("[PROJECT]", "[LOCATION]");
string instanceId = "test_instance";
Instance instance = new Instance
{
Tier = Instance.Types.Tier.Basic,
MemorySizeGb = 1,
};
// Make the request
Operation<Instance, OperationMetadata> response =
cloudRedisClient.CreateInstance(parent, instanceId, instance);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse =
response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse =
cloudRedisClient.PollOnceCreateInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateInstanceAsync</summary>
public async Task CreateInstanceAsync_RequestObject()
{
// Snippet: CreateInstanceAsync(CreateInstanceRequest,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = await CloudRedisClient.CreateAsync();
// Initialize request argument(s)
CreateInstanceRequest request = new CreateInstanceRequest
{
ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
InstanceId = "test_instance",
Instance = new Instance
{
Tier = Instance.Types.Tier.Basic,
MemorySizeGb = 1,
},
};
// Make the request
Operation<Instance, OperationMetadata> response =
await cloudRedisClient.CreateInstanceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse =
await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse =
await cloudRedisClient.PollOnceCreateInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateInstance</summary>
public void CreateInstance_RequestObject()
{
// Snippet: CreateInstance(CreateInstanceRequest,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = CloudRedisClient.Create();
// Initialize request argument(s)
CreateInstanceRequest request = new CreateInstanceRequest
{
ParentAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
InstanceId = "test_instance",
Instance = new Instance
{
Tier = Instance.Types.Tier.Basic,
MemorySizeGb = 1,
},
};
// Make the request
Operation<Instance, OperationMetadata> response =
cloudRedisClient.CreateInstance(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse =
response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse =
cloudRedisClient.PollOnceCreateInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateInstanceAsync</summary>
public async Task UpdateInstanceAsync()
{
// Snippet: UpdateInstanceAsync(FieldMask,Instance,CallSettings)
// Additional: UpdateInstanceAsync(FieldMask,Instance,CancellationToken)
// Create client
CloudRedisClient cloudRedisClient = await CloudRedisClient.CreateAsync();
// Initialize request argument(s)
FieldMask updateMask = new FieldMask
{
Paths = {
"display_name",
"memory_size_gb",
},
};
Instance instance = new Instance
{
DisplayName = "UpdatedDisplayName",
MemorySizeGb = 4,
};
// Make the request
Operation<Instance, OperationMetadata> response =
await cloudRedisClient.UpdateInstanceAsync(updateMask, instance);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse =
await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse =
await cloudRedisClient.PollOnceUpdateInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateInstance</summary>
public void UpdateInstance()
{
// Snippet: UpdateInstance(FieldMask,Instance,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = CloudRedisClient.Create();
// Initialize request argument(s)
FieldMask updateMask = new FieldMask
{
Paths = {
"display_name",
"memory_size_gb",
},
};
Instance instance = new Instance
{
DisplayName = "UpdatedDisplayName",
MemorySizeGb = 4,
};
// Make the request
Operation<Instance, OperationMetadata> response =
cloudRedisClient.UpdateInstance(updateMask, instance);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse =
response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse =
cloudRedisClient.PollOnceUpdateInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateInstanceAsync</summary>
public async Task UpdateInstanceAsync_RequestObject()
{
// Snippet: UpdateInstanceAsync(UpdateInstanceRequest,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = await CloudRedisClient.CreateAsync();
// Initialize request argument(s)
UpdateInstanceRequest request = new UpdateInstanceRequest
{
UpdateMask = new FieldMask
{
Paths = {
"display_name",
"memory_size_gb",
},
},
Instance = new Instance
{
DisplayName = "UpdatedDisplayName",
MemorySizeGb = 4,
},
};
// Make the request
Operation<Instance, OperationMetadata> response =
await cloudRedisClient.UpdateInstanceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse =
await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse =
await cloudRedisClient.PollOnceUpdateInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateInstance</summary>
public void UpdateInstance_RequestObject()
{
// Snippet: UpdateInstance(UpdateInstanceRequest,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = CloudRedisClient.Create();
// Initialize request argument(s)
UpdateInstanceRequest request = new UpdateInstanceRequest
{
UpdateMask = new FieldMask
{
Paths = {
"display_name",
"memory_size_gb",
},
},
Instance = new Instance
{
DisplayName = "UpdatedDisplayName",
MemorySizeGb = 4,
},
};
// Make the request
Operation<Instance, OperationMetadata> response =
cloudRedisClient.UpdateInstance(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse =
response.PollUntilCompleted();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse =
cloudRedisClient.PollOnceUpdateInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteInstanceAsync</summary>
public async Task DeleteInstanceAsync()
{
// Snippet: DeleteInstanceAsync(InstanceName,CallSettings)
// Additional: DeleteInstanceAsync(InstanceName,CancellationToken)
// Create client
CloudRedisClient cloudRedisClient = await CloudRedisClient.CreateAsync();
// Initialize request argument(s)
InstanceName name = new InstanceName("[PROJECT]", "[LOCATION]", "[INSTANCE]");
// Make the request
Operation<Empty, OperationMetadata> response =
await cloudRedisClient.DeleteInstanceAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse =
await response.PollUntilCompletedAsync();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse =
await cloudRedisClient.PollOnceDeleteInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for DeleteInstance</summary>
public void DeleteInstance()
{
// Snippet: DeleteInstance(InstanceName,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = CloudRedisClient.Create();
// Initialize request argument(s)
InstanceName name = new InstanceName("[PROJECT]", "[LOCATION]", "[INSTANCE]");
// Make the request
Operation<Empty, OperationMetadata> response =
cloudRedisClient.DeleteInstance(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse =
response.PollUntilCompleted();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse =
cloudRedisClient.PollOnceDeleteInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for DeleteInstanceAsync</summary>
public async Task DeleteInstanceAsync_RequestObject()
{
// Snippet: DeleteInstanceAsync(DeleteInstanceRequest,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = await CloudRedisClient.CreateAsync();
// Initialize request argument(s)
DeleteInstanceRequest request = new DeleteInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
// Make the request
Operation<Empty, OperationMetadata> response =
await cloudRedisClient.DeleteInstanceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse =
await response.PollUntilCompletedAsync();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse =
await cloudRedisClient.PollOnceDeleteInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
/// <summary>Snippet for DeleteInstance</summary>
public void DeleteInstance_RequestObject()
{
// Snippet: DeleteInstance(DeleteInstanceRequest,CallSettings)
// Create client
CloudRedisClient cloudRedisClient = CloudRedisClient.Create();
// Initialize request argument(s)
DeleteInstanceRequest request = new DeleteInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[LOCATION]", "[INSTANCE]"),
};
// Make the request
Operation<Empty, OperationMetadata> response =
cloudRedisClient.DeleteInstance(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse =
response.PollUntilCompleted();
// The long-running operation is now complete.
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse =
cloudRedisClient.PollOnceDeleteInstance(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// The long-running operation is now complete.
}
// End snippet
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using log4net;
using OpenMetaverse;
namespace OpenSim.Framework.Console
{
public class ConsoleUtil
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const int LocalIdNotFound = 0;
/// <summary>
/// Used by modules to display stock co-ordinate help, though possibly this should be under some general section
/// rather than in each help summary.
/// </summary>
public const string CoordHelp
= @"Each component of the coord is comma separated. There must be no spaces between the commas.
If you don't care about the z component you can simply omit it.
If you don't care about the x or y components then you can leave them blank (though a comma is still required)
If you want to specify the maximum value of a component then you can use ~ instead of a number
If you want to specify the minimum value of a component then you can use -~ instead of a number
e.g.
show object pos 20,20,20 to 40,40,40
delete object pos 20,20 to 40,40
show object pos ,20,20 to ,40,40
delete object pos ,,30 to ,,~
show object pos ,,-~ to ,,30";
public const string MinRawConsoleVectorValue = "-~";
public const string MaxRawConsoleVectorValue = "~";
public const string VectorSeparator = ",";
public static char[] VectorSeparatorChars = VectorSeparator.ToCharArray();
/// <summary>
/// Check if the given file path exists.
/// </summary>
/// <remarks>If not, warning is printed to the given console.</remarks>
/// <returns>true if the file does not exist, false otherwise.</returns>
/// <param name='console'></param>
/// <param name='path'></param>
public static bool CheckFileDoesNotExist(ICommandConsole console, string path)
{
if (File.Exists(path))
{
console.OutputFormat("File {0} already exists. Please move or remove it.", path);
return false;
}
return true;
}
/// <summary>
/// Try to parse a console UUID from the console.
/// </summary>
/// <remarks>
/// Will complain to the console if parsing fails.
/// </remarks>
/// <returns></returns>
/// <param name='console'>If null then no complaint is printed.</param>
/// <param name='rawUuid'></param>
/// <param name='uuid'></param>
public static bool TryParseConsoleUuid(ICommandConsole console, string rawUuid, out UUID uuid)
{
if (!UUID.TryParse(rawUuid, out uuid))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid uuid", rawUuid);
return false;
}
return true;
}
public static bool TryParseConsoleLocalId(ICommandConsole console, string rawLocalId, out uint localId)
{
if (!uint.TryParse(rawLocalId, out localId))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid local id", localId);
return false;
}
if (localId == 0)
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid local id - it must be greater than 0", localId);
return false;
}
return true;
}
/// <summary>
/// Tries to parse the input as either a UUID or a local ID.
/// </summary>
/// <returns>true if parsing succeeded, false otherwise.</returns>
/// <param name='console'></param>
/// <param name='rawId'></param>
/// <param name='uuid'></param>
/// <param name='localId'>
/// Will be set to ConsoleUtil.LocalIdNotFound if parsing result was a UUID or no parse succeeded.
/// </param>
public static bool TryParseConsoleId(ICommandConsole console, string rawId, out UUID uuid, out uint localId)
{
if (TryParseConsoleUuid(null, rawId, out uuid))
{
localId = LocalIdNotFound;
return true;
}
if (TryParseConsoleLocalId(null, rawId, out localId))
{
return true;
}
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid UUID or local id", rawId);
return false;
}
/// <summary>
/// Convert a console integer to an int, automatically complaining if a console is given.
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleBool(ICommandConsole console, string rawConsoleString, out bool b)
{
if (!bool.TryParse(rawConsoleString, out b))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a true or false value", rawConsoleString);
return false;
}
return true;
}
/// <summary>
/// Convert a console integer to an int, automatically complaining if a console is given.
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleInt'>/param>
/// <param name='i'></param>
/// <returns></returns>
public static bool TryParseConsoleInt(ICommandConsole console, string rawConsoleInt, out int i)
{
if (!int.TryParse(rawConsoleInt, out i))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid integer", rawConsoleInt);
return false;
}
return true;
}
/// <summary>
/// Convert a console integer to a natural int, automatically complaining if a console is given.
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleInt'>/param>
/// <param name='i'></param>
/// <returns></returns>
public static bool TryParseConsoleNaturalInt(ICommandConsole console, string rawConsoleInt, out int i)
{
if (TryParseConsoleInt(console, rawConsoleInt, out i))
{
if (i < 0)
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a positive integer", rawConsoleInt);
return false;
}
return true;
}
return false;
}
/// <summary>
/// Convert a minimum vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleMinVector(string rawConsoleVector, out Vector3 vector)
{
return TryParseConsoleVector(rawConsoleVector, c => float.MinValue.ToString(), out vector);
}
/// <summary>
/// Convert a maximum vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleMaxVector(string rawConsoleVector, out Vector3 vector)
{
return TryParseConsoleVector(rawConsoleVector, c => float.MaxValue.ToString(), out vector);
}
/// <summary>
/// Convert a vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>
/// A string in the form <x>,<y>,<z> where there is no space between values.
/// Any component can be missing (e.g. ,,40). blankComponentFunc is invoked to replace the blank with a suitable value
/// Also, if the blank component is at the end, then the comma can be missed off entirely (e.g. 40,30 or 40)
/// The strings "~" and "-~" are valid in components. The first substitutes float.MaxValue whilst the second is float.MinValue
/// Other than that, component values must be numeric.
/// </param>
/// <param name='blankComponentFunc'>
/// Behaviour if component is blank. If null then conversion fails on a blank component.
/// </param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleVector(
string rawConsoleVector, Func<string, string> blankComponentFunc, out Vector3 vector)
{
return Vector3.TryParse(CookVector(rawConsoleVector, 3, blankComponentFunc), out vector);
}
/// <summary>
/// Convert a vector input from the console to an OpenMetaverse.Vector2
/// </summary>
/// <param name='rawConsoleVector'>
/// A string in the form <x>,<y> where there is no space between values.
/// Any component can be missing (e.g. ,40). blankComponentFunc is invoked to replace the blank with a suitable value
/// Also, if the blank component is at the end, then the comma can be missed off entirely (e.g. 40)
/// The strings "~" and "-~" are valid in components. The first substitutes float.MaxValue whilst the second is float.MinValue
/// Other than that, component values must be numeric.
/// </param>
/// <param name='blankComponentFunc'>
/// Behaviour if component is blank. If null then conversion fails on a blank component.
/// </param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsole2DVector(
string rawConsoleVector, Func<string, string> blankComponentFunc, out Vector2 vector)
{
// We don't use Vector2.TryParse() for now because for some reason it expects an input with 3 components
// rather than 2.
string cookedVector = CookVector(rawConsoleVector, 2, blankComponentFunc);
if (cookedVector == null)
{
vector = Vector2.Zero;
return false;
}
else
{
string[] cookedComponents = cookedVector.Split(VectorSeparatorChars);
vector = new Vector2(float.Parse(cookedComponents[0]), float.Parse(cookedComponents[1]));
return true;
}
//return Vector2.TryParse(CookVector(rawConsoleVector, 2, blankComponentFunc), out vector);
}
/// <summary>
/// Convert a raw console vector into a vector that can be be parsed by the relevant OpenMetaverse.TryParse()
/// </summary>
/// <param name='rawConsoleVector'></param>
/// <param name='dimensions'></param>
/// <param name='blankComponentFunc'></param>
/// <returns>null if conversion was not possible</returns>
private static string CookVector(
string rawConsoleVector, int dimensions, Func<string, string> blankComponentFunc)
{
List<string> components = rawConsoleVector.Split(VectorSeparatorChars).ToList();
if (components.Count < 1 || components.Count > dimensions)
return null;
if (components.Count < dimensions)
{
if (blankComponentFunc == null)
return null;
else
for (int i = components.Count; i < dimensions; i++)
components.Add("");
}
List<string> cookedComponents
= components.ConvertAll<string>(
c =>
{
if (c == "")
return blankComponentFunc.Invoke(c);
else if (c == MaxRawConsoleVectorValue)
return float.MaxValue.ToString();
else if (c == MinRawConsoleVectorValue)
return float.MinValue.ToString();
else
return c;
});
return string.Join(VectorSeparator, cookedComponents.ToArray());
}
}
}
| |
// Contributor: Andrew D. Jones
using System.Collections.Generic;
using System.Diagnostics;
using FarseerGames.FarseerPhysics.Dynamics;
using FarseerGames.FarseerPhysics.Interfaces;
namespace FarseerGames.FarseerPhysics.Collisions
{
/// <summary>
/// This class is used to isolate the AABB pairs that are currently in a collision
/// state without having to check all pair combinations. It relies heavily on frame
/// coherence or the idea that objects will typically be near their last position
/// from frame to frame. The class caches the various state information and doesn't
/// update it unless an extent on an axis "swaps" positions with its neighbor.
/// Note: If your application has "teleporting" objects or objects that are
/// extremely high-speed in relation to other objects, then this Sweep and Prune
/// method may breakdown.
/// </summary>
public class SweepAndPruneCollider : IBroadPhaseCollider
{
private const float _floatTolerance = 0.01f; //1.5f; //.01f;
private PhysicsSimulator _physicsSimulator;
private ExtentList _xExtentList;
private ExtentInfoList _xInfoList;
private ExtentList _yExtentList;
private ExtentInfoList _yInfoList;
/// <summary>
/// The collision pairs
/// </summary>
public CollisionPairDictionary CollisionPairs;
public SweepAndPruneCollider(PhysicsSimulator physicsSimulator)
{
_physicsSimulator = physicsSimulator;
_xExtentList = new ExtentList(this);
_yExtentList = new ExtentList(this);
_xInfoList = new ExtentInfoList(this);
_yInfoList = new ExtentInfoList(this);
CollisionPairs = new CollisionPairDictionary();
}
#region IBroadPhaseCollider Members
/// <summary>
/// Fires when a broad phase collision occurs
/// </summary>
public event BroadPhaseCollisionHandler OnBroadPhaseCollision;
#if (!SILVERLIGHT)
/// <summary>
/// Used by the <see cref="PhysicsSimulator"/> to remove geometry from Sweep and Prune once it
/// has been disposed.
/// </summary>
public void ProcessDisposedGeoms()
{
if (_xInfoList.RemoveAll(i => i.Geometry.IsDisposed) > 0)
{
_xExtentList.RemoveAll(n => n.Info.Geometry.IsDisposed);
}
if (_yInfoList.RemoveAll(i => i.Geometry.IsDisposed) > 0)
{
_yExtentList.RemoveAll(n => n.Info.Geometry.IsDisposed);
}
CollisionPairs.Clear();
}
/// <summary>
/// Used by the <see cref="PhysicsSimulator"/> to remove geometry from Sweep and Prune once it
/// has been removed.
/// </summary>
public void ProcessRemovedGeoms()
{
if (_xInfoList.RemoveAll(i => !i.Geometry.InSimulation) > 0)
{
_xExtentList.RemoveAll(n => !n.Info.Geometry.InSimulation);
}
if (_yInfoList.RemoveAll(i => !i.Geometry.InSimulation) > 0)
{
_yExtentList.RemoveAll(n => !n.Info.Geometry.InSimulation);
}
CollisionPairs.Clear();
}
#else
private int ExtentInfoListRemoveAllRemoved(ExtentInfoList l)
{
int removed = 0;
for (int i = 0; i < l.Count; i++)
{
if (!l[i].Geometry.InSimulation)
{
removed++;
l.RemoveAt(i);
i--;
}
}
return removed;
}
private int ExtentListRemoveAllRemoved(ExtentList l)
{
int removed = 0;
for (int i = 0; i < l.Count; i++)
{
if (!l[i].Info.Geometry.InSimulation)
{
removed++;
l.RemoveAt(i);
i--;
}
}
return removed;
}
private int ExtentInfoListRemoveAllDisposed(ExtentInfoList l)
{
int removed = 0;
for (int i = 0; i < l.Count; i++)
{
if (l[i].Geometry.IsDisposed)
{
removed++;
l.RemoveAt(i);
i--;
}
}
return removed;
}
private int ExtentListRemoveAllDisposed(ExtentList l)
{
int removed = 0;
for (int i = 0; i < l.Count; i++)
{
if (l[i].Info.Geometry.IsDisposed)
{
removed++;
l.RemoveAt(i);
i--;
}
}
return removed;
}
/// <summary>
/// Used by the PhysicsSimulator to remove geometry from Sweep and Prune once it
/// has been disposed.
/// </summary>
public void ProcessDisposedGeoms()
{
if (ExtentInfoListRemoveAllDisposed(_xInfoList) > 0)
{
ExtentListRemoveAllDisposed(_xExtentList);
}
if (ExtentInfoListRemoveAllDisposed(_yInfoList) > 0)
{
ExtentListRemoveAllDisposed(_yExtentList);
}
CollisionPairs.Clear();
}
public void ProcessRemovedGeoms()
{
if (ExtentInfoListRemoveAllRemoved(_xInfoList) > 0)
{
ExtentListRemoveAllRemoved(_xExtentList);
}
if (ExtentInfoListRemoveAllRemoved(_yInfoList) > 0)
{
ExtentListRemoveAllRemoved(_yExtentList);
}
CollisionPairs.Clear();
}
#endif
/// <summary>
/// This method is used by the <see cref="PhysicsSimulator"/> to notify Sweep and Prune that
/// new geometry is to be tracked.
/// </summary>
/// <param name="geom">The geometry to be added</param>
public void Add(Geom geom)
{
ExtentInfo xExtentInfo = new ExtentInfo(geom, geom.AABB.Min.X, geom.AABB.Max.X);
_xInfoList.Add(xExtentInfo);
_xExtentList.IncrementalInsertExtent(xExtentInfo);
ExtentInfo yExtentInfo = new ExtentInfo(geom, geom.AABB.Min.Y, geom.AABB.Max.Y);
_yInfoList.Add(yExtentInfo);
_yExtentList.IncrementalInsertExtent(yExtentInfo);
}
/// <summary>
/// Incrementally updates the system. Assumes relatively good frame coherence.
/// </summary>
public void Update()
{
UpdateExtentValues();
_xExtentList.IncrementalSort();
_yExtentList.IncrementalSort();
_xInfoList.MoveUnderConsiderationToOverlaps();
_yInfoList.MoveUnderConsiderationToOverlaps();
HandleCollisions();
}
#endregion
/// <summary>
/// Updates the values in the x and y extent lists by the changing AABB values.
/// </summary>
private void UpdateExtentValues()
{
for (int i = 0; i < _xInfoList.Count; i++)
{
ExtentInfo xInfo = _xInfoList[i];
ExtentInfo yInfo = _yInfoList[i];
AABB aabb = xInfo.Geometry.AABB;
xInfo.Min.Value = aabb.min.X - _floatTolerance;
xInfo.Max.Value = aabb.max.X + _floatTolerance;
yInfo.Min.Value = aabb.min.Y - _floatTolerance;
yInfo.Max.Value = aabb.max.Y + _floatTolerance;
}
}
/// <summary>
/// Iterates over the collision pairs and creates arbiters.
/// </summary>
private void HandleCollisions()
{
foreach (CollisionPair cp in CollisionPairs.Keys)
{
// Note: Possible optimization. Maybe arbiter can be cached into Value of
// CollisionPairs? Currently, the CollisionPairs hash doesn't use its
// Value parameter - its just an unused bool Value.
Arbiter arbiter = _physicsSimulator.arbiterPool.Fetch();
arbiter.ConstructArbiter(cp.Geom1, cp.Geom2, _physicsSimulator);
if (!_physicsSimulator.arbiterList.Contains(arbiter))
_physicsSimulator.arbiterList.Add(arbiter);
else
_physicsSimulator.arbiterPool.Insert(arbiter);
}
}
#region Nested type: CollisionPair
/// <summary>
/// Houses collision pairs as geom1 and geom2. The pairs are always ordered such
/// that the lower id geometry is first. This allows the <see cref="CollisionPairDictionary"/>
/// to have a consistent key / hash code for a pair of geometry.
/// </summary>
public struct CollisionPair
{
public Geom Geom1;
public Geom Geom2;
public CollisionPair(Geom g1, Geom g2)
{
if (g1 < g2)
{
Geom1 = g1;
Geom2 = g2;
}
else
{
Geom1 = g2;
Geom2 = g1;
}
}
public override int GetHashCode()
{
// Arbitrarly choose 10000 as a number of colliders that we won't
// approach any time soon.
return (Geom1.id*10000 + Geom2.id);
}
public override bool Equals(object obj)
{
if (!(obj is CollisionPair))
return false;
return Equals((CollisionPair) obj);
}
/// <summary>
/// Checks to see if the specified <see cref="CollisionPair"/> equals this instance
/// </summary>
/// <param name="other">The other.</param>
/// <returns></returns>
public bool Equals(CollisionPair other)
{
if (Geom1 == other.Geom1)
return (Geom2 == other.Geom2);
return false;
}
public static bool operator ==(CollisionPair first, CollisionPair second)
{
return first.Equals(second);
}
public static bool operator !=(CollisionPair first, CollisionPair second)
{
return !first.Equals(second);
}
}
#endregion
#region Nested type: CollisionPairDictionary
/// <summary>
/// This class is used to keep track of the pairs of geometry that need to be
/// passed on to the narrow phase. The keys stored in the dictionary are
/// the actual geometry pairs (the boolean Value is currently unused).
/// NOTE: May eventually want to add OnEnterCollisionState /
/// OnExitCollisionState callbacks which might be useful for debugging
/// or possibly in user applications.
/// </summary>
public class CollisionPairDictionary : Dictionary<CollisionPair, bool>
{
///<summary>
///Remove a pair of geoms
///</summary>
///<param name="g1"></param>
///<param name="g2"></param>
public void RemovePair(Geom g1, Geom g2)
{
CollisionPair cp = new CollisionPair(g1, g2);
Remove(cp);
// May want a OnDeactivatedCollision here.
// For example, if you were highlighting colliding
// ABV's for debugging, this callback would let you
// know to stop.
}
/// <summary>
/// Adds the a pair of geoms.
/// </summary>
/// <param name="g1">The g1.</param>
/// <param name="g2">The g2.</param>
public void AddPair(Geom g1, Geom g2)
{
CollisionPair cp = new CollisionPair(g1, g2);
// This check is a trade-off. In many cases, we don't need to perform
// this check and we could just do a "try" block instead, however,
// when exceptions are thrown, they are mega-slow... so checking for
// the key is really the best option all round.
if (ContainsKey(cp))
return;
Add(cp, true);
}
}
#endregion
#region Nested type: Extent
/// <summary>
/// This class represents a single extent of an AABB on a single axis. It has a
/// reference to <see cref="ExtentInfo"/> which has information about the geometry it belongs
/// to.
/// </summary>
public class Extent
{
public ExtentInfo Info;
public bool IsMin;
public float Value;
public Extent(ExtentInfo info, float value, bool isMin)
{
Info = info;
Value = value;
IsMin = isMin;
}
}
#endregion
#region Nested type: ExtentInfo
/// <summary>
/// This class contains represents additional extent info for a particular axis
/// It has a reference to the geometry whose extents are being tracked. It
/// also has a min and max extent reference into the <see cref="ExtentList"/> itself.
/// The class keeps track of overlaps with other geometries.
/// </summary>
public class ExtentInfo
{
public Geom Geometry; // Specific to Farseer
public Extent Max;
public Extent Min;
public List<Geom> Overlaps;
public List<Geom> UnderConsideration;
public ExtentInfo(Geom g, float min, float max)
{
Geometry = g;
UnderConsideration = new List<Geom>();
Overlaps = new List<Geom>();
Min = new Extent(this, min, true);
Max = new Extent(this, max, false);
}
}
#endregion
#region Nested type: ExtentInfoList
/// <summary>
/// This class keeps a list of information that relates extents to geometries.
/// </summary>
private class ExtentInfoList : List<ExtentInfo>
{
public SweepAndPruneCollider Owner;
public ExtentInfoList(SweepAndPruneCollider sap)
{
Owner = sap;
}
public void MoveUnderConsiderationToOverlaps()
{
for (int i = 0; i < Count; i++)
{
if (this[i].UnderConsideration.Count == 0)
continue;
Geom geometryA = this[i].Geometry;
// First transfer those under consideration to overlaps,
// for, they have been considered...
int startIndex = this[i].Overlaps.Count;
this[i].Overlaps.AddRange(this[i].UnderConsideration);
this[i].UnderConsideration.Clear();
for (int j = startIndex; j < this[i].Overlaps.Count; j++)
{
Geom geometryB = this[i].Overlaps[j];
// It is possible that we may test the same pair of geometries
// for both extents (x and y), however, I'm banking on that
// one of the extents has probably already been cached and
// therefore, won't be checked.
if (!geometryA.body.Enabled || !geometryB.body.Enabled)
continue;
if ((geometryA.CollisionGroup == geometryB.CollisionGroup) &&
geometryA.CollisionGroup != 0 && geometryB.CollisionGroup != 0)
continue;
if (!geometryA.CollisionEnabled || !geometryB.CollisionEnabled)
continue;
if (geometryA.body.isStatic && geometryB.body.isStatic)
continue;
if (geometryA.body == geometryB.body)
continue;
if (((geometryA.CollisionCategories & geometryB.CollidesWith) == CollisionCategory.None) &
((geometryB.CollisionCategories & geometryA.CollidesWith) == CollisionCategory.None))
continue;
if (geometryA.FindDNC(geometryB) || geometryB.FindDNC(geometryA))
{
continue;
}
//TMP
AABB aabb1 = new AABB();
AABB aabb2 = new AABB();
aabb1.min = geometryA.AABB.min;
aabb1.max = geometryA.AABB.max;
aabb2.min = geometryB.AABB.min;
aabb2.max = geometryB.AABB.max;
aabb1.min.X -= _floatTolerance;
aabb1.min.Y -= _floatTolerance;
aabb1.max.X += _floatTolerance;
aabb1.max.Y += _floatTolerance;
aabb2.min.X -= _floatTolerance;
aabb2.min.Y -= _floatTolerance;
aabb2.max.X += _floatTolerance;
aabb2.max.Y += _floatTolerance;
if(!AABB.Intersect(aabb1, aabb2))
continue;
//Call the OnBroadPhaseCollision event first. If the user aborts the collision
//it will not create an arbiter
if (Owner.OnBroadPhaseCollision != null)
{
if (Owner.OnBroadPhaseCollision(geometryA, geometryB))
Owner.CollisionPairs.AddPair(geometryA, geometryB);
}
else
{
Owner.CollisionPairs.AddPair(geometryA, geometryB);
}
}
}
}
}
#endregion
#region Nested type: ExtentList
/// <summary>
/// Represents a lists of extents for a given axis. This list will be kept
/// sorted incrementally.
/// </summary>
public class ExtentList : List<Extent>
{
public SweepAndPruneCollider Owner;
public ExtentList(SweepAndPruneCollider sap)
{
Owner = sap;
}
/// <summary>
/// Inserts a new Extent into the already sorted list. As the <see cref="ExtentList"/>
/// class is currently derived from the generic List class, insertions
/// of new geometry (and extents) are going to be somewhat slow right
/// off the bat. Additionally, this function currently performs
/// linear insertion. Two big optimizations in the future would be to
/// (1) make this function perform a binary search and (2) allow for
/// a "hint" of what index to start with. The reason for this is because
/// there is always a min and max extents that need inserting and we
/// know the max extent is always after the min extent.
/// </summary>
private int InsertIntoSortedList(Extent newExtent)
{
// List<> is not the most speedy for insertion, however, since
// we don't plan to do this except for when geometry is added
// to the system, we go ahead an use List<> instead of LinkedList<>
// This code, btw, assumes the list is already sorted and that
// the new entry just needs to be inserted.
//
//TODO: Optimization Note: A binary search could be used here and would
// improve speed for when adding geometry.
int insertAt = 0;
// Check for empty list
if (Count == 0)
{
Add(newExtent);
return 0;
}
while (insertAt < Count &&
(this[insertAt].Value < newExtent.Value ||
(this[insertAt].Value == newExtent.Value &&
this[insertAt].IsMin && !newExtent.IsMin)))
{
insertAt++;
}
Insert(insertAt, newExtent);
return insertAt;
}
/// <summary>
/// Incrementally inserts the min/max extents into the <see cref="ExtentList"/>. As it
/// does so, the method ensures that overlap records, the <see cref="CollisionPair"/>
/// map, and all other book-keeping is up to date.
/// </summary>
/// <param name="ourInfo">The extent info for a give axis</param>
public void IncrementalInsertExtent(ExtentInfo ourInfo)
{
Extent min = ourInfo.Min;
Extent max = ourInfo.Max;
Debug.Assert(min.Value < max.Value);
int iMin = InsertIntoSortedList(min);
int iMax = InsertIntoSortedList(max);
Geom ourGeom = ourInfo.Geometry;
// As this is a newly inserted extent, we need to update the overlap
// information.
// RULE 1: Traverse from min to max. Look for other "min" Extents
// and when found, add our wrapper/geometry to their list.
int iCurr = iMin + 1;
while (iCurr != iMax)
{
if (this[iCurr].IsMin)
this[iCurr].Info.UnderConsideration.Add(ourGeom);
iCurr++;
}
// RULE 2: From min, traverse to the left until we encounter
// another "min" extent. If we find one, we add its geometry
// to our underConsideration list and go to RULE 3, otherwise
// there is no more work to do and we can exit.
iCurr = iMin - 1;
while (iCurr >= 0 && this[iCurr].IsMin == false)
iCurr--;
if (iCurr < 0)
return;
List<Geom> ourUnderConsideration = ourInfo.UnderConsideration;
Extent currExtent = this[iCurr];
ourUnderConsideration.Add(currExtent.Info.Geometry);
// RULE 3: Now that we have found a "min" extent, we take
// its existing overlap list and copy it into our underConsideration
// list. All except for ourselves.
ourUnderConsideration.AddRange(currExtent.Info.UnderConsideration);
ourUnderConsideration.Remove(ourGeom); // just in case
/*LinkedListNode<Geom> currGeomNode =
currExtent.info.underConsideration.First;
while (currGeomNode != null)
{
if (currGeomNode.Value != ourGeom)
{
ourUnderConsideration.AddLast(new LinkedListNode<Geom>(
currGeomNode.Value));
}
currGeomNode = currGeomNode.Next;
}*/
// RULE 4: Move from the found extent back toward our "min" extent.
// Whenever and "max" extent is found, we remove its reference
// from our extents list.
while (iCurr != iMin)
{
if (currExtent.IsMin == false)
{
ourUnderConsideration.Remove(currExtent.Info.Geometry);
if (ourInfo.Overlaps.Remove(currExtent.Info.Geometry))
{
Owner.CollisionPairs.RemovePair(ourGeom,
currExtent.Info.Geometry);
}
}
currExtent = this[++iCurr];
}
}
/// <summary>
/// Incrementally sorts <see cref="ExtentList"/>. It is assumed that there is a high level
/// of frame coherence and that much of the list is already fairly well
/// sorted. This algorithm makes use of "insert sort" which is notoriously
/// slow - except for when a list is already almost sorted - which is the
/// case when there is high frame coherence.
/// </summary>
public void IncrementalSort()
{
if (Count < 2)
return;
for (int i = 0; i < Count - 1; i++)
{
int evalCnt = i + 1;
Extent evalExtent = this[evalCnt];
Extent currExtent = this[i];
if (currExtent.Value <= evalExtent.Value)
continue;
Extent savedExtent = evalExtent;
if (evalExtent.IsMin)
{
while (currExtent.Value > evalExtent.Value)
//while (currExtent.Value >= evalExtent.Value)
{
if (currExtent.IsMin)
{
// Begin extent is inserted before another begin extent.
// So, Inserted extent's object looses reference to
// non-inserted extent and Non-inserted extent gains
// reference to inserted extent's object.
evalExtent.Info.UnderConsideration.Remove(
currExtent.Info.Geometry);
if (evalExtent.Info.Overlaps.Remove(
currExtent.Info.Geometry))
{
Owner.CollisionPairs.RemovePair(
evalExtent.Info.Geometry,
currExtent.Info.Geometry);
}
// Add extent
currExtent.Info.UnderConsideration.Add(
evalExtent.Info.Geometry);
}
else
{
// "min" extent inserted before the max extent.
// Inserted extent gains reference to non-inserted extent.
evalExtent.Info.UnderConsideration.Add(
currExtent.Info.Geometry);
}
this[evalCnt--] = this[i--];
if (i < 0)
break;
currExtent = this[i];
}
}
else
{
while (currExtent.Value > evalExtent.Value)
//while (currExtent.Value >= evalExtent.Value)
{
if (currExtent.IsMin)
{
// Ending extent inserted before a beginning extent
// the non inserted extent looses a reference to the
// inserted one
currExtent.Info.UnderConsideration.Remove(
evalExtent.Info.Geometry);
if (currExtent.Info.Overlaps.Remove(
evalExtent.Info.Geometry))
{
Owner.CollisionPairs.RemovePair(
evalExtent.Info.Geometry,
currExtent.Info.Geometry);
}
}
this[evalCnt--] = this[i--];
if (i < 0)
break;
currExtent = this[i];
}
}
this[evalCnt] = savedExtent;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using YesSql.Sql;
using YesSql.Utils;
namespace YesSql.Provider.PostgreSql
{
public class PostgreSqlDialect : BaseDialect
{
private static readonly Dictionary<DbType, string> _columnTypes = new Dictionary<DbType, string>
{
{DbType.Guid, "uuid"},
{DbType.Binary, "bytea"},
{DbType.Date, "date"},
{DbType.Time, "time"},
{DbType.DateTime, "timestamp" },
{DbType.DateTime2, "timestamp" },
{DbType.DateTimeOffset, "timestamptz" },
{DbType.Boolean, "boolean"},
{DbType.Byte, "int2"},
{DbType.SByte, "int2"},
{DbType.Decimal, "decimal({0}, {1})"},
{DbType.Single, "float4"},
{DbType.Double, "float8"},
{DbType.Int16, "int2"},
{DbType.Int32, "int4"},
{DbType.Int64, "int8"},
{DbType.UInt16, "int2"},
{DbType.UInt32, "int4"},
{DbType.UInt64, "int8"},
{DbType.AnsiStringFixedLength, "char(1)"},
{DbType.AnsiString, "varchar(255)"},
{DbType.StringFixedLength, "char(1)"},
{DbType.String, "varchar(255)"},
{DbType.Currency, "decimal(16,4)"}
};
static PostgreSqlDialect()
{
_propertyTypes = new Dictionary<Type, DbType>()
{
{ typeof(object), DbType.Binary },
{ typeof(byte[]), DbType.Binary },
{ typeof(string), DbType.String },
{ typeof(char), DbType.StringFixedLength },
{ typeof(bool), DbType.Boolean },
{ typeof(byte), DbType.Byte },
{ typeof(sbyte), DbType.SByte }, // not supported
{ typeof(short), DbType.Int16 },
{ typeof(ushort), DbType.UInt16 }, // not supported
{ typeof(int), DbType.Int32 },
{ typeof(uint), DbType.UInt32 },
{ typeof(long), DbType.Int64 },
{ typeof(ulong), DbType.UInt64 },
{ typeof(float), DbType.Single },
{ typeof(double), DbType.Double },
{ typeof(decimal), DbType.Decimal },
{ typeof(DateTime), DbType.DateTime },
{ typeof(DateTimeOffset), DbType.DateTimeOffset },
{ typeof(Guid), DbType.Guid },
{ typeof(TimeSpan), DbType.Int64 }, // stored as ticks
// Nullable types to prevent extra reflection on common ones
{ typeof(char?), DbType.StringFixedLength },
{ typeof(bool?), DbType.Boolean },
{ typeof(byte?), DbType.Byte },
{ typeof(sbyte?), DbType.Int16 },
{ typeof(short?), DbType.Int16 },
{ typeof(ushort?), DbType.UInt16 },
{ typeof(int?), DbType.Int32 },
{ typeof(uint?), DbType.UInt32 },
{ typeof(long?), DbType.Int64 },
{ typeof(ulong?), DbType.UInt64 },
{ typeof(float?), DbType.Single },
{ typeof(double?), DbType.Double },
{ typeof(decimal?), DbType.Decimal },
{ typeof(DateTime?), DbType.DateTime },
{ typeof(DateTimeOffset?), DbType.DateTimeOffset },
{ typeof(Guid?), DbType.Guid },
{ typeof(TimeSpan?), DbType.Int64 }
};
}
public PostgreSqlDialect()
{
AddTypeHandler<TimeSpan, long>(x => x.Ticks);
// DateTimes needs to be stored as Utc in timesstamp fields since npgsql 6.0.
// Can represents a Date & Time without TZ. Utc is forced by keeps the original date and time values.
AddTypeHandler<DateTime, DateTime>(x => x.Kind != DateTimeKind.Utc ? new DateTime(x.Ticks, DateTimeKind.Utc) : x);
// DateTimeOffset are stored as Utc DateTimes in timesstamptz fields
// Represents a moment in time
AddTypeHandler<DateTimeOffset, DateTime>(x => x.UtcDateTime);
Methods.Add("second", new TemplateFunction("extract(second from {0})"));
Methods.Add("minute", new TemplateFunction("extract(minute from {0})"));
Methods.Add("hour", new TemplateFunction("extract(hour from {0})"));
Methods.Add("day", new TemplateFunction("extract(day from {0})"));
Methods.Add("month", new TemplateFunction("extract(month from {0})"));
Methods.Add("year", new TemplateFunction("extract(year from {0})"));
Methods.Add("now", new TemplateFunction("now() at time zone 'utc'"));
}
public override string Name => "PostgreSql";
public override string InOperator(string values) => " = any(array[" + values + "])";
public override string NotInOperator(string values) => " <> all(array[" + values + "])";
public override string IdentitySelectString => "RETURNING";
public override string IdentityLastId => $"lastval()";
public override string IdentityColumnString => "SERIAL PRIMARY KEY";
public override string RandomOrderByClause => "random()";
public override bool SupportsIfExistsBeforeTableName => true;
public override bool PrefixIndex => true;
public override string GetTypeName(DbType dbType, int? length, byte? precision, byte? scale)
{
if (length.HasValue)
{
if (length.Value > 4000)
{
if (dbType == DbType.String)
{
return "text";
}
if (dbType == DbType.AnsiString)
{
return "text";
}
}
else
{
if (dbType == DbType.String)
{
return "varchar(" + length + ")";
}
if (dbType == DbType.AnsiString)
{
return "varchar(" + length + ")";
}
}
}
if (_columnTypes.TryGetValue(dbType, out string value))
{
if (dbType == DbType.Decimal)
{
value = string.Format(value, precision ?? DefaultDecimalPrecision, scale ?? DefaultDecimalScale);
}
return value;
}
throw new Exception("DbType not found for: " + dbType);
}
public override string FormatKeyName(string name)
{
// https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
// Postgres limits identifiers to NAMEDATALEN-1 char, where NAMEDATALEN is 64.
if (name.Length >= 63)
{
return HashHelper.HashName("FK_", name);
}
return name;
}
public override string FormatIndexName(string name)
{
// https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
// Postgres limits identifiers to NAMEDATALEN-1 char, where NAMEDATALEN is 64.
if (name.Length >= 63)
{
return HashHelper.HashName("IDX_FK_", name);
}
return name;
}
public override string GetDropForeignKeyConstraintString(string name)
{
return " drop foreign key " + name;
}
public override string DefaultValuesInsert => "DEFAULT VALUES";
public override void Page(ISqlBuilder sqlBuilder, string offset, string limit)
{
sqlBuilder.Trail(" limit ");
if (offset != null && limit == null)
{
sqlBuilder.Trail(" all");
}
if (limit != null)
{
sqlBuilder.Trail(limit);
}
if (offset != null)
{
sqlBuilder.Trail(" offset ");
sqlBuilder.Trail(offset);
}
}
public override string GetDropIndexString(string indexName, string tableName)
{
return "drop index if exists " + QuoteForColumnName(indexName);
}
public override string QuoteForColumnName(string columnName)
{
return QuoteString + columnName + QuoteString;
}
public override string QuoteForTableName(string tableName)
{
return QuoteString + tableName + QuoteString;
}
public override string CascadeConstraintsString => " cascade ";
public override byte DefaultDecimalPrecision => 19;
public override byte DefaultDecimalScale => 5;
public override string GetSqlValue(object value)
{
if (value == null)
{
return "null";
}
var type = value.GetType();
if (type == typeof(TimeSpan))
{
return ((TimeSpan)value).Ticks.ToString(CultureInfo.InvariantCulture);
}
if (type == typeof(DateTimeOffset))
{
return base.GetSqlValue(((DateTimeOffset)value).UtcDateTime);
}
switch (Convert.GetTypeCode(value))
{
case TypeCode.Boolean:
return (bool)value ? "TRUE" : "FALSE";
default:
return base.GetSqlValue(value);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableArrayExtensionsTest
{
private static readonly ImmutableArray<int> s_emptyDefault = default(ImmutableArray<int>);
private static readonly ImmutableArray<int> s_empty = ImmutableArray.Create<int>();
private static readonly ImmutableArray<int> s_oneElement = ImmutableArray.Create(1);
private static readonly ImmutableArray<int> s_manyElements = ImmutableArray.Create(1, 2, 3);
private static readonly ImmutableArray<GenericParameterHelper> s_oneElementRefType = ImmutableArray.Create(new GenericParameterHelper(1));
private static readonly ImmutableArray<string> s_twoElementRefTypeWithNull = ImmutableArray.Create("1", null);
private static readonly ImmutableArray<int>.Builder s_emptyBuilder = ImmutableArray.Create<int>().ToBuilder();
private static readonly ImmutableArray<int>.Builder s_oneElementBuilder = ImmutableArray.Create<int>(1).ToBuilder();
private static readonly ImmutableArray<int>.Builder s_manyElementsBuilder = ImmutableArray.Create<int>(1, 2, 3).ToBuilder();
[Fact]
public void Select()
{
Assert.Equal(new[] { 4, 5, 6 }, ImmutableArrayExtensions.Select(s_manyElements, n => n + 3));
AssertExtensions.Throws<ArgumentNullException>("selector", () => ImmutableArrayExtensions.Select<int, bool>(s_manyElements, null));
}
[Fact]
public void SelectEmptyDefault()
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.Select<int, bool>(s_emptyDefault, null));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.Select(s_emptyDefault, n => true));
}
[Fact]
public void SelectEmpty()
{
AssertExtensions.Throws<ArgumentNullException>("selector", () => ImmutableArrayExtensions.Select<int, bool>(s_empty, null));
Assert.False(ImmutableArrayExtensions.Select(s_empty, n => true).Any());
}
[Fact]
public void SelectMany()
{
Func<int, IEnumerable<int>> collectionSelector = i => Enumerable.Range(i, 10);
Func<int, int, int> resultSelector = (i, e) => e * 2;
foreach (var arr in new[] { s_empty, s_oneElement, s_manyElements })
{
Assert.Equal(
Enumerable.SelectMany(arr, collectionSelector, resultSelector),
ImmutableArrayExtensions.SelectMany(arr, collectionSelector, resultSelector));
}
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.SelectMany<int, int, int>(s_emptyDefault, null, null));
AssertExtensions.Throws<ArgumentNullException>("collectionSelector", () =>
ImmutableArrayExtensions.SelectMany<int, int, int>(s_manyElements, null, (i, e) => e));
AssertExtensions.Throws<ArgumentNullException>("resultSelector", () =>
ImmutableArrayExtensions.SelectMany<int, int, int>(s_manyElements, i => new[] { i }, null));
}
[Fact]
public void Where()
{
Assert.Equal(new[] { 2, 3 }, ImmutableArrayExtensions.Where(s_manyElements, n => n > 1));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Where(s_manyElements, null));
}
[Fact]
public void WhereEmptyDefault()
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.Where(s_emptyDefault, null));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.Where(s_emptyDefault, n => true));
}
[Fact]
public void WhereEmpty()
{
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Where(s_empty, null));
Assert.False(ImmutableArrayExtensions.Where(s_empty, n => true).Any());
}
[Fact]
public void Any()
{
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Any(s_oneElement, null));
Assert.True(ImmutableArrayExtensions.Any(s_oneElement));
Assert.True(ImmutableArrayExtensions.Any(s_manyElements, n => n == 2));
Assert.False(ImmutableArrayExtensions.Any(s_manyElements, n => n == 4));
Assert.True(ImmutableArrayExtensions.Any(s_oneElementBuilder));
}
[Fact]
public void AnyEmptyDefault()
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.Any(s_emptyDefault));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.Any(s_emptyDefault, n => true));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.Any(s_emptyDefault, null));
}
[Fact]
public void AnyEmpty()
{
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Any(s_empty, null));
Assert.False(ImmutableArrayExtensions.Any(s_empty));
Assert.False(ImmutableArrayExtensions.Any(s_empty, n => true));
}
[Fact]
public void All()
{
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.All(s_oneElement, null));
Assert.False(ImmutableArrayExtensions.All(s_manyElements, n => n == 2));
Assert.True(ImmutableArrayExtensions.All(s_manyElements, n => n > 0));
}
[Fact]
public void AllEmptyDefault()
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.All(s_emptyDefault, n => true));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.All(s_emptyDefault, null));
}
[Fact]
public void AllEmpty()
{
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.All(s_empty, null));
Assert.True(ImmutableArrayExtensions.All(s_empty, n => { throw new ShouldNotBeInvokedException(); })); // predicate should never be invoked.
}
[Fact]
public void SequenceEqual()
{
AssertExtensions.Throws<ArgumentNullException>("items", () => ImmutableArrayExtensions.SequenceEqual(s_oneElement, (IEnumerable<int>)null));
foreach (IEqualityComparer<int> comparer in new[] { null, EqualityComparer<int>.Default })
{
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_manyElements, comparer));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_manyElements.ToArray(), comparer));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_manyElements.ToArray()), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_oneElement, comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_oneElement.ToArray(), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_oneElement.ToArray()), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, (IEnumerable<int>)s_manyElements.Add(1).ToArray(), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(2).ToArray(), comparer));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), (IEnumerable<int>)s_manyElements.Add(2).ToArray(), comparer));
}
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_manyElements, (a, b) => true));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, s_oneElement, (a, b) => a == b));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(2), (a, b) => a == b));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_manyElements.Add(1), s_manyElements.Add(1), (a, b) => a == b));
Assert.False(ImmutableArrayExtensions.SequenceEqual(s_manyElements, ImmutableArray.Create(s_manyElements.ToArray()), (a, b) => false));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.SequenceEqual(s_oneElement, s_oneElement, (Func<int, int, bool>)null));
}
[Fact]
public void SequenceEqualEmptyDefault()
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.SequenceEqual(s_oneElement, s_emptyDefault));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_empty));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_emptyDefault));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.SequenceEqual(s_emptyDefault, s_emptyDefault, (Func<int, int, bool>)null));
}
[Fact]
public void SequenceEqualEmpty()
{
AssertExtensions.Throws<ArgumentNullException>("items", () => ImmutableArrayExtensions.SequenceEqual(s_empty, (IEnumerable<int>)null));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty.ToArray()));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty, (a, b) => true));
Assert.True(ImmutableArrayExtensions.SequenceEqual(s_empty, s_empty, (a, b) => false));
}
[Fact]
public void Aggregate()
{
AssertExtensions.Throws<ArgumentNullException>("func", () => ImmutableArrayExtensions.Aggregate(s_oneElement, null));
AssertExtensions.Throws<ArgumentNullException>("func", () => ImmutableArrayExtensions.Aggregate(s_oneElement, 1, null));
AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ImmutableArrayExtensions.Aggregate<int, int, int>(s_oneElement, 1, null, null));
AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => ImmutableArrayExtensions.Aggregate<int, int, int>(s_oneElement, 1, (a, b) => a + b, null));
Assert.Equal(Enumerable.Aggregate(s_manyElements, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(s_manyElements, (a, b) => a * b));
Assert.Equal(Enumerable.Aggregate(s_manyElements, 5, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(s_manyElements, 5, (a, b) => a * b));
Assert.Equal(Enumerable.Aggregate(s_manyElements, 5, (a, b) => a * b, a => -a), ImmutableArrayExtensions.Aggregate(s_manyElements, 5, (a, b) => a * b, a => -a));
}
[Fact]
public void AggregateEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(s_emptyDefault, (a, b) => a + b));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(s_emptyDefault, 1, (a, b) => a + b));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(s_emptyDefault, 1, (a, b) => a + b, a => a));
}
[Fact]
public void AggregateEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.Aggregate(s_empty, (a, b) => a + b));
Assert.Equal(1, ImmutableArrayExtensions.Aggregate(s_empty, 1, (a, b) => a + b));
Assert.Equal(1, ImmutableArrayExtensions.Aggregate<int, int, int>(s_empty, 1, (a, b) => a + b, a => a));
}
[Fact]
public void ElementAt()
{
// Basis for some assertions that follow
Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(s_empty, 0));
Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(s_manyElements, -1));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAt(s_emptyDefault, 0));
Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(s_empty, 0));
Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(s_manyElements, -1));
Assert.Equal(1, ImmutableArrayExtensions.ElementAt(s_oneElement, 0));
Assert.Equal(3, ImmutableArrayExtensions.ElementAt(s_manyElements, 2));
}
[Fact]
public void ElementAtOrDefault()
{
Assert.Equal(Enumerable.ElementAtOrDefault(s_manyElements, -1), ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, -1));
Assert.Equal(Enumerable.ElementAtOrDefault(s_manyElements, 3), ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, 3));
Assert.Throws<InvalidOperationException>(() => Enumerable.ElementAtOrDefault(s_emptyDefault, 0));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAtOrDefault(s_emptyDefault, 0));
Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(s_empty, 0));
Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(s_empty, 1));
Assert.Equal(1, ImmutableArrayExtensions.ElementAtOrDefault(s_oneElement, 0));
Assert.Equal(3, ImmutableArrayExtensions.ElementAtOrDefault(s_manyElements, 2));
}
[Fact]
public void First()
{
Assert.Equal(Enumerable.First(s_oneElement), ImmutableArrayExtensions.First(s_oneElement));
Assert.Equal(Enumerable.First(s_oneElement, i => true), ImmutableArrayExtensions.First(s_oneElement, i => true));
Assert.Equal(Enumerable.First(s_manyElements), ImmutableArrayExtensions.First(s_manyElements));
Assert.Equal(Enumerable.First(s_manyElements, i => true), ImmutableArrayExtensions.First(s_manyElements, i => true));
Assert.Equal(Enumerable.First(s_oneElementBuilder), ImmutableArrayExtensions.First(s_oneElementBuilder));
Assert.Equal(Enumerable.First(s_manyElementsBuilder), ImmutableArrayExtensions.First(s_manyElementsBuilder));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_manyElements, i => false));
}
[Fact]
public void FirstEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_empty, n => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.First(s_empty, null));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(s_emptyBuilder));
}
[Fact]
public void FirstEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(s_emptyDefault, n => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.First(s_emptyDefault, null));
}
[Fact]
public void FirstOrDefault()
{
Assert.Equal(Enumerable.FirstOrDefault(s_oneElement), ImmutableArrayExtensions.FirstOrDefault(s_oneElement));
Assert.Equal(Enumerable.FirstOrDefault(s_manyElements), ImmutableArrayExtensions.FirstOrDefault(s_manyElements));
foreach (bool result in new[] { true, false })
{
Assert.Equal(Enumerable.FirstOrDefault(s_oneElement, i => result), ImmutableArrayExtensions.FirstOrDefault(s_oneElement, i => result));
Assert.Equal(Enumerable.FirstOrDefault(s_manyElements, i => result), ImmutableArrayExtensions.FirstOrDefault(s_manyElements, i => result));
}
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(s_oneElement, null));
Assert.Equal(Enumerable.FirstOrDefault(s_oneElementBuilder), ImmutableArrayExtensions.FirstOrDefault(s_oneElementBuilder));
Assert.Equal(Enumerable.FirstOrDefault(s_manyElementsBuilder), ImmutableArrayExtensions.FirstOrDefault(s_manyElementsBuilder));
}
[Fact]
public void FirstOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_empty));
Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_empty, n => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.FirstOrDefault(s_empty, null));
Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(s_emptyBuilder));
}
[Fact]
public void FirstOrDefaultEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault, n => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.FirstOrDefault(s_emptyDefault, null));
}
[Fact]
public void Last()
{
Assert.Equal(Enumerable.Last(s_oneElement), ImmutableArrayExtensions.Last(s_oneElement));
Assert.Equal(Enumerable.Last(s_oneElement, i => true), ImmutableArrayExtensions.Last(s_oneElement, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_oneElement, i => false));
Assert.Equal(Enumerable.Last(s_manyElements), ImmutableArrayExtensions.Last(s_manyElements));
Assert.Equal(Enumerable.Last(s_manyElements, i => true), ImmutableArrayExtensions.Last(s_manyElements, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_manyElements, i => false));
Assert.Equal(Enumerable.Last(s_oneElementBuilder), ImmutableArrayExtensions.Last(s_oneElementBuilder));
Assert.Equal(Enumerable.Last(s_manyElementsBuilder), ImmutableArrayExtensions.Last(s_manyElementsBuilder));
}
[Fact]
public void LastEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_empty, n => true));
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Last(s_empty, null));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(s_emptyBuilder));
}
[Fact]
public void LastEmptyDefault()
{
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(s_emptyDefault));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(s_emptyDefault, n => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Last(s_emptyDefault, null));
}
[Fact]
public void LastOrDefault()
{
Assert.Equal(Enumerable.LastOrDefault(s_oneElement), ImmutableArrayExtensions.LastOrDefault(s_oneElement));
Assert.Equal(Enumerable.LastOrDefault(s_manyElements), ImmutableArrayExtensions.LastOrDefault(s_manyElements));
foreach (bool result in new[] { true, false })
{
Assert.Equal(Enumerable.LastOrDefault(s_oneElement, i => result), ImmutableArrayExtensions.LastOrDefault(s_oneElement, i => result));
Assert.Equal(Enumerable.LastOrDefault(s_manyElements, i => result), ImmutableArrayExtensions.LastOrDefault(s_manyElements, i => result));
}
Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(s_oneElement, null));
Assert.Equal(Enumerable.LastOrDefault(s_oneElementBuilder), ImmutableArrayExtensions.LastOrDefault(s_oneElementBuilder));
Assert.Equal(Enumerable.LastOrDefault(s_manyElementsBuilder), ImmutableArrayExtensions.LastOrDefault(s_manyElementsBuilder));
}
[Fact]
public void LastOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_empty));
Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_empty, n => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.LastOrDefault(s_empty, null));
Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(s_emptyBuilder));
}
[Fact]
public void LastOrDefaultEmptyDefault()
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault, n => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.LastOrDefault(s_emptyDefault, null));
}
[Fact]
public void Single()
{
Assert.Equal(Enumerable.Single(s_oneElement), ImmutableArrayExtensions.Single(s_oneElement));
Assert.Equal(Enumerable.Single(s_oneElement), ImmutableArrayExtensions.Single(s_oneElement, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements, i => true));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_manyElements, i => false));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_oneElement, i => false));
}
[Fact]
public void SingleEmpty()
{
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_empty));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(s_empty, n => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Single(s_empty, null));
}
[Fact]
public void SingleEmptyDefault()
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.Single(s_emptyDefault));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.Single(s_emptyDefault, n => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.Single(s_emptyDefault, null));
}
[Fact]
public void SingleOrDefault()
{
Assert.Equal(Enumerable.SingleOrDefault(s_oneElement), ImmutableArrayExtensions.SingleOrDefault(s_oneElement));
Assert.Equal(Enumerable.SingleOrDefault(s_oneElement), ImmutableArrayExtensions.SingleOrDefault(s_oneElement, i => true));
Assert.Equal(Enumerable.SingleOrDefault(s_oneElement, i => false), ImmutableArrayExtensions.SingleOrDefault(s_oneElement, i => false));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.SingleOrDefault(s_manyElements));
Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.SingleOrDefault(s_manyElements, i => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.SingleOrDefault(s_oneElement, null));
}
[Fact]
public void SingleOrDefaultEmpty()
{
Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(s_empty));
Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(s_empty, n => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.SingleOrDefault(s_empty, null));
}
[Fact]
public void SingleOrDefaultEmptyDefault()
{
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault));
TestExtensionsMethods.ValidateDefaultThisBehavior(() => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault, n => true));
AssertExtensions.Throws<ArgumentNullException>("predicate", () => ImmutableArrayExtensions.SingleOrDefault(s_emptyDefault, null));
}
[Fact]
public void ToDictionary()
{
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null));
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null, n => n));
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => ImmutableArrayExtensions.ToDictionary(s_manyElements, (Func<int, int>)null, n => n, EqualityComparer<int>.Default));
AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n, (Func<int, string>)null));
AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n, (Func<int, string>)null, EqualityComparer<int>.Default));
var stringToString = ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n.ToString(), n => (n * 2).ToString());
Assert.Equal(stringToString.Count, s_manyElements.Length);
Assert.Equal("2", stringToString["1"]);
Assert.Equal("4", stringToString["2"]);
Assert.Equal("6", stringToString["3"]);
var stringToInt = ImmutableArrayExtensions.ToDictionary(s_manyElements, n => n.ToString());
Assert.Equal(stringToString.Count, s_manyElements.Length);
Assert.Equal(1, stringToInt["1"]);
Assert.Equal(2, stringToInt["2"]);
Assert.Equal(3, stringToInt["3"]);
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, n => n));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, EqualityComparer<int>.Default));
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(s_emptyDefault, n => n, n => n, EqualityComparer<int>.Default));
}
[Fact]
public void ToArray()
{
Assert.Equal(0, ImmutableArrayExtensions.ToArray(s_empty).Length);
Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToArray(s_emptyDefault));
Assert.Equal(s_manyElements.ToArray(), ImmutableArrayExtensions.ToArray(s_manyElements));
}
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
using Xunit;
namespace SideBySide
{
public class UpdateTests : IClassFixture<DatabaseFixture>, IDisposable
{
public UpdateTests(DatabaseFixture database)
{
m_database = database;
m_database.Connection.Open();
}
public void Dispose()
{
m_database.Connection.Close();
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 1)]
[InlineData(3, 0)]
[InlineData(4, 0)]
public async Task UpdateRowsExecuteReader(int oldValue, int expectedRowsUpdated)
{
using (var cmd = m_database.Connection.CreateCommand())
{
cmd.CommandText = @"drop table if exists update_rows_reader;
create table update_rows_reader(id integer not null primary key auto_increment, value integer not null);
insert into update_rows_reader (value) VALUES (1), (2), (1), (4);
";
cmd.ExecuteNonQuery();
}
using (var cmd = m_database.Connection.CreateCommand())
{
cmd.CommandText = @"update update_rows_reader set value = @newValue where value = @oldValue";
var p = cmd.CreateParameter();
p.ParameterName = "@oldValue";
p.Value = oldValue;
cmd.Parameters.Add(p);
p = cmd.CreateParameter();
p.ParameterName = "@newValue";
p.Value = 4;
cmd.Parameters.Add(p);
using (var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false))
{
Assert.False(await reader.ReadAsync().ConfigureAwait(false));
Assert.Equal(expectedRowsUpdated, reader.RecordsAffected);
Assert.False(await reader.NextResultAsync().ConfigureAwait(false));
}
}
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 1)]
[InlineData(3, 0)]
[InlineData(4, 0)]
public async Task UpdateRowsExecuteNonQuery(int oldValue, int expectedRowsUpdated)
{
using (var cmd = m_database.Connection.CreateCommand())
{
cmd.CommandText = @"drop table if exists update_rows_non_query;
create table update_rows_non_query(id integer not null primary key auto_increment, value integer not null);
insert into update_rows_non_query (value) VALUES (1), (2), (1), (4);
";
cmd.ExecuteNonQuery();
}
using (var cmd = m_database.Connection.CreateCommand())
{
cmd.CommandText = @"update update_rows_non_query set value = @newValue where value = @oldValue";
var p = cmd.CreateParameter();
p.ParameterName = "@oldValue";
p.Value = oldValue;
cmd.Parameters.Add(p);
p = cmd.CreateParameter();
p.ParameterName = "@newValue";
p.Value = 4;
cmd.Parameters.Add(p);
var rowsAffected = await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
Assert.Equal(expectedRowsUpdated, rowsAffected);
}
}
[Theory]
[InlineData(1, 2)]
[InlineData(2, 1)]
[InlineData(3, 0)]
[InlineData(4, 0)]
public void UpdateRowsDapper(int oldValue, int expectedRowsUpdated)
{
using (var cmd = m_database.Connection.CreateCommand())
{
cmd.CommandText = @"drop table if exists update_rows_dapper;
create table update_rows_dapper(id integer not null primary key auto_increment, value integer not null);
insert into update_rows_dapper (value) VALUES (1), (2), (1), (4);
";
cmd.ExecuteNonQuery();
}
var rowsAffected = m_database.Connection.Execute(@"update update_rows_dapper set value = @newValue where value = @oldValue",
new { oldValue, newValue = 4 });
Assert.Equal(expectedRowsUpdated, rowsAffected);
}
[Theory]
[InlineData(true, 1, 2)]
[InlineData(true, 2, 1)]
[InlineData(true, 3, 0)]
[InlineData(true, 4, 0)]
[InlineData(false, 1, 2)]
[InlineData(false, 2, 1)]
[InlineData(false, 3, 0)]
[InlineData(false, 4, 1)]
public async Task UpdateRowsDapperAsync(bool useAffectedRows, int oldValue, int expectedRowsUpdated)
{
var csb = AppConfig.CreateConnectionStringBuilder();
csb.UseAffectedRows = useAffectedRows;
using (var connection = new MySqlConnection(csb.ConnectionString))
{
await connection.OpenAsync();
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = @"drop table if exists update_rows_dapper_async;
create table update_rows_dapper_async(id integer not null primary key auto_increment, value integer not null);
insert into update_rows_dapper_async (value) VALUES (1), (2), (1), (4);
";
cmd.ExecuteNonQuery();
}
var rowsAffected = await connection.ExecuteAsync(@"update update_rows_dapper_async set value = @newValue where value = @oldValue",
new { oldValue, newValue = 4 }).ConfigureAwait(false);
Assert.Equal(expectedRowsUpdated, rowsAffected);
}
}
[Fact]
public async Task UpdateDapperNoColumnsWereSelected()
{
await m_database.Connection.ExecuteAsync(@"drop table if exists update_station;
create table update_station (
SID bigint unsigned,
name text,
stationType_SID bigint unsigned not null,
geoPosition_SID bigint unsigned,
service_start datetime,
service_end datetime,
deleted boolean,
created_on datetime not null,
externalWebsite text,
externalTitle text
);
insert into update_station values(1, 'name', 2, null, null, null, false, '2016-09-07 06:28:00', 'https://github.com/mysql-net/MySqlConnector/issues/44', 'Issue #44');
").ConfigureAwait(false);
var queryString = @"UPDATE update_station SET name=@name,stationType_SID=@stationType_SID,geoPosition_SID=@geoPosition_SID,service_start=@service_start,service_end=@service_end,deleted=@deleted,created_on=@created_on,externalWebsite=@externalWebsite,externalTitle=@externalTitle WHERE SID=@SID";
var station = new Station
{
SID = 1,
name = "new name",
stationType_SID = 3,
geoPosition_SID = null,
service_start = new DateTime(2016, 1, 1),
service_end = new DateTime(2017, 12, 31),
deleted = true,
created_on = new DateTime(2000, 1, 1),
externalWebsite = null,
externalTitle = null,
};
try
{
await m_database.Connection.QueryAsync<Station>(queryString, station).ConfigureAwait(false);
Assert.True(false, "Should throw InvalidOperationException");
}
catch (InvalidOperationException ex)
{
Assert.Equal("No columns were selected", ex.Message);
}
}
public class Station
{
public ulong? SID { get; set; }
public string name { get; set; }
public ulong stationType_SID { get; set; }
public ulong? geoPosition_SID { get; set; }
public DateTime? service_start { get; set; }
public DateTime? service_end { get; set; }
public bool? deleted { get; set; }
public DateTime created_on { get; set; }
public string externalWebsite { get; set; }
public string externalTitle { get; set; }
}
readonly DatabaseFixture m_database;
}
}
| |
#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;
using System.Collections.Generic;
using System.ComponentModel;
#if !(NET35 || NET20 || PORTABLE40)
using System.Dynamic;
#endif
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private Type _rootType;
private int _rootLevel;
private readonly List<object> _serializeStack = new List<object>();
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
{
if (jsonWriter == null)
{
throw new ArgumentNullException(nameof(jsonWriter));
}
_rootType = objectType;
_rootLevel = _serializeStack.Count + 1;
JsonContract contract = GetContractSafe(value);
try
{
if (ShouldWriteReference(value, null, contract, null, null))
{
WriteReference(jsonWriter, value);
}
else
{
SerializeValue(jsonWriter, value, contract, null, null, null);
}
}
catch (Exception ex)
{
if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
{
HandleError(jsonWriter, 0);
}
else
{
// clear context in case serializer is being used inside a converter
// if the converter wraps the error then not clearing the context will cause this error:
// "Current error context error is different to requested error."
ClearErrorContext();
throw;
}
}
finally
{
// clear root contract to ensure that if level was > 1 then it won't
// accidently be used for non root values
_rootType = null;
}
}
private JsonSerializerProxy GetInternalSerializer()
{
if (InternalSerializer == null)
{
InternalSerializer = new JsonSerializerProxy(this);
}
return InternalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
{
return null;
}
return Serializer._contractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (contract.TypeCode == PrimitiveTypeCode.Bytes)
{
// if type name handling is enabled then wrap the base64 byte string in an object with the type name
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false);
JsonWriter.WriteValue(writer, contract.TypeCode, value);
writer.WriteEndObject();
return;
}
}
JsonWriter.WriteValue(writer, contract.TypeCode, value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null)
{
writer.WriteNull();
return;
}
JsonConverter converter =
((member != null) ? member.Converter : null) ??
((containerProperty != null) ? containerProperty.ItemConverter : null) ??
((containerContract != null) ? containerContract.ItemConverter : null) ??
valueContract.Converter ??
Serializer.GetMatchingConverter(valueContract.UnderlyingType) ??
valueContract.InternalConverter;
if (converter != null && converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
return;
}
switch (valueContract.ContractType)
{
case JsonContractType.Object:
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Array:
JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
if (!arrayContract.IsMultidimensionalArray)
{
SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty);
}
else
{
SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty);
}
break;
case JsonContractType.Primitive:
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.String:
SerializeString(writer, value, (JsonStringContract)valueContract);
break;
case JsonContractType.Dictionary:
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
SerializeDictionary(writer, (value is IDictionary) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
break;
#if !(NET35 || NET20 || PORTABLE40)
case JsonContractType.Dynamic:
SerializeDynamic(writer, (IDynamicMetaObjectProvider)value, (JsonDynamicContract)valueContract, member, containerContract, containerProperty);
break;
#endif
#if !(DOTNET || PORTABLE40 || PORTABLE)
case JsonContractType.Serializable:
SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
break;
#endif
case JsonContractType.Linq:
((JToken)value).WriteTo(writer, Serializer.Converters.ToArray());
break;
}
}
private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
{
isReference = property.IsReference;
}
if (isReference == null && containerProperty != null)
{
isReference = containerProperty.ItemIsReference;
}
if (isReference == null && collectionContract != null)
{
isReference = collectionContract.ItemIsReference;
}
if (isReference == null)
{
isReference = contract.IsReference;
}
return isReference;
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (value == null)
{
return false;
}
if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String)
{
return false;
}
bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty);
if (isReference == null)
{
if (valueContract.ContractType == JsonContractType.Array)
{
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
}
else
{
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
}
}
if (!isReference.GetValueOrDefault())
{
return false;
}
return Serializer.GetReferenceResolver().IsReferenced(this, value);
}
private bool ShouldWriteProperty(object memberValue, JsonProperty property)
{
if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
{
return false;
}
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue()))
{
return false;
}
return true;
}
private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
{
return true;
}
ReferenceLoopHandling? referenceLoopHandling = null;
if (property != null)
{
referenceLoopHandling = property.ReferenceLoopHandling;
}
if (referenceLoopHandling == null && containerProperty != null)
{
referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
}
if (referenceLoopHandling == null && containerContract != null)
{
referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
}
bool exists = (Serializer._equalityComparer != null)
? _serializeStack.Contains(value, Serializer._equalityComparer)
: _serializeStack.Contains(value);
if (exists)
{
string message = "Self referencing loop detected";
if (property != null)
{
message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
}
message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());
switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling))
{
case ReferenceLoopHandling.Error:
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
case ReferenceLoopHandling.Ignore:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null);
}
return false;
case ReferenceLoopHandling.Serialize:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null);
}
return true;
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null);
}
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false);
writer.WriteValue(reference);
writer.WriteEndObject();
}
private string GetReference(JsonWriter writer, object value)
{
try
{
string reference = Serializer.GetReferenceResolver().GetReference(this, value);
return reference;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex);
}
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
#if !(DOTNET || PORTABLE40 || PORTABLE)
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
&& !(converter is ComponentConverter)
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
{
s = converter.ConvertToInvariantString(value);
return true;
}
}
#endif
#if (DOTNET || PORTABLE)
if (value is Guid || value is Uri || value is TimeSpan)
{
s = value.ToString();
return true;
}
#endif
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
OnSerializing(writer, contract, value);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
OnSerialized(writer, contract, value);
}
private void OnSerializing(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
}
contract.InvokeOnSerializing(value, Serializer._context);
}
private void OnSerialized(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
}
contract.InvokeOnSerialized(value, Serializer._context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
{
continue;
}
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
if (contract.ExtensionDataGetter != null)
{
IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter(value);
if (extensionData != null)
{
foreach (KeyValuePair<object, object> e in extensionData)
{
JsonContract keyContract = GetContractSafe(e.Key);
JsonContract valueContract = GetContractSafe(e.Value);
bool escape;
string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape);
if (ShouldWriteReference(e.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, e.Value);
}
else
{
if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member))
{
continue;
}
writer.WritePropertyName(propertyName);
SerializeValue(writer, e.Value, valueContract, null, contract, member);
}
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue)
{
if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value))
{
if (property.PropertyContract == null)
{
property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType);
}
memberValue = property.ValueProvider.GetValue(value);
memberContract = (property.PropertyContract.IsSealed || !property.PropertyContract.ResolveRealType) ? property.PropertyContract : GetContractSafe(memberValue);
if (ShouldWriteProperty(memberValue, property))
{
if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
{
property.WritePropertyName(writer);
WriteReference(writer, memberValue);
return false;
}
if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
{
return false;
}
if (memberValue == null)
{
JsonObjectContract objectContract = contract as JsonObjectContract;
Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default;
if (resolvedRequired == Required.Always)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
if (resolvedRequired == Required.DisallowNull)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a non-null value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
}
return true;
}
}
memberContract = null;
memberValue = null;
return false;
}
private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
writer.WriteStartObject();
bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
// don't make readonly fields the referenced value because they can't be deserialized to
if (isReference && (member == null || member.Writable))
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, value);
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
}
private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null);
}
writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false);
writer.WriteValue(reference);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null);
}
writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false);
writer.WriteValue(typeName);
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
{
return;
}
_serializeStack.Add(value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
}
converter.WriteJson(writer, value, GetInternalSerializer());
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
{
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
}
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedCollection wrappedCollection = values as IWrappedCollection;
object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values;
OnSerializing(writer, contract, underlyingList);
_serializeStack.Add(underlyingList);
bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty);
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (hasWrittenMetadataObject)
{
writer.WriteEndObject();
}
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingList);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, values);
_serializeStack.Add(values);
bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);
SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]);
if (hasWrittenMetadataObject)
{
writer.WriteEndObject();
}
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, values);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
{
int dimension = indices.Length;
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
writer.WriteStartArray();
for (int i = values.GetLowerBound(dimension); i <= values.GetUpperBound(dimension); i++)
{
newIndices[dimension] = i;
bool isTopLevel = (newIndices.Length == values.Rank);
if (isTopLevel)
{
object value = values.GetValue(newIndices);
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth + 1);
}
else
{
throw;
}
}
}
else
{
SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
}
}
writer.WriteEndArray();
}
private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
// don't make readonly fields the referenced value because they can't be deserialized to
isReference = (isReference && (member == null || member.Writable));
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
bool writeMetadataObject = isReference || includeTypeDetails;
if (writeMetadataObject)
{
writer.WriteStartObject();
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, values);
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false);
}
if (contract.ItemContract == null)
{
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
}
return writeMetadataObject;
}
#if !(DOTNET || PORTABLE40 || PORTABLE)
#if !(NET20 || NET35)
[SecuritySafeCritical]
#endif
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (!JsonTypeReflector.FullyTrusted)
{
string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine +
@"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType());
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
}
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer._context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
JsonContract valueContract = GetContractSafe(serializationEntry.Value);
if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
WriteReference(writer, serializationEntry.Value);
}
else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member);
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
#if !(NET35 || NET20 || PORTABLE40)
private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
// only write non-dynamic properties that have an explicit attribute
if (property.HasMemberAttribute)
{
try
{
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
{
continue;
}
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
}
foreach (string memberName in value.GetDynamicMemberNames())
{
object memberValue;
if (contract.TryGetMember(value, memberName, out memberValue))
{
try
{
JsonContract valueContract = GetContractSafe(memberValue);
if (!ShouldWriteDynamicProperty(memberValue))
{
continue;
}
if (CheckForCircularReference(writer, memberValue, null, valueContract, contract, member))
{
string resolvedPropertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(memberName)
: memberName;
writer.WritePropertyName(resolvedPropertyName);
SerializeValue(writer, memberValue, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, memberName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
#endif
private bool ShouldWriteDynamicProperty(object memberValue)
{
if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null)
{
return false;
}
if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) &&
(memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType()))))
{
return false;
}
return true;
}
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
TypeNameHandling resolvedTypeNameHandling =
((member != null) ? member.TypeNameHandling : null)
?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null)
?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
?? Serializer._typeNameHandling;
if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag))
{
return true;
}
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto))
{
if (member != null)
{
if (contract.UnderlyingType != member.PropertyContract.CreatedType)
{
return true;
}
}
else if (containerContract != null)
{
if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType)
{
return true;
}
}
else if (_rootType != null && _serializeStack.Count == _rootLevel)
{
JsonContract rootContract = Serializer._contractResolver.ResolveContract(_rootType);
if (contract.UnderlyingType != rootContract.CreatedType)
{
return true;
}
}
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;
OnSerializing(writer, contract, underlyingDictionary);
_serializeStack.Add(underlyingDictionary);
WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);
if (contract.ItemContract == null)
{
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
}
if (contract.KeyContract == null)
{
contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
}
int initialDepth = writer.Top;
foreach (DictionaryEntry entry in values)
{
bool escape;
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);
propertyName = (contract.DictionaryKeyResolver != null)
? contract.DictionaryKeyResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName, escape);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
continue;
}
writer.WritePropertyName(propertyName, escape);
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
{
HandleError(writer, initialDepth);
}
else
{
throw;
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingDictionary);
}
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{
string propertyName;
if (contract.ContractType == JsonContractType.Primitive)
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable)
{
DateTime dt = DateTimeUtils.EnsureDateTime((DateTime)name, writer.DateTimeZoneHandling);
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeString(sw, dt, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#if !NET20
else if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffset || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeOffsetNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeOffsetString(sw, (DateTimeOffset)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
#endif
else
{
escape = true;
return Convert.ToString(name, CultureInfo.InvariantCulture);
}
}
else if (TryConvertToString(name, name.GetType(), out propertyName))
{
escape = true;
return propertyName;
}
else
{
escape = true;
return name.ToString();
}
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
if (writer.WriteState == WriteState.Property)
{
writer.WriteNull();
}
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
{
return true;
}
bool shouldSerialize = property.ShouldSerialize(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null);
}
return shouldSerialize;
}
private bool IsSpecified(JsonWriter writer, JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
{
return true;
}
bool isSpecified = property.GetIsSpecified(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
{
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null);
}
return isSpecified;
}
}
}
| |
using Xunit;
using System;
using System.Collections;
using System.Collections.Generic;
using HandlebarsDotNet.Features;
using HandlebarsDotNet.Helpers;
using HandlebarsDotNet.PathStructure;
using HandlebarsDotNet.ValueProviders;
namespace HandlebarsDotNet.Test
{
public class HelperTests
{
[Fact]
public void HelperWithLiteralArguments()
{
Handlebars.RegisterHelper("myHelper", (writer, context, args) => {
var count = 0;
foreach(var arg in args)
{
writer.Write("\nThing {0}: {1}", ++count, arg);
}
});
var source = "Here are some things: {{myHelper 'foo' 'bar'}}";
var template = Handlebars.Compile(source);
var output = template(new { });
var expected = "Here are some things: \nThing 1: foo\nThing 2: bar";
Assert.Equal(expected, output);
}
[Fact]
public void HelperWithOptions()
{
var handlebars = Handlebars.Create();
handlebars.RegisterHelper("myHelper",
(in EncodedTextWriter writer, in HelperOptions options, in Context context, in Arguments arguments) =>
{
var i = options.Data.Value<int>("i");
for (int j = 0; j < i; j++) writer.Write(j);
}
);
var source = "{{myHelper}}";
var template = handlebars.Compile(source);
var output = template(new { }, new { i = 5 });
var expected = "01234";
Assert.Equal(expected, output);
}
[Fact]
public void HelperWithOptionsStatic()
{
Handlebars.RegisterHelper("myHelper",
(in EncodedTextWriter writer, in HelperOptions options, in Context context, in Arguments arguments) =>
{
var i = options.Data.Value<int>("i");
for (int j = 0; j < i; j++) writer.Write(j);
}
);
var source = "{{myHelper}}";
var template = Handlebars.Compile(source);
var output = template(new { }, new { i = 5 });
var expected = "01234";
Assert.Equal(expected, output);
}
[Fact]
public void ReturnHelperWithOptions()
{
var handlebars = Handlebars.Create();
handlebars.RegisterHelper("myHelper",
(in HelperOptions options, in Context context, in Arguments arguments) =>
{
var data = options.Frame.Data;
var i = data.Value<int>("i");
return Enumerate(i);
static IEnumerable<int> Enumerate(int count)
{
for (var j = 0; j < count; j++) yield return j;
}
}
);
var source = "{{#each (myHelper)}}{{.}}{{/each}}";
var template = handlebars.Compile(source);
var output = template(new { }, new { i = 5 });
var expected = "01234";
Assert.Equal(expected, output);
}
[Fact]
public void ReturnHelperWithOptionsStatic()
{
Handlebars.RegisterHelper("myHelper",
(in HelperOptions options, in Context context, in Arguments arguments) =>
{
var data = options.Frame.Data;
var i = data.Value<int>("i");
return Enumerate(i);
static IEnumerable<int> Enumerate(int count)
{
for (var j = 0; j < count; j++) yield return j;
}
}
);
var source = "{{#each (myHelper)}}{{.}}{{/each}}";
var template = Handlebars.Compile(source);
var output = template(new { }, new { i = 5 });
var expected = "01234";
Assert.Equal(expected, output);
}
[Theory]
[InlineData("one.two")]
[InlineData("[one.two]")]
[InlineData("[one].two")]
[InlineData("one.[two]")]
public void HelperWithDotSeparatedNameWithNoParameters(string helperName)
{
var source = "{{ " + helperName + " }}";
var handlebars = Handlebars.Create();
handlebars.Configuration.Compatibility.RelaxedHelperNaming = true;
handlebars.RegisterHelper("one.two", (context, arguments) => 42);
var template = handlebars.Compile(source);
var actual = template(null);
Assert.Equal("42", actual);
}
[Theory]
[InlineData("one.two")]
[InlineData("[one.two]")]
[InlineData("[one].two")]
[InlineData("one.[two]")]
public void HelperWithDotSeparatedNameWithParameters(string helperName)
{
var source = "{{ " + helperName + " 'a' 'b' }}";
var handlebars = Handlebars.Create();
handlebars.Configuration.Compatibility.RelaxedHelperNaming = true;
handlebars.RegisterHelper("one.two", (context, arguments) => "42" + arguments[0] + arguments[1]);
var template = handlebars.Compile(source);
var actual = template(null);
Assert.Equal("42ab", actual);
}
[Fact]
public void BlockHelperWithBlockParams()
{
var handlebars = Handlebars.Create();
handlebars.RegisterHelper("myHelper", (writer, options, context, args) =>
{
using var frame = options.CreateFrame();
var blockParamsValues = new BlockParamsValues(frame, options.BlockVariables);
blockParamsValues.CreateProperty(0, out var _0);
for (var index = 0; index < args.Length; index++)
{
var arg = args[index];
blockParamsValues[_0] = index;
frame.Value = arg;
options.Template(writer, frame);
}
});
var source = "Here are some things: {{#myHelper 'foo' 'bar' as |counter|}}{{counter}}:{{this}}\n{{/myHelper}}";
var template = handlebars.Compile(source);
var output = template(new { });
var expected = "Here are some things: 0:foo\n1:bar\n";
Assert.Equal(expected, output);
}
[Fact]
public void BlockHelperLateBindWithBlockParams()
{
var handlebars = Handlebars.Create();
var source = "Here are some things: {{#myHelper 'foo' 'bar' as |counter|}}{{counter}}:{{this}}\n{{/myHelper}}";
var template = handlebars.Compile(source);
handlebars.RegisterHelper("myHelper", (writer, options, context, args) =>
{
using var frame = options.CreateFrame();
var blockParamsValues = new BlockParamsValues(frame, options.BlockVariables);
blockParamsValues.CreateProperty(0, out var _0);
for (var index = 0; index < args.Length; index++)
{
var arg = args[index];
blockParamsValues[_0] = index;
frame.Value = arg;
options.Template(writer, frame);
}
});
var output = template(new { });
var expected = "Here are some things: 0:foo\n1:bar\n";
Assert.Equal(expected, output);
}
[Fact]
public void BlockHelperLateBound()
{
var source = "Here are some things: \n" +
"{{#myHelper 'foo' 'bar' as |counter|}}\n" +
"{{counter}}:{{this}}\n" +
"{{/myHelper}}";
var template = Handlebars.Compile(source);
Handlebars.RegisterHelper("myHelper", (writer, options, context, args) =>
{
using var frame = options.CreateFrame();
var blockParamsValues = new BlockParamsValues(frame, options.BlockVariables);
blockParamsValues.CreateProperty(0, out var _0);
for (var index = 0; index < args.Length; index++)
{
var arg = args[index];
blockParamsValues[_0] = index;
frame.Value = arg;
options.Template(writer, frame);
}
});
var output = template(new { });
var expected = "Here are some things: \n0:foo\n1:bar\n";
Assert.Equal(expected, output);
}
[Fact]
public void BlockHelperLateBoundConflictsWithValue()
{
var source = "{{#late}}late{{/late}}";
var handlebars = Handlebars.Create();
var template = handlebars.Compile(source);
handlebars.RegisterHelper("late", (writer, options, context, args) =>
{
options.Template(writer, context);
});
var output = template(new { late = "should be ignored" });
var expected = "late";
Assert.Equal(expected, output);
}
[Fact]
public void BlockHelperLateBoundMissingHelperFallbackToDeferredSection()
{
var source = "{{#late}}late{{/late}}";
var handlebars = Handlebars.Create();
handlebars.Configuration.RegisterMissingHelperHook(
(in HelperOptions options, in Context context, in Arguments arguments) => "Hook"
);
var template = handlebars.Compile(source);
var output = template(new { late = "late" });
var expected = "late";
Assert.Equal(expected, output);
}
[Fact]
public void HelperLateBound()
{
var source = "{{lateHelper}}";
var template = Handlebars.Compile(source);
var expected = "late";
Handlebars.RegisterHelper("lateHelper", (writer, context, arguments) =>
{
writer.WriteSafeString(expected);
});
var output = template(null);
Assert.Equal(expected, output);
}
[Theory]
[InlineData("[$lateHelper]")]
[InlineData("[late.Helper]")]
[InlineData("[@lateHelper]")]
public void HelperEscapedLateBound(string helperName)
{
var handlebars = Handlebars.Create();
var source = "{{" + helperName + "}}";
var template = handlebars.Compile(source);
var expected = "late";
handlebars.RegisterHelper(helperName.Trim('[', ']'), (writer, context, arguments) =>
{
writer.WriteSafeString(expected);
});
var output = template(null);
Assert.Equal(expected, output);
}
[Theory]
[InlineData("{{lateHelper.a}}")]
[InlineData("{{[lateHelper].a}}")]
[InlineData("{{[lateHelper.a]}}")]
public void WrongHelperLiteralLateBound(string source)
{
var handlebars = Handlebars.Create();
var template = handlebars.Compile(source);
handlebars.RegisterHelper("lateHelper", (writer, context, arguments) =>
{
writer.WriteSafeString("should not appear");
});
var output = template(null);
Assert.Equal(string.Empty, output);
}
[Theory]
[InlineData("missing")]
[InlineData("[missing]")]
[InlineData("[$missing]")]
[InlineData("[m.i.s.s.i.n.g]")]
public void MissingHelperHook(string helperName)
{
var handlebars = Handlebars.Create();
var format = "Missing helper: {0}";
handlebars.Configuration
.RegisterMissingHelperHook(
(in HelperOptions options, in Context context, in Arguments arguments) =>
{
return string.Format(format, options.Name.TrimmedPath);
}
);
var source = "{{"+ helperName +"}}";
var template = handlebars.Compile(source);
var output = template(null);
var expected = string.Format(format, helperName.Trim('[', ']'));
Assert.Equal(expected, output);
}
[Fact]
public void MissingHelperHookViaFeatureAndMethod()
{
var expected = "Hook";
var handlebars = Handlebars.Create();
handlebars.Configuration
.RegisterMissingHelperHook(
(in HelperOptions options, in Context context, in Arguments arguments) => "Should be ignored"
);
handlebars.RegisterHelper("helperMissing",
(context, arguments) => expected
);
var source = "{{missing}}";
var template = handlebars.Compile(source);
var output = template(null);
Assert.Equal(expected, output);
}
[Theory]
[InlineData("missing")]
[InlineData("[missing]")]
[InlineData("[$missing]")]
[InlineData("[m.i.s.s.i.n.g]")]
public void MissingHelperHookViaHelperRegistration(string helperName)
{
var handlebars = Handlebars.Create();
var format = "Missing helper: {0}";
handlebars.RegisterHelper("helperMissing",
(in HelperOptions options, in Context context, in Arguments arguments) =>
{
return string.Format(format, options.Name.TrimmedPath);
});
var source = "{{"+ helperName +"}}";
var template = handlebars.Compile(source);
var output = template(null);
var expected = string.Format(format, helperName.Trim('[', ']'));
Assert.Equal(expected, output);
}
[Theory]
[InlineData("missing")]
[InlineData("[missing]")]
[InlineData("[$missing]")]
[InlineData("[m.i.s.s.i.n.g]")]
public void MissingBlockHelperHook(string helperName)
{
var handlebars = Handlebars.Create();
var format = "Missing block helper: {0}";
handlebars.Configuration
.RegisterMissingHelperHook(
blockHelperMissing: (writer, options, context, arguments) =>
{
writer.WriteSafeString(string.Format(format, options.Name.TrimmedPath));
});
var source = "{{#"+ helperName +"}}should not appear{{/" + helperName + "}}";
var template = handlebars.Compile(source);
var output = template(null);
var expected = string.Format(format, helperName.Trim('[', ']'));
Assert.Equal(expected, output);
}
[Theory]
[InlineData("missing")]
[InlineData("[missing]")]
[InlineData("[$missing]")]
[InlineData("[m.i.s.s.i.n.g]")]
public void MissingBlockHelperHookViaHelperRegistration(string helperName)
{
var handlebars = Handlebars.Create();
var format = "Missing block helper: {0}";
handlebars.RegisterHelper("blockHelperMissing", (writer, options, context, arguments) =>
{
writer.WriteSafeString(string.Format(format, options.Name.TrimmedPath));
});
var source = "{{#"+ helperName +"}}should not appear{{/" + helperName + "}}";
var template = handlebars.Compile(source);
var output = template(null);
var expected = string.Format(format, helperName.Trim('[', ']'));
Assert.Equal(expected, output);
}
[Fact]
public void MissingHelperHookWhenVariableExists()
{
var handlebars = Handlebars.Create();
var expected = "Variable";
handlebars.Configuration
.RegisterMissingHelperHook(
(in HelperOptions options, in Context context, in Arguments arguments) => "Hook"
);
var source = "{{missing}}";
var template = Handlebars.Compile(source);
var output = template(new { missing = "Variable" });
Assert.Equal(expected, output);
}
[Fact]
public void HelperWithLiteralArgumentsWithQuotes()
{
var helperName = "helper-" + Guid.NewGuid().ToString(); //randomize helper name
Handlebars.RegisterHelper(helperName, (writer, context, args) => {
var count = 0;
foreach(var arg in args)
{
writer.WriteSafeString(
string.Format("\nThing {0}: {1}", ++count, arg));
}
});
var source = "Here are some things: {{" + helperName + " 'My \"favorite\" movie' 'bar'}}";
var template = Handlebars.Compile(source);
var output = template(new { });
var expected = "Here are some things: \nThing 1: My \"favorite\" movie\nThing 2: bar";
Assert.Equal(expected, output);
}
[Fact]
public void InversionNoKey()
{
var source = "{{^key}}No key!{{/key}}";
var template = Handlebars.Compile(source);
var output = template(new { });
var expected = "No key!";
Assert.Equal(expected, output);
}
[Fact]
public void InversionFalsy()
{
var source = "{{^key}}Falsy value!{{/key}}";
var template = Handlebars.Compile(source);
var data = new
{
key = false
};
var output = template(data);
var expected = "Falsy value!";
Assert.Equal(expected, output);
}
[Fact]
public void InversionEmptySequence()
{
var source = "{{^key}}Empty sequence!{{/key}}";
var template = Handlebars.Compile(source);
var data = new
{
key = new string[] { }
};
var output = template(data);
var expected = "Empty sequence!";
Assert.Equal(expected, output);
}
[Fact]
public void InversionNonEmptySequence()
{
var source = "{{^key}}Empty sequence!{{/key}}";
var template = Handlebars.Compile(source);
var data = new
{
key = new[] { "element" }
};
var output = template(data);
var expected = "";
Assert.Equal(expected, output);
}
[Fact]
public void BlockHelperWithArbitraryInversion()
{
var source = "{{#ifCond arg1 arg2}}Args are same{{else}}Args are not same{{/ifCond}}";
Handlebars.RegisterHelper("ifCond", (writer, options, context, arguments) => {
if(arguments[0] == arguments[1])
{
options.Template(writer, context);
}
else
{
options.Inverse(writer, context);
}
});
var dataWithSameValues = new
{
arg1 = "a",
arg2 = "a"
};
var dataWithDifferentValues = new
{
arg1 = "a",
arg2 = "b"
};
var template = Handlebars.Compile(source);
var outputIsSame = template(dataWithSameValues);
var expectedIsSame = "Args are same";
var outputIsDifferent = template(dataWithDifferentValues);
var expectedIsDifferent = "Args are not same";
Assert.Equal(expectedIsSame, outputIsSame);
Assert.Equal(expectedIsDifferent, outputIsDifferent);
}
[Fact]
public void BlockHelperWithArbitraryInversionAndComplexOperator()
{
Handlebars.RegisterHelper("ifCond", (writer, options, context, args) => {
if (args.Length != 3)
{
writer.Write("ifCond:Wrong number of arguments");
return;
}
if (args[0] == null || args[0].GetType().Name == "UndefinedBindingResult")
{
writer.Write("ifCond:args[0] undefined");
return;
}
if (args[1] == null || args[1].GetType().Name == "UndefinedBindingResult")
{
writer.Write("ifCond:args[1] undefined");
return;
}
if (args[2] == null || args[2].GetType().Name == "UndefinedBindingResult")
{
writer.Write("ifCond:args[2] undefined");
return;
}
if (args[0].GetType().Name == "String" || args[0].GetType().Name == "JValue")
{
var val1 = args[0].ToString();
var val2 = args[2].ToString();
switch (args[1].ToString())
{
case ">":
if (val1.Length > val2.Length)
{
options.Template(writer, context);
}
else
{
options.Inverse(writer, context);
}
break;
case "=":
case "==":
if (val1 == val2)
{
options.Template(writer, context);
}
else
{
options.Inverse(writer, context);
}
break;
case "<":
if (val1.Length < val2.Length)
{
options.Template(writer, context);
}
else
{
options.Inverse(writer, context);
}
break;
case "!=":
case "<>":
if (val1 != val2)
{
options.Template(writer, context);
}
else
{
options.Inverse(writer, context);
}
break;
}
}
else
{
var val1 = float.Parse(args[0].ToString());
var val2 = float.Parse(args[2].ToString());
switch (args[1].ToString())
{
case ">":
if (val1 > val2)
{
options.Template(writer, context);
}
else
{
options.Inverse(writer, context);
}
break;
case "=":
case "==":
if (val1 == val2)
{
options.Template(writer, context);
}
else
{
options.Inverse(writer, context);
}
break;
case "<":
if (val1 < val2)
{
options.Template(writer, context);
}
else
{
options.Inverse(writer, context);
}
break;
case "!=":
case "<>":
if (val1 != val2)
{
options.Template(writer, context);
}
else
{
options.Inverse(writer, context);
}
break;
}
}
});
var template = Handlebars.Compile(@"{{#ifCond arg1 '>' arg2}}{{arg1}} is greater than {{arg2}}{{else}}{{arg1}} is less than {{arg2}}{{/ifCond}}");
var data = new { arg1 = 2, arg2 = 1 };
var result = template(data);
Assert.Equal("2 is greater than 1", result);
data = new { arg1 = 1, arg2 = 2 };
result = template(data);
Assert.Equal("1 is less than 2", result);
template = Handlebars.Compile(@"{{#ifCond arg1 '<' arg2}}{{arg1}} is less than {{arg2}}{{else}}{{arg1}} is greater than {{arg2}}{{/ifCond}}");
data = new { arg1 = 2, arg2 = 1 };
result = template(data);
Assert.Equal("2 is greater than 1", result);
data = new { arg1 = 1, arg2 = 2 };
result = template(data);
Assert.Equal("1 is less than 2", result);
template = Handlebars.Compile(@"{{#ifCond arg1 '=' arg2}}{{arg1}} is eq to {{arg2}}{{else}}{{arg1}} is not eq to {{arg2}}{{/ifCond}}");
data = new { arg1 = 1, arg2 = 1 };
result = template(data);
Assert.Equal("1 is eq to 1", result);
data = new { arg1 = 2, arg2 = 1 };
result = template(data);
Assert.Equal("2 is not eq to 1", result);
template = Handlebars.Compile(@"{{#ifCond arg1 '!=' arg2}}{{arg1}} is not eq to {{arg2}}{{else}}{{arg1}} is eq to {{arg2}}{{/ifCond}}");
data = new { arg1 = 2, arg2 = 1 };
result = template(data);
Assert.Equal("2 is not eq to 1", result);
template = Handlebars.Compile(@"{{#ifCond str '!=' ''}}not empty{{else}}empty{{/ifCond}}");
var datastr = new { str = "abc" };
result = template(datastr);
Assert.Equal("not empty", result);
template = Handlebars.Compile(@"{{#ifCond str '==' ''}}empty{{else}}not empty{{/ifCond}}");
datastr = new { str = "" };
result = template(datastr);
Assert.Equal("empty", result);
}
[Fact]
public void HelperWithNumericArguments()
{
Handlebars.RegisterHelper("myHelper", (writer, context, args) => {
var count = 0;
foreach(var arg in args)
{
writer.Write("\nThing {0}: {1}", ++count, arg);
}
});
var source = "Here are some things: {{myHelper 123 4567 -98.76}}";
var template = Handlebars.Compile(source);
var output = template(new { });
var expected = "Here are some things: \nThing 1: 123\nThing 2: 4567\nThing 3: -98.76";
Assert.Equal(expected, output);
}
[Fact]
public void HelperWithHashArgument()
{
var h = Handlebars.Create();
h.RegisterHelper("myHelper", (writer, context, args) => {
var hash = args[2] as Dictionary<string, object>;
foreach(var item in hash)
{
writer.Write(" {0}: {1}", item.Key, item.Value);
}
});
var source = "Here are some things:{{myHelper 'foo' 'bar' item1='val1' item2='val2'}}";
var template = h.Compile(source);
var output = template(new { });
var expected = "Here are some things: item1: val1 item2: val2";
Assert.Equal(expected, output);
}
[Fact]
public void BlockHelperWithSubExpression()
{
Handlebars.RegisterHelper("isEqual", (writer, context, args) =>
{
writer.WriteSafeString(args[0].ToString() == args[1].ToString() ? "true" : null);
});
var source = "{{#if (isEqual arg1 arg2)}}True{{/if}}";
var template = Handlebars.Compile(source);
var expectedIsTrue = "True";
var outputIsTrue = template(new { arg1 = 1, arg2 = 1 });
Assert.Equal(expectedIsTrue, outputIsTrue);
var expectedIsFalse = "";
var outputIsFalse = template(new { arg1 = 1, arg2 = 2 });
Assert.Equal(expectedIsFalse, outputIsFalse);
}
[Fact]
public void HelperWithSegmentLiteralArguments()
{
Handlebars.RegisterHelper("myHelper", (writer, context, args) => {
var count = 0;
foreach (var arg in args)
{
writer.Write("\nThing {0}: {1}", ++count, arg);
}
});
var source = "Here are some things: {{myHelper args.[0].arg args.[1].arg 'another argument'}}";
var template = Handlebars.Compile(source);
var data = new
{
args = new[] { new { arg = "foo" }, new { arg = "bar" } }
};
var output = template(data);
var expected = "Here are some things: \nThing 1: foo\nThing 2: bar\nThing 3: another argument";
Assert.Equal(expected, output);
}
[Fact]
public void EmptyBlockHelperWithInversion()
{
var source = "{{#ifCond}}{{else}}Inverse{{/ifCond}}";
Handlebars.RegisterHelper("ifCond", (writer, options, context, arguments) => {
options.Inverse(writer, context);
});
var data = new
{
};
var template = Handlebars.Compile(source);
var output = template(data);
Assert.Equal("Inverse", output);
}
[Fact]
public void HelperWithLiteralHashValues()
{
var source = "{{literalHelper Bool=true Integer=1 String=\"abc\"}}";
Handlebars.RegisterHelper("literalHelper", (writer, context, arguments) => {
var parameters = arguments[0] as IDictionary<string, object>;
Assert.IsType<bool>(parameters["Bool"]);
Assert.IsType<int>(parameters["Integer"]);
Assert.IsType<string>(parameters["String"]);
writer.Write($"{parameters["Bool"]} {parameters["Integer"]} {parameters["String"]}");
});
var data = new
{
};
var template = Handlebars.Compile(source);
var output = template(data);
Assert.Equal("True 1 abc", output);
}
[Fact]
public void HelperWithLiteralValues()
{
var source = "{{literalHelper true 1 \"abc\"}}";
Handlebars.RegisterHelper("literalHelper", (writer, context, arguments) => {
Assert.IsType<bool>(arguments[0]);
Assert.IsType<int>(arguments[1]);
Assert.IsType<string>(arguments[2]);
writer.Write($"{arguments[0]} {arguments[1]} {arguments[2]}");
});
var data = new
{
};
var template = Handlebars.Compile(source);
var output = template(data);
Assert.Equal("True 1 abc", output);
}
[Fact]
public void BlockHelperWithCustomIndex()
{
var handlebars = Handlebars.Create();
handlebars.RegisterHelper(new CustomEachBlockHelper());
var template = handlebars.Compile("{{#customEach this}}{{@value}}'s index is {{@index}} {{/customEach}}");
var result = template(new[] { "one", "two" });
Assert.Equal("one's index is 0 two's index is 1 ", result);
}
[Fact]
public void BlockHelperThis()
{
var handlebars = Handlebars.Create();
handlebars.RegisterHelper("bold",
(writer, options, context, arguments) =>
{
writer.WriteSafeString("<bold>");
writer.WriteSafeString(options.Template());
writer.WriteSafeString("</bold>");
});
const string source = "{{#bold}}This should be bold{{/bold}}";
var template = handlebars.Compile(source);
var actual = template(null);
Assert.Equal("<bold>This should be bold</bold>", actual);
}
[Fact]
public void BlockHelperElseThis()
{
var handlebars = Handlebars.Create();
handlebars.RegisterHelper("bold",
(writer, options, context, arguments) =>
{
writer.WriteSafeString("<bold>");
writer.WriteSafeString(options.Inverse());
writer.WriteSafeString("</bold>");
});
const string source = "{{^bold}}This should be bold{{/bold}}";
var template = handlebars.Compile(source);
var actual = template(null);
Assert.Equal("<bold>This should be bold</bold>", actual);
}
private class CustomEachBlockHelper : IHelperDescriptor<BlockHelperOptions>
{
public PathInfo Name { get; } = "customEach";
public object Invoke(in BlockHelperOptions options, in Context context, in Arguments arguments)
{
throw new NotImplementedException();
}
public void Invoke(in EncodedTextWriter output, in BlockHelperOptions options, in Context context, in Arguments arguments)
{
using var frame = options.CreateFrame();
var data = new DataValues(frame);
data.CreateProperty(ChainSegment.Value, null, out var valueIndex);
var iterationIndex = 0;
foreach (var item in (IEnumerable) arguments[0])
{
data[ChainSegment.Index] = iterationIndex;
data[valueIndex] = item;
frame.Value = item;
options.Template(output, frame);
++iterationIndex;
}
}
}
}
}
| |
using System;
using BigMath;
using NUnit.Framework;
using Raksha.Asn1;
using Raksha.Asn1.Icao;
using Raksha.Asn1.X509;
using Raksha.Math;
using Raksha.Tests.Utilities;
namespace Raksha.Tests.Asn1
{
[TestFixture]
public class LDSSecurityObjectUnitTest
: SimpleTest
{
public override string Name
{
get { return "LDSSecurityObject"; }
}
private byte[] GenerateHash()
{
Random rand = new Random();
byte[] bytes = new byte[20];
rand.NextBytes(bytes);
return bytes;
}
public override void PerformTest()
{
AlgorithmIdentifier algoId = new AlgorithmIdentifier("1.3.14.3.2.26");
DataGroupHash[] datas = new DataGroupHash[2];
datas[0] = new DataGroupHash(1, new DerOctetString(GenerateHash()));
datas[1] = new DataGroupHash(2, new DerOctetString(GenerateHash()));
LdsSecurityObject so = new LdsSecurityObject(algoId, datas);
CheckConstruction(so, algoId, datas);
LdsVersionInfo versionInfo = new LdsVersionInfo("Hello", "world");
so = new LdsSecurityObject(algoId, datas, versionInfo);
CheckConstruction(so, algoId, datas, versionInfo);
try
{
LdsSecurityObject.GetInstance(null);
}
catch (Exception)
{
Fail("GetInstance() failed to handle null.");
}
try
{
LdsSecurityObject.GetInstance(new object());
Fail("GetInstance() failed to detect bad object.");
}
catch (ArgumentException)
{
// expected
}
try
{
LdsSecurityObject.GetInstance(DerSequence.Empty);
Fail("constructor failed to detect empty sequence.");
}
catch (ArgumentException)
{
// expected
}
try
{
new LdsSecurityObject(algoId, new DataGroupHash[1]);
Fail("constructor failed to detect small DataGroupHash array.");
}
catch (ArgumentException)
{
// expected
}
try
{
new LdsSecurityObject(algoId, new DataGroupHash[LdsSecurityObject.UBDataGroups + 1]);
Fail("constructor failed to out of bounds DataGroupHash array.");
}
catch (ArgumentException)
{
// expected
}
}
private void CheckConstruction(
LdsSecurityObject so,
AlgorithmIdentifier digestAlgorithmIdentifier,
DataGroupHash[] datagroupHash)
{
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, null);
so = LdsSecurityObject.GetInstance(so);
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, null);
Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(
so.ToAsn1Object().GetEncoded());
so = LdsSecurityObject.GetInstance(seq);
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, null);
}
private void CheckConstruction(
LdsSecurityObject so,
AlgorithmIdentifier digestAlgorithmIdentifier,
DataGroupHash[] datagroupHash,
LdsVersionInfo versionInfo)
{
if (!so.Version.Equals(BigInteger.One))
{
Fail("version number not 1");
}
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, versionInfo);
so = LdsSecurityObject.GetInstance(so);
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, versionInfo);
Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(
so.ToAsn1Object().GetEncoded());
so = LdsSecurityObject.GetInstance(seq);
CheckStatement(so, digestAlgorithmIdentifier, datagroupHash, versionInfo);
}
private void CheckStatement(
LdsSecurityObject so,
AlgorithmIdentifier digestAlgorithmIdentifier,
DataGroupHash[] datagroupHash,
LdsVersionInfo versionInfo)
{
if (digestAlgorithmIdentifier != null)
{
if (!so.DigestAlgorithmIdentifier.Equals(digestAlgorithmIdentifier))
{
Fail("ids don't match.");
}
}
else if (so.DigestAlgorithmIdentifier != null)
{
Fail("digest algorithm Id found when none expected.");
}
if (datagroupHash != null)
{
DataGroupHash[] datas = so.GetDatagroupHash();
for (int i = 0; i != datas.Length; i++)
{
if (!datagroupHash[i].Equals(datas[i]))
{
Fail("name registration authorities don't match.");
}
}
}
else if (so.GetDatagroupHash() != null)
{
Fail("data hash groups found when none expected.");
}
if (versionInfo != null)
{
if (!versionInfo.Equals(so.VersionInfo))
{
Fail("versionInfo doesn't match");
}
}
else if (so.VersionInfo != null)
{
Fail("version info found when none expected.");
}
}
public static void Main(
string[] args)
{
RunTest(new LDSSecurityObjectUnitTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebApiContrib.Tracing.Slab.DemoApp.WithSignalR.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Text;
using Xunit;
namespace System.Text.EncodingTests
{
//System.Test.UnicodeEncoding.GetChars(System.Byte[],System.Int32,System.Int32,System.Char[],System.Int32)
public class UnicodeEncodingGetChars
{
#region Positive Tests
// PosTest1:Invoke the method
[Fact]
public void PosTest1()
{
int actualValue;
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
actualValue = uEncoding.GetChars(bytes, 0, 20, desChars, 0);
Assert.Equal(10, actualValue);
}
// PosTest2:Invoke the method with random char count
[Fact]
public void PosTest2()
{
int expectedValue = TestLibrary.Generator.GetInt16(-55) % 10 + 1;
int actualValue;
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, expectedValue, bytes, 0);
actualValue = uEncoding.GetChars(bytes, 0, expectedValue * 2, desChars, 0);
Assert.Equal(expectedValue, actualValue);
}
// PosTest3:Invoke the method and set charIndex as 10
[Fact]
public void PosTest3()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
int actualValue;
actualValue = uEncoding.GetChars(bytes, 0, 0, desChars, 10);
Assert.Equal(0, actualValue);
}
// PosTest4:Invoke the method and set byteIndex as 20
[Fact]
public void PosTest4()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
int actualValue;
actualValue = uEncoding.GetChars(bytes, 20, 0, desChars, 10);
Assert.Equal(0, actualValue);
}
#endregion
#region Negative Tests
// NegTest1:Invoke the method and set chars as null
[Fact]
public void NegTest1()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = null;
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
int actualValue;
Assert.Throws<ArgumentNullException>(() =>
{
actualValue = uEncoding.GetChars(bytes, 0, 0, desChars, 0);
});
}
// NegTest2:Invoke the method and set bytes as null
[Fact]
public void NegTest2()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = null;
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentNullException>(() =>
{
actualValue = uEncoding.GetChars(bytes, 0, 0, desChars, 0);
});
}
// NegTest3:Invoke the method and the destination buffer is not enough
[Fact]
public void NegTest3()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[5];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
int actualValue;
Assert.Throws<ArgumentException>(() =>
{
actualValue = uEncoding.GetChars(bytes, 0, 20, desChars, 0);
});
}
// NegTest4:Invoke the method and the destination buffer is not enough
[Fact]
public void NegTest4()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
int actualValue;
Assert.Throws<ArgumentException>(() =>
{
actualValue = uEncoding.GetChars(bytes, 0, 20, desChars, 5);
});
}
// NegTest5:Invoke the method and set byteIndex as -1
[Fact]
public void NegTest5()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetChars(bytes, -1, 0, desChars, 0);
});
}
// NegTest6:Invoke the method and set byteIndex as 20
[Fact]
public void NegTest6()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetChars(bytes, 20, 1, desChars, 10);
});
}
// NegTest7:Invoke the method and set byteCount as -1
[Fact]
public void NegTest7()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetChars(bytes, 0, -1, desChars, 0);
});
}
// NegTest8:Invoke the method and set byteCount as 21
[Fact]
public void NegTest8()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetChars(bytes, 0, 21, desChars, 0);
});
}
// NegTest9:Invoke the method and set charIndex as -1
[Fact]
public void NegTest9()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetChars(bytes, 0, 0, desChars, -1);
});
}
// NegTest10:Invoke the method and set charIndex as 11
[Fact]
public void NegTest10()
{
Char[] srcChars = GetCharArray(10);
Char[] desChars = new Char[10];
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int byteCount = uEncoding.GetBytes(srcChars, 0, 10, bytes, 0);
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetChars(bytes, 0, 0, desChars, 11);
});
}
#endregion
#region Helper Methods
//Create a None-Surrogate-Char Array.
public Char[] GetCharArray(int length)
{
if (length <= 0) return new Char[] { };
Char[] charArray = new Char[length];
int i = 0;
while (i < length)
{
Char temp = TestLibrary.Generator.GetChar(-55);
if (!Char.IsSurrogate(temp))
{
charArray[i] = temp;
i++;
}
}
return charArray;
}
//Convert Char Array to String
public String ToString(Char[] chars)
{
String str = "{";
for (int i = 0; i < chars.Length; i++)
{
str = str + @"\u" + String.Format("{0:X04}", (int)chars[i]);
if (i != chars.Length - 1) str = str + ",";
}
str = str + "}";
return str;
}
#endregion
}
}
| |
using System;
using System.Collections;
public class ArrayBinarySort2
{
private const int c_MIN_SIZE = 64;
private const int c_MAX_SIZE = 1024;
private const int c_NUM_LOOPS = 50;
public static int Main()
{
ArrayBinarySort2 ac = new ArrayBinarySort2();
TestLibrary.TestFramework.BeginTestCase("Array.Sort(Array, Array, int, int, IComparer)");
if (ac.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
TestLibrary.TestFramework.LogInformation("");
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
Array keys;
Array items;
int length;
IComparer myc;
byte element;
TestLibrary.TestFramework.BeginScenario("PosTest1: Array.Sort(Array, Array, int, int, IComparer) ");
try
{
myc = new MyComparer();
for (int j=0; j<c_NUM_LOOPS; j++)
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
keys = Array.CreateInstance(typeof(byte), length);
items = Array.CreateInstance(typeof(byte), length);
// fill the array
for (int i=0; i<keys.Length; i++)
{
keys.SetValue((object)TestLibrary.Generator.GetByte(-55), i);
items.SetValue(keys.GetValue(i), i);
}
Array.Sort(keys, items, 0, length, myc);
// ensure that all the elements are sorted
element = (byte)keys.GetValue(0);
for(int i=0; i<keys.Length; i++)
{
if (element > (byte)keys.GetValue(i))
{
TestLibrary.TestFramework.LogError("000", "Unexpected key: Element (" + element + ") is greater than (" + (byte)keys.GetValue(i) + ")");
retVal = false;
}
if ((byte)items.GetValue(i) != (byte)keys.GetValue(i))
{
TestLibrary.TestFramework.LogError("001", "Unexpected item: Expected(" + (byte)keys.GetValue(i) + ") Actual(" + (byte)items.GetValue(i) + ")");
retVal = false;
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
Array keys;
Array items;
int length;
IComparer myc;
byte element;
TestLibrary.TestFramework.BeginScenario("PosTest2: Array.Sort(Array, Array, int, int, IComparer) items is null");
try
{
myc = new MyComparer();
for (int j=0; j<c_NUM_LOOPS; j++)
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
keys = Array.CreateInstance(typeof(byte), length);
items = null;
// fill the array
for (int i=0; i<keys.Length; i++)
{
keys.SetValue((object)TestLibrary.Generator.GetByte(-55), i);
}
Array.Sort(keys, items, 0, length, myc);
// ensure that all the elements are sorted
element = (byte)keys.GetValue(0);
for(int i=0; i<keys.Length; i++)
{
if (element > (byte)keys.GetValue(i))
{
TestLibrary.TestFramework.LogError("003", "Unexpected key: Element (" + element + ") is greater than (" + (byte)keys.GetValue(i) + ")");
retVal = false;
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
Array keys;
Array items;
IComparer myc;
TestLibrary.TestFramework.BeginScenario("NegTest1: Array.Sort(Array, Array, int, int, IComparer) keys is null");
try
{
keys = null;
items = null;
myc = new MyComparer();
Array.Sort(keys, items, 0, 0, myc);
TestLibrary.TestFramework.LogError("005", "Exception expected.");
retVal = false;
}
catch (ArgumentNullException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
Array keys;
Array items;
IComparer myc;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest2: Array.Sort(Array, Array, int, int, IComparer) length < 0");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
keys = Array.CreateInstance(typeof(byte), length);
items = Array.CreateInstance(typeof(byte), length);
myc = new MyComparer();
Array.Sort(keys, items, 0, -1, myc);
TestLibrary.TestFramework.LogError("007", "Exception expected.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
Array keys;
Array items;
IComparer myc;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest3: Array.Sort(Array, Array, int, int, IComparer) length too long");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
keys = Array.CreateInstance(typeof(byte), length);
items = Array.CreateInstance(typeof(byte), length);
myc = new MyComparer();
Array.Sort(keys, items, length+10, length, myc);
TestLibrary.TestFramework.LogError("009", "Exception expected.");
retVal = false;
}
catch (ArgumentException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public class MyComparer : IComparer
{
public int Compare(object obj1, object obj2)
{
if ((byte)obj1 == (byte)obj2) return 0;
return ((byte)obj1 < (byte)obj2) ? -1 : 1;
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Avalonia.Collections;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Diagnostics;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Logging;
using Avalonia.LogicalTree;
using Avalonia.Styling;
namespace Avalonia.Controls
{
/// <summary>
/// Base class for Avalonia controls.
/// </summary>
/// <remarks>
/// The control class extends <see cref="InputElement"/> and adds the following features:
///
/// - An inherited <see cref="DataContext"/>.
/// - A <see cref="Tag"/> property to allow user-defined data to be attached to the control.
/// - A collection of class strings for custom styling.
/// - Implements <see cref="IStyleable"/> to allow styling to work on the control.
/// - Implements <see cref="ILogical"/> to form part of a logical tree.
/// </remarks>
public class Control : InputElement, IControl, INamed, ISetInheritanceParent, ISetLogicalParent, ISupportInitialize
{
/// <summary>
/// Defines the <see cref="DataContext"/> property.
/// </summary>
public static readonly StyledProperty<object> DataContextProperty =
AvaloniaProperty.Register<Control, object>(
nameof(DataContext),
inherits: true,
notifying: DataContextNotifying);
/// <summary>
/// Defines the <see cref="FocusAdorner"/> property.
/// </summary>
public static readonly StyledProperty<ITemplate<IControl>> FocusAdornerProperty =
AvaloniaProperty.Register<Control, ITemplate<IControl>>(nameof(FocusAdorner));
/// <summary>
/// Defines the <see cref="Name"/> property.
/// </summary>
public static readonly DirectProperty<Control, string> NameProperty =
AvaloniaProperty.RegisterDirect<Control, string>(nameof(Name), o => o.Name, (o, v) => o.Name = v);
/// <summary>
/// Defines the <see cref="Parent"/> property.
/// </summary>
public static readonly DirectProperty<Control, IControl> ParentProperty =
AvaloniaProperty.RegisterDirect<Control, IControl>(nameof(Parent), o => o.Parent);
/// <summary>
/// Defines the <see cref="Tag"/> property.
/// </summary>
public static readonly StyledProperty<object> TagProperty =
AvaloniaProperty.Register<Control, object>(nameof(Tag));
/// <summary>
/// Defines the <see cref="TemplatedParent"/> property.
/// </summary>
public static readonly StyledProperty<ITemplatedControl> TemplatedParentProperty =
AvaloniaProperty.Register<Control, ITemplatedControl>(nameof(TemplatedParent), inherits: true);
/// <summary>
/// Defines the <see cref="ContextMenu"/> property.
/// </summary>
public static readonly StyledProperty<ContextMenu> ContextMenuProperty =
AvaloniaProperty.Register<Control, ContextMenu>(nameof(ContextMenu));
/// <summary>
/// Event raised when an element wishes to be scrolled into view.
/// </summary>
public static readonly RoutedEvent<RequestBringIntoViewEventArgs> RequestBringIntoViewEvent =
RoutedEvent.Register<Control, RequestBringIntoViewEventArgs>("RequestBringIntoView", RoutingStrategies.Bubble);
private int _initCount;
private string _name;
private IControl _parent;
private readonly Classes _classes = new Classes();
private DataTemplates _dataTemplates;
private IControl _focusAdorner;
private bool _isAttachedToLogicalTree;
private IAvaloniaList<ILogical> _logicalChildren;
private INameScope _nameScope;
private Styles _styles;
private bool _styled;
private Subject<IStyleable> _styleDetach = new Subject<IStyleable>();
/// <summary>
/// Initializes static members of the <see cref="Control"/> class.
/// </summary>
static Control()
{
AffectsMeasure(IsVisibleProperty);
PseudoClass(IsEnabledCoreProperty, x => !x, ":disabled");
PseudoClass(IsFocusedProperty, ":focus");
PseudoClass(IsPointerOverProperty, ":pointerover");
PseudoClass(ValidationStatusProperty, status => !status.IsValid, ":invalid");
}
/// <summary>
/// Initializes a new instance of the <see cref="Control"/> class.
/// </summary>
public Control()
{
_nameScope = this as INameScope;
}
/// <summary>
/// Raised when the control is attached to a rooted logical tree.
/// </summary>
public event EventHandler<LogicalTreeAttachmentEventArgs> AttachedToLogicalTree;
/// <summary>
/// Raised when the control is detached from a rooted logical tree.
/// </summary>
public event EventHandler<LogicalTreeAttachmentEventArgs> DetachedFromLogicalTree;
/// <summary>
/// Occurs when the <see cref="DataContext"/> property changes.
/// </summary>
/// <remarks>
/// This event will be raised when the <see cref="DataContext"/> property has changed and
/// all subscribers to that change have been notified.
/// </remarks>
public event EventHandler DataContextChanged;
/// <summary>
/// Occurs when the control has finished initialization.
/// </summary>
/// <remarks>
/// The Initialized event indicates that all property values on the control have been set.
/// When loading the control from markup, it occurs when
/// <see cref="ISupportInitialize.EndInit"/> is called *and* the control
/// is attached to a rooted logical tree. When the control is created by code and
/// <see cref="ISupportInitialize"/> is not used, it is called when the control is attached
/// to the visual tree.
/// </remarks>
public event EventHandler Initialized;
/// <summary>
/// Gets or sets the name of the control.
/// </summary>
/// <remarks>
/// An element's name is used to uniquely identify a control within the control's name
/// scope. Once the element is added to a logical tree, its name cannot be changed.
/// </remarks>
public string Name
{
get
{
return _name;
}
set
{
if (value.Trim() == string.Empty)
{
throw new InvalidOperationException("Cannot set Name to empty string.");
}
if (_styled)
{
throw new InvalidOperationException("Cannot set Name : control already styled.");
}
_name = value;
}
}
/// <summary>
/// Gets or sets the control's classes.
/// </summary>
/// <remarks>
/// <para>
/// Classes can be used to apply user-defined styling to controls, or to allow controls
/// that share a common purpose to be easily selected.
/// </para>
/// <para>
/// Even though this property can be set, the setter is only intended for use in object
/// initializers. Assigning to this property does not change the underlying collection,
/// it simply clears the existing collection and addds the contents of the assigned
/// collection.
/// </para>
/// </remarks>
public Classes Classes
{
get
{
return _classes;
}
set
{
if (_classes != value)
{
_classes.Replace(value);
}
}
}
/// <summary>
/// Gets or sets the control's data context.
/// </summary>
/// <remarks>
/// The data context is an inherited property that specifies the default object that will
/// be used for data binding.
/// </remarks>
public object DataContext
{
get { return GetValue(DataContextProperty); }
set { SetValue(DataContextProperty, value); }
}
/// <summary>
/// Gets or sets the control's focus adorner.
/// </summary>
public ITemplate<IControl> FocusAdorner
{
get { return GetValue(FocusAdornerProperty); }
set { SetValue(FocusAdornerProperty, value); }
}
/// <summary>
/// Gets or sets the data templates for the control.
/// </summary>
/// <remarks>
/// Each control may define data templates which are applied to the control itself and its
/// children.
/// </remarks>
public DataTemplates DataTemplates
{
get { return _dataTemplates ?? (_dataTemplates = new DataTemplates()); }
set { _dataTemplates = value; }
}
/// <summary>
/// Gets a value that indicates whether the element has finished initialization.
/// </summary>
/// <remarks>
/// For more information about when IsInitialized is set, see the <see cref="Initialized"/>
/// event.
/// </remarks>
public bool IsInitialized { get; private set; }
/// <summary>
/// Gets or sets the styles for the control.
/// </summary>
/// <remarks>
/// Styles for the entire application are added to the Application.Styles collection, but
/// each control may in addition define its own styles which are applied to the control
/// itself and its children.
/// </remarks>
public Styles Styles
{
get { return _styles ?? (_styles = new Styles()); }
set { _styles = value; }
}
/// <summary>
/// Gets the control's logical parent.
/// </summary>
public IControl Parent => _parent;
/// <summary>
/// Gets or sets a context menu to the control.
/// </summary>
public ContextMenu ContextMenu
{
get { return GetValue(ContextMenuProperty); }
set { SetValue(ContextMenuProperty, value); }
}
/// <summary>
/// Gets or sets a user-defined object attached to the control.
/// </summary>
public object Tag
{
get { return GetValue(TagProperty); }
set { SetValue(TagProperty, value); }
}
/// <summary>
/// Gets the control whose lookless template this control is part of.
/// </summary>
public ITemplatedControl TemplatedParent
{
get { return GetValue(TemplatedParentProperty); }
internal set { SetValue(TemplatedParentProperty, value); }
}
/// <summary>
/// Gets a value indicating whether the element is attached to a rooted logical tree.
/// </summary>
bool ILogical.IsAttachedToLogicalTree => _isAttachedToLogicalTree;
/// <summary>
/// Gets the control's logical parent.
/// </summary>
ILogical ILogical.LogicalParent => Parent;
/// <summary>
/// Gets the control's logical children.
/// </summary>
IAvaloniaReadOnlyList<ILogical> ILogical.LogicalChildren => LogicalChildren;
/// <inheritdoc/>
IAvaloniaReadOnlyList<string> IStyleable.Classes => Classes;
/// <summary>
/// Gets the type by which the control is styled.
/// </summary>
/// <remarks>
/// Usually controls are styled by their own type, but there are instances where you want
/// a control to be styled by its base type, e.g. creating SpecialButton that
/// derives from Button and adds extra functionality but is still styled as a regular
/// Button.
/// </remarks>
Type IStyleable.StyleKey => GetType();
/// <inheritdoc/>
IObservable<IStyleable> IStyleable.StyleDetach => _styleDetach;
/// <inheritdoc/>
IStyleHost IStyleHost.StylingParent => (IStyleHost)InheritanceParent;
/// <inheritdoc/>
public virtual void BeginInit()
{
++_initCount;
}
/// <inheritdoc/>
public virtual void EndInit()
{
if (_initCount == 0)
{
throw new InvalidOperationException("BeginInit was not called.");
}
if (--_initCount == 0 && _isAttachedToLogicalTree)
{
if (!_styled)
{
RegisterWithNameScope();
ApplyStyling();
_styled = true;
}
if (!IsInitialized)
{
IsInitialized = true;
Initialized?.Invoke(this, EventArgs.Empty);
}
}
}
/// <inheritdoc/>
void ILogical.NotifyDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
this.OnDetachedFromLogicalTreeCore(e);
}
/// <summary>
/// Gets the control's logical children.
/// </summary>
protected IAvaloniaList<ILogical> LogicalChildren
{
get
{
if (_logicalChildren == null)
{
var list = new AvaloniaList<ILogical>();
list.ResetBehavior = ResetBehavior.Remove;
list.Validate = ValidateLogicalChild;
list.CollectionChanged += LogicalChildrenCollectionChanged;
_logicalChildren = list;
}
return _logicalChildren;
}
}
/// <summary>
/// Gets the <see cref="Classes"/> collection in a form that allows adding and removing
/// pseudoclasses.
/// </summary>
protected IPseudoClasses PseudoClasses => Classes;
/// <inheritdoc/>
protected override void DataValidationChanged(AvaloniaProperty property, IValidationStatus status)
{
base.DataValidationChanged(property, status);
ValidationStatus.UpdateValidationStatus(status);
}
/// <summary>
/// Sets the control's logical parent.
/// </summary>
/// <param name="parent">The parent.</param>
void ISetLogicalParent.SetParent(ILogical parent)
{
var old = Parent;
if (parent != old)
{
if (old != null && parent != null)
{
throw new InvalidOperationException("The Control already has a parent.");
}
if (_isAttachedToLogicalTree)
{
var oldRoot = FindStyleRoot(old);
if (oldRoot == null)
{
throw new AvaloniaInternalException("Was attached to logical tree but cannot find root.");
}
var e = new LogicalTreeAttachmentEventArgs(oldRoot);
OnDetachedFromLogicalTreeCore(e);
}
if (InheritanceParent == null || parent == null)
{
InheritanceParent = parent as AvaloniaObject;
}
_parent = (IControl)parent;
if (_parent is IStyleRoot || _parent?.IsAttachedToLogicalTree == true)
{
var newRoot = FindStyleRoot(this);
if (newRoot == null)
{
throw new AvaloniaInternalException("Parent is atttached to logical tree but cannot find root.");
}
var e = new LogicalTreeAttachmentEventArgs(newRoot);
OnAttachedToLogicalTreeCore(e);
}
RaisePropertyChanged(ParentProperty, old, _parent, BindingPriority.LocalValue);
}
}
/// <summary>
/// Sets the control's inheritance parent.
/// </summary>
/// <param name="parent">The parent.</param>
void ISetInheritanceParent.SetParent(IAvaloniaObject parent)
{
InheritanceParent = parent;
}
/// <summary>
/// Adds a pseudo-class to be set when a property is true.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="className">The pseudo-class.</param>
protected static void PseudoClass(AvaloniaProperty<bool> property, string className)
{
PseudoClass(property, x => x, className);
}
/// <summary>
/// Adds a pseudo-class to be set when a property equals a certain value.
/// </summary>
/// <typeparam name="T">The type of the property.</typeparam>
/// <param name="property">The property.</param>
/// <param name="selector">Returns a boolean value based on the property value.</param>
/// <param name="className">The pseudo-class.</param>
protected static void PseudoClass<T>(
AvaloniaProperty<T> property,
Func<T, bool> selector,
string className)
{
Contract.Requires<ArgumentNullException>(property != null);
Contract.Requires<ArgumentNullException>(selector != null);
Contract.Requires<ArgumentNullException>(className != null);
Contract.Requires<ArgumentNullException>(property != null);
if (string.IsNullOrWhiteSpace(className))
{
throw new ArgumentException("Cannot supply an empty className.");
}
property.Changed.Merge(property.Initialized)
.Where(e => e.Sender is Control)
.Subscribe(e =>
{
if (selector((T)e.NewValue))
{
((Control)e.Sender).PseudoClasses.Add(className);
}
else
{
((Control)e.Sender).PseudoClasses.Remove(className);
}
});
}
/// <summary>
/// Gets the element that recieves the focus adorner.
/// </summary>
/// <returns>The control that recieves the focus adorner.</returns>
protected virtual IControl GetTemplateFocusTarget()
{
return this;
}
/// <summary>
/// Called when the control is added to a rooted logical tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
{
AttachedToLogicalTree?.Invoke(this, e);
}
/// <summary>
/// Called when the control is removed from a rooted logical tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
DetachedFromLogicalTree?.Invoke(this, e);
}
/// <inheritdoc/>
protected sealed override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTreeCore(e);
if (!IsInitialized)
{
IsInitialized = true;
Initialized?.Invoke(this, EventArgs.Empty);
}
}
/// <inheritdoc/>
protected sealed override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
base.OnDetachedFromVisualTreeCore(e);
}
/// <summary>
/// Called before the <see cref="DataContext"/> property changes.
/// </summary>
protected virtual void OnDataContextChanging()
{
}
/// <summary>
/// Called after the <see cref="DataContext"/> property changes.
/// </summary>
protected virtual void OnDataContextChanged()
{
DataContextChanged?.Invoke(this, EventArgs.Empty);
}
/// <inheritdoc/>
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
if (IsFocused &&
(e.NavigationMethod == NavigationMethod.Tab ||
e.NavigationMethod == NavigationMethod.Directional))
{
var adornerLayer = AdornerLayer.GetAdornerLayer(this);
if (adornerLayer != null)
{
if (_focusAdorner == null)
{
var template = GetValue(FocusAdornerProperty);
if (template != null)
{
_focusAdorner = template.Build();
}
}
if (_focusAdorner != null)
{
var target = (Visual)GetTemplateFocusTarget();
if (target != null)
{
AdornerLayer.SetAdornedElement((Visual)_focusAdorner, target);
adornerLayer.Children.Add(_focusAdorner);
}
}
}
}
}
/// <inheritdoc/>
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
if (_focusAdorner != null)
{
var adornerLayer = _focusAdorner.Parent as Panel;
adornerLayer.Children.Remove(_focusAdorner);
_focusAdorner = null;
}
}
/// <summary>
/// Called when the <see cref="DataContext"/> property begins and ends being notified.
/// </summary>
/// <param name="o">The object on which the DataContext is changing.</param>
/// <param name="notifying">Whether the notifcation is beginning or ending.</param>
private static void DataContextNotifying(IAvaloniaObject o, bool notifying)
{
var control = o as Control;
if (control != null)
{
if (notifying)
{
control.OnDataContextChanging();
}
else
{
control.OnDataContextChanged();
}
}
}
private static IStyleRoot FindStyleRoot(IStyleHost e)
{
while (e != null)
{
var root = e as IStyleRoot;
if (root != null && root.StylingParent == null)
{
return root;
}
e = e.StylingParent;
}
return null;
}
private void ApplyStyling()
{
AvaloniaLocator.Current.GetService<IStyler>()?.ApplyStyles(this);
}
private void RegisterWithNameScope()
{
if (_nameScope == null)
{
_nameScope = NameScope.GetNameScope(this) ?? ((Control)Parent)?._nameScope;
}
if (Name != null)
{
_nameScope?.Register(Name, this);
}
}
private static void ValidateLogicalChild(ILogical c)
{
if (c == null)
{
throw new ArgumentException("Cannot add null to LogicalChildren.");
}
}
private void OnAttachedToLogicalTreeCore(LogicalTreeAttachmentEventArgs e)
{
// This method can be called when a control is already attached to the logical tree
// in the following scenario:
// - ListBox gets assigned Items containing ListBoxItem
// - ListBox makes ListBoxItem a logical child
// - ListBox template gets applied; making its Panel get attached to logical tree
// - That AttachedToLogicalTree signal travels down to the ListBoxItem
if (!_isAttachedToLogicalTree)
{
_isAttachedToLogicalTree = true;
if (_initCount == 0)
{
RegisterWithNameScope();
ApplyStyling();
_styled = true;
}
OnAttachedToLogicalTree(e);
}
foreach (var child in LogicalChildren.OfType<Control>())
{
child.OnAttachedToLogicalTreeCore(e);
}
}
private void OnDetachedFromLogicalTreeCore(LogicalTreeAttachmentEventArgs e)
{
if (_isAttachedToLogicalTree)
{
if (Name != null)
{
_nameScope?.Unregister(Name);
}
_isAttachedToLogicalTree = false;
_styleDetach.OnNext(this);
this.TemplatedParent = null;
OnDetachedFromLogicalTree(e);
foreach (var child in LogicalChildren.OfType<Control>())
{
child.OnDetachedFromLogicalTreeCore(e);
}
#if DEBUG
if (((INotifyCollectionChangedDebug)_classes).GetCollectionChangedSubscribers()?.Length > 0)
{
Logger.Warning(
LogArea.Control,
this,
"{Type} detached from logical tree but still has class listeners",
this.GetType());
}
#endif
}
}
private void LogicalChildrenCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
SetLogicalParent(e.NewItems.Cast<ILogical>());
break;
case NotifyCollectionChangedAction.Remove:
ClearLogicalParent(e.OldItems.Cast<ILogical>());
break;
case NotifyCollectionChangedAction.Replace:
ClearLogicalParent(e.OldItems.Cast<ILogical>());
SetLogicalParent(e.NewItems.Cast<ILogical>());
break;
case NotifyCollectionChangedAction.Reset:
throw new NotSupportedException("Reset should not be signalled on LogicalChildren collection");
}
}
private void SetLogicalParent(IEnumerable<ILogical> children)
{
foreach (var i in children)
{
if (i.LogicalParent == null)
{
((ISetLogicalParent)i).SetParent(this);
}
}
}
private void ClearLogicalParent(IEnumerable<ILogical> children)
{
foreach (var i in children)
{
if (i.LogicalParent == this)
{
((ISetLogicalParent)i).SetParent(null);
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using SIL.Code;
using SIL.IO;
using SIL.Reporting;
namespace SIL.Windows.Forms.ImageToolbox.Cropping
{
public partial class ImageCropper : UserControl, IImageToolboxControl
{
private PalasoImage _image;
private Grip _gripperBeingDragged;
private Rectangle _sourceImageArea;
private const int GripThickness = 20;
private const int GripLength = 80;
private const int BorderSize = GripThickness;
private Grip _bottomGrip;
private Grip _topGrip;
private Grip _leftGrip;
private Grip _rightGrip;
/// <summary>
/// Used to mark the spot where the user first started dragging the mouse, when he clicks somewhere other than one of the grips.
/// We use this to create the new crop rectangle as he continues the drag.
/// </summary>
private Point _startOfDrag = default(Point);
//we will be cropping the image, so we need to keep the original lest we be cropping the crop, so to speak
private ImageFormat _originalFormat;
private TempFile _savedOriginalImage;
private Image _croppingImage;
private const int MarginAroundPicture = GripThickness;
private const int MinDistanceBetweenGrips = 20;
private bool didReportThatUserCameInHere;
public ImageCropper()
{
InitializeComponent();
Application.Idle += new EventHandler(Application_Idle);
}
private void Application_Idle(object sender, EventArgs e)
{
if (_image == null)
return;
if (_startOfDrag != default(Point))
{
DoCropDrag();
}
else if (_gripperBeingDragged != null)
{
DoGripDrag();
}
Invalidate();
}
private void DoGripDrag()
{
Point mouse = PointToClient(MousePosition);
if (_gripperBeingDragged.MovesVertically)
{
_gripperBeingDragged.Value = mouse.Y - MarginAroundPicture;
//adjust the vertical position of other axis' grips
foreach (var grip in HorizontalControlGrips)
{
grip.UpdateRectangle();
}
}
else
{
_gripperBeingDragged.Value = mouse.X - MarginAroundPicture;
foreach (var grip in VerticalControlGrips)
{
grip.UpdateRectangle();
}
}
if(!didReportThatUserCameInHere)
{
didReportThatUserCameInHere = true;
UsageReporter.SendNavigationNotice("ImageToolbox:Cropper");
}
}
private void DoCropDrag()
{
return;
// REVIEW: Is this code intentionally disabled?
// REVIEW (Hasso) 2020.04: looks like hatton started work on this in 2010-12 and gave up in 2012-04
Grip hStart, vStart, hEnd, vEnd;
Point mouse = PointToClient(MousePosition);
if (_startOfDrag.X < mouse.X)
{
hStart = _leftGrip;
hEnd = _rightGrip;
}
else
{
hEnd = _leftGrip;
hStart = _rightGrip;
}
if (_startOfDrag.Y < mouse.Y)
{
vStart = _topGrip;
vEnd = _bottomGrip;
}
else
{
vEnd = _topGrip;
vStart = _bottomGrip;
}
hStart.Value = _startOfDrag.X - MarginAroundPicture;
vStart.Value = _startOfDrag.Y - MarginAroundPicture;
hEnd.Value = mouse.X - MarginAroundPicture;
vEnd.Value = mouse.Y - MarginAroundPicture;
}
protected int MiddleOfVerticalGrips()
{
return _leftGrip.Right + ((_rightGrip.Left - _leftGrip.Right)/2);
}
protected int MiddleOfHorizontalGrips()
{
return _topGrip.Bottom + ((_bottomGrip.Top - _topGrip.Bottom)/2);
}
public PalasoImage Image
{
get { return _image; }
set
{
if (value == null)
return;
//other code changes the image of this palaso image, at which time the PI disposes of its copy,
//so we better keep our own.
// save the original in a temp file instead of an Image object to free up memory
_savedOriginalImage = TempFile.CreateAndGetPathButDontMakeTheFile();
value.Image.Save(_savedOriginalImage.Path, ImageFormat.Png);
// make a reasonable sized copy to crop
if ((value.Image.Width > 1000) || (value.Image.Width > 1000))
{
_croppingImage = CreateCroppingImage(value.Image.Height, value.Image.Width);
var srcRect = new Rectangle(0, 0, value.Image.Width, value.Image.Height);
var destRect = new Rectangle(0, 0, _croppingImage.Width, _croppingImage.Height);
using (var g = Graphics.FromImage(_croppingImage))
{
g.DrawImage(value.Image, destRect, srcRect, GraphicsUnit.Pixel);
}
}
else
{
_croppingImage = (Image)value.Image.Clone();
}
_image = value;
CalculateSourceImageArea();
CreateGrips();
foreach (var grip in Grips)
{
grip.UpdateRectangle();
}
Invalidate();
}
}
/// <summary>
/// To conserve memory we will shrink large images before cropping
/// </summary>
/// <param name="oldHeight"></param>
/// <param name="oldWidth"></param>
/// <returns></returns>
private static Image CreateCroppingImage(int oldHeight, int oldWidth)
{
int newHeight;
int newWidth;
if (oldHeight > oldWidth)
{
newHeight = 800;
newWidth = newHeight * oldWidth / oldHeight;
}
else
{
newWidth = 800;
newHeight = newWidth * oldHeight / oldWidth;
}
return new Bitmap(newWidth, newHeight);
}
private void CreateGrips()
{
_bottomGrip = new Grip(_sourceImageArea.Height, GripLength, GripThickness, Grip.Sides.Bottom,
MiddleOfVerticalGrips,
() => _topGrip.Value + MinDistanceBetweenGrips,
() => _sourceImageArea.Height);
_topGrip = new Grip(0, GripLength, GripThickness, Grip.Sides.Top,
MiddleOfVerticalGrips,
() => 0,
() => _bottomGrip.Value - MinDistanceBetweenGrips);
_leftGrip = new Grip(0, GripThickness, GripLength, Grip.Sides.Left,
MiddleOfHorizontalGrips,
() => 0,
() => _rightGrip.Value - MinDistanceBetweenGrips);
_rightGrip = new Grip(_sourceImageArea.Width, GripThickness, GripLength, Grip.Sides.Right,
MiddleOfHorizontalGrips,
() => _leftGrip.Value + MinDistanceBetweenGrips,
() => _sourceImageArea.Width);
}
private void ImageCropper_Resize(object sender, EventArgs e)
{
if (_image == null)
return;
var old = _sourceImageArea;
CalculateSourceImageArea();
if (old.Width == 0 || old.Height == 0)
return;
float horizontalGrowthFactor = ((float) _sourceImageArea.Width)/((float) old.Width);
float verticalGrowthFactor = ((float) _sourceImageArea.Height)/((float) old.Height);
foreach (var grip in VerticalControlGrips)
{
grip.Value = (int) ((float) grip.Value*verticalGrowthFactor);
}
foreach (var grip in HorizontalControlGrips)
{
grip.Value = (int) ((float) grip.Value*horizontalGrowthFactor);
}
foreach (var grip in Grips)
{
grip.UpdateRectangle();
}
Invalidate();
}
private void CalculateSourceImageArea()
{
float imageToCanvaseScaleFactor = GetImageToCanvasScaleFactor(_croppingImage);
_sourceImageArea = new Rectangle(GripThickness, GripThickness,
(int)(_croppingImage.Width*imageToCanvaseScaleFactor),
(int)(_croppingImage.Height*imageToCanvaseScaleFactor));
}
private float GetImageToCanvasScaleFactor(Image img)
{
var availArea = new Rectangle(BorderSize, BorderSize, Width - (2*BorderSize), Height - (2*BorderSize));
float hProportion = (float)availArea.Width / ((float)img.Width);
float vProportion = (float)availArea.Height / ((float)img.Height);
return Math.Min(hProportion, vProportion);
}
protected override void OnPaint(PaintEventArgs e)
{
if (_croppingImage == null || _sourceImageArea.Width == 0)
return;
try
{
e.Graphics.FillRectangle(Brushes.Gray, ClientRectangle);
e.Graphics.DrawImage(
_croppingImage,
_sourceImageArea,
new Rectangle( // Source
0, 0,
_croppingImage.Width, _croppingImage.Height),
GraphicsUnit.Pixel);
using (Brush brush = new Pen(Color.FromArgb(150, Color.LightBlue)).Brush)
{
e.Graphics.FillRectangle(brush, _leftGrip.InnerEdge, _bottomGrip.InnerEdge,
_rightGrip.InnerEdge - _leftGrip.InnerEdge
/*this avoids overlapp which makes it twice as light*/
, Height - _bottomGrip.InnerEdge);
e.Graphics.FillRectangle(brush, _leftGrip.InnerEdge, 0, _rightGrip.InnerEdge - _leftGrip.InnerEdge,
_topGrip.InnerEdge);
e.Graphics.FillRectangle(brush, 0, 0, _leftGrip.InnerEdge, Height);
e.Graphics.FillRectangle(brush, _rightGrip.InnerEdge, 0, Width - _rightGrip.InnerEdge, Height);
}
e.Graphics.DrawRectangle(Pens.LightBlue, _leftGrip.Right, _topGrip.Bottom,
_rightGrip.Left - _leftGrip.Right, _bottomGrip.Top - _topGrip.Bottom);
_bottomGrip.Paint(e.Graphics);
_topGrip.Paint(e.Graphics);
_leftGrip.Paint(e.Graphics);
_rightGrip.Paint(e.Graphics);
}
catch (Exception error)
{
Debug.Fail(error.Message);
// UserControl does not have UseCompatibleTextRendering.
TextRenderer.DrawText(e.Graphics, "Error in OnPaint()", SystemFonts.DefaultFont, new Point(20,20), Color.Red);
//swallow in release build
}
}
private Grip[] Grips
{
get { return new Grip[] {_bottomGrip, _topGrip, _leftGrip, _rightGrip}; }
}
private Grip[] VerticalControlGrips
{
get { return new Grip[] {_bottomGrip, _topGrip}; }
}
private Grip[] HorizontalControlGrips
{
get { return new Grip[] {_leftGrip, _rightGrip}; }
}
private void ImageCropper_MouseDown(object sender, MouseEventArgs e)
{
foreach (var grip in Grips)
{
if (grip.Contains(e.Location))
{
_gripperBeingDragged = grip;
return;
}
}
_startOfDrag = e.Location;
}
private void ImageCropper_MouseUp(object sender, MouseEventArgs e)
{
_gripperBeingDragged = null;
_startOfDrag = default(Point);
if (ImageChanged != null)
ImageChanged.Invoke(this, null);
}
// public void CheckBug()
// {
// var z = 1.0/GetImageToCanvasScaleFactor();
// double d = z*_leftGrip.Value + z*(_rightGrip.Value - _leftGrip.Value);
// {
// var s = "";
// if (d > _image.Width)
// s = " > ImageWidth="+_image.Width;
// Debug.WriteLine(string.Format("scale={0} z={1} left={2} right={3} left+(right-left)={4} "+s,
// GetImageToCanvasScaleFactor(), z, _leftGrip.Value, _rightGrip.Value, d));
// }
// }
public Image GetCroppedImage()
{
if (_image == null || _image.Disposed)
return null;
try
{
//jpeg = b96b3c *AE* -0728-11d3-9d7b-0000f81ef32e
//bitmap = b96b3c *AA* -0728-11d3-9d7b-0000f81ef32e
//NB: this worked for tiff and png, but would crash with Out Of Memory for jpegs.
//This may be because I closed the stream? THe doc says you have to keep that stream open.
//Also, note that this method, too, lost our jpeg encoding:
// return bmp.Clone(selection, _image.PixelFormat);
//So now, I first copy it, then clone with the bounds of our crop:
using (var originalImage = new Bitmap(_savedOriginalImage.Path)) //**** here we lose the jpeg rawimageformat, if it's a jpeg. Grrr.
{
double z = 1.0 / GetImageToCanvasScaleFactor(originalImage);
int width = Math.Max(1, _rightGrip.Value - _leftGrip.Value);
int height = Math.Max(1, _bottomGrip.Value - _topGrip.Value);
var selection = new Rectangle((int)Math.Round(z * _leftGrip.Value),
(int)Math.Round(z * _topGrip.Value),
(int)Math.Round(z * width),
(int)Math.Round(z * height));
var cropped = originalImage.Clone(selection, originalImage.PixelFormat); //do the actual cropping
if (_originalFormat.Guid == ImageFormat.Jpeg.Guid)
{
//We've sadly lost our jpeg formatting, so now we encode a new image in jpeg
using (var stream = new MemoryStream())
{
cropped.Save(stream, ImageFormat.Jpeg);
var oldCropped = cropped;
cropped = System.Drawing.Image.FromStream(stream) as Bitmap;
oldCropped.Dispose();
Require.That(ImageFormat.Jpeg.Guid == cropped.RawFormat.Guid, "lost jpeg formatting");
}
}
return cropped;
}
}
catch (Exception e)
{
Debug.Fail(e.Message);
ErrorReport.NotifyUserOfProblem(e, "Sorry, there was a problem getting the image");
return null;
}
}
public void SetImage(PalasoImage image)
{
if (image == null)
{
Image = null;
}
else
{
_originalFormat = image.Image.RawFormat;
Image = image;
}
}
public PalasoImage GetImage()
{
Image x = GetCroppedImage();
// BL-5830 somehow user was cropping an image and this PalasoImage was already disposed
if (x == null || _image.Disposed)
return null;
//we want to retain the metdata of the PalasoImage we started with; we just want to update its actual image
_image.Image = x;
return _image;
}
public event EventHandler ImageChanged;
/// <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)
{
if (components != null)
{
components.Dispose();
components = null;
}
try
{
if (_savedOriginalImage != null)
{
_savedOriginalImage.Dispose();
_savedOriginalImage = null;
}
if (_croppingImage != null)
{
_croppingImage.Dispose();
_croppingImage = null;
}
}
// BL-2680, somehow user can get in a state where we CAN'T delete a temp file.
// I think we can afford to just ignore it. One temp file will be leaked.
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
}
base.Dispose(disposing);
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
using FluentMigrator.Builders.Create.Table;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
using Moq;
using NUnit.Framework;
namespace FluentMigrator.Tests.Unit.Builders.Create
{
[TestFixture]
public class CreateTableExpressionBuilderTests
{
[Test]
public void CallingAsAnsiStringSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString());
}
[Test]
public void CallingAsAnsiStringWithSizeSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString(255));
}
[Test]
public void CallingAsAnsiStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsAnsiString(255));
}
[Test]
public void CallingAsBinarySetsColumnDbTypeToBinary()
{
VerifyColumnDbType(DbType.Binary, b => b.AsBinary(255));
}
[Test]
public void CallingAsBinarySetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsBinary(255));
}
[Test]
public void CallingAsBooleanSetsColumnDbTypeToBoolean()
{
VerifyColumnDbType(DbType.Boolean, b => b.AsBoolean());
}
[Test]
public void CallingAsByteSetsColumnDbTypeToByte()
{
VerifyColumnDbType(DbType.Byte, b => b.AsByte());
}
[Test]
public void CallingAsCurrencySetsColumnDbTypeToCurrency()
{
VerifyColumnDbType(DbType.Currency, b => b.AsCurrency());
}
[Test]
public void CallingAsDateSetsColumnDbTypeToDate()
{
VerifyColumnDbType(DbType.Date, b => b.AsDate());
}
[Test]
public void CallingAsDateTimeSetsColumnDbTypeToDateTime()
{
VerifyColumnDbType(DbType.DateTime, b => b.AsDateTime());
}
[Test]
public void CallingAsDecimalSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal());
}
[Test]
public void CallingAsDecimalWithSizeSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(1, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnPrecisionToSpecifiedValue()
{
VerifyColumnPrecision(2, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDoubleSetsColumnDbTypeToDouble()
{
VerifyColumnDbType(DbType.Double, b => b.AsDouble());
}
[Test]
public void CallingAsGuidSetsColumnDbTypeToGuid()
{
VerifyColumnDbType(DbType.Guid, b => b.AsGuid());
}
[Test]
public void CallingAsFixedLengthStringSetsColumnDbTypeToStringFixedLength()
{
VerifyColumnDbType(DbType.StringFixedLength, e => e.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnDbTypeToAnsiStringFixedLength()
{
VerifyColumnDbType(DbType.AnsiStringFixedLength, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFloatSetsColumnDbTypeToSingle()
{
VerifyColumnDbType(DbType.Single, b => b.AsFloat());
}
[Test]
public void CallingAsInt16SetsColumnDbTypeToInt16()
{
VerifyColumnDbType(DbType.Int16, b => b.AsInt16());
}
[Test]
public void CallingAsInt32SetsColumnDbTypeToInt32()
{
VerifyColumnDbType(DbType.Int32, b => b.AsInt32());
}
[Test]
public void CallingAsInt64SetsColumnDbTypeToInt64()
{
VerifyColumnDbType(DbType.Int64, b => b.AsInt64());
}
[Test]
public void CallingAsStringSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString());
}
[Test]
public void CallingAsStringWithSizeSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString(255));
}
[Test]
public void CallingAsStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsTimeSetsColumnDbTypeToTime()
{
VerifyColumnDbType(DbType.Time, b => b.AsTime());
}
[Test]
public void CallingAsXmlSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml());
}
[Test]
public void CallingAsXmlWithSizeSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml(255));
}
[Test]
public void CallingAsXmlSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsXml(255));
}
[Test]
public void CallingAsCustomSetsTypeToNullAndSetsCustomType()
{
VerifyColumnProperty(c => c.Type = null, b => b.AsCustom("Test"));
VerifyColumnProperty(c => c.CustomType = "Test", b => b.AsCustom("Test"));
}
[Test]
public void CallingWithDefaultValueSetsDefaultValue()
{
const int value = 42;
var contextMock = new Mock<IMigrationContext>();
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateTableExpression>();
var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
builder.WithDefaultValue(42);
columnMock.VerifySet(c => c.DefaultValue = value);
}
[Test]
public void CallingForeignKeySetsIsForeignKeyToTrue()
{
VerifyColumnProperty(c => c.IsForeignKey = true, b => b.ForeignKey());
}
[Test]
public void CallingIdentitySetsIsIdentityToTrue()
{
VerifyColumnProperty(c => c.IsIdentity = true, b => b.Identity());
}
[Test]
public void CallingIndexedSetsIsIndexedToTrue()
{
VerifyColumnProperty(c => c.IsIndexed = true, b => b.Indexed());
}
[Test]
public void CallingPrimaryKeySetsIsPrimaryKeyToTrue()
{
VerifyColumnProperty(c => c.IsPrimaryKey = true, b => b.PrimaryKey());
}
[Test]
public void CallingNullableSetsIsNullableToTrue()
{
VerifyColumnProperty(c => c.IsNullable = true, b => b.Nullable());
}
[Test]
public void CallingNotNullableSetsIsNullableToFalse()
{
VerifyColumnProperty(c => c.IsNullable = false, b => b.NotNullable());
}
[Test]
public void CallingUniqueSetsIsUniqueToTrue()
{
VerifyColumnProperty(c => c.IsUnique = true, b => b.Unique());
}
[Test]
public void CallingReferencesAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateTableExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object)
{
CurrentColumn = columnMock.Object
};
builder.References("fk_foo", "FooTable", new[] { "BarColumn" });
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.ForeignTable == "FooTable" &&
fk.ForeignKey.ForeignColumns.Contains("BarColumn") &&
fk.ForeignKey.ForeignColumns.Count == 1 &&
fk.ForeignKey.PrimaryTable == "Bacon" &&
fk.ForeignKey.PrimaryColumns.Contains("BaconId") &&
fk.ForeignKey.PrimaryColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingReferencedByAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateTableExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object)
{
CurrentColumn = columnMock.Object
};
builder.ReferencedBy("fk_foo", "FooTable", "BarColumn");
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.ForeignTable == "FooTable" &&
fk.ForeignKey.ForeignColumns.Contains("BarColumn") &&
fk.ForeignKey.ForeignColumns.Count == 1 &&
fk.ForeignKey.PrimaryTable == "Bacon" &&
fk.ForeignKey.PrimaryColumns.Contains("BaconId") &&
fk.ForeignKey.PrimaryColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingForeignKeyAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateTableExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object)
{
CurrentColumn = columnMock.Object
};
builder.ForeignKey("fk_foo", "FooTable", "BarColumn");
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.PrimaryTable == "FooTable" &&
fk.ForeignKey.PrimaryColumns.Contains("BarColumn") &&
fk.ForeignKey.PrimaryColumns.Count == 1 &&
fk.ForeignKey.ForeignTable == "Bacon" &&
fk.ForeignKey.ForeignColumns.Contains("BaconId") &&
fk.ForeignKey.ForeignColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingWithColumnAddsNewColumnToExpression()
{
const string name = "BaconId";
var collectionMock = new Mock<IList<ColumnDefinition>>();
var expressionMock = new Mock<CreateTableExpression>();
expressionMock.SetupGet(e => e.Columns).Returns(collectionMock.Object);
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.WithColumn(name);
collectionMock.Verify(x => x.Add(It.Is<ColumnDefinition>(c => c.Name.Equals(name))));
expressionMock.VerifyGet(e => e.Columns);
}
private void VerifyColumnProperty(Action<ColumnDefinition> columnExpression, Action<CreateTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(columnExpression);
}
private void VerifyColumnDbType(DbType expected, Action<CreateTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(c => c.Type = expected);
}
private void VerifyColumnSize(int expected, Action<CreateTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(c => c.Size = expected);
}
private void VerifyColumnPrecision(int expected, Action<CreateTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(c => c.Precision = expected);
}
}
}
| |
using Ocelot.Configuration.Builder;
using Ocelot.DownstreamRouteFinder;
using Ocelot.DownstreamRouteFinder.UrlMatcher;
using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer;
using Ocelot.Responses;
using Ocelot.Values;
using Shouldly;
using System.Collections.Generic;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.DownstreamUrlCreator.UrlTemplateReplacer
{
public class UpstreamUrlPathTemplateVariableReplacerTests
{
private DownstreamRoute _downstreamRoute;
private Response<DownstreamPath> _result;
private readonly IDownstreamPathPlaceholderReplacer _downstreamPathReplacer;
public UpstreamUrlPathTemplateVariableReplacerTests()
{
_downstreamPathReplacer = new DownstreamTemplatePathPlaceholderReplacer();
}
[Fact]
public void can_replace_no_template_variables()
{
this.Given(x => x.GivenThereIsAUrlMatch(
new DownstreamRoute(
new List<PlaceholderNameAndValue>(),
new ReRouteBuilder()
.WithDownstreamReRoute(new DownstreamReRouteBuilder()
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())))
.When(x => x.WhenIReplaceTheTemplateVariables())
.Then(x => x.ThenTheDownstreamUrlPathIsReturned(""))
.BDDfy();
}
[Fact]
public void can_replace_no_template_variables_with_slash()
{
this.Given(x => x.GivenThereIsAUrlMatch(
new DownstreamRoute(
new List<PlaceholderNameAndValue>(),
new ReRouteBuilder()
.WithDownstreamReRoute(new DownstreamReRouteBuilder()
.WithDownstreamPathTemplate("/")
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())))
.When(x => x.WhenIReplaceTheTemplateVariables())
.Then(x => x.ThenTheDownstreamUrlPathIsReturned("/"))
.BDDfy();
}
[Fact]
public void can_replace_url_no_slash()
{
this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List<PlaceholderNameAndValue>(),
new ReRouteBuilder()
.WithDownstreamReRoute(new DownstreamReRouteBuilder()
.WithDownstreamPathTemplate("api")
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())))
.When(x => x.WhenIReplaceTheTemplateVariables())
.Then(x => x.ThenTheDownstreamUrlPathIsReturned("api"))
.BDDfy();
}
[Fact]
public void can_replace_url_one_slash()
{
this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List<PlaceholderNameAndValue>(),
new ReRouteBuilder()
.WithDownstreamReRoute(new DownstreamReRouteBuilder()
.WithDownstreamPathTemplate("api/")
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())))
.When(x => x.WhenIReplaceTheTemplateVariables())
.Then(x => x.ThenTheDownstreamUrlPathIsReturned("api/"))
.BDDfy();
}
[Fact]
public void can_replace_url_multiple_slash()
{
this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List<PlaceholderNameAndValue>(),
new ReRouteBuilder()
.WithDownstreamReRoute(new DownstreamReRouteBuilder()
.WithDownstreamPathTemplate("api/product/products/")
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())))
.When(x => x.WhenIReplaceTheTemplateVariables())
.Then(x => x.ThenTheDownstreamUrlPathIsReturned("api/product/products/"))
.BDDfy();
}
[Fact]
public void can_replace_url_one_template_variable()
{
var templateVariables = new List<PlaceholderNameAndValue>()
{
new PlaceholderNameAndValue("{productId}", "1")
};
this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables,
new ReRouteBuilder()
.WithDownstreamReRoute(new DownstreamReRouteBuilder()
.WithDownstreamPathTemplate("productservice/products/{productId}/")
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())))
.When(x => x.WhenIReplaceTheTemplateVariables())
.Then(x => x.ThenTheDownstreamUrlPathIsReturned("productservice/products/1/"))
.BDDfy();
}
[Fact]
public void can_replace_url_one_template_variable_with_path_after()
{
var templateVariables = new List<PlaceholderNameAndValue>()
{
new PlaceholderNameAndValue("{productId}", "1")
};
this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables,
new ReRouteBuilder()
.WithDownstreamReRoute(new DownstreamReRouteBuilder()
.WithDownstreamPathTemplate("productservice/products/{productId}/variants")
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())))
.When(x => x.WhenIReplaceTheTemplateVariables())
.Then(x => x.ThenTheDownstreamUrlPathIsReturned("productservice/products/1/variants"))
.BDDfy();
}
[Fact]
public void can_replace_url_two_template_variable()
{
var templateVariables = new List<PlaceholderNameAndValue>()
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{variantId}", "12")
};
this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables,
new ReRouteBuilder()
.WithDownstreamReRoute(new DownstreamReRouteBuilder()
.WithDownstreamPathTemplate("productservice/products/{productId}/variants/{variantId}")
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())))
.When(x => x.WhenIReplaceTheTemplateVariables())
.Then(x => x.ThenTheDownstreamUrlPathIsReturned("productservice/products/1/variants/12"))
.BDDfy();
}
[Fact]
public void can_replace_url_three_template_variable()
{
var templateVariables = new List<PlaceholderNameAndValue>()
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{variantId}", "12"),
new PlaceholderNameAndValue("{categoryId}", "34")
};
this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables,
new ReRouteBuilder()
.WithDownstreamReRoute(new DownstreamReRouteBuilder()
.WithDownstreamPathTemplate("productservice/category/{categoryId}/products/{productId}/variants/{variantId}")
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())))
.When(x => x.WhenIReplaceTheTemplateVariables())
.Then(x => x.ThenTheDownstreamUrlPathIsReturned("productservice/category/34/products/1/variants/12"))
.BDDfy();
}
private void GivenThereIsAUrlMatch(DownstreamRoute downstreamRoute)
{
_downstreamRoute = downstreamRoute;
}
private void WhenIReplaceTheTemplateVariables()
{
_result = _downstreamPathReplacer.Replace(_downstreamRoute.ReRoute.DownstreamReRoute[0].DownstreamPathTemplate.Value, _downstreamRoute.TemplatePlaceholderNameAndValues);
}
private void ThenTheDownstreamUrlPathIsReturned(string expected)
{
_result.Data.Value.ShouldBe(expected);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic{
/// <summary>
/// Strongly-typed collection for the VwAspnetWebPartStateShared class.
/// </summary>
[Serializable]
public partial class VwAspnetWebPartStateSharedCollection : ReadOnlyList<VwAspnetWebPartStateShared, VwAspnetWebPartStateSharedCollection>
{
public VwAspnetWebPartStateSharedCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vw_aspnet_WebPartState_Shared view.
/// </summary>
[Serializable]
public partial class VwAspnetWebPartStateShared : ReadOnlyRecord<VwAspnetWebPartStateShared>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("vw_aspnet_WebPartState_Shared", TableType.View, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarPathId = new TableSchema.TableColumn(schema);
colvarPathId.ColumnName = "PathId";
colvarPathId.DataType = DbType.Guid;
colvarPathId.MaxLength = 0;
colvarPathId.AutoIncrement = false;
colvarPathId.IsNullable = false;
colvarPathId.IsPrimaryKey = false;
colvarPathId.IsForeignKey = false;
colvarPathId.IsReadOnly = false;
schema.Columns.Add(colvarPathId);
TableSchema.TableColumn colvarDataSize = new TableSchema.TableColumn(schema);
colvarDataSize.ColumnName = "DataSize";
colvarDataSize.DataType = DbType.Int32;
colvarDataSize.MaxLength = 0;
colvarDataSize.AutoIncrement = false;
colvarDataSize.IsNullable = true;
colvarDataSize.IsPrimaryKey = false;
colvarDataSize.IsForeignKey = false;
colvarDataSize.IsReadOnly = false;
schema.Columns.Add(colvarDataSize);
TableSchema.TableColumn colvarLastUpdatedDate = new TableSchema.TableColumn(schema);
colvarLastUpdatedDate.ColumnName = "LastUpdatedDate";
colvarLastUpdatedDate.DataType = DbType.DateTime;
colvarLastUpdatedDate.MaxLength = 0;
colvarLastUpdatedDate.AutoIncrement = false;
colvarLastUpdatedDate.IsNullable = false;
colvarLastUpdatedDate.IsPrimaryKey = false;
colvarLastUpdatedDate.IsForeignKey = false;
colvarLastUpdatedDate.IsReadOnly = false;
schema.Columns.Add(colvarLastUpdatedDate);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("vw_aspnet_WebPartState_Shared",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VwAspnetWebPartStateShared()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VwAspnetWebPartStateShared(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VwAspnetWebPartStateShared(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VwAspnetWebPartStateShared(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("PathId")]
[Bindable(true)]
public Guid PathId
{
get
{
return GetColumnValue<Guid>("PathId");
}
set
{
SetColumnValue("PathId", value);
}
}
[XmlAttribute("DataSize")]
[Bindable(true)]
public int? DataSize
{
get
{
return GetColumnValue<int?>("DataSize");
}
set
{
SetColumnValue("DataSize", value);
}
}
[XmlAttribute("LastUpdatedDate")]
[Bindable(true)]
public DateTime LastUpdatedDate
{
get
{
return GetColumnValue<DateTime>("LastUpdatedDate");
}
set
{
SetColumnValue("LastUpdatedDate", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string PathId = @"PathId";
public static string DataSize = @"DataSize";
public static string LastUpdatedDate = @"LastUpdatedDate";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using Hacknet;
using Hacknet.Effects;
using Hacknet.Factions;
using Hacknet.Misc;
using Hacknet.Modules.Overlays;
using Hacknet.PlatformAPI.Storage;
using Hacknet.Screens;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Pathfinder.Event;
using Pathfinder.GUI;
using Pathfinder.Util;
using Pathfinder.Util.Attribute;
using EMSState = Hacknet.Screens.ExtensionsMenuScreen.EMSState;
using Gui = Hacknet.Gui;
namespace Pathfinder.Internal.GUI
{
static class ModExtensionsUI
{
private static Button returnButton = new Button(-1, -1, 450, 25, "Return to Main Menu", MainMenu.exitButtonColor)
{
DrawFinish = r =>
{
if (r.JustReleased)
{
Extension.Handler.ActiveInfo = null;
buttonsLoaded = false;
}
}
};
private static EMSState state = EMSState.Normal;
private static int tickWaits = -2;
private static bool buttonsLoaded;
private static void LoadButtons(ref Vector2 pos, ExtensionsMenuScreen ms)
{
foreach (var pair in Extension.Handler.ModExtensions)
{
pair.Value.Item3.Position = pos;
pair.Value.Item3.DrawFinish = r =>
{
if (r.JustReleased)
{
Extension.Handler.ActiveInfo = Extension.Handler.ModExtensions[pair.Key].Item1;
ms.ExtensionInfoToShow = new PlaceholderExtensionInfo(Extension.Handler.ActiveInfo);
Extension.Handler.ActiveExtension = ms.ExtensionInfoToShow;
ms.ReportOverride = null;
ms.SaveScreen.ProjectName = Extension.Handler.ActiveInfo.Name;
SaveFileManager.Init();
ms.SaveScreen.ResetForNewAccount();
}
};
pos.Y += 55;
}
buttonsLoaded = true;
}
private static void DrawModExtensionInfo(SpriteBatch sb, ref Vector2 pos, Rectangle rect, ExtensionsMenuScreen ms)
{
if (Extension.Handler.ActiveInfo == null) return;
sb.DrawString(GuiData.titlefont, Extension.Handler.ActiveInfo.Name.ToUpper(), pos, Utils.AddativeWhite * 0.66f);
pos.Y += 80;
var height = sb.GraphicsDevice.Viewport.Height;
var num = 256;
if (height < 900)
num = 120;
var dest2 = new Rectangle((int)pos.X, (int)pos.Y, num, num);
var texture = ms.DefaultModImage;
if (Extension.Handler.ModExtensions[Extension.Handler.ActiveInfo.Id].Item2 != null)
texture = Extension.Handler.ModExtensions[Extension.Handler.ActiveInfo.Id].Item2;
FlickeringTextEffect.DrawFlickeringSprite(sb, dest2, texture, 2f, 0.5f, null, Color.White);
var position = pos + new Vector2(num + 40f, 20f);
var num2 = rect.Width - (pos.X - rect.X);
var description = Extension.Handler.ActiveInfo.Description;
var text = Utils.SuperSmartTwimForWidth(description, (int)num2, GuiData.smallfont);
sb.DrawString(GuiData.smallfont, text, position, Utils.AddativeWhite * 0.7f);
pos = new Vector2(pos.X, pos.Y + num + 10);
if (ms.IsInPublishScreen)
{
sb.DrawString(GuiData.font, "Mod Extensions don't support publishment on the workshop", new Vector2(300), Utils.AddativeWhite);
if (tickWaits < -1)
tickWaits = 10000;
else if (tickWaits > -1)
--tickWaits;
else
{
ms.IsInPublishScreen = false;
tickWaits = -2;
}
}
else
{
if (ms.ReportOverride != null)
{
var text2 = Utils.SuperSmartTwimForWidth(ms.ReportOverride, 800, GuiData.smallfont);
sb.DrawString(GuiData.smallfont, text2, pos + new Vector2(460f, 0f),
(ms.ReportOverride.Length > 250) ? Utils.AddativeRed : Utils.AddativeWhite);
}
int num3 = 40;
int num4 = 5;
int num5 = Extension.Handler.ActiveInfo.AllowSaves ? 4 : 2;
int num6 = height - (int)pos.Y - 55;
num3 = Math.Min(num3, (num6 - num5 * num4) / num5);
if (Gui.Button.doButton(7900010, (int)pos.X, (int)pos.Y, 450, num3, "New " + Extension.Handler.ActiveInfo.Name + " Account",
MainMenu.buttonColor))
{
state = EMSState.GetUsername;
ms.SaveScreen.ResetForNewAccount();
}
pos.Y += num3 + num4;
if (Extension.Handler.ActiveInfo.AllowSaves)
{
bool flag = !string.IsNullOrWhiteSpace(SaveFileManager.LastLoggedInUser.FileUsername);
if (Gui.Button.doButton(7900019, (int)pos.X, (int)pos.Y, 450, num3,
flag ? ("Continue Account : " + SaveFileManager.LastLoggedInUser.Username) : " - No Accounts - ",
flag ? MainMenu.buttonColor : Color.Black))
{
OS.WillLoadSave = true;
if (ms.LoadAccountForExtension_FileAndUsername != null)
ms.LoadAccountForExtension_FileAndUsername.Invoke(SaveFileManager.LastLoggedInUser.FileUsername,
SaveFileManager.LastLoggedInUser.Username);
}
pos.Y += num3 + num4;
if (Gui.Button.doButton(7900020, (int)pos.X, (int)pos.Y, 450, num3, "Login...", flag ? MainMenu.buttonColor : Color.Black))
{
state = EMSState.ShowAccounts;
ms.SaveScreen.ResetForLogin();
}
pos.Y += num3 + num4;
}
if (Gui.Button.doButton(7900030,
(int)pos.X,
(int)pos.Y,
450,
num3,
"Run Verification Tests",
MainMenu.buttonColor))
Logger.Info("Extension verification tests can not be performed on mod extensions");
pos.Y += num3 + num4;
if (Settings.AllowExtensionPublish && PlatformAPISettings.Running)
{
ms.IsInPublishScreen |= Gui.Button.doButton(7900031, (int)pos.X, (int)pos.Y, 450, num3, "Steam Workshop Publishing",
MainMenu.buttonColor);
pos.Y += num3 + num4;
}
if (Gui.Button.doButton(7900040, (int)pos.X, (int)pos.Y, 450, 25, "Back to Extension List", MainMenu.exitButtonColor))
{
ms.ExtensionInfoToShow = null;
Extension.Handler.ActiveInfo = null;
}
pos.Y += 30;
}
}
private static void DrawUserScreenModExtensionInfo(MainMenu m, SpriteBatch sb, Rectangle rect, ExtensionsMenuScreen ms)
{
ms.CreateNewAccountForExtension_UserAndPass = (n, p) =>
{
OS.WillLoadSave = false;
MainMenu.CreateNewAccountForExtensionAndStart(n, p, m.ScreenManager, m, ms);
};
ms.LoadAccountForExtension_FileAndUsername = (userFile, username) =>
{
m.ExitScreen();
MainMenu.resetOS();
OS.WillLoadSave = SaveFileManager.StorageMethods[0].FileExists(userFile);
var o = new OS
{
SaveGameUserName = userFile,
SaveUserAccountName = username
};
m.ScreenManager.AddScreen(o);
};
ms.SaveScreen.Draw(sb, new Rectangle(rect.X, rect.Y + rect.Height / 4, rect.Width, (int)(rect.Height * 0.8f)));
}
internal static void ExtensionMenuListener(DrawExtensionMenuEvent e)
{
if (Extension.Handler.ActiveInfo == null && e.ExtensionMenuScreen.ExtensionInfoToShow == null)
{
var v = e.ButtonPosition;
e.IsCancelled = true;
e.ButtonPosition = e.ExtensionMenuScreen.DrawExtensionList(e.ButtonPosition, e.Rectangle, e.SpriteBatch);
returnButton.Position = e.ButtonPosition;
if (returnButton.Draw())
e.ExtensionMenuScreen.ExitExtensionsScreen();
}
else if (Extension.Handler.ActiveInfo != null)
{
e.IsCancelled = true;
switch (state)
{
case EMSState.Normal:
var pos = e.ButtonPosition;
DrawModExtensionInfo(e.SpriteBatch, ref pos, e.Rectangle, e.ExtensionMenuScreen);
e.ButtonPosition = pos;
break;
default:
MainMenu m = null;
foreach (var s in e.ScreenManager.GetScreens())
{
m = s as MainMenu;
if (m != null) break;
}
DrawUserScreenModExtensionInfo(m, e.SpriteBatch, e.Rectangle, e.ExtensionMenuScreen);
break;
}
}
}
internal static void ExtensionListMenuListener(DrawExtensionMenuListEvent e)
{
var pos = e.ButtonPosition;
if (Extension.Handler.ModExtensions.Count > 0)
{
if (!buttonsLoaded)
LoadButtons(ref pos, e.ExtensionMenuScreen);
pos.Y += 55;
}
e.ButtonPosition = pos;
if (e.ExtensionMenuScreen.HasLoaded)
foreach (var pair in Extension.Handler.ModExtensions)
pair.Value.Item3.Draw();
}
[EventPriority(-100)]
internal static void LoadContentForModExtensionListener(OSLoadContentEvent e)
{
if (Extension.Handler.ActiveInfo == null)
return;
e.IsCancelled = true;
var os = e.OS;
if (os.canRunContent)
{
// setup for proper game function
Settings.slowOSStartup = false;
Settings.initShowsTutorial = false;
os.initShowsTutorial = false;
// replacing OS.LoadContent
os.delayer = new ActionDelayer();
ComputerLoader.init(os);
os.content = e.OS.ScreenManager.Game.Content;
os.username = (os.SaveUserAccountName ?? (Settings.isConventionDemo ? Settings.ConventionLoginName : Environment.UserName));
os.username = FileSanitiser.purifyStringForDisplay(os.username);
var compLocation = new Vector2(0.1f, 0.5f);
if (os.multiplayer && !os.isServer)
compLocation = new Vector2(0.8f, 0.8f);
os.ramAvaliable = os.totalRam;
os.thisComputer = new Computer(os.username + " PC", Utility.GenerateRandomIP(), compLocation, 5, 4, os);
os.thisComputer.adminIP = os.thisComputer.ip;
os.thisComputer.idName = "playerComp";
os.thisComputer.Memory = new MemoryContents();
os.GibsonIP = Utility.GenerateRandomIP();
UserDetail value = os.thisComputer.users[0];
value.known = true;
os.thisComputer.users[0] = value;
os.defaultUser = new UserDetail(os.username, "password", 1);
os.defaultUser.known = true;
ThemeManager.setThemeOnComputer(os.thisComputer, OSTheme.HacknetBlue);
if (os.multiplayer)
{
os.thisComputer.addMultiplayerTargetFile();
os.sendMessage("newComp #" + os.thisComputer.ip + "#" + compLocation.X +
"#" + compLocation.Y + "#" + 5 + "#" + os.thisComputer.name);
os.multiplayerMissionLoaded = false;
}
if (!OS.WillLoadSave)
People.init();
os.modules = new List<Module>();
os.exes = new List<ExeModule>();
os.shells = new List<ShellExe>();
os.shellIPs = new List<string>();
Viewport viewport = os.ScreenManager.GraphicsDevice.Viewport;
int num2 = 205;
var num3 = (int)((viewport.Width - RamModule.MODULE_WIDTH - 6) * 0.44420000000000004);
var num4 = (int)((viewport.Width - RamModule.MODULE_WIDTH - 6) * 0.5558);
int height = viewport.Height - num2 - OS.TOP_BAR_HEIGHT - 6;
os.terminal = new Terminal(new Rectangle(viewport.Width - 2 - num3,
OS.TOP_BAR_HEIGHT,
num3,
viewport.Height - OS.TOP_BAR_HEIGHT - 2), os)
{
name = "TERMINAL"
};
os.modules.Add(os.terminal);
os.netMap = new NetworkMap(new Rectangle(RamModule.MODULE_WIDTH + 4,
viewport.Height - num2 - 2,
num4 - 1,
num2), os)
{
name = "netMap v1.7"
};
os.modules.Add(os.netMap);
os.display = new DisplayModule(new Rectangle(RamModule.MODULE_WIDTH + 4,
OS.TOP_BAR_HEIGHT,
num4 - 2,
height), os)
{
name = "DISPLAY"
};
os.modules.Add(os.display);
os.ram = new RamModule(new Rectangle(2,
OS.TOP_BAR_HEIGHT,
RamModule.MODULE_WIDTH,
os.ramAvaliable + RamModule.contentStartOffset), os)
{
name = "RAM"
};
os.modules.Add(os.ram);
foreach (var m in os.modules.ToArray())
m.LoadContent();
if (os.allFactions == null)
{
os.allFactions = new AllFactions();
os.allFactions.init();
}
bool flag = false;
if (!OS.WillLoadSave)
{
os.netMap.nodes.Insert(0, os.thisComputer);
os.netMap.visibleNodes.Add(0);
MusicManager.loadAsCurrentSong(os.IsDLCConventionDemo ? "Music\\out_run_the_wolves" : "Music\\Revolve");
os.LanguageCreatedIn = Settings.ActiveLocale;
}
else
{
os.loadSaveFile();
flag = true;
Settings.initShowsTutorial = false;
SaveFixHacks.FixSavesWithTerribleHacks(os);
}
var computer = new Computer("JMail Email Server", Utility.GenerateRandomIP(), new Vector2(0.8f, 0.2f), 6, 1, os)
{
idName = "jmail"
};
computer.daemons.Add(new MailServer(computer, "JMail", os));
MailServer.shouldGenerateJunk = false;
computer.users.Add(new UserDetail(os.defaultUser.name, "mailpassword", 2));
computer.initDaemons();
os.netMap.nodes.Add(computer);
os.netMap.mailServer = computer;
os.topBar = new Rectangle(0, 0, viewport.Width, OS.TOP_BAR_HEIGHT - 1);
os.crashModule = new CrashModule(new Rectangle(0, 0, os.ScreenManager.GraphicsDevice.Viewport.Width, os.ScreenManager.GraphicsDevice.Viewport.Height), os);
os.crashModule.LoadContent();
Settings.IsInExtensionMode = false; // little hack to prevent intro text module ctor from throwing nullref
os.introTextModule = new IntroTextModule(new Rectangle(0, 0, os.ScreenManager.GraphicsDevice.Viewport.Width, os.ScreenManager.GraphicsDevice.Viewport.Height), os)
{
complete = true,
text = new string[] { "" }
};
os.introTextModule.LoadContent();
Settings.IsInExtensionMode = true; // hack end
os.traceTracker = new TraceTracker(os);
os.IncConnectionOverlay = new IncomingConnectionOverlay(os);
os.scanLines = os.content.Load<Texture2D>("ScanLines");
os.cross = os.content.Load<Texture2D>("Cross");
os.cog = os.content.Load<Texture2D>("Cog");
os.saveIcon = os.content.Load<Texture2D>("SaveIcon");
os.beepSound = os.content.Load<SoundEffect>("SFX/beep");
os.mailicon = new MailIcon(os, new Vector2(0f, 0f));
os.mailicon.pos.X = viewport.Width - os.mailicon.getWidth() - 2;
os.hubServerAlertsIcon = new HubServerAlertsIcon(os.content, "dhs",
new string[] { "@channel", "@" + os.defaultUser.name }
);
os.hubServerAlertsIcon.Init(os);
if (os.HasLoadedDLCContent)
os.AircraftInfoOverlay = new AircraftInfoOverlay(os);
SAChangeAlertIcon.UpdateAlertIcon(os);
os.introTextModule.complete |= (flag || !Settings.slowOSStartup);
if (!flag)
MusicManager.playSong();
os.inputEnabled = true;
os.isLoaded = true;
os.fullscreen = new Rectangle(0, 0, os.ScreenManager.GraphicsDevice.Viewport.Width, os.ScreenManager.GraphicsDevice.Viewport.Height);
os.TraceDangerSequence = new TraceDangerSequence(os.content, os.ScreenManager.SpriteBatch, os.fullscreen, os);
os.endingSequence = new EndingSequenceModule(os.fullscreen, os);
if (Settings.EnableDLC && DLC1SessionUpgrader.HasDLC1Installed)
os.BootAssitanceModule = new BootCrashAssistanceModule(os.fullscreen, os);
if (Settings.EnableDLC && DLC1SessionUpgrader.HasDLC1Installed && HostileHackerBreakinSequence.IsInBlockingHostileFileState(os))
{
os.rebootThisComputer();
os.BootAssitanceModule.ShouldSkipDialogueTypeout = true;
}
else
{
if (Settings.EnableDLC && HostileHackerBreakinSequence.IsFirstSuccessfulBootAfterBlockingState(os))
{
HostileHackerBreakinSequence.ReactToFirstSuccesfulBoot(os);
os.rebootThisComputer();
}
if (!OS.TestingPassOnly)
os.runCommand("connect " + os.thisComputer.ip);
var folder2 = os.thisComputer.files.root.searchForFolder("sys");
if (folder2.searchForFile("Notes_Reopener.bat") != null)
os.runCommand("notes");
}
if (Settings.EnableDLC && DLC1SessionUpgrader.HasDLC1Installed && os.HasLoadedDLCContent)
{
bool flag4 = false;
if (!os.Flags.HasFlag("AircraftInfoOverlayDeactivated"))
{
flag4 |= os.Flags.HasFlag("AircraftInfoOverlayActivated");
if (!flag4)
{
var c = Programs.getComputer(os, "dair_crash");
var folder3 = c.files.root.searchForFolder("FlightSystems");
bool flag5 = false;
for (int i = 0; i < folder3.files.Count; i++)
flag5 |= folder3.files[i].name == "747FlightOps.dll";
var aircraftDaemon = (AircraftDaemon)c.getDaemon(typeof(AircraftDaemon));
if (!flag5 && !os.Flags.HasFlag("DLC_PlaneResult"))
flag4 = true;
}
}
if (flag4)
{
var c = Programs.getComputer(os, "dair_crash");
var aircraftDaemon = (AircraftDaemon)c.getDaemon(typeof(AircraftDaemon));
aircraftDaemon.StartReloadFirmware();
aircraftDaemon.StartUpdating();
os.AircraftInfoOverlay.Activate();
os.AircraftInfoOverlay.IsMonitoringDLCEndingCases = true;
MissionFunctions.runCommand(0, "playAirlineCrashSongSequence");
}
}
}
else if (os.multiplayer)
os.initializeNetwork();
os.Flags.AddFlag("FirstAlertComplete");
os.IsInDLCMode = false;
os.ShowDLCAlertsIcon = false;
if (OS.WillLoadSave)
{
Stream stream = null;
if (e.OS.ForceLoadOverrideStream != null && OS.TestingPassOnly)
stream = e.OS.ForceLoadOverrideStream;
else
stream = SaveFileManager.GetSaveReadStream(e.OS.SaveGameUserName);
Extension.Handler.LoadExtension(Extension.Handler.ActiveInfo.Id);
Extension.Handler.ActiveInfo.OnLoad(e.OS, stream);
}
else
{
Extension.Handler.CanRegister = true;
Extension.Handler.ActiveInfo.OnConstruct(e.OS);
Extension.Handler.CanRegister = false;
}
}
public static void UnloadContentForModExtensionListener(OSUnloadContentEvent e)
{
if (Extension.Handler.ActiveInfo != null)
{
Extension.Handler.UnloadExtension(Extension.Handler.ActiveInfo.Id);
Extension.Handler.ActiveInfo.OnUnload(e.OS);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Numerics.Hashing;
namespace Microsoft.CSharp.RuntimeBinder
{
internal static class BinderHelper
{
private static MethodInfo s_DoubleIsNaN;
private static MethodInfo s_SingleIsNaN;
internal static DynamicMetaObject Bind(
ICSharpBinder action,
RuntimeBinder binder,
DynamicMetaObject[] args,
IEnumerable<CSharpArgumentInfo> arginfos,
DynamicMetaObject onBindingError)
{
Expression[] parameters = new Expression[args.Length];
BindingRestrictions restrictions = BindingRestrictions.Empty;
ICSharpInvokeOrInvokeMemberBinder callPayload = action as ICSharpInvokeOrInvokeMemberBinder;
ParameterExpression tempForIncrement = null;
IEnumerator<CSharpArgumentInfo> arginfosEnum = (arginfos ?? Array.Empty<CSharpArgumentInfo>()).GetEnumerator();
for (int index = 0; index < args.Length; ++index)
{
DynamicMetaObject o = args[index];
// Our contract with the DLR is such that we will not enter a bind unless we have
// values for the meta-objects involved.
Debug.Assert(o.HasValue);
CSharpArgumentInfo info = arginfosEnum.MoveNext() ? arginfosEnum.Current : null;
if (index == 0 && IsIncrementOrDecrementActionOnLocal(action))
{
// We have an inc or a dec operation. Insert the temp local instead.
//
// We need to do this because for value types, the object will come
// in boxed, and we'd need to unbox it to get the original type in order
// to increment. The only way to do that is to create a new temporary.
object value = o.Value;
tempForIncrement = Expression.Variable(value != null ? value.GetType() : typeof(object), "t0");
parameters[0] = tempForIncrement;
}
else
{
parameters[index] = o.Expression;
}
BindingRestrictions r = DeduceArgumentRestriction(index, callPayload, o, info);
restrictions = restrictions.Merge(r);
// Here we check the argument info. If the argument info shows that the current argument
// is a literal constant, then we also add an instance restriction on the value of
// the constant.
if (info != null && info.LiteralConstant)
{
if (o.Value is double && double.IsNaN((double)o.Value))
{
MethodInfo isNaN = s_DoubleIsNaN ?? (s_DoubleIsNaN = typeof(double).GetMethod("IsNaN"));
Expression e = Expression.Call(null, isNaN, o.Expression);
restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e));
}
else if (o.Value is float && float.IsNaN((float)o.Value))
{
MethodInfo isNaN = s_SingleIsNaN ?? (s_SingleIsNaN = typeof(float).GetMethod("IsNaN"));
Expression e = Expression.Call(null, isNaN, o.Expression);
restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e));
}
else
{
Expression e = Expression.Equal(o.Expression, Expression.Constant(o.Value, o.Expression.Type));
r = BindingRestrictions.GetExpressionRestriction(e);
restrictions = restrictions.Merge(r);
}
}
}
// Get the bound expression.
try
{
Expression expression = binder.Bind(action, parameters, args, out DynamicMetaObject deferredBinding);
if (deferredBinding != null)
{
expression = ConvertResult(deferredBinding.Expression, action);
restrictions = deferredBinding.Restrictions.Merge(restrictions);
return new DynamicMetaObject(expression, restrictions);
}
if (tempForIncrement != null)
{
// If we have a ++ or -- payload, we need to do some temp rewriting.
// We rewrite to the following:
//
// temp = (type)o;
// temp++;
// o = temp;
// return o;
DynamicMetaObject arg0 = args[0];
expression = Expression.Block(
new[] {tempForIncrement},
Expression.Assign(tempForIncrement, Expression.Convert(arg0.Expression, arg0.Value.GetType())),
expression,
Expression.Assign(arg0.Expression, Expression.Convert(tempForIncrement, arg0.Expression.Type)));
}
expression = ConvertResult(expression, action);
return new DynamicMetaObject(expression, restrictions);
}
catch (RuntimeBinderException e)
{
if (onBindingError != null)
{
return onBindingError;
}
return new DynamicMetaObject(
Expression.Throw(
Expression.New(
typeof(RuntimeBinderException).GetConstructor(new Type[] { typeof(string) }),
Expression.Constant(e.Message)
),
GetTypeForErrorMetaObject(action, args)
),
restrictions
);
}
}
public static void ValidateBindArgument(DynamicMetaObject argument, string paramName)
{
if (argument == null)
{
throw Error.ArgumentNull(paramName);
}
if (!argument.HasValue)
{
throw Error.DynamicArgumentNeedsValue(paramName);
}
}
public static void ValidateBindArgument(DynamicMetaObject[] arguments, string paramName)
{
if (arguments != null) // null is treated as empty, so not invalid
{
for (int i = 0; i != arguments.Length; ++i)
{
ValidateBindArgument(arguments[i], $"{paramName}[{i}]");
}
}
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsTypeOfStaticCall(
int parameterIndex,
ICSharpInvokeOrInvokeMemberBinder callPayload)
{
return parameterIndex == 0 && callPayload != null && callPayload.StaticCall;
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsComObject(object obj)
{
return obj != null && Marshal.IsComObject(obj);
}
#if ENABLECOMBINDER
/////////////////////////////////////////////////////////////////////////////////
// Try to determine if this object represents a WindowsRuntime object - i.e. it either
// is coming from a WinMD file or is derived from a class coming from a WinMD.
// The logic here matches the CLR's logic of finding a WinRT object.
internal static bool IsWindowsRuntimeObject(DynamicMetaObject obj)
{
Type curType = obj?.RuntimeType;
while (curType != null)
{
TypeAttributes attributes = curType.Attributes;
if ((attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime)
{
// Found a WinRT COM object
return true;
}
if ((attributes & TypeAttributes.Import) == TypeAttributes.Import)
{
// Found a class that is actually imported from COM but not WinRT
// this is definitely a non-WinRT COM object
return false;
}
curType = curType.BaseType;
}
return false;
}
#endif
/////////////////////////////////////////////////////////////////////////////////
private static bool IsTransparentProxy(object obj)
{
// In the full framework, this checks:
// return obj != null && RemotingServices.IsTransparentProxy(obj);
// but transparent proxies don't exist in .NET Core.
return false;
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsDynamicallyTypedRuntimeProxy(DynamicMetaObject argument, CSharpArgumentInfo info)
{
// This detects situations where, although the argument has a value with
// a given type, that type is insufficient to determine, statically, the
// set of reference conversions that are going to exist at bind time for
// different values. For instance, one __ComObject may allow a conversion
// to IFoo while another does not.
bool isDynamicObject =
info != null &&
!info.UseCompileTimeType &&
(IsComObject(argument.Value) || IsTransparentProxy(argument.Value));
return isDynamicObject;
}
/////////////////////////////////////////////////////////////////////////////////
private static BindingRestrictions DeduceArgumentRestriction(
int parameterIndex,
ICSharpInvokeOrInvokeMemberBinder callPayload,
DynamicMetaObject argument,
CSharpArgumentInfo info)
{
// Here we deduce what predicates the DLR can apply to future calls in order to
// determine whether to use the previously-computed-and-cached delegate, or
// whether we need to bind the site again. Ideally we would like the
// predicate to be as broad as is possible; if we can re-use analysis based
// solely on the type of the argument, that is preferable to re-using analysis
// based on object identity with a previously-analyzed argument.
// The times when we need to restrict re-use to a particular instance, rather
// than its type, are:
//
// * if the argument is a null reference then we have no type information.
//
// * if we are making a static call then the first argument is
// going to be a Type object. In this scenario we should always check
// for a specific Type object rather than restricting to the Type type.
//
// * if the argument was dynamic at compile time and it is a dynamic proxy
// object that the runtime manages, such as COM RCWs and transparent
// proxies.
//
// ** there is also a case for constant values (such as literals) to use
// something like value restrictions, and that is accomplished in Bind().
bool useValueRestriction =
argument.Value == null ||
IsTypeOfStaticCall(parameterIndex, callPayload) ||
IsDynamicallyTypedRuntimeProxy(argument, info);
return useValueRestriction ?
BindingRestrictions.GetInstanceRestriction(argument.Expression, argument.Value) :
BindingRestrictions.GetTypeRestriction(argument.Expression, argument.RuntimeType);
}
/////////////////////////////////////////////////////////////////////////////////
private static Expression ConvertResult(Expression binding, ICSharpBinder action)
{
// Need to handle the following cases:
// (1) Call to a constructor: no conversions.
// (2) Call to a void-returning method: return null iff result is discarded.
// (3) Call to a value-type returning method: box to object.
//
// In all other cases, binding.Type should be equivalent or
// reference assignable to resultType.
// No conversions needed for , the call site has the correct type.
if (action is CSharpInvokeConstructorBinder)
{
return binding;
}
if (binding.Type == typeof(void))
{
if (action is ICSharpInvokeOrInvokeMemberBinder invoke && invoke.ResultDiscarded)
{
Debug.Assert(action.ReturnType == typeof(object));
return Expression.Block(binding, Expression.Default(action.ReturnType));
}
throw Error.BindToVoidMethodButExpectResult();
}
if (binding.Type.IsValueType && !action.ReturnType.IsValueType)
{
Debug.Assert(action.ReturnType == typeof(object));
return Expression.Convert(binding, action.ReturnType);
}
return binding;
}
/////////////////////////////////////////////////////////////////////////////////
private static Type GetTypeForErrorMetaObject(ICSharpBinder action, DynamicMetaObject[] args)
{
// This is similar to ConvertResult but has fewer things to worry about.
if (action is CSharpInvokeConstructorBinder)
{
Debug.Assert(args != null);
Debug.Assert(args.Length != 0);
Debug.Assert(args[0].Value is Type);
return args[0].Value as Type;
}
return action.ReturnType;
}
/////////////////////////////////////////////////////////////////////////////////
private static bool IsIncrementOrDecrementActionOnLocal(ICSharpBinder action) =>
action is CSharpUnaryOperationBinder operatorPayload
&& (operatorPayload.Operation == ExpressionType.Increment || operatorPayload.Operation == ExpressionType.Decrement);
/////////////////////////////////////////////////////////////////////////////////
internal static T[] Cons<T>(T sourceHead, T[] sourceTail)
{
if (sourceTail?.Length != 0)
{
T[] array = new T[sourceTail.Length + 1];
array[0] = sourceHead;
sourceTail.CopyTo(array, 1);
return array;
}
return new[] { sourceHead };
}
internal static T[] Cons<T>(T sourceHead, T[] sourceMiddle, T sourceLast)
{
if (sourceMiddle?.Length != 0)
{
T[] array = new T[sourceMiddle.Length + 2];
array[0] = sourceHead;
array[array.Length - 1] = sourceLast;
sourceMiddle.CopyTo(array, 1);
return array;
}
return new[] {sourceHead, sourceLast};
}
/////////////////////////////////////////////////////////////////////////////////
internal static T[] ToArray<T>(IEnumerable<T> source) => source == null ? Array.Empty<T>() : source.ToArray();
/////////////////////////////////////////////////////////////////////////////////
internal static CallInfo CreateCallInfo(ref IEnumerable<CSharpArgumentInfo> argInfos, int discard)
{
// This function converts the C# Binder's notion of argument information to the
// DLR's notion. The DLR counts arguments differently than C#. Here are some
// examples:
// Expression Binder C# ArgInfos DLR CallInfo
//
// d.M(1, 2, 3); CSharpInvokeMemberBinder 4 3
// d(1, 2, 3); CSharpInvokeBinder 4 3
// d[1, 2] = 3; CSharpSetIndexBinder 4 2
// d[1, 2, 3] CSharpGetIndexBinder 4 3
//
// The "discard" parameter tells this function how many of the C# arg infos it
// should not count as DLR arguments.
int argCount = 0;
List<string> argNames = new List<string>();
CSharpArgumentInfo[] infoArray = ToArray(argInfos);
argInfos = infoArray; // Write back the array to allow single enumeration.
foreach (CSharpArgumentInfo info in infoArray)
{
if (info.NamedArgument)
{
argNames.Add(info.Name);
}
++argCount;
}
Debug.Assert(discard <= argCount);
Debug.Assert(argNames.Count <= argCount - discard);
return new CallInfo(argCount - discard, argNames);
}
internal static string GetCLROperatorName(this ExpressionType p)
{
switch (p)
{
default:
return null;
// Binary Operators
case ExpressionType.Add:
return SpecialNames.CLR_Add;
case ExpressionType.Subtract:
return SpecialNames.CLR_Subtract;
case ExpressionType.Multiply:
return SpecialNames.CLR_Multiply;
case ExpressionType.Divide:
return SpecialNames.CLR_Division;
case ExpressionType.Modulo:
return SpecialNames.CLR_Modulus;
case ExpressionType.LeftShift:
return SpecialNames.CLR_LShift;
case ExpressionType.RightShift:
return SpecialNames.CLR_RShift;
case ExpressionType.LessThan:
return SpecialNames.CLR_LT;
case ExpressionType.GreaterThan:
return SpecialNames.CLR_GT;
case ExpressionType.LessThanOrEqual:
return SpecialNames.CLR_LTE;
case ExpressionType.GreaterThanOrEqual:
return SpecialNames.CLR_GTE;
case ExpressionType.Equal:
return SpecialNames.CLR_Equality;
case ExpressionType.NotEqual:
return SpecialNames.CLR_Inequality;
case ExpressionType.And:
return SpecialNames.CLR_BitwiseAnd;
case ExpressionType.ExclusiveOr:
return SpecialNames.CLR_ExclusiveOr;
case ExpressionType.Or:
return SpecialNames.CLR_BitwiseOr;
// "op_LogicalNot";
case ExpressionType.AddAssign:
return SpecialNames.CLR_InPlaceAdd;
case ExpressionType.SubtractAssign:
return SpecialNames.CLR_InPlaceSubtract;
case ExpressionType.MultiplyAssign:
return SpecialNames.CLR_InPlaceMultiply;
case ExpressionType.DivideAssign:
return SpecialNames.CLR_InPlaceDivide;
case ExpressionType.ModuloAssign:
return SpecialNames.CLR_InPlaceModulus;
case ExpressionType.AndAssign:
return SpecialNames.CLR_InPlaceBitwiseAnd;
case ExpressionType.ExclusiveOrAssign:
return SpecialNames.CLR_InPlaceExclusiveOr;
case ExpressionType.OrAssign:
return SpecialNames.CLR_InPlaceBitwiseOr;
case ExpressionType.LeftShiftAssign:
return SpecialNames.CLR_InPlaceLShift;
case ExpressionType.RightShiftAssign:
return SpecialNames.CLR_InPlaceRShift;
// Unary Operators
case ExpressionType.Negate:
return SpecialNames.CLR_UnaryNegation;
case ExpressionType.UnaryPlus:
return SpecialNames.CLR_UnaryPlus;
case ExpressionType.Not:
return SpecialNames.CLR_LogicalNot;
case ExpressionType.OnesComplement:
return SpecialNames.CLR_OnesComplement;
case ExpressionType.IsTrue:
return SpecialNames.CLR_True;
case ExpressionType.IsFalse:
return SpecialNames.CLR_False;
case ExpressionType.Increment:
return SpecialNames.CLR_Increment;
case ExpressionType.Decrement:
return SpecialNames.CLR_Decrement;
}
}
internal static int AddArgHashes(int hash, Type[] typeArguments, CSharpArgumentInfo[] argInfos)
{
foreach (var typeArg in typeArguments)
{
hash = HashHelpers.Combine(hash, typeArg.GetHashCode());
}
return AddArgHashes(hash, argInfos);
}
internal static int AddArgHashes(int hash, CSharpArgumentInfo[] argInfos)
{
foreach (var argInfo in argInfos)
{
hash = HashHelpers.Combine(hash, (int)argInfo.Flags);
var argName = argInfo.Name;
if (!string.IsNullOrEmpty(argName))
{
hash = HashHelpers.Combine(hash, argName.GetHashCode());
}
}
return hash;
}
internal static bool CompareArgInfos(Type[] typeArgs, Type[] otherTypeArgs, CSharpArgumentInfo[] argInfos, CSharpArgumentInfo[] otherArgInfos)
{
for (int i = 0; i < typeArgs.Length; i++)
{
if (typeArgs[i] != otherTypeArgs[i])
{
return false;
}
}
return CompareArgInfos(argInfos, otherArgInfos);
}
internal static bool CompareArgInfos(CSharpArgumentInfo[] argInfos, CSharpArgumentInfo[] otherArgInfos)
{
for (int i = 0; i < argInfos.Length; i++)
{
var argInfo = argInfos[i];
var otherArgInfo = otherArgInfos[i];
if (argInfo.Flags != otherArgInfo.Flags ||
argInfo.Name != otherArgInfo.Name)
{
return false;
}
}
return true;
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetDataPersistenceRulesSpectraS3Request : Ds3Request
{
private string _dataPolicyId;
public string DataPolicyId
{
get { return _dataPolicyId; }
set { WithDataPolicyId(value); }
}
private DataIsolationLevel? _isolationLevel;
public DataIsolationLevel? IsolationLevel
{
get { return _isolationLevel; }
set { WithIsolationLevel(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private DataPlacementRuleState? _state;
public DataPlacementRuleState? State
{
get { return _state; }
set { WithState(value); }
}
private string _storageDomainId;
public string StorageDomainId
{
get { return _storageDomainId; }
set { WithStorageDomainId(value); }
}
private DataPersistenceRuleType? _type;
public DataPersistenceRuleType? Type
{
get { return _type; }
set { WithType(value); }
}
public GetDataPersistenceRulesSpectraS3Request WithDataPolicyId(Guid? dataPolicyId)
{
this._dataPolicyId = dataPolicyId.ToString();
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId.ToString());
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request WithDataPolicyId(string dataPolicyId)
{
this._dataPolicyId = dataPolicyId;
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId);
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request WithIsolationLevel(DataIsolationLevel? isolationLevel)
{
this._isolationLevel = isolationLevel;
if (isolationLevel != null)
{
this.QueryParams.Add("isolation_level", isolationLevel.ToString());
}
else
{
this.QueryParams.Remove("isolation_level");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request WithState(DataPlacementRuleState? state)
{
this._state = state;
if (state != null)
{
this.QueryParams.Add("state", state.ToString());
}
else
{
this.QueryParams.Remove("state");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request WithStorageDomainId(Guid? storageDomainId)
{
this._storageDomainId = storageDomainId.ToString();
if (storageDomainId != null)
{
this.QueryParams.Add("storage_domain_id", storageDomainId.ToString());
}
else
{
this.QueryParams.Remove("storage_domain_id");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request WithStorageDomainId(string storageDomainId)
{
this._storageDomainId = storageDomainId;
if (storageDomainId != null)
{
this.QueryParams.Add("storage_domain_id", storageDomainId);
}
else
{
this.QueryParams.Remove("storage_domain_id");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request WithType(DataPersistenceRuleType? type)
{
this._type = type;
if (type != null)
{
this.QueryParams.Add("type", type.ToString());
}
else
{
this.QueryParams.Remove("type");
}
return this;
}
public GetDataPersistenceRulesSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/data_persistence_rule";
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
using System.Collections.Generic;
using System.Diagnostics;
using Address = System.UInt64;
namespace Microsoft.Diagnostics.Tracing.Utilities
{
// Utilities for TraceEventParsers
/// <summary>
/// A HistoryDictionary is designed to look up 'handles' (pointer sized quantities), that might get reused
/// over time (eg Process IDs, thread IDs). Thus it takes a handle AND A TIME, and finds the value
/// associated with that handle at that time.
/// </summary>
internal class HistoryDictionary<T>
{
public HistoryDictionary(int initialSize)
{
entries = new Dictionary<long, HistoryValue>(initialSize);
}
/// <summary>
/// Adds the association that 'id' has the value 'value' from 'startTime100ns' ONWARD until
/// it is supersede by the same id being added with a time that is after this. Thus if
/// I did Add(58, 1000, MyValue1), and add(58, 500, MyValue2) 'TryGetValue(58, 750, out val) will return
/// MyValue2 (since that value is 'in force' between time 500 and 1000.
/// </summary>
public void Add(Address id, long startTime, T value, bool isEndRundown = false)
{
HistoryValue entry;
if (!entries.TryGetValue((long)id, out entry))
{
// rundown events are 'last chance' events that we only add if we don't already have an entry for it.
if (isEndRundown)
{
startTime = 0;
}
entries.Add((long)id, new HistoryValue(startTime, id, value));
}
else
{
Debug.Assert(entry != null);
var firstEntry = entry;
// See if we can jump ahead. Currently we only do this of the first entry,
// But you could imagine using some of the other nodes's skipAhead entries.
if (firstEntry.skipAhead != null && firstEntry.skipAhead.startTime <= startTime)
{
entry = firstEntry.skipAhead;
}
for (; ; )
{
// We found exact match
if (startTime == entry.StartTime)
{
// Just update the value and exit immediately as there is no need to
// update skipAhead or increment count
entry.value = value;
return;
}
if (entry.next == null)
{
entry.next = new HistoryValue(startTime, id, value);
break;
}
// We sort the entries from smallest to largest time.
if (startTime < entry.startTime)
{
// This entry belongs in front of this entry.
// Insert it before the current entry by moving the current entry after it.
HistoryValue newEntry = new HistoryValue(entry);
entry.startTime = startTime;
entry.value = value;
entry.next = newEntry;
Debug.Assert(entry.startTime <= entry.next.startTime);
break;
}
entry = entry.next;
}
firstEntry.skipAhead = entry.next;
}
count++;
}
// TryGetValue will return the value associated with an id that was placed in the stream
// at time100ns OR BEFORE.
public bool TryGetValue(Address id, long time, out T value)
{
HistoryValue entry;
if (entries.TryGetValue((long)id, out entry))
{
// The entries are sorted smallest to largest.
// We want the last entry that is smaller (or equal) to the target time)
var firstEntry = entry;
// See if we can jump ahead. Currently we only do this of the first entry,
// But you could imagine using some of the other nodes's skipAhead entries.
if (firstEntry.skipAhead != null && firstEntry.skipAhead.startTime < time)
{
entry = firstEntry.skipAhead;
}
HistoryValue last = null;
for (; ; )
{
if (time < entry.startTime)
{
break;
}
last = entry;
entry = entry.next;
if (entry == null)
{
break;
}
}
if (last != null)
{
value = last.value;
firstEntry.skipAhead = last;
return true;
}
}
value = default(T);
return false;
}
public IEnumerable<HistoryValue> Entries
{
get
{
#if DEBUG
int ctr = 0;
#endif
foreach (HistoryValue entry in entries.Values)
{
HistoryValue list = entry;
while (list != null)
{
#if DEBUG
ctr++;
#endif
yield return list;
list = list.next;
}
}
#if DEBUG
Debug.Assert(ctr == count);
#endif
}
}
public int Count { get { return count; } }
/// <summary>
/// Remove all entries associated with a given key (over all time).
/// </summary>
public void Remove(Address id)
{
HistoryValue entry;
if (entries.TryGetValue((long)id, out entry))
{
// Fix up the count by the number of entries we remove.
while (entry != null)
{
entry.skipAhead = null; // Throw away optimization data.
--count;
entry = entry.next;
}
entries.Remove((long)id);
}
}
public class HistoryValue
{
public Address Key { get { return key; } }
public long StartTime { get { return startTime; } }
public T Value { get { return value; } }
#region private
internal HistoryValue(HistoryValue entry)
{
key = entry.key;
startTime = entry.startTime;
value = entry.value;
next = entry.next;
}
internal HistoryValue(long startTime100ns, Address key, T value)
{
this.key = key;
startTime = startTime100ns;
this.value = value;
}
internal Address key;
internal long startTime;
internal T value;
internal HistoryValue next;
// To improve getting to the end quickly, we allow nodes to store values that 'skip ahead'.
// Today we only use this field for the first node to skip to the end (for fast append)
// The only strong invarient for this field is that it point further up the same list.
internal HistoryValue skipAhead;
#endregion
}
#region private
private Dictionary<long, HistoryValue> entries;
private int count;
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
#if FEATURE_SECURITY_PRINCIPAL_WINDOWS
using System.Security.AccessControl;
using System.Security.Principal;
#endif
using System.Text;
using System.Threading;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Engine.UnitTests;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Shared;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using ProjectCollection = Microsoft.Build.Evaluation.ProjectCollection;
using Xunit;
namespace Microsoft.Build.UnitTests.OM.Construction
{
/// <summary>
/// Test the ProjectRootElement class
/// </summary>
public class ProjectRootElement_Tests
{
private const string SimpleProject =
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<PropertyGroup>
<ProjectFile>$(MSBuildProjectFullPath)</ProjectFile>
<ThisFile>$(MSBuildThisFileFullPath)</ThisFile>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>";
private const string ComplexProject =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup Condition=""false"">
<p>p1</p>
<q>q1</q>
</PropertyGroup>
<PropertyGroup/>
<PropertyGroup>
<r>r1</r>
</PropertyGroup>
<PropertyGroup>
<ProjectFile>$(MSBuildProjectFullPath)</ProjectFile>
<ThisFile>$(MSBuildThisFileFullPath)</ThisFile>
</PropertyGroup>
<Choose>
<When Condition=""true"">
<Choose>
<When Condition=""true"">
<PropertyGroup>
<s>s1</s>
</PropertyGroup>
</When>
</Choose>
</When>
<When Condition=""false"">
<PropertyGroup>
<s>s2</s> <!-- both esses -->
</PropertyGroup>
</When>
<Otherwise>
<Choose>
<When Condition=""false""/>
<Otherwise>
<PropertyGroup>
<t>t1</t>
</PropertyGroup>
</Otherwise>
</Choose>
</Otherwise>
</Choose>
<Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets'/>
</Project>";
/// <summary>
/// Empty project content
/// </summary>
[Fact]
public void EmptyProject()
{
ProjectRootElement project = ProjectRootElement.Create();
Assert.Equal(0, Helpers.Count(project.Children));
Assert.Equal(string.Empty, project.DefaultTargets);
Assert.Equal(string.Empty, project.InitialTargets);
Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.ToolsVersion);
Assert.True(project.HasUnsavedChanges); // it is indeed unsaved
}
/// <summary>
/// Set default targets
/// </summary>
[Fact]
public void SetDefaultTargets()
{
ProjectRootElement project = ProjectRootElement.Create();
project.DefaultTargets = "dt";
Assert.Equal("dt", project.DefaultTargets);
Assert.True(project.HasUnsavedChanges);
}
/// <summary>
/// Set initialtargets
/// </summary>
[Fact]
public void SetInitialTargets()
{
ProjectRootElement project = ProjectRootElement.Create();
project.InitialTargets = "it";
Assert.Equal("it", project.InitialTargets);
Assert.True(project.HasUnsavedChanges);
}
/// <summary>
/// Set toolsversion
/// </summary>
[Fact]
public void SetToolsVersion()
{
ProjectRootElement project = ProjectRootElement.Create();
project.ToolsVersion = "tv";
Assert.Equal("tv", project.ToolsVersion);
Assert.True(project.HasUnsavedChanges);
}
/// <summary>
/// Setting full path should accept and update relative path
/// </summary>
[Fact]
public void SetFullPath()
{
ProjectRootElement project = ProjectRootElement.Create();
project.FullPath = "X";
Assert.Equal(project.FullPath, Path.Combine(Directory.GetCurrentDirectory(), "X"));
}
/// <summary>
/// Attempting to load a second ProjectRootElement over the same file path simply
/// returns the first one.
/// A ProjectRootElement is notionally a "memory mapped" view of a file, and we assume there is only
/// one per file path, so we must reject attempts to make another.
/// </summary>
[Fact]
public void ConstructOverSameFileReturnsSame()
{
ProjectRootElement projectXml1 = ProjectRootElement.Create();
projectXml1.Save(FileUtilities.GetTemporaryFile());
ProjectRootElement projectXml2 = ProjectRootElement.Open(projectXml1.FullPath);
Assert.True(object.ReferenceEquals(projectXml1, projectXml2));
}
/// <summary>
/// Attempting to load a second ProjectRootElement over the same file path simply
/// returns the first one. This should work even if one of the paths is not a full path.
/// </summary>
[Fact]
public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath()
{
ProjectRootElement projectXml1 = ProjectRootElement.Create();
projectXml1.FullPath = Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc");
ProjectRootElement projectXml2 = ProjectRootElement.Open(@"xyz\abc");
Assert.True(object.ReferenceEquals(projectXml1, projectXml2));
}
/// <summary>
/// Attempting to load a second ProjectRootElement over the same file path simply
/// returns the first one. This should work even if one of the paths is not a full path.
/// </summary>
[Fact]
public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath2()
{
ProjectRootElement projectXml1 = ProjectRootElement.Create();
projectXml1.FullPath = @"xyz\abc";
ProjectRootElement projectXml2 = ProjectRootElement.Open(Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc"));
Assert.True(object.ReferenceEquals(projectXml1, projectXml2));
}
/// <summary>
/// Using TextReader
/// </summary>
[Fact]
public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath3()
{
string content = "<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n</Project>";
ProjectRootElement projectXml1 = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
projectXml1.FullPath = @"xyz\abc";
ProjectRootElement projectXml2 = ProjectRootElement.Open(Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc"));
Assert.True(object.ReferenceEquals(projectXml1, projectXml2));
}
/// <summary>
/// Using TextReader
/// </summary>
[Fact]
public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath4()
{
string content = "<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n</Project>";
ProjectRootElement projectXml1 = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
projectXml1.FullPath = Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc");
ProjectRootElement projectXml2 = ProjectRootElement.Open(@"xyz\abc");
Assert.True(object.ReferenceEquals(projectXml1, projectXml2));
}
/// <summary>
/// Two ProjectRootElement's over the same file path does not throw (although you shouldn't do it)
/// </summary>
[Fact]
public void SetFullPathProjectXmlAlreadyLoaded()
{
ProjectRootElement projectXml1 = ProjectRootElement.Create();
projectXml1.FullPath = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
ProjectRootElement projectXml2 = ProjectRootElement.Create();
projectXml2.FullPath = projectXml1.FullPath;
}
/// <summary>
/// Invalid XML
/// </summary>
[Fact]
public void InvalidXml()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
ProjectRootElement.Create(XmlReader.Create(new StringReader("XXX")));
}
);
}
/// <summary>
/// Valid Xml, invalid namespace on the root
/// </summary>
[Fact]
public void InvalidNamespace()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
var content = @"<Project xmlns='XXX'/>";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
});
}
/// <summary>
/// Invalid root tag
/// </summary>
[Fact]
public void InvalidRootTag()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<XXX xmlns='http://schemas.microsoft.com/developer/msbuild/2003'/>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Valid Xml, invalid syntax below the root
/// </summary>
[Fact]
public void InvalidChildBelowRoot()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<XXX/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Root indicates upgrade needed
/// </summary>
[Fact]
public void NeedsUpgrade()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<VisualStudioProject/>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Valid Xml, invalid namespace below the root
/// </summary>
[Fact]
public void InvalidNamespaceBelowRoot()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup xmlns='XXX'/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Tests that the namespace error reports are correct
/// </summary>
[Fact]
public void InvalidNamespaceErrorReport()
{
string content = @"
<msb:Project xmlns:msb=`http://schemas.microsoft.com/developer/msbuild/2003`>
<msb:Target Name=`t`>
<msb:Message Text=`[t]`/>
</msb:Target>
</msb:Project>
";
content = content.Replace("`", "\"");
bool exceptionThrown = false;
try
{
Project project = new Project(XmlReader.Create(new StringReader(content)));
}
catch (InvalidProjectFileException ex)
{
exceptionThrown = true;
// MSB4068: The element <msb:Project> is unrecognized, or not supported in this context.
Assert.NotEqual("MSB4068", ex.ErrorCode);
// MSB4041: The default XML namespace of the project must be the MSBuild XML namespace.
Assert.Equal("MSB4041", ex.ErrorCode);
}
Assert.True(exceptionThrown); // "ERROR: An invalid project file exception should have been thrown."
}
/// <summary>
/// Valid Xml, invalid syntax thrown by child element parsing
/// </summary>
[Fact]
public void ValidXmlInvalidSyntaxInChildElement()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ItemGroup>
<XXX YYY='ZZZ'/>
</ItemGroup>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Valid Xml, invalid syntax, should not get added to the Xml cache and
/// thus returned on the second request!
/// </summary>
[Fact]
public void ValidXmlInvalidSyntaxOpenFromDiskTwice()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ItemGroup>
<XXX YYY='ZZZ'/>
</ItemGroup>
</Project>
";
string path = null;
try
{
try
{
path = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
File.WriteAllText(path, content);
ProjectRootElement.Open(path);
}
catch (InvalidProjectFileException)
{
}
// Should throw again, not get from cache
ProjectRootElement.Open(path);
}
finally
{
File.Delete(path);
}
}
);
}
/// <summary>
/// Verify that opening project using XmlTextReader does not add it to the Xml cache
/// </summary>
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void ValidXmlXmlTextReaderNotCache()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
</Project>
";
string path = null;
try
{
path = FileUtilities.GetTemporaryFile();
File.WriteAllText(path, content);
var reader1 = XmlReader.Create(path);
ProjectRootElement root1 = ProjectRootElement.Create(reader1);
root1.AddItem("type", "include");
// If it's in the cache, then the 2nd document won't see the add.
var reader2 = XmlReader.Create(path);
ProjectRootElement root2 = ProjectRootElement.Create(reader2);
Assert.Single(root1.Items);
Assert.Empty(root2.Items);
reader1.Dispose();
reader2.Dispose();
}
finally
{
File.Delete(path);
}
}
/// <summary>
/// Verify that opening project using the same path adds it to the Xml cache
/// </summary>
[Fact]
public void ValidXmlXmlReaderCache()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
</Project>
";
string content2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' DefaultTargets='t'>
</Project>
";
string path = null;
try
{
path = FileUtilities.GetTemporaryFile();
File.WriteAllText(path, content);
ProjectRootElement root1 = ProjectRootElement.Create(path);
File.WriteAllText(path, content2);
// If it went in the cache, and this path also reads from the cache,
// then we'll see the first version of the file.
ProjectRootElement root2 = ProjectRootElement.Create(path);
Assert.Equal(string.Empty, root1.DefaultTargets);
Assert.Equal(string.Empty, root2.DefaultTargets);
}
finally
{
File.Delete(path);
}
}
/// <summary>
/// A simple "system" test: load microsoft.*.targets and verify we don't throw
/// </summary>
[Fact]
public void LoadCommonTargets()
{
ProjectCollection projectCollection = new ProjectCollection();
string toolsPath = projectCollection.Toolsets.Where(toolset => (string.Compare(toolset.ToolsVersion, ObjectModelHelpers.MSBuildDefaultToolsVersion, StringComparison.OrdinalIgnoreCase) == 0)).First().ToolsPath;
string[] targets =
{
"Microsoft.Common.targets",
"Microsoft.CSharp.targets",
"Microsoft.VisualBasic.targets"
};
foreach (string target in targets)
{
string path = Path.Combine(toolsPath, target);
ProjectRootElement project = ProjectRootElement.Open(path);
Console.WriteLine(@"Loaded target: {0}", target);
Console.WriteLine(@"Children: {0}", Helpers.Count(project.Children));
Console.WriteLine(@"Targets: {0}", Helpers.MakeList(project.Targets).Count);
Console.WriteLine(@"Root ItemGroups: {0}", Helpers.MakeList(project.ItemGroups).Count);
Console.WriteLine(@"Root PropertyGroups: {0}", Helpers.MakeList(project.PropertyGroups).Count);
Console.WriteLine(@"UsingTasks: {0}", Helpers.MakeList(project.UsingTasks).Count);
Console.WriteLine(@"ItemDefinitionGroups: {0}", Helpers.MakeList(project.ItemDefinitionGroups).Count);
}
}
/// <summary>
/// Save project loaded from TextReader, without setting FullPath.
/// </summary>
[Fact]
public void InvalidSaveWithoutFullPath()
{
Assert.Throws<InvalidOperationException>(() =>
{
XmlReader reader = XmlReader.Create(new StringReader("<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"/>"));
ProjectRootElement project = ProjectRootElement.Create(reader);
project.Save();
}
);
}
/// <summary>
/// Save content with transforms.
/// The ">" should not turn into "<"
/// </summary>
[Fact]
public void SaveWithTransforms()
{
ProjectRootElement project = ProjectRootElement.Create();
project.AddItem("i", "@(h->'%(x)')");
StringBuilder builder = new StringBuilder();
StringWriter writer = new StringWriter(builder);
project.Save(writer);
// UTF-16 because writer.Encoding is UTF-16
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemGroup>
<i Include=""@(h->'%(x)')"" />
</ItemGroup>
</Project>");
Helpers.VerifyAssertLineByLine(expected, builder.ToString());
}
/// <summary>
/// Save content with transforms to a file.
/// The ">" should not turn into "<"
/// </summary>
[Fact]
public void SaveWithTransformsToFile()
{
ProjectRootElement project = ProjectRootElement.Create();
project.AddItem("i", "@(h->'%(x)')");
string file = null;
try
{
file = FileUtilities.GetTemporaryFile();
project.Save(file);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-8""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemGroup>
<i Include=""@(h->'%(x)')"" />
</ItemGroup>
</Project>");
string actual = File.ReadAllText(file);
Helpers.VerifyAssertLineByLine(expected, actual);
}
finally
{
File.Delete(file);
}
}
/// <summary>
/// Save should create a directory if it is missing
/// </summary>
[Fact]
public void SaveToNonexistentDirectory()
{
ProjectRootElement project = ProjectRootElement.Create();
string directory = null;
try
{
directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
string file = "foo.proj";
string path = Path.Combine(directory, file);
project.Save(path);
Assert.True(File.Exists(path));
Assert.Equal(path, project.FullPath);
Assert.Equal(directory, project.DirectoryPath);
}
finally
{
FileUtilities.DeleteWithoutTrailingBackslash(directory, true);
}
}
/// <summary>
/// Save should create a directory if it is missing
/// </summary>
[Fact]
public void SaveToNonexistentDirectoryRelativePath()
{
ProjectRootElement project = ProjectRootElement.Create();
string directory = null;
string savedCurrentDirectory = Directory.GetCurrentDirectory();
try
{
Directory.SetCurrentDirectory(Path.GetTempPath()); // should be used for project.DirectoryPath; it must exist
// Use the *real* current directory for constructing the path
var curDir = Directory.GetCurrentDirectory();
string file = "bar" + Path.DirectorySeparatorChar + "foo.proj";
string path = Path.Combine(curDir, file);
directory = Path.Combine(curDir, "bar");
project.Save(file); // relative path: file and a single directory only; should create the "bar" part
Assert.True(File.Exists(file));
Assert.Equal(path, project.FullPath);
Assert.Equal(directory, project.DirectoryPath);
}
finally
{
FileUtilities.DeleteWithoutTrailingBackslash(directory, true);
Directory.SetCurrentDirectory(savedCurrentDirectory);
}
}
/// <summary>
/// Saving an unnamed project without a path specified should give a nice exception
/// </summary>
[Fact]
public void SaveUnnamedProject()
{
Assert.Throws<InvalidOperationException>(() =>
{
ProjectRootElement project = ProjectRootElement.Create();
project.Save();
}
);
}
/// <summary>
/// Verifies that the ProjectRootElement.Encoding property getter returns values
/// that are based on the XML declaration in the file.
/// </summary>
[Fact]
public void EncodingGetterBasedOnXmlDeclaration()
{
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
</Project>"))));
Assert.Equal(Encoding.Unicode, project.Encoding);
project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"<?xml version=""1.0"" encoding=""utf-8""?>
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
</Project>"))));
Assert.Equal(Encoding.UTF8, project.Encoding);
project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"<?xml version=""1.0"" encoding=""us-ascii""?>
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
</Project>"))));
Assert.Equal(Encoding.ASCII, project.Encoding);
}
/// <summary>
/// Verifies that ProjectRootElement.Encoding returns the correct value
/// after reading a file off disk, even if no xml declaration is present.
/// </summary>
[Fact]
public void EncodingGetterBasedOnActualEncodingWhenXmlDeclarationIsAbsent()
{
string projectFullPath = FileUtilities.GetTemporaryFile();
try
{
VerifyLoadedProjectHasEncoding(projectFullPath, Encoding.UTF8);
VerifyLoadedProjectHasEncoding(projectFullPath, Encoding.Unicode);
// We don't test ASCII, since there is no byte order mark for it,
// and the XmlReader will legitimately decide to interpret it as UTF8,
// which would fail the test although it's a reasonable assumption
// when no xml declaration is present.
////VerifyLoadedProjectHasEncoding(projectFullPath, Encoding.ASCII);
}
finally
{
File.Delete(projectFullPath);
}
}
/// <summary>
/// Verifies that the Save method saves an otherwise unmodified project
/// with a specified file encoding.
/// </summary>
[Fact]
public void SaveUnmodifiedWithNewEncoding()
{
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
</Project>"))));
project.FullPath = FileUtilities.GetTemporaryFile();
string projectFullPath = project.FullPath;
try
{
project.Save();
project = null;
// We haven't made any changes to the project, but we want to save it using various encodings.
SaveProjectWithEncoding(projectFullPath, Encoding.Unicode);
SaveProjectWithEncoding(projectFullPath, Encoding.ASCII);
SaveProjectWithEncoding(projectFullPath, Encoding.UTF8);
}
finally
{
File.Delete(projectFullPath);
}
}
/// <summary>
/// Enumerate over all properties from the project directly.
/// It should traverse into Choose's.
/// </summary>
[Fact]
public void PropertiesEnumerator()
{
string content = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup Condition=""false"">
<p>p1</p>
<q>q1</q>
</PropertyGroup>
<PropertyGroup/>
<PropertyGroup>
<r>r1</r>
</PropertyGroup>
<Choose>
<When Condition=""true"">
<Choose>
<When Condition=""true"">
<PropertyGroup>
<s>s1</s>
</PropertyGroup>
</When>
</Choose>
</When>
<When Condition=""false"">
<PropertyGroup>
<s>s2</s> <!-- both esses -->
</PropertyGroup>
</When>
<Otherwise>
<Choose>
<When Condition=""false""/>
<Otherwise>
<PropertyGroup>
<t>t1</t>
</PropertyGroup>
</Otherwise>
</Choose>
</Otherwise>
</Choose>
</Project>");
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
List<ProjectPropertyElement> properties = Helpers.MakeList(project.Properties);
Assert.Equal(6, properties.Count);
Assert.Equal("q", properties[1].Name);
Assert.Equal("r1", properties[2].Value);
Assert.Equal("t1", properties[5].Value);
}
/// <summary>
/// Enumerate over all items from the project directly.
/// It should traverse into Choose's.
/// </summary>
[Fact]
public void ItemsEnumerator()
{
string content = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemGroup Condition=""false"">
<i Include=""i1""/>
<j Include=""j1""/>
</ItemGroup>
<ItemGroup/>
<ItemGroup>
<k Include=""k1""/>
</ItemGroup>
<Choose>
<When Condition=""true"">
<Choose>
<When Condition=""true"">
<ItemGroup>
<k Include=""k2""/>
</ItemGroup>
</When>
</Choose>
</When>
<When Condition=""false"">
<ItemGroup>
<k Include=""k3""/>
</ItemGroup>
</When>
<Otherwise>
<Choose>
<When Condition=""false""/>
<Otherwise>
<ItemGroup>
<k Include=""k4""/>
</ItemGroup>
</Otherwise>
</Choose>
</Otherwise>
</Choose>
</Project>");
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
List<ProjectItemElement> items = Helpers.MakeList(project.Items);
Assert.Equal(6, items.Count);
Assert.Equal("j", items[1].ItemType);
Assert.Equal("k1", items[2].Include);
Assert.Equal("k4", items[5].Include);
}
#if FEATURE_SECURITY_PRINCIPAL_WINDOWS
/// <summary>
/// Build a solution file that can't be accessed
/// </summary>
[Fact]
public void SolutionCanNotBeOpened()
{
if (NativeMethodsShared.IsUnixLike)
{
// Security classes are not supported on Unix
return;
}
Assert.Throws<InvalidProjectFileException>(() =>
{
string solutionFile = null;
string tempFileSentinel = null;
IdentityReference identity = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
FileSystemAccessRule rule = new FileSystemAccessRule(identity, FileSystemRights.Read, AccessControlType.Deny);
FileSecurity security = null;
try
{
tempFileSentinel = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
solutionFile = Path.ChangeExtension(tempFileSentinel, ".sln");
File.Copy(tempFileSentinel, solutionFile);
security = new FileSecurity(solutionFile, System.Security.AccessControl.AccessControlSections.All);
security.AddAccessRule(rule);
File.SetAccessControl(solutionFile, security);
ProjectRootElement.Open(solutionFile);
}
catch (PrivilegeNotHeldException)
{
throw new InvalidProjectFileException("Running unelevated so skipping this scenario.");
}
finally
{
if (security != null)
{
security.RemoveAccessRule(rule);
}
File.Delete(solutionFile);
File.Delete(tempFileSentinel);
Assert.False(File.Exists(solutionFile));
}
}
);
}
/// <summary>
/// Build a project file that can't be accessed
/// </summary>
[Fact]
public void ProjectCanNotBeOpened()
{
if (NativeMethodsShared.IsUnixLike)
{
return; // FileSecurity class is not supported on Unix
}
Assert.Throws<InvalidProjectFileException>(() =>
{
string projectFile = null;
IdentityReference identity = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
FileSystemAccessRule rule = new FileSystemAccessRule(identity, FileSystemRights.Read, AccessControlType.Deny);
FileSecurity security = null;
try
{
// Does not have .sln or .vcproj extension so loads as project
projectFile = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
security = new FileSecurity(projectFile, System.Security.AccessControl.AccessControlSections.All);
security.AddAccessRule(rule);
File.SetAccessControl(projectFile, security);
ProjectRootElement.Open(projectFile);
}
catch (PrivilegeNotHeldException)
{
throw new InvalidProjectFileException("Running unelevated so skipping the scenario.");
}
finally
{
if (security != null)
{
security.RemoveAccessRule(rule);
}
File.Delete(projectFile);
Assert.False(File.Exists(projectFile));
}
}
);
}
#endif
/// <summary>
/// Build a corrupt solution
/// </summary>
[Fact]
public void SolutionCorrupt()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string solutionFile = null;
try
{
solutionFile = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
// Arbitrary corrupt content
string content = @"Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio Codename Orcas
Project(""{";
File.WriteAllText(solutionFile, content);
ProjectRootElement.Open(solutionFile);
}
finally
{
File.Delete(solutionFile);
}
}
);
}
/// <summary>
/// Open lots of projects concurrently to try to trigger problems
/// </summary>
[Fact]
public void ConcurrentProjectOpenAndCloseThroughProject()
{
if (NativeMethodsShared.IsUnixLike)
{
return; // TODO: This test hangs on Linux. Investigate
}
int iterations = 500;
string[] paths = ObjectModelHelpers.GetTempFiles(iterations);
try
{
Project[] projects = new Project[iterations];
for (int i = 0; i < iterations; i++)
{
CreatePREWithSubstantialContent().Save(paths[i]);
}
var collection = new ProjectCollection();
int counter = 0;
int remaining = iterations;
var done = new ManualResetEvent(false);
for (int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
var current = Interlocked.Increment(ref counter) - 1;
projects[current] = collection.LoadProject(paths[current]);
if (Interlocked.Decrement(ref remaining) == 0)
{
done.Set();
}
});
}
done.WaitOne();
Assert.Equal(iterations, collection.LoadedProjects.Count);
counter = 0;
remaining = iterations;
done.Reset();
for (int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
var current = Interlocked.Increment(ref counter) - 1;
var pre = projects[current].Xml;
collection.UnloadProject(projects[current]);
collection.UnloadProject(pre);
if (Interlocked.Decrement(ref remaining) == 0)
{
done.Set();
}
});
}
done.WaitOne();
Assert.Empty(collection.LoadedProjects);
}
finally
{
for (int i = 0; i < iterations; i++)
{
File.Delete(paths[i]);
}
}
}
/// <summary>
/// Open lots of projects concurrently to try to trigger problems
/// </summary>
[Fact]
public void ConcurrentProjectOpenAndCloseThroughProjectRootElement()
{
int iterations = 500;
string[] paths = ObjectModelHelpers.GetTempFiles(iterations);
try
{
var projects = new ProjectRootElement[iterations];
var collection = new ProjectCollection();
int counter = 0;
int remaining = iterations;
var done = new ManualResetEvent(false);
for (int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
var current = Interlocked.Increment(ref counter) - 1;
CreatePREWithSubstantialContent().Save(paths[current]);
projects[current] = ProjectRootElement.Open(paths[current], collection);
if (Interlocked.Decrement(ref remaining) == 0)
{
done.Set();
}
});
}
done.WaitOne();
counter = 0;
remaining = iterations;
done.Reset();
for (int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
var current = Interlocked.Increment(ref counter) - 1;
collection.UnloadProject(projects[current]);
if (Interlocked.Decrement(ref remaining) == 0)
{
done.Set();
}
});
}
done.WaitOne();
}
finally
{
for (int i = 0; i < iterations; i++)
{
File.Delete(paths[i]);
}
}
}
/// <summary>
/// Tests DeepClone and CopyFrom for ProjectRootElements.
/// </summary>
[Fact]
public void DeepClone()
{
var pre = ProjectRootElement.Create();
var pg = pre.AddPropertyGroup();
pg.AddProperty("a", "$(b)");
pg.AddProperty("c", string.Empty);
var ig = pre.AddItemGroup();
var item = ig.AddItem("Foo", "boo$(hoo)");
item.AddMetadata("Some", "Value");
var target = pre.AddTarget("SomeTarget");
target.Condition = "Some Condition";
var task = target.AddTask("SomeTask");
task.AddOutputItem("p1", "it");
task.AddOutputProperty("prop", "it2");
target.AppendChild(pre.CreateOnErrorElement("someTarget"));
var idg = pre.AddItemDefinitionGroup();
var id = idg.AddItemDefinition("SomeType");
id.AddMetadata("sm", "sv");
pre.AddUsingTask("name", "assembly", null);
var inlineUt = pre.AddUsingTask("anotherName", "somefile", null);
inlineUt.TaskFactory = "SomeFactory";
inlineUt.AddUsingTaskBody("someEvaluate", "someTaskBody");
var choose = pre.CreateChooseElement();
pre.AppendChild(choose);
var when1 = pre.CreateWhenElement("some condition");
choose.AppendChild(when1);
when1.AppendChild(pre.CreatePropertyGroupElement());
var otherwise = pre.CreateOtherwiseElement();
choose.AppendChild(otherwise);
otherwise.AppendChild(pre.CreateItemGroupElement());
var importGroup = pre.AddImportGroup();
importGroup.AddImport("Some imported project");
pre.AddImport("direct import");
ValidateDeepCloneAndCopyFrom(pre);
}
/// <summary>
/// Tests DeepClone and CopyFrom for ProjectRootElement that contain ProjectExtensions with text inside.
/// </summary>
[Fact]
public void DeepCloneWithProjectExtensionsElementOfText()
{
var pre = ProjectRootElement.Create();
var extensions = pre.CreateProjectExtensionsElement();
extensions.Content = "Some foo content";
pre.AppendChild(extensions);
ValidateDeepCloneAndCopyFrom(pre);
}
/// <summary>
/// Tests DeepClone and CopyFrom for ProjectRootElement that contain ProjectExtensions with xml inside.
/// </summary>
[Fact]
public void DeepCloneWithProjectExtensionsElementOfXml()
{
var pre = ProjectRootElement.Create();
var extensions = pre.CreateProjectExtensionsElement();
extensions.Content = "<a><b/></a>";
pre.AppendChild(extensions);
ValidateDeepCloneAndCopyFrom(pre);
}
/// <summary>
/// Tests DeepClone and CopyFrom when there is metadata expressed as attributes
/// </summary>
[Fact]
public void DeepCloneWithMetadataAsAttributes()
{
var project =
@"<?xml version=`1.0` encoding=`utf-8`?>
<Project xmlns = 'msbuildnamespace'>
<ItemDefinitionGroup>
<Compile A=`a`/>
<B M1=`dv1`>
<M2>dv2</M2>
</B>
<C/>
</ItemDefinitionGroup>
<ItemGroup>
<Compile Include=`Class1.cs` A=`a` />
<Compile Include=`Class2.cs` />
</ItemGroup>
<PropertyGroup>
<P>val</P>
</PropertyGroup>
<Target Name=`Build`>
<ItemGroup>
<A Include=`a` />
<B Include=`b` M1=`v1`>
<M2>v2</M2>
</B>
<C Include=`c`/>
</ItemGroup>
</Target>
</Project>";
var pre = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(project))));
ValidateDeepCloneAndCopyFrom(pre);
}
/// <summary>
/// Tests TryOpen when preserveFormatting is the same and different than the cached project.
/// </summary>
[Fact]
public void TryOpenWithPreserveFormatting()
{
string project =
@"<?xml version=`1.0` encoding=`utf-8`?>
<Project xmlns = 'msbuildnamespace'>
</Project>";
using (var env = TestEnvironment.Create())
using (var projectCollection = new ProjectCollection())
{
var projectFiles = env.CreateTestProjectWithFiles("", new[] { "build.proj" });
var projectFile = projectFiles.CreatedFiles.First();
var projectXml = ProjectRootElement.Create(
XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(project))),
projectCollection,
preserveFormatting: true);
projectXml.Save(projectFile);
var xml0 = ProjectRootElement.TryOpen(projectXml.FullPath, projectCollection, preserveFormatting: true);
Assert.True(xml0.PreserveFormatting);
var xml1 = ProjectRootElement.TryOpen(projectXml.FullPath, projectCollection, preserveFormatting: false);
Assert.False(xml1.PreserveFormatting);
var xml2 = ProjectRootElement.TryOpen(projectXml.FullPath, projectCollection, preserveFormatting: null);
// reuses existing setting
Assert.False(xml2.PreserveFormatting);
Assert.NotNull(xml0);
Assert.Same(xml0, xml1);
Assert.Same(xml0, xml2);
}
}
[Theory]
[InlineData(true, false, false)]
[InlineData(true, true, true)]
[InlineData(false, false, false)]
[InlineData(false, true, true)]
[InlineData(true, null, true)]
[InlineData(false, null, false)]
public void ReloadCanSpecifyPreserveFormatting(bool initialPreserveFormatting, bool? reloadShouldPreserveFormatting, bool expectedFormattingAfterReload)
{
using (var env = TestEnvironment.Create())
{
var testFiles = env.CreateTestProjectWithFiles("", new[] { "build.proj" });
var projectFile = testFiles.CreatedFiles.First();
var projectElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(SimpleProject, null, initialPreserveFormatting);
projectElement.Save(projectFile);
Assert.Equal(initialPreserveFormatting, projectElement.PreserveFormatting);
projectElement.Reload(false, reloadShouldPreserveFormatting);
Assert.Equal(expectedFormattingAfterReload, projectElement.PreserveFormatting);
// reset project to original preserve formatting
projectElement.Reload(false, initialPreserveFormatting);
Assert.Equal(initialPreserveFormatting, projectElement.PreserveFormatting);
projectElement.ReloadFrom(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(SimpleProject))), false, reloadShouldPreserveFormatting);
Assert.Equal(expectedFormattingAfterReload, projectElement.PreserveFormatting);
// reset project to original preserve formatting
projectElement.Reload(false, initialPreserveFormatting);
Assert.Equal(initialPreserveFormatting, projectElement.PreserveFormatting);
projectElement.ReloadFrom(projectFile, false, reloadShouldPreserveFormatting);
Assert.Equal(expectedFormattingAfterReload, projectElement.PreserveFormatting);
}
}
[Theory]
// same content should still dirty the project
[InlineData(
SimpleProject,
SimpleProject,
true, false, false)]
// new comment
[InlineData(
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
@"
<!-- new comment -->
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P><!-- new comment -->property value<!-- new comment --></P>
</PropertyGroup>
<!-- new comment -->
<ItemGroup>
<i Include=`a`>
<!-- new comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
true, false, true)]
// changed comment
[InlineData(
@"
<!-- new comment -->
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P><!-- new comment -->property value<!-- new comment --></P>
</PropertyGroup>
<!-- new comment -->
<ItemGroup>
<i Include=`a`>
<!-- new comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
@"
<!-- changed comment -->
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P><!-- changed comment -->property value<!-- changed comment --></P>
</PropertyGroup>
<!-- changed comment -->
<ItemGroup>
<i Include=`a`>
<!-- changed comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
true, false, true)]
// deleted comment
[InlineData(
@"
<!-- new comment -->
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P><!-- new comment -->property value<!-- new comment --></P>
</PropertyGroup>
<!-- new comment -->
<ItemGroup>
<i Include=`a`>
<!-- new comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
@"
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
true, false, true)]
// new comments and changed code
[InlineData(
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
@"
<!-- new comment -->
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
<P2><!-- new comment -->property value<!-- new comment --></P2>
</PropertyGroup>
</Project>",
true, true, true)]
// commented out code
[InlineData(
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<!--
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
-->
</Project>",
true, true, true)]
public void ReloadRespectsNewContents(string initialProjectContents, string changedProjectContents, bool versionChanged, bool msbuildChildrenChanged, bool xmlChanged)
{
Action<ProjectRootElement, string> act = (p, c) =>
{
p.ReloadFrom(
XmlReader.Create(new StringReader(c)),
throwIfUnsavedChanges: false);
};
AssertReload(initialProjectContents, changedProjectContents, versionChanged, msbuildChildrenChanged, xmlChanged, act);
}
[Fact]
public void ReloadedStateIsResilientToChangesAndDiskRoundtrip()
{
var initialProjectContents = ObjectModelHelpers.CleanupFileContents(
@"
<!-- new comment -->
<Project xmlns=`msbuildnamespace`>
<!-- new comment -->
<ItemGroup>
<i Include=`a`>
<!-- new comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>");
var changedProjectContents1 = ObjectModelHelpers.CleanupFileContents(
@"
<!-- changed comment -->
<Project xmlns=`msbuildnamespace`>
<!-- changed comment -->
<ItemGroup>
<i Include=`a`>
<!-- changed comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>");
var changedProjectContents2 = ObjectModelHelpers.CleanupFileContents(
// spurious comment placement issue: https://github.com/Microsoft/msbuild/issues/1503
@"
<!-- changed comment -->
<Project xmlns=`msbuildnamespace`>
<!-- changed comment -->
<PropertyGroup>
<P>v</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<!-- changed comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>");
using (var env = TestEnvironment.Create())
{
var projectCollection1 = env.CreateProjectCollection().Collection;
var projectCollection2 = env.CreateProjectCollection().Collection;
var testFiles = env.CreateTestProjectWithFiles("", new[] { "build.proj" });
var projectPath = testFiles.CreatedFiles.First();
var projectElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(initialProjectContents, projectCollection1, preserveFormatting: true);
projectElement.Save(projectPath);
projectElement.ReloadFrom(XmlReader.Create(new StringReader(changedProjectContents1)));
VerifyAssertLineByLine(changedProjectContents1, projectElement.RawXml);
projectElement.AddProperty("P", "v");
VerifyAssertLineByLine(changedProjectContents2, projectElement.RawXml);
projectElement.Save();
var projectElement2 = ProjectRootElement.Open(projectPath, projectCollection2, preserveFormatting: true);
VerifyAssertLineByLine(changedProjectContents2, projectElement2.RawXml);
}
}
[Fact]
public void ReloadThrowsOnInvalidXmlSyntax()
{
var missingClosingTag =
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value<m>
</i>
</ItemGroup>
</Project>";
Action<ProjectRootElement, string> act = (p, c) =>
{
var exception =
Assert.Throws<InvalidProjectFileException>(
() =>
p.ReloadFrom(
XmlReader.Create(
new StringReader(c)),
throwIfUnsavedChanges: false));
Assert.Contains(@"The project file could not be loaded. The 'm' start tag on line", exception.Message);
};
// reload does not mutate the project element
AssertReload(SimpleProject, missingClosingTag, false, false, false, act);
}
[Fact]
public void ReloadThrowsForInMemoryProjectsWithoutAPath()
{
Action<ProjectRootElement, string> act = (p, c) =>
{
var exception =
Assert.Throws<InvalidOperationException>(
() =>
p.Reload(throwIfUnsavedChanges: false));
Assert.Contains(@"Value not set:", exception.Message);
};
// reload does not mutate the project element
AssertReload(SimpleProject, ComplexProject, false, false, false, act);
}
[Fact]
public void ReloadFromAPathThrowsOnMissingPath()
{
Action<ProjectRootElement, string> act = (p, c) =>
{
var fullPath = Path.GetFullPath("foo");
var exception =
Assert.Throws<InvalidOperationException>(
() =>
p.ReloadFrom(fullPath, throwIfUnsavedChanges: false));
Assert.Contains(@"File to reload from does not exist:", exception.Message);
};
// reload does not mutate the project element
AssertReload(SimpleProject, ComplexProject, false, false, false, act);
}
[Fact]
public void ReloadFromMemoryWhenProjectIsInMemoryKeepsProjectFileEmpty()
{
AssertProjectFileAfterReload(
true,
true,
(initial, reload, actualFile) => { Assert.Equal(String.Empty, actualFile); });
}
[Fact]
public void ReloadFromMemoryWhenProjectIsInFileKeepsProjectFile()
{
AssertProjectFileAfterReload(
false,
true,
(initial, reload, actualFile) => { Assert.Equal(initial, actualFile); });
}
[Fact]
public void ReloadFromFileWhenProjectIsInMemorySetsProjectFile()
{
AssertProjectFileAfterReload(
true,
false,
(initial, reload, actualFile) => { Assert.Equal(reload, actualFile);});
}
[Fact]
public void ReloadFromFileWhenProjectIsInFileUpdatesProjectFile()
{
AssertProjectFileAfterReload(
false,
false,
(initial, reload, actualFile) => { Assert.Equal(reload, actualFile); });
}
private void AssertProjectFileAfterReload(
bool initialProjectFromMemory,
bool reloadProjectFromMemory,
Action<string, string, string> projectFileAssert)
{
using (var env = TestEnvironment.Create())
{
var projectCollection = env.CreateProjectCollection().Collection;
string initialLocation = null;
ProjectRootElement rootElement = null;
if (initialProjectFromMemory)
{
rootElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(SimpleProject, projectCollection);
}
else
{
initialLocation = env.CreateFile().Path;
File.WriteAllText(initialLocation, ObjectModelHelpers.CleanupFileContents(SimpleProject));
rootElement = ProjectRootElement.Open(initialLocation, projectCollection);
}
var project = new Project(rootElement, null, null, projectCollection);
string reloadLocation = null;
if (reloadProjectFromMemory)
{
rootElement.ReloadFrom(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(ComplexProject))), false);
}
else
{
reloadLocation = env.CreateFile().Path;
File.WriteAllText(reloadLocation, ObjectModelHelpers.CleanupFileContents(ComplexProject));
rootElement.ReloadFrom(reloadLocation, false);
}
project.ReevaluateIfNecessary();
projectFileAssert.Invoke(initialLocation, reloadLocation, EmptyIfNull(rootElement.FullPath));
projectFileAssert.Invoke(initialLocation, reloadLocation, rootElement.ProjectFileLocation.File);
projectFileAssert.Invoke(initialLocation, reloadLocation, rootElement.AllChildren.Last().Location.File);
projectFileAssert.Invoke(initialLocation, reloadLocation, project.GetPropertyValue("ProjectFile"));
projectFileAssert.Invoke(initialLocation, reloadLocation, project.GetPropertyValue("ThisFile"));
if (initialProjectFromMemory && reloadProjectFromMemory)
{
Assert.Equal(NativeMethodsShared.GetCurrentDirectory(), rootElement.DirectoryPath);
}
else
{
projectFileAssert.Invoke(Path.GetDirectoryName(initialLocation), Path.GetDirectoryName(reloadLocation), rootElement.DirectoryPath);
}
}
}
private static string EmptyIfNull(string aString) => aString ?? string.Empty;
[Fact]
public void ReloadThrowsOnInvalidMsBuildSyntax()
{
var unknownAttribute =
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup Foo=`bar`>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>";
Action<ProjectRootElement, string> act = (p, c) =>
{
var exception =
Assert.Throws<InvalidProjectFileException>(
() =>
p.ReloadFrom(
XmlReader.Create(
new StringReader(c)),
throwIfUnsavedChanges: false));
Assert.Contains(@"The attribute ""Foo"" in element <PropertyGroup> is unrecognized", exception.Message);
};
// reload does not mutate the project element
AssertReload(SimpleProject, unknownAttribute, false, false, false, act);
}
[Fact]
public void ReloadThrowsByDefaultIfThereAreUnsavedChanges()
{
Action<ProjectRootElement, string> act = (p, c) =>
{
var exception =
Assert.Throws<InvalidOperationException>(
() =>
p.ReloadFrom(
XmlReader.Create(
new StringReader(c))));
Assert.Contains(@"ProjectRootElement can't reload if it contains unsaved changes.", exception.Message);
};
// reload does not mutate the project element
AssertReload(SimpleProject, ComplexProject, false, false, false, act);
}
[Fact]
public void ReloadCanOverwriteUnsavedChanges()
{
Action<ProjectRootElement, string> act = (p, c) =>
{
p.ReloadFrom(
XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(c))),
throwIfUnsavedChanges: false);
};
AssertReload(SimpleProject, ComplexProject, true, true, true, act);
}
private void AssertReload(
string initialContents,
string changedContents,
bool versionChanged,
bool msbuildChildrenChanged,
bool xmlChanged,
Action<ProjectRootElement, string> act)
{
var projectElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(initialContents);
var version = projectElement.Version;
var childrenCount = projectElement.AllChildren.Count();
var xml = projectElement.RawXml;
Assert.True(projectElement.HasUnsavedChanges);
act(projectElement, ObjectModelHelpers.CleanupFileContents(changedContents));
if (versionChanged)
{
Assert.NotEqual(version, projectElement.Version);
}
else
{
Assert.Equal(version, projectElement.Version);
}
if (msbuildChildrenChanged)
{
Assert.NotEqual(childrenCount, projectElement.AllChildren.Count());
}
else
{
Assert.Equal(childrenCount, projectElement.AllChildren.Count());
}
if (xmlChanged)
{
Assert.NotEqual(xml, projectElement.RawXml);
}
else
{
Assert.Equal(xml, projectElement.RawXml);
}
}
/// <summary>
/// Test helper for validating that DeepClone and CopyFrom work as advertised.
/// </summary>
private static void ValidateDeepCloneAndCopyFrom(ProjectRootElement pre)
{
var pre2 = pre.DeepClone();
Assert.NotSame(pre2, pre);
Assert.Equal(pre.RawXml, pre2.RawXml);
var pre3 = ProjectRootElement.Create();
pre3.AddPropertyGroup(); // this should get wiped out in the DeepCopyFrom
pre3.DeepCopyFrom(pre);
Assert.Equal(pre.RawXml, pre3.RawXml);
}
/// <summary>
/// Re-saves a project with a new encoding and thoroughly verifies that the right things happen.
/// </summary>
private void SaveProjectWithEncoding(string projectFullPath, Encoding encoding)
{
// Always use a new project collection to guarantee we're reading off disk.
ProjectRootElement project = ProjectRootElement.Open(projectFullPath, new ProjectCollection());
project.Save(encoding);
Assert.Equal(encoding, project.Encoding); // "Changing an unmodified project's encoding failed to update ProjectRootElement.Encoding."
// Try to verify that the xml declaration was emitted, and that the correct byte order marks
// are also present.
using (var reader = FileUtilities.OpenRead(projectFullPath, encoding, true))
{
Assert.Equal(encoding, reader.CurrentEncoding);
string actual = reader.ReadLine();
string expected = string.Format(@"<?xml version=""1.0"" encoding=""{0}""?>", encoding.WebName);
Assert.Equal(expected, actual); // "The encoding was not emitted as an XML declaration."
}
project = ProjectRootElement.Open(projectFullPath, new ProjectCollection());
// It's ok for the read Encoding to differ in fields like DecoderFallback,
// so a pure equality check here is too much.
Assert.Equal(encoding.CodePage, project.Encoding.CodePage);
Assert.Equal(encoding.EncodingName, project.Encoding.EncodingName);
}
/// <summary>
/// Creates a project at a given path with a given encoding but without the Xml declaration,
/// and then verifies that when loaded by MSBuild, the encoding is correctly reported.
/// </summary>
private void VerifyLoadedProjectHasEncoding(string projectFullPath, Encoding encoding)
{
CreateProjectWithEncodingWithoutDeclaration(projectFullPath, encoding);
// Let's just be certain the project has been read off disk...
ProjectRootElement project = ProjectRootElement.Open(projectFullPath, new ProjectCollection());
Assert.Equal(encoding.WebName, project.Encoding.WebName);
}
/// <summary>
/// Creates a project file with a specific encoding, but without an XML declaration.
/// </summary>
private void CreateProjectWithEncodingWithoutDeclaration(string projectFullPath, Encoding encoding)
{
const string EmptyProject = @"<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
</Project>";
using (StreamWriter writer = FileUtilities.OpenWrite(projectFullPath, false, encoding))
{
writer.Write(ObjectModelHelpers.CleanupFileContents(EmptyProject));
}
}
/// <summary>
/// Create a nice big PRE
/// </summary>
private ProjectRootElement CreatePREWithSubstantialContent()
{
string content = ObjectModelHelpers.CleanupFileContents(ComplexProject);
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
return project;
}
private void VerifyAssertLineByLine(string expected, string actual)
{
Helpers.VerifyAssertLineByLine(expected, actual, false);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
//
// @module Assets Common Lib
// @author Osipov Stanislav (Stan's Assets)
// @support support@stansassets.com
// @website https://stansassets.com
//
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace SA.Common.Data {
// Example usage:
//
// using UnityEngine;
// using System.Collections;
// using System.Collections.Generic;
// using MiniJSON;
//
// public class MiniJSONTest : MonoBehaviour {
// void Start () {
// var jsonString = "{ \"array\": [1.44,2,3], " +
// "\"object\": {\"key1\":\"value1\", \"key2\":256}, " +
// "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " +
// "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " +
// "\"int\": 65536, " +
// "\"float\": 3.1415926, " +
// "\"bool\": true, " +
// "\"null\": null }";
//
// var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
//
// Debug.Log("deserialized: " + dict.GetType());
// Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]);
// Debug.Log("dict['string']: " + (string) dict["string"]);
// Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles
// Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs
// Debug.Log("dict['unicode']: " + (string) dict["unicode"]);
//
// var str = Json.Serialize(dict);
//
// Debug.Log("serialized: " + str);
// }
// }
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary.
/// All numbers are parsed to doubles.
/// </summary>
public static class Json {
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An List<object>, a Dictionary<string, object>, a double, an integer,a string, null, true, or false</returns>
public static object Deserialize(string json) {
// save the string for debug information
if (json == null) {
return null;
}
return Parser.Parse(json);
}
sealed class Parser : IDisposable {
const string WHITE_SPACE = " \t\n\r";
const string WORD_BREAK = " \t\n\r{}[],:\"";
enum TOKEN {
NONE,
CURLY_OPEN,
CURLY_CLOSE,
SQUARED_OPEN,
SQUARED_CLOSE,
COLON,
COMMA,
STRING,
NUMBER,
TRUE,
FALSE,
NULL
};
StringReader json;
Parser(string jsonString) {
json = new StringReader(jsonString);
}
public static object Parse(string jsonString) {
using (var instance = new Parser(jsonString)) {
return instance.ParseValue();
}
}
public void Dispose() {
json.Dispose();
json = null;
}
Dictionary<string, object> ParseObject() {
Dictionary<string, object> table = new Dictionary<string, object>();
// ditch opening brace
json.Read();
// {
while (true) {
switch (NextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.CURLY_CLOSE:
return table;
default:
// name
string name = ParseString();
if (name == null) {
return null;
}
// :
if (NextToken != TOKEN.COLON) {
return null;
}
// ditch the colon
json.Read();
// value
table[name] = ParseValue();
break;
}
}
}
List<object> ParseArray() {
List<object> array = new List<object>();
// ditch opening bracket
json.Read();
// [
var parsing = true;
while (parsing) {
TOKEN nextToken = NextToken;
switch (nextToken) {
case TOKEN.NONE:
return null;
case TOKEN.COMMA:
continue;
case TOKEN.SQUARED_CLOSE:
parsing = false;
break;
default:
object value = ParseByToken(nextToken);
array.Add(value);
break;
}
}
return array;
}
object ParseValue() {
TOKEN nextToken = NextToken;
return ParseByToken(nextToken);
}
object ParseByToken(TOKEN token) {
switch (token) {
case TOKEN.STRING:
return ParseString();
case TOKEN.NUMBER:
return ParseNumber();
case TOKEN.CURLY_OPEN:
return ParseObject();
case TOKEN.SQUARED_OPEN:
return ParseArray();
case TOKEN.TRUE:
return true;
case TOKEN.FALSE:
return false;
case TOKEN.NULL:
return null;
default:
return null;
}
}
string ParseString() {
StringBuilder s = new StringBuilder();
char c;
// ditch opening quote
json.Read();
bool parsing = true;
while (parsing) {
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
parsing = false;
break;
case '\\':
if (json.Peek() == -1) {
parsing = false;
break;
}
c = NextChar;
switch (c) {
case '"':
case '\\':
case '/':
s.Append(c);
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'u':
var hex = new StringBuilder();
for (int i=0; i< 4; i++) {
hex.Append(NextChar);
}
s.Append((char) Convert.ToInt32(hex.ToString(), 16));
break;
}
break;
default:
s.Append(c);
break;
}
}
return s.ToString();
}
object ParseNumber() {
string number = NextWord;
if (number.IndexOf('.') == -1) {
long parsedInt;
Int64.TryParse(number, out parsedInt);
return parsedInt;
}
double parsedDouble;
Double.TryParse(number, out parsedDouble);
return parsedDouble;
}
void EatWhitespace() {
while (WHITE_SPACE.IndexOf(PeekChar) != -1) {
json.Read();
if (json.Peek() == -1) {
break;
}
}
}
char PeekChar {
get {
return Convert.ToChar(json.Peek());
}
}
char NextChar {
get {
return Convert.ToChar(json.Read());
}
}
string NextWord {
get {
StringBuilder word = new StringBuilder();
while (WORD_BREAK.IndexOf(PeekChar) == -1) {
word.Append(NextChar);
if (json.Peek() == -1) {
break;
}
}
return word.ToString();
}
}
TOKEN NextToken {
get {
EatWhitespace();
if (json.Peek() == -1) {
return TOKEN.NONE;
}
char c = PeekChar;
switch (c) {
case '{':
return TOKEN.CURLY_OPEN;
case '}':
json.Read();
return TOKEN.CURLY_CLOSE;
case '[':
return TOKEN.SQUARED_OPEN;
case ']':
json.Read();
return TOKEN.SQUARED_CLOSE;
case ',':
json.Read();
return TOKEN.COMMA;
case '"':
return TOKEN.STRING;
case ':':
return TOKEN.COLON;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return TOKEN.NUMBER;
}
string word = NextWord;
switch (word) {
case "false":
return TOKEN.FALSE;
case "true":
return TOKEN.TRUE;
case "null":
return TOKEN.NULL;
}
return TOKEN.NONE;
}
}
}
/// <summary>
/// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string
/// </summary>
/// <param name="json">A Dictionary<string, object> / List<object></param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string Serialize(object obj) {
return Serializer.Serialize(obj);
}
sealed class Serializer {
StringBuilder builder;
Serializer() {
builder = new StringBuilder();
}
public static string Serialize(object obj) {
var instance = new Serializer();
instance.SerializeValue(obj);
return instance.builder.ToString();
}
void SerializeValue(object value) {
IList asList;
IDictionary asDict;
string asStr;
if (value == null) {
builder.Append("null");
}
else if ((asStr = value as string) != null) {
SerializeString(asStr);
}
else if (value is bool) {
builder.Append(value.ToString().ToLower());
}
else if ((asList = value as IList) != null) {
SerializeArray(asList);
}
else if ((asDict = value as IDictionary) != null) {
SerializeObject(asDict);
}
else if (value is char) {
SerializeString(value.ToString());
}
else {
SerializeOther(value);
}
}
void SerializeObject(IDictionary obj) {
bool first = true;
builder.Append('{');
foreach (object e in obj.Keys) {
if (!first) {
builder.Append(',');
}
SerializeString(e.ToString());
builder.Append(':');
SerializeValue(obj[e]);
first = false;
}
builder.Append('}');
}
void SerializeArray(IList anArray) {
builder.Append('[');
bool first = true;
foreach (object obj in anArray) {
if (!first) {
builder.Append(',');
}
SerializeValue(obj);
first = false;
}
builder.Append(']');
}
void SerializeString(string str) {
builder.Append('\"');
char[] charArray = str.ToCharArray();
foreach (var c in charArray) {
switch (c) {
case '"':
builder.Append("\\\"");
break;
case '\\':
builder.Append("\\\\");
break;
case '\b':
builder.Append("\\b");
break;
case '\f':
builder.Append("\\f");
break;
case '\n':
builder.Append("\\n");
break;
case '\r':
builder.Append("\\r");
break;
case '\t':
builder.Append("\\t");
break;
default:
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
}
else {
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
break;
}
}
builder.Append('\"');
}
void SerializeOther(object value) {
if (value is float
|| value is int
|| value is uint
|| value is long
|| value is double
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong
|| value is decimal) {
builder.Append(value.ToString());
}
else {
SerializeString(value.ToString());
}
}
}
}
}
| |
// 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.
namespace Microsoft.Azure.Batch.Protocol
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for FileOperations.
/// </summary>
public static partial class FileOperationsExtensions
{
/// <summary>
/// Deletes the specified task file from the compute node where the task ran.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose file you want to delete.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the fileName parameter
/// represents a directory instead of a file, you can set Recursive to true
/// to delete the directory and all of the files and subdirectories in it. If
/// Recursive is false then the directory must be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
public static FileDeleteFromTaskHeaders DeleteFromTask(this IFileOperations operations, string jobId, string taskId, string fileName, bool? recursive = default(bool?), FileDeleteFromTaskOptions fileDeleteFromTaskOptions = default(FileDeleteFromTaskOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFileOperations)s).DeleteFromTaskAsync(jobId, taskId, fileName, recursive, fileDeleteFromTaskOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified task file from the compute node where the task ran.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose file you want to delete.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the fileName parameter
/// represents a directory instead of a file, you can set Recursive to true
/// to delete the directory and all of the files and subdirectories in it. If
/// Recursive is false then the directory must be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<FileDeleteFromTaskHeaders> DeleteFromTaskAsync(this IFileOperations operations, string jobId, string taskId, string fileName, bool? recursive = default(bool?), FileDeleteFromTaskOptions fileDeleteFromTaskOptions = default(FileDeleteFromTaskOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.DeleteFromTaskWithHttpMessagesAsync(jobId, taskId, fileName, recursive, fileDeleteFromTaskOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Returns the content of the specified task file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose file you want to retrieve.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to get the content of.
/// </param>
/// <param name='fileGetFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
public static System.IO.Stream GetFromTask(this IFileOperations operations, string jobId, string taskId, string fileName, FileGetFromTaskOptions fileGetFromTaskOptions = default(FileGetFromTaskOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFileOperations)s).GetFromTaskAsync(jobId, taskId, fileName, fileGetFromTaskOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the content of the specified task file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose file you want to retrieve.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to get the content of.
/// </param>
/// <param name='fileGetFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<System.IO.Stream> GetFromTaskAsync(this IFileOperations operations, string jobId, string taskId, string fileName, FileGetFromTaskOptions fileGetFromTaskOptions = default(FileGetFromTaskOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var _result = await operations.GetFromTaskWithHttpMessagesAsync(jobId, taskId, fileName, fileGetFromTaskOptions, null, cancellationToken).ConfigureAwait(false);
_result.Request.Dispose();
return _result.Body;
}
/// <summary>
/// Gets the properties of the specified task file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose file you want to get the properties of.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to get the properties of.
/// </param>
/// <param name='fileGetNodeFilePropertiesFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
public static FileGetNodeFilePropertiesFromTaskHeaders GetNodeFilePropertiesFromTask(this IFileOperations operations, string jobId, string taskId, string fileName, FileGetNodeFilePropertiesFromTaskOptions fileGetNodeFilePropertiesFromTaskOptions = default(FileGetNodeFilePropertiesFromTaskOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFileOperations)s).GetNodeFilePropertiesFromTaskAsync(jobId, taskId, fileName, fileGetNodeFilePropertiesFromTaskOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the properties of the specified task file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose file you want to get the properties of.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to get the properties of.
/// </param>
/// <param name='fileGetNodeFilePropertiesFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<FileGetNodeFilePropertiesFromTaskHeaders> GetNodeFilePropertiesFromTaskAsync(this IFileOperations operations, string jobId, string taskId, string fileName, FileGetNodeFilePropertiesFromTaskOptions fileGetNodeFilePropertiesFromTaskOptions = default(FileGetNodeFilePropertiesFromTaskOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetNodeFilePropertiesFromTaskWithHttpMessagesAsync(jobId, taskId, fileName, fileGetNodeFilePropertiesFromTaskOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Deletes the specified task file from the compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node from which you want to delete the file.
/// </param>
/// <param name='fileName'>
/// The path to the file that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the fileName parameter
/// represents a directory instead of a file, you can set Recursive to true
/// to delete the directory and all of the files and subdirectories in it. If
/// Recursive is false then the directory must be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
public static FileDeleteFromComputeNodeHeaders DeleteFromComputeNode(this IFileOperations operations, string poolId, string nodeId, string fileName, bool? recursive = default(bool?), FileDeleteFromComputeNodeOptions fileDeleteFromComputeNodeOptions = default(FileDeleteFromComputeNodeOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFileOperations)s).DeleteFromComputeNodeAsync(poolId, nodeId, fileName, recursive, fileDeleteFromComputeNodeOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified task file from the compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node from which you want to delete the file.
/// </param>
/// <param name='fileName'>
/// The path to the file that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the fileName parameter
/// represents a directory instead of a file, you can set Recursive to true
/// to delete the directory and all of the files and subdirectories in it. If
/// Recursive is false then the directory must be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<FileDeleteFromComputeNodeHeaders> DeleteFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, string fileName, bool? recursive = default(bool?), FileDeleteFromComputeNodeOptions fileDeleteFromComputeNodeOptions = default(FileDeleteFromComputeNodeOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.DeleteFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, fileName, recursive, fileDeleteFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Returns the content of the specified task file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node that contains the file.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to get the content of.
/// </param>
/// <param name='fileGetFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
public static System.IO.Stream GetFromComputeNode(this IFileOperations operations, string poolId, string nodeId, string fileName, FileGetFromComputeNodeOptions fileGetFromComputeNodeOptions = default(FileGetFromComputeNodeOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFileOperations)s).GetFromComputeNodeAsync(poolId, nodeId, fileName, fileGetFromComputeNodeOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the content of the specified task file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node that contains the file.
/// </param>
/// <param name='fileName'>
/// The path to the task file that you want to get the content of.
/// </param>
/// <param name='fileGetFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<System.IO.Stream> GetFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, string fileName, FileGetFromComputeNodeOptions fileGetFromComputeNodeOptions = default(FileGetFromComputeNodeOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var _result = await operations.GetFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, fileName, fileGetFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false);
_result.Request.Dispose();
return _result.Body;
}
/// <summary>
/// Gets the properties of the specified compute node file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node that contains the file.
/// </param>
/// <param name='fileName'>
/// The path to the compute node file that you want to get the properties of.
/// </param>
/// <param name='fileGetNodeFilePropertiesFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
public static FileGetNodeFilePropertiesFromComputeNodeHeaders GetNodeFilePropertiesFromComputeNode(this IFileOperations operations, string poolId, string nodeId, string fileName, FileGetNodeFilePropertiesFromComputeNodeOptions fileGetNodeFilePropertiesFromComputeNodeOptions = default(FileGetNodeFilePropertiesFromComputeNodeOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFileOperations)s).GetNodeFilePropertiesFromComputeNodeAsync(poolId, nodeId, fileName, fileGetNodeFilePropertiesFromComputeNodeOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the properties of the specified compute node file.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node that contains the file.
/// </param>
/// <param name='fileName'>
/// The path to the compute node file that you want to get the properties of.
/// </param>
/// <param name='fileGetNodeFilePropertiesFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<FileGetNodeFilePropertiesFromComputeNodeHeaders> GetNodeFilePropertiesFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, string fileName, FileGetNodeFilePropertiesFromComputeNodeOptions fileGetNodeFilePropertiesFromComputeNodeOptions = default(FileGetNodeFilePropertiesFromComputeNodeOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetNodeFilePropertiesFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, fileName, fileGetNodeFilePropertiesFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory.
/// </param>
/// <param name='fileListFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<NodeFile> ListFromTask(this IFileOperations operations, string jobId, string taskId, bool? recursive = default(bool?), FileListFromTaskOptions fileListFromTaskOptions = default(FileListFromTaskOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFileOperations)s).ListFromTaskAsync(jobId, taskId, recursive, fileListFromTaskOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory.
/// </param>
/// <param name='fileListFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<NodeFile>> ListFromTaskAsync(this IFileOperations operations, string jobId, string taskId, bool? recursive = default(bool?), FileListFromTaskOptions fileListFromTaskOptions = default(FileListFromTaskOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListFromTaskWithHttpMessagesAsync(jobId, taskId, recursive, fileListFromTaskOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the files in task directories on the specified compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory.
/// </param>
/// <param name='fileListFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<NodeFile> ListFromComputeNode(this IFileOperations operations, string poolId, string nodeId, bool? recursive = default(bool?), FileListFromComputeNodeOptions fileListFromComputeNodeOptions = default(FileListFromComputeNodeOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFileOperations)s).ListFromComputeNodeAsync(poolId, nodeId, recursive, fileListFromComputeNodeOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the files in task directories on the specified compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='poolId'>
/// The id of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The id of the compute node whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory.
/// </param>
/// <param name='fileListFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<NodeFile>> ListFromComputeNodeAsync(this IFileOperations operations, string poolId, string nodeId, bool? recursive = default(bool?), FileListFromComputeNodeOptions fileListFromComputeNodeOptions = default(FileListFromComputeNodeOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListFromComputeNodeWithHttpMessagesAsync(poolId, nodeId, recursive, fileListFromComputeNodeOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromTaskNextOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<NodeFile> ListFromTaskNext(this IFileOperations operations, string nextPageLink, FileListFromTaskNextOptions fileListFromTaskNextOptions = default(FileListFromTaskNextOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFileOperations)s).ListFromTaskNextAsync(nextPageLink, fileListFromTaskNextOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromTaskNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<NodeFile>> ListFromTaskNextAsync(this IFileOperations operations, string nextPageLink, FileListFromTaskNextOptions fileListFromTaskNextOptions = default(FileListFromTaskNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListFromTaskNextWithHttpMessagesAsync(nextPageLink, fileListFromTaskNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all of the files in task directories on the specified compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromComputeNodeNextOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<NodeFile> ListFromComputeNodeNext(this IFileOperations operations, string nextPageLink, FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions = default(FileListFromComputeNodeNextOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IFileOperations)s).ListFromComputeNodeNextAsync(nextPageLink, fileListFromComputeNodeNextOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the files in task directories on the specified compute node.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromComputeNodeNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<NodeFile>> ListFromComputeNodeNextAsync(this IFileOperations operations, string nextPageLink, FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions = default(FileListFromComputeNodeNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListFromComputeNodeNextWithHttpMessagesAsync(nextPageLink, fileListFromComputeNodeNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Conversations.V1.Conversation
{
/// <summary>
/// Add a new message to the conversation
/// </summary>
public class CreateMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The unique ID of the Conversation for this message.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// The channel specific identifier of the message's author.
/// </summary>
public string Author { get; set; }
/// <summary>
/// The content of the message.
/// </summary>
public string Body { get; set; }
/// <summary>
/// The date that this resource was created.
/// </summary>
public DateTime? DateCreated { get; set; }
/// <summary>
/// The date that this resource was last updated.
/// </summary>
public DateTime? DateUpdated { get; set; }
/// <summary>
/// A string metadata field you can use to store any data you wish.
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// The Media SID to be attached to the new Message.
/// </summary>
public string MediaSid { get; set; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public MessageResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new CreateMessageOptions
/// </summary>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this message. </param>
public CreateMessageOptions(string pathConversationSid)
{
PathConversationSid = pathConversationSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Author != null)
{
p.Add(new KeyValuePair<string, string>("Author", Author));
}
if (Body != null)
{
p.Add(new KeyValuePair<string, string>("Body", Body));
}
if (DateCreated != null)
{
p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated)));
}
if (DateUpdated != null)
{
p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated)));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
if (MediaSid != null)
{
p.Add(new KeyValuePair<string, string>("MediaSid", MediaSid.ToString()));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Update an existing message in the conversation
/// </summary>
public class UpdateMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The unique ID of the Conversation for this message.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// The channel specific identifier of the message's author.
/// </summary>
public string Author { get; set; }
/// <summary>
/// The content of the message.
/// </summary>
public string Body { get; set; }
/// <summary>
/// The date that this resource was created.
/// </summary>
public DateTime? DateCreated { get; set; }
/// <summary>
/// The date that this resource was last updated.
/// </summary>
public DateTime? DateUpdated { get; set; }
/// <summary>
/// A string metadata field you can use to store any data you wish.
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public MessageResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new UpdateMessageOptions
/// </summary>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this message. </param>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public UpdateMessageOptions(string pathConversationSid, string pathSid)
{
PathConversationSid = pathConversationSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Author != null)
{
p.Add(new KeyValuePair<string, string>("Author", Author));
}
if (Body != null)
{
p.Add(new KeyValuePair<string, string>("Body", Body));
}
if (DateCreated != null)
{
p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated)));
}
if (DateUpdated != null)
{
p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated)));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Remove a message from the conversation
/// </summary>
public class DeleteMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The unique ID of the Conversation for this message.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public MessageResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new DeleteMessageOptions
/// </summary>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this message. </param>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public DeleteMessageOptions(string pathConversationSid, string pathSid)
{
PathConversationSid = pathConversationSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Fetch a message from the conversation
/// </summary>
public class FetchMessageOptions : IOptions<MessageResource>
{
/// <summary>
/// The unique ID of the Conversation for this message.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchMessageOptions
/// </summary>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this message. </param>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public FetchMessageOptions(string pathConversationSid, string pathSid)
{
PathConversationSid = pathConversationSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Retrieve a list of all messages in the conversation
/// </summary>
public class ReadMessageOptions : ReadOptions<MessageResource>
{
/// <summary>
/// The unique ID of the Conversation for messages.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// The sort order of the returned messages
/// </summary>
public MessageResource.OrderTypeEnum Order { get; set; }
/// <summary>
/// Construct a new ReadMessageOptions
/// </summary>
/// <param name="pathConversationSid"> The unique ID of the Conversation for messages. </param>
public ReadMessageOptions(string pathConversationSid)
{
PathConversationSid = pathConversationSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Order != null)
{
p.Add(new KeyValuePair<string, string>("Order", Order.ToString()));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
namespace MS.Internal.Xml.XPath
{
internal sealed class StringFunctions : ValueQuery
{
private Function.FunctionType _funcType;
private IList<Query> _argList;
public StringFunctions(Function.FunctionType funcType, IList<Query> argList)
{
Debug.Assert(argList != null, "Use 'new Query[]{}' instead.");
_funcType = funcType;
_argList = argList;
}
private StringFunctions(StringFunctions other) : base(other)
{
_funcType = other._funcType;
Query[] tmp = new Query[other._argList.Count];
{
for (int i = 0; i < tmp.Length; i++)
{
tmp[i] = Clone(other._argList[i]);
}
}
_argList = tmp;
}
public override void SetXsltContext(XsltContext context)
{
for (int i = 0; i < _argList.Count; i++)
{
_argList[i].SetXsltContext(context);
}
}
public override object Evaluate(XPathNodeIterator nodeIterator)
{
switch (_funcType)
{
case Function.FunctionType.FuncString: return toString(nodeIterator);
case Function.FunctionType.FuncConcat: return Concat(nodeIterator);
case Function.FunctionType.FuncStartsWith: return StartsWith(nodeIterator);
case Function.FunctionType.FuncContains: return Contains(nodeIterator);
case Function.FunctionType.FuncSubstringBefore: return SubstringBefore(nodeIterator);
case Function.FunctionType.FuncSubstringAfter: return SubstringAfter(nodeIterator);
case Function.FunctionType.FuncSubstring: return Substring(nodeIterator);
case Function.FunctionType.FuncStringLength: return StringLength(nodeIterator);
case Function.FunctionType.FuncNormalize: return Normalize(nodeIterator);
case Function.FunctionType.FuncTranslate: return Translate(nodeIterator);
}
return string.Empty;
}
internal static string toString(double num)
{
return num.ToString("R", NumberFormatInfo.InvariantInfo);
}
internal static string toString(bool b)
{
return b ? "true" : "false";
}
private string toString(XPathNodeIterator nodeIterator)
{
if (_argList.Count > 0)
{
object argVal = _argList[0].Evaluate(nodeIterator);
switch (GetXPathType(argVal))
{
case XPathResultType.NodeSet:
XPathNavigator value = _argList[0].Advance();
return value != null ? value.Value : string.Empty;
case XPathResultType.String:
return (string)argVal;
case XPathResultType.Boolean:
return ((bool)argVal) ? "true" : "false";
case XPathResultType_Navigator:
return ((XPathNavigator)argVal).Value;
default:
Debug.Assert(GetXPathType(argVal) == XPathResultType.Number);
return toString((double)argVal);
}
}
return nodeIterator.Current.Value;
}
public override XPathResultType StaticType
{
get
{
if (_funcType == Function.FunctionType.FuncStringLength)
{
return XPathResultType.Number;
}
if (
_funcType == Function.FunctionType.FuncStartsWith ||
_funcType == Function.FunctionType.FuncContains
)
{
return XPathResultType.Boolean;
}
return XPathResultType.String;
}
}
private string Concat(XPathNodeIterator nodeIterator)
{
int count = 0;
StringBuilder s = new StringBuilder();
while (count < _argList.Count)
{
s.Append(_argList[count++].Evaluate(nodeIterator).ToString());
}
return s.ToString();
}
private bool StartsWith(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
return s1.Length >= s2.Length && string.CompareOrdinal(s1, 0, s2, 0, s2.Length) == 0;
}
private static readonly CompareInfo s_compareInfo = CultureInfo.InvariantCulture.CompareInfo;
private bool Contains(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
return s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal) >= 0;
}
private string SubstringBefore(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
if (s2.Length == 0) { return s2; }
int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal);
return (idx < 1) ? string.Empty : s1.Substring(0, idx);
}
private string SubstringAfter(XPathNodeIterator nodeIterator)
{
string s1 = _argList[0].Evaluate(nodeIterator).ToString();
string s2 = _argList[1].Evaluate(nodeIterator).ToString();
if (s2.Length == 0) { return s1; }
int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal);
return (idx < 0) ? string.Empty : s1.Substring(idx + s2.Length);
}
private string Substring(XPathNodeIterator nodeIterator)
{
string str1 = _argList[0].Evaluate(nodeIterator).ToString();
double num = XmlConvertEx.XPathRound(XmlConvertEx.ToXPathDouble(_argList[1].Evaluate(nodeIterator))) - 1;
if (Double.IsNaN(num) || str1.Length <= num)
{
return string.Empty;
}
if (_argList.Count == 3)
{
double num1 = XmlConvertEx.XPathRound(XmlConvertEx.ToXPathDouble(_argList[2].Evaluate(nodeIterator)));
if (Double.IsNaN(num1))
{
return string.Empty;
}
if (num < 0 || num1 < 0)
{
num1 = num + num1;
// NOTE: condition is true for NaN
if (!(num1 > 0))
{
return string.Empty;
}
num = 0;
}
double maxlength = str1.Length - num;
if (num1 > maxlength)
{
num1 = maxlength;
}
return str1.Substring((int)num, (int)num1);
}
if (num < 0)
{
num = 0;
}
return str1.Substring((int)num);
}
private Double StringLength(XPathNodeIterator nodeIterator)
{
if (_argList.Count > 0)
{
return _argList[0].Evaluate(nodeIterator).ToString().Length;
}
return nodeIterator.Current.Value.Length;
}
private string Normalize(XPathNodeIterator nodeIterator)
{
string value;
if (_argList.Count > 0)
{
value = _argList[0].Evaluate(nodeIterator).ToString();
}
else
{
value = nodeIterator.Current.Value;
}
int modifyPos = -1;
char[] chars = value.ToCharArray();
bool firstSpace = false; // Start false to trim the beginning
XmlCharType xmlCharType = XmlCharType.Instance;
for (int comparePos = 0; comparePos < chars.Length; comparePos++)
{
if (!xmlCharType.IsWhiteSpace(chars[comparePos]))
{
firstSpace = true;
modifyPos++;
chars[modifyPos] = chars[comparePos];
}
else if (firstSpace)
{
firstSpace = false;
modifyPos++;
chars[modifyPos] = ' ';
}
}
// Trim end
if (modifyPos > -1 && chars[modifyPos] == ' ')
modifyPos--;
return new string(chars, 0, modifyPos + 1);
}
private string Translate(XPathNodeIterator nodeIterator)
{
string value = _argList[0].Evaluate(nodeIterator).ToString();
string mapFrom = _argList[1].Evaluate(nodeIterator).ToString();
string mapTo = _argList[2].Evaluate(nodeIterator).ToString();
int modifyPos = -1;
char[] chars = value.ToCharArray();
for (int comparePos = 0; comparePos < chars.Length; comparePos++)
{
int index = mapFrom.IndexOf(chars[comparePos]);
if (index != -1)
{
if (index < mapTo.Length)
{
modifyPos++;
chars[modifyPos] = mapTo[index];
}
}
else
{
modifyPos++;
chars[modifyPos] = chars[comparePos];
}
}
return new string(chars, 0, modifyPos + 1);
}
public override XPathNodeIterator Clone() { return new StringFunctions(this); }
public override void PrintQuery(XmlWriter w)
{
w.WriteStartElement(this.GetType().Name);
w.WriteAttributeString("name", _funcType.ToString());
foreach (Query arg in _argList)
{
arg.PrintQuery(w);
}
w.WriteEndElement();
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServiceFabric
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
public partial class ServiceFabricManagementClient : ServiceClient<ServiceFabricManagementClient>, IServiceFabricManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The customer subscription identifier
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// The version of the ServiceFabric resouce provider api
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IClustersOperations.
/// </summary>
public virtual IClustersOperations Clusters { get; private set; }
/// <summary>
/// Gets the IClusterVersionsOperations.
/// </summary>
public virtual IClusterVersionsOperations ClusterVersions { get; private set; }
/// <summary>
/// Gets the IOperations.
/// </summary>
public virtual IOperations Operations { get; private set; }
/// <summary>
/// Initializes a new instance of the ServiceFabricManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ServiceFabricManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the ServiceFabricManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected ServiceFabricManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the ServiceFabricManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected ServiceFabricManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ServiceFabricManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected ServiceFabricManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the ServiceFabricManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ServiceFabricManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ServiceFabricManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ServiceFabricManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ServiceFabricManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ServiceFabricManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the ServiceFabricManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public ServiceFabricManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Clusters = new ClustersOperations(this);
ClusterVersions = new ClusterVersionsOperations(this);
Operations = new Operations(this);
BaseUri = new System.Uri("https://management.azure.com");
ApiVersion = "2016-09-01";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
using System;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class FrameSwitchingTest : DriverTestFixture
{
// ----------------------------------------------------------------------------------------------
//
// Tests that WebDriver doesn't do anything fishy when it navigates to a page with frames.
//
// ----------------------------------------------------------------------------------------------
[Test]
public void ShouldAlwaysFocusOnTheTopMostFrameAfterANavigationEvent()
{
driver.Url = framesetPage;
IWebElement element = driver.FindElement(By.TagName("frameset"));
Assert.IsNotNull(element);
}
[Test]
public void ShouldNotAutomaticallySwitchFocusToAnIFrameWhenAPageContainingThemIsLoaded()
{
driver.Url = iframePage;
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1);
IWebElement element = driver.FindElement(By.Id("iframe_page_heading"));
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(0);
Assert.IsNotNull(element);
}
[Test]
public void ShouldOpenPageWithBrokenFrameset()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("framesetPage3.html");
IWebElement frame1 = driver.FindElement(By.Id("first"));
driver.SwitchTo().Frame(frame1);
driver.SwitchTo().DefaultContent();
IWebElement frame2 = driver.FindElement(By.Id("second"));
try
{
driver.SwitchTo().Frame(frame2);
}
catch (WebDriverException)
{
// IE9 can not switch to this broken frame - it has no window.
}
}
// ----------------------------------------------------------------------------------------------
//
// Tests that WebDriver can switch to frames as expected.
//
// ----------------------------------------------------------------------------------------------
[Test]
public void ShouldBeAbleToSwitchToAFrameByItsIndex()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame(1);
Assert.AreEqual("2", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
public void ShouldBeAbleToSwitchToAnIframeByItsIndex()
{
driver.Url = iframePage;
driver.SwitchTo().Frame(0);
Assert.AreEqual("name", driver.FindElement(By.Name("id-name1")).GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToSwitchToAFrameByItsName()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fourth");
Assert.AreEqual("child1", driver.FindElement(By.TagName("frame")).GetAttribute("name"));
}
[Test]
public void ShouldBeAbleToSwitchToAnIframeByItsName()
{
driver.Url = iframePage;
driver.SwitchTo().Frame("iframe1-name");
Assert.AreEqual("name", driver.FindElement(By.Name("id-name1")).GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToSwitchToAFrameByItsID()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fifth");
Assert.AreEqual("Open new window", driver.FindElement(By.Name("windowOne")).Text);
}
[Test]
public void ShouldBeAbleToSwitchToAnIframeByItsID()
{
driver.Url = iframePage;
driver.SwitchTo().Frame("iframe1");
Assert.AreEqual("name", driver.FindElement(By.Name("id-name1")).GetAttribute("value"));
}
[Test]
public void ShouldBeAbleToSwitchToFrameWithNameContainingDot()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("sixth.iframe1");
Assert.IsTrue(driver.FindElement(By.TagName("body")).Text.Contains("Page number 3"));
}
[Test]
public void ShouldBeAbleToSwitchToAFrameUsingAPreviouslyLocatedWebElement()
{
driver.Url = framesetPage;
IWebElement frame = driver.FindElement(By.TagName("frame"));
driver.SwitchTo().Frame(frame);
Assert.AreEqual("1", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
public void ShouldBeAbleToSwitchToAnIFrameUsingAPreviouslyLocatedWebElement()
{
driver.Url = iframePage;
IWebElement frame = driver.FindElement(By.TagName("iframe"));
driver.SwitchTo().Frame(frame);
Assert.AreEqual("name", driver.FindElement(By.Name("id-name1")).GetAttribute("value"));
}
[Test]
public void ShouldEnsureElementIsAFrameBeforeSwitching()
{
driver.Url = framesetPage;
IWebElement frame = driver.FindElement(By.TagName("frameset"));
Assert.Throws<NoSuchFrameException>(() => driver.SwitchTo().Frame(frame));
}
[Test]
public void FrameSearchesShouldBeRelativeToTheCurrentlySelectedFrame()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("second");
Assert.AreEqual("2", driver.FindElement(By.Id("pageNumber")).Text);
try
{
driver.SwitchTo().Frame("third");
Assert.Fail();
}
catch (NoSuchFrameException)
{
// Do nothing
}
driver.SwitchTo().DefaultContent();
driver.SwitchTo().Frame("third");
try
{
driver.SwitchTo().Frame("second");
Assert.Fail();
}
catch (NoSuchFrameException)
{
// Do nothing
}
driver.SwitchTo().DefaultContent();
driver.SwitchTo().Frame("second");
Assert.AreEqual("2", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
public void ShouldSelectChildFramesByChainedCalls()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fourth").SwitchTo().Frame("child2");
Assert.AreEqual("11", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
public void ShouldThrowFrameNotFoundExceptionLookingUpSubFramesWithSuperFrameNames()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fourth");
Assert.Throws<NoSuchFrameException>(() => driver.SwitchTo().Frame("second"));
}
[Test]
public void ShouldThrowAnExceptionWhenAFrameCannotBeFound()
{
driver.Url = xhtmlTestPage;
Assert.Throws<NoSuchFrameException>(() => driver.SwitchTo().Frame("Nothing here"));
}
[Test]
public void ShouldThrowAnExceptionWhenAFrameCannotBeFoundByIndex()
{
driver.Url = xhtmlTestPage;
Assert.Throws<NoSuchFrameException>(() => driver.SwitchTo().Frame(27));
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.PhantomJS, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.Android, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.PhantomJS, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.Opera, "Browser does not support parent frame navigation")]
public void ShouldBeAbleToSwitchToParentFrame()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fourth").SwitchTo().ParentFrame().SwitchTo().Frame("first");
Assert.AreEqual("1", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.PhantomJS, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.Android, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.PhantomJS, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.Opera, "Browser does not support parent frame navigation")]
public void ShouldBeAbleToSwitchToParentFrameFromASecondLevelFrame()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fourth").SwitchTo().Frame("child1").SwitchTo().ParentFrame().SwitchTo().Frame("child2");
Assert.AreEqual("11", driver.FindElement(By.Id("pageNumber")).Text);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.PhantomJS, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.Android, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.PhantomJS, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.Opera, "Browser does not support parent frame navigation")]
public void SwitchingToParentFrameFromDefaultContextIsNoOp()
{
driver.Url = xhtmlTestPage;
driver.SwitchTo().ParentFrame();
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
[IgnoreBrowser(Browser.Chrome, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.PhantomJS, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.Android, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.PhantomJS, "Browser does not support parent frame navigation")]
[IgnoreBrowser(Browser.Opera, "Browser does not support parent frame navigation")]
public void ShouldBeAbleToSwitchToParentFromAnIframe()
{
driver.Url = iframePage;
driver.SwitchTo().Frame(0);
driver.SwitchTo().ParentFrame();
driver.FindElement(By.Id("iframe_page_heading"));
}
// ----------------------------------------------------------------------------------------------
//
// General frame handling behavior tests
//
// ----------------------------------------------------------------------------------------------
[Test]
public void ShouldContinueToReferToTheSameFrameOnceItHasBeenSelected()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame(2);
IWebElement checkbox = driver.FindElement(By.XPath("//input[@name='checky']"));
checkbox.Click();
checkbox.Submit();
Assert.AreEqual("Success!", driver.FindElement(By.XPath("//p")).Text);
}
[Test]
public void ShouldFocusOnTheReplacementWhenAFrameFollowsALinkToA_TopTargettedPage()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame(0);
driver.FindElement(By.LinkText("top")).Click();
// TODO(simon): Avoid going too fast when native events are there.
System.Threading.Thread.Sleep(1000);
Assert.AreEqual("XHTML Test Page", driver.Title);
}
[Test]
public void ShouldAllowAUserToSwitchFromAnIframeBackToTheMainContentOfThePage()
{
driver.Url = iframePage;
driver.SwitchTo().Frame(0);
driver.SwitchTo().DefaultContent();
driver.FindElement(By.Id("iframe_page_heading"));
}
[Test]
public void ShouldAllowTheUserToSwitchToAnIFrameAndRemainFocusedOnIt()
{
driver.Url = iframePage;
driver.SwitchTo().Frame(0);
driver.FindElement(By.Id("submitButton")).Click();
string hello = GetTextOfGreetingElement();
Assert.AreEqual(hello, "Success!");
}
[Test]
public void ShouldBeAbleToClickInAFrame()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("third");
// This should replace frame "third" ...
driver.FindElement(By.Id("submitButton")).Click();
// driver should still be focused on frame "third" ...
Assert.AreEqual("Success!", GetTextOfGreetingElement());
// Make sure it was really frame "third" which was replaced ...
driver.SwitchTo().DefaultContent().SwitchTo().Frame("third");
Assert.AreEqual("Success!", GetTextOfGreetingElement());
}
[Test]
public void testShouldBeAbleToClickInAFrameThatRewritesTopWindowLocation()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/issue5237.html");
driver.SwitchTo().Frame("search");
driver.FindElement(By.Id("submit")).Click();
driver.SwitchTo().DefaultContent();
WaitFor(() => { return driver.Title == "Target page for issue 5237"; }, "Browser title was not 'Target page for issue 5237'");
}
[Test]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldBeAbleToClickInASubFrame()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("sixth").SwitchTo().Frame("iframe1");
// This should replaxe frame "iframe1" inside frame "sixth" ...
driver.FindElement(By.Id("submitButton")).Click();
// driver should still be focused on frame "iframe1" inside frame "sixth" ...
Assert.AreEqual("Success!", GetTextOfGreetingElement());
// Make sure it was really frame "iframe1" inside frame "sixth" which was replaced ...
driver.SwitchTo().DefaultContent().SwitchTo().Frame("sixth").SwitchTo().Frame("iframe1");
Assert.AreEqual("Success!", driver.FindElement(By.Id("greeting")).Text);
}
[Test]
public void ShouldBeAbleToFindElementsInIframesByXPath()
{
driver.Url = iframePage;
driver.SwitchTo().Frame("iframe1");
IWebElement element = driver.FindElement(By.XPath("//*[@id = 'changeme']"));
Assert.IsNotNull(element);
}
[Test]
public void GetCurrentUrlShouldReturnTopLevelBrowsingContextUrl()
{
driver.Url = framesetPage;
Assert.AreEqual(framesetPage, driver.Url);
driver.SwitchTo().Frame("second");
Assert.AreEqual(framesetPage, driver.Url);
}
[Test]
public void GetCurrentUrlShouldReturnTopLevelBrowsingContextUrlForIframes()
{
driver.Url = iframePage;
Assert.AreEqual(iframePage, driver.Url);
driver.SwitchTo().Frame("iframe1");
Assert.AreEqual(iframePage, driver.Url);
}
[Test]
[IgnoreBrowser(Browser.PhantomJS, "Causes browser to exit")]
public void ShouldBeAbleToSwitchToTheTopIfTheFrameIsDeletedFromUnderUs()
{
driver.Url = deletingFrame;
driver.SwitchTo().Frame("iframe1");
IWebElement killIframe = driver.FindElement(By.Id("killIframe"));
killIframe.Click();
driver.SwitchTo().DefaultContent();
bool frameExists = true;
DateTime timeout = DateTime.Now.Add(TimeSpan.FromMilliseconds(4000));
while (DateTime.Now < timeout)
{
try
{
driver.SwitchTo().Frame("iframe1");
}
catch (NoSuchFrameException)
{
frameExists = false;
break;
}
}
Assert.IsFalse(frameExists);
IWebElement addIFrame = driver.FindElement(By.Id("addBackFrame"));
addIFrame.Click();
timeout = DateTime.Now.Add(TimeSpan.FromMilliseconds(4000));
while (DateTime.Now < timeout)
{
try
{
driver.SwitchTo().Frame("iframe1");
break;
}
catch (NoSuchFrameException)
{
}
}
try
{
WaitFor(() =>
{
IWebElement success = null;
try
{
success = driver.FindElement(By.Id("success"));
}
catch (NoSuchElementException)
{
}
return success != null;
}, "Element with id 'success' still exists on page");
}
catch (WebDriverException)
{
Assert.Fail("Could not find element after switching frame");
}
}
[Test]
public void ShouldReturnWindowTitleInAFrameset()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("third");
Assert.AreEqual("Unique title", driver.Title);
}
[Test]
public void JavaScriptShouldExecuteInTheContextOfTheCurrentFrame()
{
IJavaScriptExecutor executor = driver as IJavaScriptExecutor;
driver.Url = framesetPage;
Assert.IsTrue((bool)executor.ExecuteScript("return window == window.top"));
driver.SwitchTo().Frame("third");
Assert.IsTrue((bool)executor.ExecuteScript("return window != window.top"));
}
// ----------------------------------------------------------------------------------------------
//
// Frame handling behavior tests not included in Java tests
//
// ----------------------------------------------------------------------------------------------
[Test]
[NeedsFreshDriver(IsCreatedAfterTest = true)]
public void ClosingTheFinalBrowserWindowShouldNotCauseAnExceptionToBeThrown()
{
driver.Url = simpleTestPage;
driver.Close();
}
[Test]
public void ShouldBeAbleToFlipToAFrameIdentifiedByItsId()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("fifth");
driver.FindElement(By.Id("username"));
}
[Test]
public void ShouldBeAbleToSelectAFrameByName()
{
driver.Url = framesetPage;
driver.SwitchTo().Frame("second");
Assert.AreEqual(driver.FindElement(By.Id("pageNumber")).Text, "2");
driver.SwitchTo().DefaultContent().SwitchTo().Frame("third");
driver.FindElement(By.Id("changeme")).Click();
driver.SwitchTo().DefaultContent().SwitchTo().Frame("second");
Assert.AreEqual(driver.FindElement(By.Id("pageNumber")).Text, "2");
}
[Test]
public void ShouldBeAbleToFindElementsInIframesByName()
{
driver.Url = iframePage;
driver.SwitchTo().Frame("iframe1");
IWebElement element = driver.FindElement(By.Name("id-name1"));
Assert.IsNotNull(element);
}
private string GetTextOfGreetingElement()
{
string text = string.Empty;
DateTime end = DateTime.Now.Add(TimeSpan.FromMilliseconds(3000));
while (DateTime.Now < end)
{
try
{
IWebElement element = driver.FindElement(By.Id("greeting"));
text = element.Text;
break;
}
catch (NoSuchElementException)
{
}
}
return text;
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace PhysXtest
{
public partial class Form1 : Form
{
PhysX.Material material;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private PhysX.RigidDynamic CreateBox(PhysX.Scene scene, int offset)
{
const float HEIGHT = 20.0f;
var rigid = scene.Physics.CreateRigidDynamic();
var shape = rigid.CreateShape(new PhysX.BoxGeometry(1.0f, 1.0f, 1.0f), material);
rigid.GlobalPose = PhysX.Math.Matrix.Translation(130f, 130f, HEIGHT + offset);
return rigid;
}
private PhysX.RigidDynamic CreateSphere(PhysX.Scene scene, int offset)
{
const float HEIGHT = 20.0f;
var rigid = scene.Physics.CreateRigidDynamic();
var shape = rigid.CreateShape(new PhysX.SphereGeometry(1.0f), material);
rigid.GlobalPose = PhysX.Math.Matrix.Translation(128f, 128f, HEIGHT + offset);
rigid.AngularDamping = 0.2f;
rigid.LinearDamping = 0.2f;
return rigid;
}
static Random rand = new Random();
private static PhysX.HeightFieldSample[] CreateSampleGrid(int rows, int columns)
{
var samples = new PhysX.HeightFieldSample[rows * columns];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < columns; c++)
{
var sample = new PhysX.HeightFieldSample()
{
Height = 0//(short)rand.Next(10)
};
samples[r * columns + c] = sample;
}
}
return samples;
}
public PhysX.RigidStatic CreateTriangle(PhysX.Scene scene)
{
List<PhysX.Math.Vector3> Vertices = new List<PhysX.Math.Vector3>();
List<int> Indices = new List<int>();
PhysX.TriangleMeshDesc TriangleMeshDesc = new PhysX.TriangleMeshDesc()
{
Triangles = new int[12] { 0, 1, 2, 0, 3, 1, 3, 4, 1, 3, 5, 4 },
Points = new PhysX.Math.Vector3[6] {
new PhysX.Math.Vector3 { X = 0, Y = 0, Z = 0 },
new PhysX.Math.Vector3 { X = 1, Y = 1, Z = 0 },
new PhysX.Math.Vector3 { X = 0, Y = 1, Z = 0 },
new PhysX.Math.Vector3 { X = 1, Y = 0, Z = 0 },
new PhysX.Math.Vector3 { X = 2, Y = 1, Z = 0 },
new PhysX.Math.Vector3 { X = 2, Y = 0, Z = 0 },
}
};
MemoryStream ms = new MemoryStream();
PhysX.Cooking cook = scene.Physics.CreateCooking();
cook.CookTriangleMesh(TriangleMeshDesc, ms);
cook.Dispose();
ms.Position = 0;
PhysX.TriangleMesh triangleMesh = scene.Physics.CreateTriangleMesh(ms);
PhysX.TriangleMeshGeometry triangleMeshShapeDesc = new PhysX.TriangleMeshGeometry(triangleMesh);
//PhysX.Math.Matrix.RotationYawPitchRoll(0f, (float)Math.PI / 2, 0f) * PhysX.Math.Matrix.Translation(0f, 0f, 0f)
var hfActor = scene.Physics.CreateRigidStatic();
hfActor.CreateShape(triangleMeshShapeDesc, scene.Physics.CreateMaterial(0.75f, 0.75f, 0.1f));
return hfActor;
}
private PhysX.RigidStatic CreateGround(PhysX.Scene scene)
{
var hfGeom = this.CreateHfGeom(scene);
return this.CreateGround(scene, hfGeom);
//return CreateTriangle(scene);
}
private PhysX.HeightFieldGeometry CreateHfGeom(PhysX.Scene scene)
{
const int rows = 256, columns = 256;
var samples = CreateSampleGrid(rows, columns);
var heightFieldDesc = new PhysX.HeightFieldDesc()
{
NumberOfRows = rows,
NumberOfColumns = columns,
Samples = samples
};
PhysX.HeightField heightField = scene.Physics.CreateHeightField(heightFieldDesc);
PhysX.HeightFieldGeometry hfGeom = new PhysX.HeightFieldGeometry(heightField, 0, 1.0f, 1.0f, 1.0f);
return hfGeom;
}
private PhysX.RigidStatic CreateGround(PhysX.Scene scene, PhysX.HeightFieldGeometry hfGeom)
{
var hfActor = scene.Physics.CreateRigidStatic();
hfActor.CreateShape(hfGeom, material);
hfActor.GlobalPose = PhysX.Math.Matrix.RotationYawPitchRoll(0f, (float)Math.PI / 2, 0f) * PhysX.Math.Matrix.Translation(0f, 256 - 1, 0f);
return hfActor;
//return CreateTriangle(scene);
}
private void button1_Click(object sender, EventArgs e)
{
PhysX.Physics phys = new PhysX.Physics();
PhysX.SceneDesc desc = new PhysX.SceneDesc();
desc.Gravity = new PhysX.Math.Vector3(0f, 0f, -9.8f);
PhysX.Scene scene = phys.CreateScene(desc);
material = scene.Physics.CreateMaterial(0.5f, 0.5f, 0.1f);
var conn = phys.ConnectToRemoteDebugger("localhost", null, null, null, PhysX.RemoteDebuggerConnectionFlags.Debug);
/*scene.SetVisualizationParameter(PhysX.VisualizationParameter.Scale, 1.0f);
scene.SetVisualizationParameter(PhysX.VisualizationParameter.CollisionShapes, true);
scene.SetVisualizationParameter(PhysX.VisualizationParameter.JointLocalFrames, true);
scene.SetVisualizationParameter(PhysX.VisualizationParameter.JointLimits, true);
scene.SetVisualizationParameter(PhysX.VisualizationParameter.ParticleSystemPosition, true);
scene.SetVisualizationParameter(PhysX.VisualizationParameter.ActorAxes, true);*/
var hfGeom = this.CreateHfGeom(scene);
while (true)
{
PhysX.RigidDynamic sphere = CreateSphere(scene, 0);
sphere.Dispose();
PhysX.RigidStatic ground = CreateGround(scene, hfGeom);
ground.Dispose();
GC.Collect();
}
scene.AddActor(CreateGround(scene));
/*PhysX.RigidDynamic box1 = null;
for (int i = 0; i < 10; i += 2)
{
PhysX.RigidDynamic mahBox = CreateBox(scene, i);
scene.AddActor(mahBox);
if (i == 0)
{
box1 = mahBox;
((PhysX.Actor)box1).Flags = PhysX.ActorFlag.DisableGravity;
}
}*/
for (int i = 0; i < 10; i += 2)
{
PhysX.RigidDynamic mahBox = CreateSphere(scene, i);
scene.AddActor(mahBox);
}
Stopwatch sw = new Stopwatch();
while (true)
{
sw.Start();
scene.Simulate(0.025f);
scene.FetchResults(true);
sw.Stop();
int sleep = 25 - (int)sw.ElapsedMilliseconds;
if (sleep < 0) sleep = 0;
System.Threading.Thread.Sleep(sleep);
sw.Reset();
//label1.Text = DecomposeToPosition(mahBox.GlobalPose).ToString();
this.Update();
}
}
public static PhysX.Math.Vector3 DecomposeToPosition(PhysX.Math.Matrix matrix)
{
return new PhysX.Math.Vector3(matrix.M41, matrix.M42, matrix.M43);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
using osu.Framework.Extensions.EnumExtensions;
namespace osu.Framework.Platform.Windows.Native
{
/// <summary>
/// Static class for interacting with the Input Method Manager,
/// the interface between applications and the IME.
/// </summary>
internal static class Imm
{
/// <summary>
/// Cancels the currently active IME composition (if any).
/// Resets the internal composition string and hides the candidate window.
/// </summary>
internal static void CancelComposition(IntPtr hWnd)
{
using (var inputContext = new InputContext(hWnd))
{
inputContext.CancelComposition();
}
}
/// <summary>
/// Sets whether IME is allowed.
/// </summary>
/// <remarks>
/// If IME is disallowed, text input is active and a language that uses IME is selected,
/// then IME will be forced into alphanumeric mode, behaving as normal keyboard input (no compositing will happen).
/// </remarks>
internal static void SetImeAllowed(IntPtr hWnd, bool allowed)
{
ImmAssociateContextEx(hWnd, IntPtr.Zero, allowed ? AssociationFlags.IACE_DEFAULT : AssociationFlags.IACE_IGNORENOCONTEXT);
}
/// <summary>
/// Provides an IMC (Input Method Context) allowing interaction with the IMM (Input Method Manager).
/// </summary>
internal class InputContext : IDisposable
{
/// <summary>
/// The IMM handle, used as the <c>hImc</c> param of native functions.
/// </summary>
private readonly InputContextHandle handle;
private readonly CompositionString lParam;
public InputContext(IntPtr hWnd, long lParam = 0)
{
handle = new InputContextHandle(hWnd);
this.lParam = (CompositionString)lParam;
}
/// <summary>
/// Gets the current composition text and selection.
/// </summary>
public bool TryGetImeComposition(out string compositionText, out int start, out int length)
{
if (handleInvalidOrClosed())
{
start = 0;
length = 0;
compositionText = null;
return false;
}
if (!tryGetCompositionText(CompositionString.GCS_COMPSTR, out compositionText))
{
start = 0;
length = 0;
return false;
}
if (tryGetCompositionTargetRange(out int targetStart, out int targetEnd))
{
start = targetStart;
length = targetEnd - targetStart;
return true;
}
// couldn't get selection length, so default to 0
length = 0;
if (tryGetCompositionSize(CompositionString.GCS_CURSORPOS, out int cursorPosition))
{
start = cursorPosition;
return true;
}
// couldn't get selection start, so default to end of string.
start = compositionText.Length;
return true;
}
/// <summary>
/// Gets the current result text.
/// </summary>
public bool TryGetImeResult(out string resultText)
{
if (handleInvalidOrClosed())
{
resultText = null;
return false;
}
return tryGetCompositionText(CompositionString.GCS_RESULTSTR, out resultText);
}
/// <summary>
/// Cancels the currently active IME composition (if any).
/// </summary>
/// <remarks>
/// Resets the internal composition string and hides the candidate window.
/// </remarks>
public void CancelComposition()
{
if (handleInvalidOrClosed()) return;
ImmNotifyIME(handle, NotificationCode.NI_COMPOSITIONSTR, (uint)CompositionStringAction.CPS_CANCEL, 0);
}
/// <summary>
/// Get the <paramref name="size"/> of the corresponding <paramref name="compositionString"/> from the IMM.
/// </summary>
/// <remarks>
/// The size has a different meaning, depending on the provided <paramref name="compositionString"/>:
/// <list type="bullet">
/// <item>For most <see cref="CompositionString"/>s, returns the size of buffer required to store the data.</item>
/// <item>For <see cref="CompositionString.GCS_CURSORPOS"/>, returns the cursor position in the current composition text.</item>
/// </list>
/// </remarks>
private bool tryGetCompositionSize(CompositionString compositionString, out int size)
{
size = -1;
if (!lParam.HasFlagFast(compositionString))
return false;
size = ImmGetCompositionString(handle, compositionString, null, 0);
// negative return value means that an error has occured.
return size >= 0;
}
/// <summary>
/// Get the <paramref name="size"/> and <paramref name="data"/> of the corresponding <paramref name="compositionString"/> from the IMM.
/// </summary>
/// <remarks>
/// The <paramref name="size"/> and <paramref name="data"/> have different meanings, depending on the provided <paramref name="compositionString"/>:
/// <list type="bullet">
/// <item>For <see cref="CompositionString.GCS_COMPSTR"/> and <see cref="CompositionString.GCS_RESULTSTR"/> data is UTF-16 encoded text.</item>
/// <item>For <see cref="CompositionString.GCS_COMPATTR"/> .</item>
/// </list>
/// </remarks>
private bool tryGetCompositionString(CompositionString compositionString, out int size, out byte[] data)
{
data = null;
if (!tryGetCompositionSize(compositionString, out size))
return false;
data = new byte[size];
int ret = ImmGetCompositionString(handle, compositionString, data, (uint)size);
// negative return value means that an error has occured.
return ret >= 0;
}
/// <summary>
/// Gets the text of the current composition (<see cref="CompositionString.GCS_COMPSTR"/>) or result (<see cref="CompositionString.GCS_RESULTSTR"/>).
/// </summary>
private bool tryGetCompositionText(CompositionString compositionString, out string text)
{
if (tryGetCompositionString(compositionString, out _, out byte[] buffer))
{
text = Encoding.Unicode.GetString(buffer);
return true;
}
text = null;
return false;
}
/// <summary>
/// Determines whether or not the given attribute represents a target (a.k.a. a selection).
/// </summary>
private bool isTargetAttribute(byte attribute) => attribute == (byte)Attribute.ATTR_TARGET_CONVERTED || attribute == (byte)Attribute.ATTR_TARGET_NOTCONVERTED;
/// <summary>
/// Gets the target range that's selected by the user in the current composition string.
/// </summary>
private bool tryGetCompositionTargetRange(out int targetStart, out int targetEnd)
{
targetStart = 0;
targetEnd = 0;
if (!tryGetCompositionString(CompositionString.GCS_COMPATTR, out int size, out byte[] attributeData))
return false;
int start;
int end;
bool targetFound = false;
// find the first character that is part of the current conversion.
for (start = 0; start < size; start++)
{
if (isTargetAttribute(attributeData[start]))
{
targetFound = true;
break;
}
}
if (!targetFound)
return false;
// find the last character that is part of the current conversion.
for (end = start; end < size; end++)
{
if (!isTargetAttribute(attributeData[end]))
break;
}
targetStart = start;
targetEnd = end;
return true;
}
/// <summary>
/// Checks whether the <see cref="handle"/> is invalid or closed.
/// </summary>
/// <remarks>Should be checked before calling native functions with the <see cref="handle"/>.</remarks>
/// <returns><c>true</c> if the handle is invalid.</returns>
/// <exception cref="ObjectDisposedException">Thrown if the <see cref="handle"/> was disposed/closed.</exception>
private bool handleInvalidOrClosed()
{
if (handle.IsClosed)
throw new ObjectDisposedException(handle.ToString(), $"Attempted to use a closed {nameof(InputContextHandle)}.");
return handle.IsInvalid;
}
public void Dispose()
{
handle.Dispose();
}
}
#region Native functions and handles
private class InputContextHandle : SafeHandleZeroOrMinusOneIsInvalid
{
[DllImport("imm32.dll", SetLastError = true)]
private static extern IntPtr ImmGetContext(IntPtr hWnd);
[DllImport("imm32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ImmReleaseContext(IntPtr hWnd, IntPtr hImc);
private readonly IntPtr windowHandle;
public InputContextHandle(IntPtr windowHandle)
: base(true)
{
if (windowHandle == IntPtr.Zero)
throw new ArgumentException($"Invalid {nameof(windowHandle)}");
this.windowHandle = windowHandle;
SetHandle(ImmGetContext(windowHandle));
}
protected override bool ReleaseHandle()
{
return ImmReleaseContext(windowHandle, handle);
}
}
// ReSharper disable IdentifierTypo
[DllImport("imm32.dll", CharSet = CharSet.Unicode)]
private static extern int ImmGetCompositionString(InputContextHandle hImc, CompositionString dwIndex, byte[] lpBuf, uint dwBufLen);
[DllImport("imm32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ImmNotifyIME(InputContextHandle hImc, NotificationCode dwAction, uint dwIndex, uint dwValue);
[DllImport("imm32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ImmAssociateContextEx(IntPtr hWnd, IntPtr hImc, AssociationFlags dwFlags);
// window messages
internal const int WM_IME_STARTCOMPOSITION = 0x010D;
internal const int WM_IME_ENDCOMPOSITION = 0x010E;
internal const int WM_IME_COMPOSITION = 0x010F;
/// <summary>
/// IME composition string values.
/// <c>lParam</c> values of <see cref="WM_IME_COMPOSITION"/> event.
/// Parameter <c>dwIndex</c> of <see cref="ImmGetCompositionString"/>.
/// </summary>
[Flags]
private enum CompositionString : uint
{
/// <summary>
/// Retrieve or update the reading string of the current composition.
/// </summary>
GCS_COMPREADSTR = 0x0001,
/// <summary>
/// Retrieve or update the <see cref="Attribute"/>s of the reading string of the current composition.
/// </summary>
GCS_COMPREADATTR = 0x0002,
/// <summary>
/// Retrieve or update the clause information of the reading string of the composition string.
/// </summary>
GCS_COMPREADCLAUSE = 0x0004,
/// <summary>
/// Retrieve or update the current composition string.
/// </summary>
GCS_COMPSTR = 0x0008,
/// <summary>
/// Retrieve or update the <see cref="Attribute"/>s of the composition string.
/// </summary>
GCS_COMPATTR = 0x0010,
/// <summary>
/// Retrieve or update clause information of the composition string.
/// </summary>
GCS_COMPCLAUSE = 0x0020,
/// <summary>
/// Retrieve or update the cursor position in composition string.
/// </summary>
GCS_CURSORPOS = 0x0080,
/// <summary>
/// Retrieve or update the starting position of any changes in composition string.
/// </summary>
GCS_DELTASTART = 0x0100,
/// <summary>
/// Retrieve or update the reading string.
/// </summary>
GCS_RESULTREADSTR = 0x0200,
/// <summary>
/// Retrieve or update clause information of the result string.
/// </summary>
GCS_RESULTREADCLAUSE = 0x0400,
/// <summary>
/// Retrieve or update the string of the composition result.
/// </summary>
GCS_RESULTSTR = 0x0800,
/// <summary>
/// Retrieve or update clause information of the result string.
/// </summary>
GCS_RESULTCLAUSE = 0x1000,
/// <summary>
/// Insert the wParam composition character at the current insertion point.
/// An application should display the composition character if it processes this message.
/// </summary>
CS_INSERTCHAR = 0x2000,
/// <summary>
/// Do not move the caret position as a result of processing the message.
/// </summary>
CS_NOMOVECARET = 0x4000,
}
/// <summary>
/// Attribute for each character in the current composition string (<see cref="CompositionString.GCS_COMPSTR"/>).
/// </summary>
private enum Attribute : byte
{
/// <summary>
/// Character being entered by the user. The IME has yet to convert this character.
/// </summary>
ATTR_INPUT = 0x00,
/// <summary>
/// Character selected by the user and then converted by the IME.
/// </summary>
ATTR_TARGET_CONVERTED = 0x01,
/// <summary>
/// Character that the IME has already converted.
/// </summary>
ATTR_CONVERTED = 0x02,
/// <summary>
/// Character being converted. The user has selected this character but the IME has not yet converted it.
/// </summary>
ATTR_TARGET_NOTCONVERTED = 0x03,
/// <summary>
/// An error character that the IME cannot convert. For example, the IME cannot put together some consonants.
/// </summary>
ATTR_INPUT_ERROR = 0x04,
/// <summary>
/// Character that the IME will no longer convert.
/// </summary>
ATTR_FIXEDCONVERTED = 0x05,
}
/// <summary>
/// dwAction for <see cref="ImmNotifyIME"/>.
/// </summary>
private enum NotificationCode : uint
{
/// <summary>
/// An application directs the IME to open a candidate list.
/// The dwIndex parameter specifies the index of the list to open, and dwValue is not used.
/// </summary>
NI_OPENCANDIDATE = 0x0010,
/// <summary>
/// An application directs the IME to close a candidate list.
/// The dwIndex parameter specifies an index of the list to close, and dwValue is not used.
/// </summary>
NI_CLOSECANDIDATE = 0x0011,
/// <summary>
/// An application has selected one of the candidates.
/// The dwIndex parameter specifies an index of a candidate list to be selected.
/// The dwValue parameter specifies an index of a candidate string in the selected candidate list.
/// </summary>
NI_SELECTCANDIDATESTR = 0x0012,
/// <summary>
/// An application changed the current selected candidate.
/// The dwIndex parameter specifies an index of a candidate list to be selected and dwValue is not used.
/// </summary>
NI_CHANGECANDIDATELIST = 0x0013,
NI_FINALIZECONVERSIONRESULT = 0x0014,
/// <summary>
/// An application directs the IME to carry out an action on the composition string.
/// The dwIndex parameter can be from <see cref="CompositionStringAction"/>.
/// </summary>
NI_COMPOSITIONSTR = 0x0015,
/// <summary>
/// The application changes the page starting index of a candidate list.
/// The dwIndex parameter specifies the candidate list to be changed and must have a value in the range 0 to 3.
/// The dwValue parameter specifies the new page start index.
/// </summary>
NI_SETCANDIDATE_PAGESTART = 0x0016,
/// <summary>
/// The application changes the page size of a candidate list.
/// The dwIndex parameter specifies the candidate list to be changed and must have a value in the range 0 to 3.
/// The dwValue parameter specifies the new page size.
/// </summary>
NI_SETCANDIDATE_PAGESIZE = 0x0017,
/// <summary>
/// An application directs the IME to allow the application to handle the specified menu.
/// The dwIndex parameter specifies the ID of the menu and dwValue is an application-defined value for that menu item.
/// </summary>
NI_IMEMENUSELECTED = 0x0018,
}
/// <summary>
/// dwIndex for <see cref="ImmNotifyIME"/> when using <see cref="NotificationCode.NI_COMPOSITIONSTR"/>.
/// </summary>
private enum CompositionStringAction : uint
{
/// <summary>
/// Set the composition string as the result string.
/// </summary>
CPS_COMPLETE = 0x0001,
/// <summary>
/// Convert the composition string.
/// </summary>
CPS_CONVERT = 0x0002,
/// <summary>
/// Cancel the current composition string and set the composition string to be the unconverted string.
/// </summary>
CPS_REVERT = 0x0003,
/// <summary>
/// Clear the composition string and set the status to no composition string.
/// </summary>
CPS_CANCEL = 0x0004,
}
/// <summary>
/// Flags specifying the type of association between the window and the input method context.
/// dwFlags for <see cref="ImmAssociateContextEx"/>.
/// </summary>
private enum AssociationFlags : uint
{
/// <summary>
/// Associate the input method context to the child windows of the specified window only.
/// </summary>
IACE_CHILDREN = 0x0001,
/// <summary>
/// Restore the default input method context of the window.
/// </summary>
IACE_DEFAULT = 0x0010,
/// <summary>
/// Do not associate the input method context with windows that are not associated with any input method context.
/// </summary>
IACE_IGNORENOCONTEXT = 0x0020,
}
// ReSharper restore IdentifierTypo
#endregion
}
}
| |
using System;
using System.IO;
using BigMath;
using Raksha.Asn1;
using Raksha.Crypto;
using Raksha.Crypto.Agreement;
using Raksha.Crypto.Parameters;
using Raksha.Asn1.X509;
using Raksha.Crypto.Agreement.Srp;
using Raksha.Crypto.Digests;
using Raksha.Crypto.IO;
using Raksha.Math;
using Raksha.Security;
using Raksha.Utilities;
namespace Raksha.Crypto.Tls
{
/// <summary>
/// TLS 1.1 SRP key exchange.
/// </summary>
internal class TlsSrpKeyExchange
: TlsKeyExchange
{
protected TlsClientContext context;
protected KeyExchangeAlgorithm keyExchange;
protected TlsSigner tlsSigner;
protected byte[] identity;
protected byte[] password;
protected AsymmetricKeyParameter serverPublicKey = null;
protected byte[] s = null;
protected BigInteger B = null;
protected Srp6Client srpClient = new Srp6Client();
internal TlsSrpKeyExchange(TlsClientContext context, KeyExchangeAlgorithm keyExchange,
byte[] identity, byte[] password)
{
switch (keyExchange)
{
case KeyExchangeAlgorithm.SRP:
this.tlsSigner = null;
break;
case KeyExchangeAlgorithm.SRP_RSA:
this.tlsSigner = new TlsRsaSigner();
break;
case KeyExchangeAlgorithm.SRP_DSS:
this.tlsSigner = new TlsDssSigner();
break;
default:
throw new ArgumentException("unsupported key exchange algorithm", "keyExchange");
}
this.context = context;
this.keyExchange = keyExchange;
this.identity = identity;
this.password = password;
}
public virtual void SkipServerCertificate()
{
if (tlsSigner != null)
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
}
public virtual void ProcessServerCertificate(Certificate serverCertificate)
{
if (tlsSigner == null)
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
X509CertificateStructure x509Cert = serverCertificate.certs[0];
SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;
try
{
this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo);
}
// catch (RuntimeException)
catch (Exception)
{
throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
}
if (!tlsSigner.IsValidPublicKey(this.serverPublicKey))
{
throw new TlsFatalAlert(AlertDescription.certificate_unknown);
}
TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);
// TODO
/*
* Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the
* signing algorithm for the certificate must be the same as the algorithm for the
* certificate key."
*/
}
public virtual void SkipServerKeyExchange()
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
public virtual void ProcessServerKeyExchange(Stream input)
{
SecurityParameters securityParameters = context.SecurityParameters;
Stream sigIn = input;
ISigner signer = null;
if (tlsSigner != null)
{
signer = InitSigner(tlsSigner, securityParameters);
sigIn = new SignerStream(input, signer, null);
}
byte[] NBytes = TlsUtilities.ReadOpaque16(sigIn);
byte[] gBytes = TlsUtilities.ReadOpaque16(sigIn);
byte[] sBytes = TlsUtilities.ReadOpaque8(sigIn);
byte[] BBytes = TlsUtilities.ReadOpaque16(sigIn);
if (signer != null)
{
byte[] sigByte = TlsUtilities.ReadOpaque16(input);
if (!signer.VerifySignature(sigByte))
{
throw new TlsFatalAlert(AlertDescription.bad_certificate);
}
}
BigInteger N = new BigInteger(1, NBytes);
BigInteger g = new BigInteger(1, gBytes);
// TODO Validate group parameters (see RFC 5054)
//throw new TlsFatalAlert(AlertDescription.insufficient_security);
this.s = sBytes;
/*
* RFC 5054 2.5.3: The client MUST abort the handshake with an "illegal_parameter"
* alert if B % N = 0.
*/
try
{
this.B = Srp6Utilities.ValidatePublicValue(N, new BigInteger(1, BBytes));
}
catch (CryptoException)
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
this.srpClient.Init(N, g, new Sha1Digest(), context.SecureRandom);
}
public virtual void ValidateCertificateRequest(CertificateRequest certificateRequest)
{
throw new TlsFatalAlert(AlertDescription.unexpected_message);
}
public virtual void SkipClientCredentials()
{
// OK
}
public virtual void ProcessClientCredentials(TlsCredentials clientCredentials)
{
throw new TlsFatalAlert(AlertDescription.internal_error);
}
public virtual void GenerateClientKeyExchange(Stream output)
{
byte[] keData = BigIntegers.AsUnsignedByteArray(srpClient.GenerateClientCredentials(s,
this.identity, this.password));
TlsUtilities.WriteUint24(keData.Length + 2, output);
TlsUtilities.WriteOpaque16(keData, output);
}
public virtual byte[] GeneratePremasterSecret()
{
try
{
// TODO Check if this needs to be a fixed size
return BigIntegers.AsUnsignedByteArray(srpClient.CalculateSecret(B));
}
catch (CryptoException)
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
}
protected virtual ISigner InitSigner(TlsSigner tlsSigner, SecurityParameters securityParameters)
{
ISigner signer = tlsSigner.CreateVerifyer(this.serverPublicKey);
signer.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length);
signer.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length);
return signer;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static class OpenSsl
{
private static Ssl.SslCtxSetVerifyCallback s_verifyClientCertificate = VerifyClientCertificate;
#region internal methods
internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, bool isServer, bool remoteCertRequired)
{
SafeSslHandle context = null;
IntPtr method = GetSslMethod(protocols);
using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(method))
{
if (innerContext.IsInvalid)
{
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
Ssl.SetProtocolOptions(innerContext, protocols);
Ssl.SslCtxSetQuietShutdown(innerContext);
Ssl.SetEncryptionPolicy(innerContext, policy);
if (certHandle != null && certKeyHandle != null)
{
SetSslCertificate(innerContext, certHandle, certKeyHandle);
}
if (remoteCertRequired)
{
Debug.Assert(isServer, "isServer flag should be true");
Ssl.SslCtxSetVerify(innerContext,
s_verifyClientCertificate);
//update the client CA list
UpdateCAListFromRootStore(innerContext);
}
context = SafeSslHandle.Create(innerContext, isServer);
Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create");
if (context.IsInvalid)
{
context.Dispose();
throw CreateSslException(SR.net_allocate_ssl_context_failed);
}
}
return context;
}
internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount)
{
sendBuf = null;
sendCount = 0;
if ((recvBuf != null) && (recvCount > 0))
{
BioWrite(context.InputBio, recvBuf, recvOffset, recvCount);
}
Ssl.SslErrorCode error;
int retVal = Ssl.SslDoHandshake(context);
if (retVal != 1)
{
error = GetSslError(context, retVal);
if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ))
{
throw CreateSslException(context, SR.net_ssl_handshake_failed_error, retVal);
}
}
sendCount = Crypto.BioCtrlPending(context.OutputBio);
if (sendCount > 0)
{
sendBuf = new byte[sendCount];
try
{
sendCount = BioRead(context.OutputBio, sendBuf, sendCount);
}
finally
{
if (sendCount <= 0)
{
sendBuf = null;
sendCount = 0;
}
}
}
return Ssl.IsSslStateOK(context);
}
internal static int Encrypt(SafeSslHandle context, byte[] buffer, int offset, int count, out Ssl.SslErrorCode errorCode)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= offset + count);
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal;
unsafe
{
fixed (byte* fixedBuffer = buffer)
{
retVal = Ssl.SslWrite(context, fixedBuffer + offset, count);
}
}
if (retVal != count)
{
errorCode = GetSslError(context, retVal);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
break;
default:
throw CreateSslException(SR.net_ssl_encrypt_failed, errorCode);
}
}
else
{
int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio);
Debug.Assert(buffer.Length >= capacityNeeded, "Input buffer of size " + buffer.Length +
" bytes is insufficient since encryption needs " + capacityNeeded + " bytes.");
retVal = BioRead(context.OutputBio, buffer, capacityNeeded);
}
return retVal;
}
internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int count, out Ssl.SslErrorCode errorCode)
{
errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE;
int retVal = BioWrite(context.InputBio, outBuffer, 0, count);
if (retVal == count)
{
retVal = Ssl.SslRead(context, outBuffer, retVal);
if (retVal > 0)
{
count = retVal;
}
}
if (retVal != count)
{
errorCode = GetSslError(context, retVal);
retVal = 0;
switch (errorCode)
{
// indicate end-of-file
case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN:
break;
case Ssl.SslErrorCode.SSL_ERROR_WANT_READ:
// update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ
errorCode = Ssl.IsSslRenegotiatePending(context) ?
Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE :
Ssl.SslErrorCode.SSL_ERROR_WANT_READ;
break;
default:
throw CreateSslException(SR.net_ssl_decrypt_failed, errorCode);
}
}
return retVal;
}
internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context)
{
return Ssl.SslGetPeerCertificate(context);
}
internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context)
{
return Ssl.SslGetPeerCertChain(context);
}
internal static void FreeSslContext(SafeSslHandle context)
{
Debug.Assert((context != null) && !context.IsInvalid, "Expected a valid context in FreeSslContext");
Disconnect(context);
context.Dispose();
}
#endregion
#region private methods
private static IntPtr GetSslMethod(SslProtocols protocols)
{
Debug.Assert(protocols != SslProtocols.None, "All protocols are disabled");
bool ssl2 = (protocols & SslProtocols.Ssl2) == SslProtocols.Ssl2;
bool ssl3 = (protocols & SslProtocols.Ssl3) == SslProtocols.Ssl3;
bool tls10 = (protocols & SslProtocols.Tls) == SslProtocols.Tls;
bool tls11 = (protocols & SslProtocols.Tls11) == SslProtocols.Tls11;
bool tls12 = (protocols & SslProtocols.Tls12) == SslProtocols.Tls12;
IntPtr method = Ssl.SslMethods.SSLv23_method; // default
string methodName = "SSLv23_method";
if (!ssl2)
{
if (!ssl3)
{
if (!tls11 && !tls12)
{
method = Ssl.SslMethods.TLSv1_method;
methodName = "TLSv1_method";
}
else if (!tls10 && !tls12)
{
method = Ssl.SslMethods.TLSv1_1_method;
methodName = "TLSv1_1_method";
}
else if (!tls10 && !tls11)
{
method = Ssl.SslMethods.TLSv1_2_method;
methodName = "TLSv1_2_method";
}
}
else if (!tls10 && !tls11 && !tls12)
{
method = Ssl.SslMethods.SSLv3_method;
methodName = "SSLv3_method";
}
}
if (IntPtr.Zero == method)
{
throw new SslException(SR.Format(SR.net_get_ssl_method_failed, methodName));
}
return method;
}
private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr)
{
using (SafeX509StoreCtxHandle storeHandle = new SafeX509StoreCtxHandle(x509_ctx_ptr, false))
{
using (var chain = new X509Chain())
{
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
using (SafeX509StackHandle chainStack = Crypto.X509StoreCtxGetChain(storeHandle))
{
if (chainStack.IsInvalid)
{
Debug.Fail("Invalid chain stack handle");
return 0;
}
IntPtr certPtr = Crypto.GetX509StackField(chainStack, 0);
if (IntPtr.Zero == certPtr)
{
return 0;
}
using (X509Certificate2 cert = new X509Certificate2(certPtr))
{
return chain.Build(cert) ? 1 : 0;
}
}
}
}
}
private static void UpdateCAListFromRootStore(SafeSslContextHandle context)
{
using (SafeX509NameStackHandle nameStack = Crypto.NewX509NameStack())
{
//maintaining the HashSet of Certificate's issuer name to keep track of duplicates
HashSet<string> issuerNameHashSet = new HashSet<string>();
//Enumerate Certificates from LocalMachine and CurrentUser root store
AddX509Names(nameStack, StoreLocation.LocalMachine, issuerNameHashSet);
AddX509Names(nameStack, StoreLocation.CurrentUser, issuerNameHashSet);
Ssl.SslCtxSetClientCAList(context, nameStack);
// The handle ownership has been transferred into the CTX.
nameStack.SetHandleAsInvalid();
}
}
private static void AddX509Names(SafeX509NameStackHandle nameStack, StoreLocation storeLocation, HashSet<string> issuerNameHashSet)
{
using (var store = new X509Store(StoreName.Root, storeLocation))
{
store.Open(OpenFlags.ReadOnly);
foreach (var certificate in store.Certificates)
{
//Check if issuer name is already present
//Avoiding duplicate names
if (!issuerNameHashSet.Add(certificate.Issuer))
{
continue;
}
using (SafeX509Handle certHandle = Crypto.X509Duplicate(certificate.Handle))
{
using (SafeX509NameHandle nameHandle = Crypto.DuplicateX509Name(Crypto.X509GetIssuerName(certHandle)))
{
if (Crypto.PushX509NameStackField(nameStack, nameHandle))
{
// The handle ownership has been transferred into the STACK_OF(X509_NAME).
nameHandle.SetHandleAsInvalid();
}
else
{
throw new CryptographicException(SR.net_ssl_x509Name_push_failed_error);
}
}
}
}
}
}
private static void Disconnect(SafeSslHandle context)
{
int retVal = Ssl.SslShutdown(context);
if (retVal < 0)
{
//TODO (Issue #4031) check this error
Ssl.SslGetError(context, retVal);
}
}
//TODO (Issue #3362) should we check Bio should retry?
private static int BioRead(SafeBioHandle bio, byte[] buffer, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= count);
int bytes = Crypto.BioRead(bio, buffer, count);
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_read_bio_failed_error);
}
return bytes;
}
//TODO (Issue #3362) should we check Bio should retry?
private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(offset >= 0);
Debug.Assert(count >= 0);
Debug.Assert(buffer.Length >= offset + count);
int bytes;
unsafe
{
fixed (byte* bufPtr = buffer)
{
bytes = Ssl.BioWrite(bio, bufPtr + offset, count);
}
}
if (bytes != count)
{
throw CreateSslException(SR.net_ssl_write_bio_failed_error);
}
return bytes;
}
private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result)
{
Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result);
if (retVal == Ssl.SslErrorCode.SSL_ERROR_SYSCALL)
{
retVal = (Ssl.SslErrorCode)Crypto.ErrGetError();
}
return retVal;
}
private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr)
{
Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid");
Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid");
int retVal = Ssl.SslCtxUseCertificate(contextPtr, certPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_cert_failed);
}
retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_use_private_key_failed);
}
//check private key
retVal = Ssl.SslCtxCheckPrivateKey(contextPtr);
if (1 != retVal)
{
throw CreateSslException(SR.net_ssl_check_private_key_failed);
}
}
internal static SslException CreateSslException(string message)
{
ulong errorVal = Crypto.ErrGetError();
string msg = SR.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal)));
return new SslException(msg, (int)errorVal);
}
private static SslException CreateSslException(string message, Ssl.SslErrorCode error)
{
string msg = SR.Format(message, error);
switch (error)
{
case Ssl.SslErrorCode.SSL_ERROR_SYSCALL:
return CreateSslException(msg);
case Ssl.SslErrorCode.SSL_ERROR_SSL:
Exception innerEx = Interop.Crypto.CreateOpenSslCryptographicException();
return new SslException(innerEx.Message, innerEx);
default:
return new SslException(msg, error);
}
}
private static SslException CreateSslException(SafeSslHandle context, string message, int error)
{
return CreateSslException(message, Ssl.SslGetError(context, error));
}
#endregion
#region Internal class
internal sealed class SslException : Exception
{
public SslException(string inputMessage)
: base(inputMessage)
{
}
public SslException(string inputMessage, Exception ex)
: base(inputMessage, ex)
{
}
public SslException(string inputMessage, Ssl.SslErrorCode error)
: this(inputMessage, (int)error)
{
}
public SslException(string inputMessage, int error)
: this(inputMessage)
{
HResult = error;
}
public SslException(int error)
: this(SR.Format(SR.net_generic_operation_failed, error))
{
HResult = error;
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Baseline;
using Weasel.Postgresql;
using Marten.Schema;
using Newtonsoft.Json.Linq;
using Shouldly;
using Weasel.Core;
namespace Marten.Testing.Harness
{
public static class Exception<T> where T : Exception
{
public static T ShouldBeThrownBy(Action action)
{
T exception = null;
try
{
action();
}
catch (Exception e)
{
exception = e.ShouldBeOfType<T>();
}
exception.ShouldNotBeNull("An exception was expected, but not thrown by the given action.");
return exception;
}
public static async Task<T> ShouldBeThrownByAsync(Func<Task> action)
{
T exception = null;
try
{
await action();
}
catch (Exception e)
{
exception = e.ShouldBeOfType<T>();
}
exception.ShouldNotBeNull("An exception was expected, but not thrown by the given action.");
return exception;
}
}
public delegate void MethodThatThrows();
public static class SpecificationExtensions
{
public static void ShouldBeSemanticallySameJsonAs(this string json, string expectedJson)
{
var actual = JToken.Parse(json);
var expected = JToken.Parse(expectedJson);
JToken.DeepEquals(expected, actual).ShouldBeTrue($"Expected:\n{expectedJson}\nGot:\n{json}");
}
public static void ShouldContain<T>(this IEnumerable<T> actual, Func<T, bool> expected)
{
actual.Count().ShouldBeGreaterThan(0);
actual.Any(expected).ShouldBeTrue();
}
public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, IEnumerable<T> expected)
{
var actualList = (actual is IList tempActual) ? tempActual : actual.ToList();
var expectedList = (expected is IList tempExpected) ? tempExpected : expected.ToList();
ShouldHaveTheSameElementsAs(actualList, expectedList);
}
public static void ShouldHaveTheSameElementsAs<T>(this IEnumerable<T> actual, params T[] expected)
{
var actualList = (actual is IList tempActual) ? tempActual : actual.ToList();
var expectedList = (expected is IList tempExpected) ? tempExpected : expected.ToList();
ShouldHaveTheSameElementsAs(actualList, expectedList);
}
public static void ShouldHaveTheSameElementsAs(this IList actual, IList expected)
{
actual.ShouldNotBeNull();
expected.ShouldNotBeNull();
try
{
actual.Count.ShouldBe(expected.Count);
for (var i = 0; i < actual.Count; i++)
{
actual[i].ShouldBe(expected[i]);
}
}
catch (Exception)
{
Debug.WriteLine("ACTUAL:");
foreach (var o in actual)
{
Debug.WriteLine(o);
}
throw;
}
}
public static void ShouldBeNull(this object anObject)
{
anObject.ShouldBe(null);
}
public static void ShouldNotBeNull(this object anObject)
{
anObject.ShouldNotBe(null);
}
public static object ShouldBeTheSameAs(this object actual, object expected)
{
ReferenceEquals(actual, expected).ShouldBeTrue();
return expected;
}
public static T IsType<T>(this object actual)
{
actual.ShouldBeOfType(typeof(T));
return (T)actual;
}
public static object ShouldNotBeTheSameAs(this object actual, object expected)
{
ReferenceEquals(actual, expected).ShouldBeFalse();
return expected;
}
public static void ShouldNotBeOfType<T>(this object actual)
{
actual.ShouldNotBeOfType(typeof(T));
}
public static void ShouldNotBeOfType(this object actual, Type expected)
{
actual.GetType().ShouldNotBe(expected);
}
public static IComparable ShouldBeGreaterThan(this IComparable arg1, IComparable arg2)
{
(arg1.CompareTo(arg2) > 0).ShouldBeTrue();
return arg2;
}
public static string ShouldNotBeEmpty(this string aString)
{
aString.IsNotEmpty().ShouldBeTrue();
return aString;
}
public static void ShouldContain(this string actual, string expected, StringComparisonOption options = StringComparisonOption.Default)
{
if (options == StringComparisonOption.NormalizeWhitespaces)
{
actual = Regex.Replace(actual, @"\s+", " ");
expected = Regex.Replace(expected, @"\s+", " ");
}
actual.Contains(expected).ShouldBeTrue($"Actual: {actual}{Environment.NewLine}Expected: {expected}");
}
public static string ShouldNotContain(this string actual, string expected, StringComparisonOption options = StringComparisonOption.NormalizeWhitespaces)
{
if (options == StringComparisonOption.NormalizeWhitespaces)
{
actual = Regex.Replace(actual, @"\s+", " ");
expected = Regex.Replace(expected, @"\s+", " ");
}
actual.Contains(expected).ShouldBeFalse($"Actual: {actual}{Environment.NewLine}Expected: {expected}");
return actual;
}
public static void ShouldStartWith(this string actual, string expected)
{
actual.StartsWith(expected).ShouldBeTrue();
}
public static Exception ShouldBeThrownBy(this Type exceptionType, MethodThatThrows method)
{
Exception exception = null;
try
{
method();
}
catch (Exception e)
{
e.GetType().ShouldBe(exceptionType);
exception = e;
}
exception.ShouldNotBeNull("Expected {0} to be thrown.".ToFormat(exceptionType.FullName));
return exception;
}
public static void ShouldBeEqualWithDbPrecision(this DateTime actual, DateTime expected)
{
static DateTime toDbPrecision(DateTime date) => new DateTime(date.Ticks / 1000 * 1000);
toDbPrecision(actual).ShouldBe(toDbPrecision(expected));
}
public static void ShouldBeEqualWithDbPrecision(this DateTimeOffset actual, DateTimeOffset expected)
{
static DateTimeOffset toDbPrecision(DateTimeOffset date) => new DateTimeOffset(date.Ticks / 1000 * 1000, new TimeSpan(date.Offset.Ticks / 1000 * 1000));
toDbPrecision(actual).ShouldBe(toDbPrecision(expected));
}
public static void ShouldContain(this DbObjectName[] names, string qualifiedName)
{
if (names == null)
throw new ArgumentNullException(nameof(names));
var function = DbObjectName.Parse(PostgresqlProvider.Instance, qualifiedName);
names.ShouldContain(function);
}
}
public enum StringComparisonOption
{
Default,
NormalizeWhitespaces
}
}
| |
// 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.DirectoryServices.ActiveDirectory
{
using System;
using System.Text;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Globalization;
public enum SchemaClassType : int
{
Type88 = 0,
Structural = 1,
Abstract = 2,
Auxiliary = 3
}
[Flags]
public enum PropertyTypes : int
{
Indexed = 2,
InGlobalCatalog = 4
}
public class ActiveDirectorySchema : ActiveDirectoryPartition
{
private bool _disposed = false;
private DirectoryEntry _schemaEntry = null;
private DirectoryEntry _abstractSchemaEntry = null;
private DirectoryServer _cachedSchemaRoleOwner = null;
#region constructors
internal ActiveDirectorySchema(DirectoryContext context, string distinguishedName)
: base(context, distinguishedName)
{
this.directoryEntryMgr = new DirectoryEntryManager(context);
_schemaEntry = DirectoryEntryManager.GetDirectoryEntry(context, distinguishedName);
}
internal ActiveDirectorySchema(DirectoryContext context, string distinguishedName, DirectoryEntryManager directoryEntryMgr)
: base(context, distinguishedName)
{
this.directoryEntryMgr = directoryEntryMgr;
_schemaEntry = DirectoryEntryManager.GetDirectoryEntry(context, distinguishedName);
}
#endregion constructors
#region IDisposable
// private Dispose method
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
try
{
// if there are any managed or unmanaged
// resources to be freed, those should be done here
// if not an explicit dispose only unmanaged resources should
// be disposed
if (disposing)
{
// dispose schema entry
if (_schemaEntry != null)
{
_schemaEntry.Dispose();
_schemaEntry = null;
}
// dispose the abstract schema entry
if (_abstractSchemaEntry != null)
{
_abstractSchemaEntry.Dispose();
_abstractSchemaEntry = null;
}
}
_disposed = true;
}
finally
{
base.Dispose();
}
}
}
#endregion IDisposable
#region public methods
public static ActiveDirectorySchema GetSchema(DirectoryContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
// contexttype should be Forest, DirectoryServer or ConfigurationSet
if ((context.ContextType != DirectoryContextType.Forest) &&
(context.ContextType != DirectoryContextType.ConfigurationSet) &&
(context.ContextType != DirectoryContextType.DirectoryServer))
{
throw new ArgumentException(SR.NotADOrADAM, "context");
}
if ((context.Name == null) && (!context.isRootDomain()))
{
throw new ActiveDirectoryObjectNotFoundException(SR.ContextNotAssociatedWithDomain, typeof(ActiveDirectorySchema), null);
}
if (context.Name != null)
{
// the target should be a valid forest name or a server
if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || (context.isServer())))
{
if (context.ContextType == DirectoryContextType.Forest)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ForestNotFound, typeof(ActiveDirectorySchema), context.Name);
}
else if (context.ContextType == DirectoryContextType.ConfigurationSet)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name);
}
else
{
throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ServerNotFound , context.Name), typeof(ActiveDirectorySchema), null);
}
}
}
// work with copy of the context
context = new DirectoryContext(context);
DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context);
string schemaNC = null;
try
{
DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryOrADAM)))
{
throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ServerNotFound , context.Name), typeof(ActiveDirectorySchema), null);
}
schemaNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.SchemaNamingContext);
}
catch (COMException e)
{
int errorCode = e.ErrorCode;
if (errorCode == unchecked((int)0x8007203a))
{
if (context.ContextType == DirectoryContextType.Forest)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ForestNotFound, typeof(ActiveDirectorySchema), context.Name);
}
else if (context.ContextType == DirectoryContextType.ConfigurationSet)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name);
}
else
{
throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ServerNotFound , context.Name), typeof(ActiveDirectorySchema), null);
}
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
catch (ActiveDirectoryObjectNotFoundException)
{
if (context.ContextType == DirectoryContextType.ConfigurationSet)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
throw new ActiveDirectoryObjectNotFoundException(SR.ConfigSetNotFound, typeof(ActiveDirectorySchema), context.Name);
}
else
throw;
}
return new ActiveDirectorySchema(context, schemaNC, directoryEntryMgr);
}
public void RefreshSchema()
{
CheckIfDisposed();
// Refresh the schema on the server
DirectoryEntry rootDSE = null;
try
{
rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
rootDSE.Properties[PropertyManager.SchemaUpdateNow].Value = 1;
rootDSE.CommitChanges();
// refresh the schema on the client
// bind to the abstract schema
if (_abstractSchemaEntry == null)
{
_abstractSchemaEntry = directoryEntryMgr.GetCachedDirectoryEntry("Schema");
}
_abstractSchemaEntry.RefreshCache();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (rootDSE != null)
{
rootDSE.Dispose();
}
}
}
//
// This method finds only among non-defunct classes
//
public ActiveDirectorySchemaClass FindClass(string ldapDisplayName)
{
CheckIfDisposed();
return ActiveDirectorySchemaClass.FindByName(context, ldapDisplayName);
}
//
// This method finds only among defunct classes
//
public ActiveDirectorySchemaClass FindDefunctClass(string commonName)
{
CheckIfDisposed();
if (commonName == null)
{
throw new ArgumentNullException("commonName");
}
if (commonName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, "commonName");
}
// this will bind to the schema container and load the properties of this class
// (will also check whether or not the class exists)
Hashtable propertiesFromServer = ActiveDirectorySchemaClass.GetPropertiesFromSchemaContainer(context, _schemaEntry, commonName, true /* isDefunctOnServer */);
ActiveDirectorySchemaClass schemaClass = new ActiveDirectorySchemaClass(context, commonName, propertiesFromServer, _schemaEntry);
return schemaClass;
}
//
// This method returns only non-defunct classes
//
public ReadOnlyActiveDirectorySchemaClassCollection FindAllClasses()
{
CheckIfDisposed();
string filter = "(&(" + PropertyManager.ObjectCategory + "=classSchema)" +
"(!(" + PropertyManager.IsDefunct + "=TRUE)))";
return GetAllClasses(context, _schemaEntry, filter);
}
//
// This method returns only non-defunct classes of the specified type
//
public ReadOnlyActiveDirectorySchemaClassCollection FindAllClasses(SchemaClassType type)
{
CheckIfDisposed();
// validate the type
if (type < SchemaClassType.Type88 || type > SchemaClassType.Auxiliary)
{
throw new InvalidEnumArgumentException("type", (int)type, typeof(SchemaClassType));
}
string filter = "(&(" + PropertyManager.ObjectCategory + "=classSchema)" +
"(" + PropertyManager.ObjectClassCategory + "=" + (int)type + ")" +
"(!(" + PropertyManager.IsDefunct + "=TRUE)))";
return GetAllClasses(context, _schemaEntry, filter);
}
//
// This method returns only defunct classes
//
public ReadOnlyActiveDirectorySchemaClassCollection FindAllDefunctClasses()
{
CheckIfDisposed();
string filter = "(&(" + PropertyManager.ObjectCategory + "=classSchema)" +
"(" + PropertyManager.IsDefunct + "=TRUE))";
return GetAllClasses(context, _schemaEntry, filter);
}
//
// This method finds only among non-defunct properties
//
public ActiveDirectorySchemaProperty FindProperty(string ldapDisplayName)
{
CheckIfDisposed();
return ActiveDirectorySchemaProperty.FindByName(context, ldapDisplayName);
}
//
// This method finds only among defunct properties
//
public ActiveDirectorySchemaProperty FindDefunctProperty(string commonName)
{
CheckIfDisposed();
if (commonName == null)
{
throw new ArgumentNullException("commonName");
}
if (commonName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, "commonName");
}
// this will bind to the schema container and load the properties of this property
// (will also check whether or not the property exists)
SearchResult propertiesFromServer = ActiveDirectorySchemaProperty.GetPropertiesFromSchemaContainer(context, _schemaEntry, commonName, true /* isDefunctOnServer */);
ActiveDirectorySchemaProperty schemaProperty = new ActiveDirectorySchemaProperty(context, commonName, propertiesFromServer, _schemaEntry);
return schemaProperty;
}
//
// This method returns only non-defunct properties
//
public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllProperties()
{
CheckIfDisposed();
string filter = "(&(" + PropertyManager.ObjectCategory + "=attributeSchema)" +
"(!(" + PropertyManager.IsDefunct + "=TRUE)))";
return GetAllProperties(context, _schemaEntry, filter);
}
//
// This method returns only non-defunct properties meeting the specified criteria
//
public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllProperties(PropertyTypes type)
{
CheckIfDisposed();
// check validity of type
if ((type & (~(PropertyTypes.Indexed | PropertyTypes.InGlobalCatalog))) != 0)
{
throw new ArgumentException(SR.InvalidFlags, "type");
}
// start the filter
StringBuilder str = new StringBuilder(25);
str.Append("(&(");
str.Append(PropertyManager.ObjectCategory);
str.Append("=attributeSchema)");
str.Append("(!(");
str.Append(PropertyManager.IsDefunct);
str.Append("=TRUE))");
if (((int)type & (int)PropertyTypes.Indexed) != 0)
{
str.Append("(");
str.Append(PropertyManager.SearchFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SearchFlags.IsIndexed);
str.Append(")");
}
if (((int)type & (int)PropertyTypes.InGlobalCatalog) != 0)
{
str.Append("(");
str.Append(PropertyManager.IsMemberOfPartialAttributeSet);
str.Append("=TRUE)");
}
str.Append(")"); // end filter
return GetAllProperties(context, _schemaEntry, str.ToString());
}
//
// This method returns only defunct properties
//
public ReadOnlyActiveDirectorySchemaPropertyCollection FindAllDefunctProperties()
{
CheckIfDisposed();
string filter = "(&(" + PropertyManager.ObjectCategory + "=attributeSchema)" +
"(" + PropertyManager.IsDefunct + "=TRUE))";
return GetAllProperties(context, _schemaEntry, filter);
}
public override DirectoryEntry GetDirectoryEntry()
{
CheckIfDisposed();
return DirectoryEntryManager.GetDirectoryEntry(context, Name);
}
public static ActiveDirectorySchema GetCurrentSchema()
{
return ActiveDirectorySchema.GetSchema(new DirectoryContext(DirectoryContextType.Forest));
}
#endregion public methods
#region public properties
public DirectoryServer SchemaRoleOwner
{
get
{
CheckIfDisposed();
if (_cachedSchemaRoleOwner == null)
{
_cachedSchemaRoleOwner = GetSchemaRoleOwner();
}
return _cachedSchemaRoleOwner;
}
}
#endregion public properties
#region private methods
internal static ReadOnlyActiveDirectorySchemaPropertyCollection GetAllProperties(DirectoryContext context, DirectoryEntry schemaEntry, string filter)
{
ArrayList propertyList = new ArrayList();
string[] propertiesToLoad = new string[3];
propertiesToLoad[0] = PropertyManager.LdapDisplayName;
propertiesToLoad[1] = PropertyManager.Cn;
propertiesToLoad[2] = PropertyManager.IsDefunct;
ADSearcher searcher = new ADSearcher(schemaEntry, filter, propertiesToLoad, SearchScope.OneLevel);
SearchResultCollection resCol = null;
try
{
resCol = searcher.FindAll();
foreach (SearchResult res in resCol)
{
string ldapDisplayName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.LdapDisplayName);
DirectoryEntry directoryEntry = res.GetDirectoryEntry();
directoryEntry.AuthenticationType = Utils.DefaultAuthType;
directoryEntry.Username = context.UserName;
directoryEntry.Password = context.Password;
bool isDefunct = false;
if ((res.Properties[PropertyManager.IsDefunct] != null) && (res.Properties[PropertyManager.IsDefunct].Count > 0))
{
isDefunct = (bool)res.Properties[PropertyManager.IsDefunct][0];
}
if (isDefunct)
{
string commonName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.Cn);
propertyList.Add(new ActiveDirectorySchemaProperty(context, commonName, ldapDisplayName, directoryEntry, schemaEntry));
}
else
{
propertyList.Add(new ActiveDirectorySchemaProperty(context, ldapDisplayName, directoryEntry, schemaEntry));
}
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
// dispose off the result collection
if (resCol != null)
{
resCol.Dispose();
}
}
return new ReadOnlyActiveDirectorySchemaPropertyCollection(propertyList);
}
internal static ReadOnlyActiveDirectorySchemaClassCollection GetAllClasses(DirectoryContext context, DirectoryEntry schemaEntry, string filter)
{
ArrayList classList = new ArrayList();
string[] propertiesToLoad = new string[3];
propertiesToLoad[0] = PropertyManager.LdapDisplayName;
propertiesToLoad[1] = PropertyManager.Cn;
propertiesToLoad[2] = PropertyManager.IsDefunct;
ADSearcher searcher = new ADSearcher(schemaEntry, filter, propertiesToLoad, SearchScope.OneLevel);
SearchResultCollection resCol = null;
try
{
resCol = searcher.FindAll();
foreach (SearchResult res in resCol)
{
string ldapDisplayName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.LdapDisplayName);
DirectoryEntry directoryEntry = res.GetDirectoryEntry();
directoryEntry.AuthenticationType = Utils.DefaultAuthType;
directoryEntry.Username = context.UserName;
directoryEntry.Password = context.Password;
bool isDefunct = false;
if ((res.Properties[PropertyManager.IsDefunct] != null) && (res.Properties[PropertyManager.IsDefunct].Count > 0))
{
isDefunct = (bool)res.Properties[PropertyManager.IsDefunct][0];
}
if (isDefunct)
{
string commonName = (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.Cn);
classList.Add(new ActiveDirectorySchemaClass(context, commonName, ldapDisplayName, directoryEntry, schemaEntry));
}
else
{
classList.Add(new ActiveDirectorySchemaClass(context, ldapDisplayName, directoryEntry, schemaEntry));
}
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
// dispose off the result collection
if (resCol != null)
{
resCol.Dispose();
}
}
return new ReadOnlyActiveDirectorySchemaClassCollection(classList);
}
private DirectoryServer GetSchemaRoleOwner()
{
try
{
_schemaEntry.RefreshCache();
if (context.isADAMConfigSet())
{
// ADAM
string adamInstName = Utils.GetAdamDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, _schemaEntry, PropertyManager.FsmoRoleOwner));
DirectoryContext adamInstContext = Utils.GetNewDirectoryContext(adamInstName, DirectoryContextType.DirectoryServer, context);
return new AdamInstance(adamInstContext, adamInstName);
}
else
{
// could be AD or adam server
DirectoryServer server = null;
DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if (Utils.CheckCapability(rootDSE, Capability.ActiveDirectory))
{
string dcName = Utils.GetDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, _schemaEntry, PropertyManager.FsmoRoleOwner));
DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context);
server = new DomainController(dcContext, dcName);
}
else
{
// ADAM case again
string adamInstName = Utils.GetAdamDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, _schemaEntry, PropertyManager.FsmoRoleOwner));
DirectoryContext adamInstContext = Utils.GetNewDirectoryContext(adamInstName, DirectoryContextType.DirectoryServer, context);
server = new AdamInstance(adamInstContext, adamInstName);
}
return server;
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
#endregion private methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Provider;
using Java.IO;
using CompressedVideoDemo.Helpers;
using System.Windows.Input;
using XamarinAndroidFFmpeg;
using Xamarin.Forms;
namespace CompressedVideoDemo.Droid.DS
{
internal class IntentHelper
{
static readonly Dictionary<int, Action<Result, Intent>> _CallbackDictionary = new Dictionary<int, Action<Result, Intent>>();
public struct RequestCodes
{
public const int RecordVideo = 103;
public const int PlayVideo = 104;
public const int CompressVideo = 106;
public const int SelectVideo = 105;
}
static Java.IO.File _destFile;
static Action<string> _callback;
static Activity CurrentActivity
{
get
{
return (Xamarin.Forms.Forms.Context as MainActivity);
}
}
#region Public Methods
public static void StartIntent(Intent intent, int requestCode, Action<Result, Intent> callback)
{
if (_CallbackDictionary.ContainsKey(requestCode))
_CallbackDictionary.Remove(requestCode);
_CallbackDictionary.Add(requestCode, callback);
(Xamarin.Forms.Forms.Context as Activity).StartActivityForResult(intent, requestCode);
}
public static void ActivityResult(int requestCode, Result resultCode, Intent data)
{
if (_callback == null)
return;
if (resultCode == Result.Ok)
{
if (requestCode == RequestCodes.RecordVideo)
{
_callback(_destFile.Path);
}
else if (requestCode == RequestCodes.CompressVideo)
{
}
else if (requestCode == RequestCodes.SelectVideo)
{
var destFilePath = ImageFilePath.GetPath(CurrentActivity, data.Data);
_callback(destFilePath);
}
else if (requestCode == RequestCodes.PlayVideo)
{
_callback(null);
}
}
}
public static bool IsMobileIntent(int code)
{
return code == (int)RequestCodes.RecordVideo
|| code == (int)RequestCodes.PlayVideo
|| code == (int)RequestCodes.CompressVideo
|| code == (int)RequestCodes.SelectVideo;
}
public static void RecordVideo(Action<string> callback)
{
_callback = callback;
_destFile = new File(FileHelper.CreateNewVideoPath());
Intent captureVideoIntent = new Intent(MediaStore.ActionVideoCapture);
captureVideoIntent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(_destFile));
// captureVideoIntent.PutExtra(MediaStore.ExtraVideoQuality, 1);
CurrentActivity.StartActivityForResult(captureVideoIntent, RequestCodes.RecordVideo);
}
public static void SelectVideo(Action<string> callback)
{
_callback = callback;
_destFile = new File(FileHelper.CreateNewVideoPath());
Intent selectVideoIntent = new Intent(Intent.ActionPick);
selectVideoIntent.SetType("video/*");
selectVideoIntent.SetAction(Intent.ActionGetContent);
CurrentActivity.StartActivityForResult(Intent.CreateChooser(selectVideoIntent, "Select Video"), RequestCodes.SelectVideo);
}
public static void CompressVideo(string inputPath, string outputPath, Action<string> callback)
{
Activity activity = new Activity();
_callback = callback;
ProgressDialog progress = new ProgressDialog(Forms.Context);
progress.Indeterminate = true;
progress.SetProgressStyle(ProgressDialogStyle.Spinner);
progress.SetMessage("Compressing Video. Please wait...");
progress.SetCancelable(false);
progress.Show();
Task.Run(() =>
{
var _workingDirectory = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var sourceMp4 = inputPath;
var destinationPath1 = outputPath;
FFMpeg ffmpeg = new FFMpeg(Android.App.Application.Context, _workingDirectory);
TransposeVideoFilter vfTranspose = new TransposeVideoFilter(TransposeVideoFilter.NINETY_CLOCKWISE);
var filters = new List<VideoFilter>();
filters.Add(vfTranspose);
var sourceClip = new Clip(System.IO.Path.Combine(_workingDirectory, sourceMp4)) { videoFilter = VideoFilter.Build(filters) };
var br = System.Environment.NewLine;
var onComplete = new MyCommand((_) =>
{
_callback(destinationPath1);
progress.Dismiss();
});
var onMessage = new MyCommand((message) =>
{
System.Console.WriteLine(message);
});
var callbacks = new FFMpegCallbacks(onComplete, onMessage);
string[] cmds = new string[] {
"-y",
"-i",
sourceClip.path,
"-strict", "experimental",
"-vcodec", "libx264",
"-preset", "ultrafast",
"-crf","30", "-acodec","aac", "-ar", "44100" ,
"-q:v", "20",
"-vf",sourceClip.videoFilter,
// "mp=eq2=1:1.68:0.3:1.25:1:0.96:1",
destinationPath1 ,
};
ffmpeg.Execute(cmds, callbacks);
});
}
public class MyCommand : ICommand
{
public delegate void ICommandOnExecute(object parameter = null);
public delegate bool ICommandOnCanExecute(object parameter);
private ICommandOnExecute _execute;
private ICommandOnCanExecute _canExecute;
public MyCommand(ICommandOnExecute onExecuteMethod)
{
_execute = onExecuteMethod;
}
public MyCommand(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod)
{
_execute = onExecuteMethod;
_canExecute = onCanExecuteMethod;
}
#region ICommand Members
public event EventHandler CanExecuteChanged
{
add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
}
public bool CanExecute(object parameter)
{
if (_canExecute == null && _execute != null)
return true;
return _canExecute.Invoke(parameter);
}
public void Execute(object parameter)
{
if (_execute == null)
return;
_execute.Invoke(parameter);
}
#endregion
}
public static void PlayVideo(string videoPath, Action<string> callback)
{
_callback = callback;
try
{
Intent playVideoIntent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(videoPath));
playVideoIntent.SetDataAndType(Android.Net.Uri.Parse(videoPath), "video/mp4");
CurrentActivity.StartActivityForResult(playVideoIntent, RequestCodes.PlayVideo);
}
catch (Exception ex)
{
}
}
#endregion
}
static class IntentHelpers
{
static readonly Dictionary<int, Action<Result, Intent>> _CallbackDictionary = new Dictionary<int, Action<Result, Intent>>();
internal static void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if (!_CallbackDictionary.ContainsKey(requestCode))
return;
_CallbackDictionary[requestCode].Invoke(resultCode, data);
_CallbackDictionary.Remove(requestCode);
}
public static void StartIntent(Intent intent, int requestCode, Action<Result, Intent> callback)
{
if (_CallbackDictionary.ContainsKey(requestCode))
_CallbackDictionary.Remove(requestCode);
_CallbackDictionary.Add(requestCode, callback);
(Xamarin.Forms.Forms.Context as Activity).StartActivityForResult(intent, requestCode);
}
}
}
| |
#region
/*
Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions
(http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu.
All rights reserved. http://code.google.com/p/msnp-sharp/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of Bas Geertsema or Xih Solutions nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
namespace MSNPSharp.P2P
{
using MSNPSharp;
using MSNPSharp.Apps;
using MSNPSharp.Core;
/// <summary>
/// New P2P handler
/// </summary>
public class P2PHandler : IDisposable
{
#region Events
/// <summary>
/// Occurs when interaction with user has required for a file transfer, activity.
/// Emoticons, display pictures and other msn objects are automatically accepted.
/// </summary>
public event EventHandler<P2PSessionEventArgs> InvitationReceived;
protected internal virtual void OnInvitationReceived(P2PSessionEventArgs e)
{
if (InvitationReceived != null)
InvitationReceived(this, e);
}
#endregion
#region Members
private SDGBridge sdgBridge;
private SLPHandler slpHandler;
private NSMessageHandler nsMessageHandler = null;
private P2PMessagePool slpMessagePool = new P2PMessagePool();
private List<P2PBridge> bridges = new List<P2PBridge>();
private List<P2PSession> p2pV1Sessions = new List<P2PSession>();
private List<P2PSession> p2pV2Sessions = new List<P2PSession>();
protected internal P2PHandler(NSMessageHandler nsHandler)
{
this.nsMessageHandler = nsHandler;
this.sdgBridge = new SDGBridge(nsHandler);
this.slpHandler = new SLPHandler(nsHandler);
}
#endregion
#region Properties
public SDGBridge SDGBridge
{
get
{
return sdgBridge;
}
}
#endregion
#region Public
#region RequestMsnObject & SendFile & AddTransfer
public ObjectTransfer RequestMsnObject(Contact remoteContact, MSNObject msnObject)
{
ObjectTransfer objectTransferApp = new ObjectTransfer(msnObject, remoteContact);
AddTransfer(objectTransferApp);
return objectTransferApp;
}
public FileTransfer SendFile(Contact remoteContact, string filename, FileStream fileStream)
{
FileTransfer fileTransferApp = new FileTransfer(remoteContact, fileStream, Path.GetFileName(filename));
AddTransfer(fileTransferApp);
return fileTransferApp;
}
public P2PSession AddTransfer(P2PApplication app)
{
P2PSession session = new P2PSession(app);
session.Closed += P2PSessionClosed;
if (app.P2PVersion == P2PVersion.P2PV2)
p2pV2Sessions.Add(session);
else
p2pV1Sessions.Add(session);
session.Invite();
return session;
}
#endregion
#region ProcessP2PMessage
public bool ProcessP2PMessage(P2PBridge bridge, Contact source, Guid sourceGuid, P2PMessage p2pMessage)
{
// 1) SLP BUFFERING: Combine splitted SLP messages
if (slpMessagePool.BufferMessage(ref p2pMessage))
{
// * Buffering: Not completed yet, we must wait next packets -OR-
// * Invalid packet received: Don't kill me, just ignore it...
return true;
}
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("Received P2PMessage from {0}\r\n{1}", bridge.ToString(), p2pMessage.ToDebugString()), GetType().Name);
// 2) CHECK SLP: Check destination, source, endpoints
SLPMessage slp = p2pMessage.IsSLPData ? p2pMessage.InnerMessage as SLPMessage : null;
if (slp != null)
{
if (!slpHandler.CheckSLPMessage(bridge, source, sourceGuid, p2pMessage, slp))
return true; // HANDLED, This SLP is not for us.
}
// 3) FIRST SLP MESSAGE: Create applications/sessions based on invitation
if (slp != null && slp is SLPRequestMessage &&
(slp as SLPRequestMessage).Method == "INVITE" &&
slp.ContentType == "application/x-msnmsgr-sessionreqbody")
{
uint appId = slp.BodyValues.ContainsKey("AppID") ? uint.Parse(slp.BodyValues["AppID"].Value) : 0;
Guid eufGuid = slp.BodyValues.ContainsKey("EUF-GUID") ? new Guid(slp.BodyValues["EUF-GUID"].Value) : Guid.Empty;
P2PVersion ver = slp.P2PVersion;
if (P2PApplication.IsRegistered(eufGuid, appId))
{
P2PSession newSession = FindSessionByCallId(slp.CallId, ver);
if (newSession == null)
{
newSession = new P2PSession(slp as SLPRequestMessage, p2pMessage, nsMessageHandler, bridge);
newSession.Closed += P2PSessionClosed;
if (newSession.Version == P2PVersion.P2PV2)
p2pV2Sessions.Add(newSession);
else
p2pV1Sessions.Add(newSession);
}
else
{
// P2PSession exists, bridge changed...
if (newSession.Bridge != bridge)
{
// BRIDGETODO
}
}
return true;
}
// Not registered application. Decline it without create a new session...
slpHandler.SendSLPStatus(bridge, p2pMessage, source, sourceGuid, 603, "Decline");
return true;
}
// 4) FIND SESSION: Search session by SessionId/ExpectedIdentifier
P2PSession session = FindSession(p2pMessage, slp);
if (session != null)
{
// ResetTimeoutTimer();
// Keep track of theremoteIdentifier
// Keep track of the remote identifier
session.remoteIdentifier = (p2pMessage.Version == P2PVersion.P2PV2) ?
p2pMessage.Header.Identifier + p2pMessage.Header.MessageSize :
p2pMessage.Header.Identifier;
// Session SLP
if (slp != null && slpHandler.HandleP2PSessionSignal(bridge, p2pMessage, slp, session))
return true;
// Session Data
if (slp == null && session.ProcessP2PData(bridge, p2pMessage))
return true;
}
return false;
}
#endregion
#region Dispose
public void Dispose()
{
lock (slpMessagePool)
slpMessagePool.Clear();
lock (p2pV1Sessions)
p2pV1Sessions.Clear();
lock (p2pV2Sessions)
p2pV2Sessions.Clear();
lock (bridges)
bridges.Clear();
sdgBridge.Dispose();
slpHandler.Dispose();
}
#endregion
#endregion
#region Internal & Protected
#region GetBridge & BridgeClosed
internal P2PBridge GetBridge(P2PSession session)
{
foreach (P2PBridge existing in bridges)
if (existing.SuitableFor(session))
return existing;
return nsMessageHandler.SDGBridge;
/*MSNP21TODO
P2PBridge bridge = new SBBridge(session);
bridge.BridgeClosed += BridgeClosed;
bridges.Add(bridge);
return bridge;
* */
}
private void BridgeClosed(object sender, EventArgs args)
{
P2PBridge bridge = sender as P2PBridge;
if (!bridges.Contains(bridge))
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, "Closed bridge not found in list", GetType().Name);
return;
}
bridges.Remove(bridge);
}
#endregion
#endregion
#region Private
#region FindSession & P2PSessionClosed
private P2PSession FindSessionByCallId(Guid callId, P2PVersion version)
{
List<P2PSession> sessions = (version == P2PVersion.P2PV2) ? p2pV2Sessions : p2pV1Sessions;
foreach (P2PSession session in sessions)
{
if (session.Invitation.CallId == callId)
return session;
}
return null;
}
private P2PSession FindSessionBySessionId(uint sessionId, P2PVersion version)
{
List<P2PSession> sessions = (version == P2PVersion.P2PV2) ? p2pV2Sessions : p2pV1Sessions;
foreach (P2PSession session in sessions)
{
if (session.SessionId == sessionId)
return session;
}
return null;
}
private P2PSession FindSessionByExpectedIdentifier(P2PMessage p2pMessage)
{
if (p2pMessage.Version == P2PVersion.P2PV2)
{
foreach (P2PSession session in p2pV2Sessions)
{
uint expected = session.RemoteIdentifier;
if (p2pMessage.Header.Identifier == expected)
return session;
}
}
else
{
foreach (P2PSession session in p2pV1Sessions)
{
uint expected = session.RemoteIdentifier + 1;
if (expected == session.RemoteBaseIdentifier)
expected++;
if (p2pMessage.Header.Identifier == expected)
return session;
}
}
return null;
}
private P2PSession FindSession(P2PMessage msg, SLPMessage slp)
{
P2PSession p2pSession = null;
uint sessionID = (msg != null) ? msg.Header.SessionId : 0;
if ((sessionID == 0) && (slp != null))
{
if (slp.BodyValues.ContainsKey("SessionID"))
{
if (!uint.TryParse(slp.BodyValues["SessionID"].Value, out sessionID))
{
Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning,
"Unable to parse SLP message SessionID", GetType().Name);
sessionID = 0;
}
}
if (sessionID == 0)
{
// We don't get a session ID in BYE requests
// So we need to find the session by its call ID
P2PVersion p2pVersion = slp.P2PVersion;
p2pSession = FindSessionByCallId(slp.CallId, p2pVersion);
if (p2pSession != null)
return p2pSession;
}
}
// Sometimes we only have a messageID to find the session with...
if ((sessionID == 0) && (msg.Header.Identifier != 0))
{
p2pSession = FindSessionByExpectedIdentifier(msg);
if (p2pSession != null)
return p2pSession;
}
if (sessionID != 0)
{
p2pSession = FindSessionBySessionId(sessionID, msg.Version);
if (p2pSession != null)
return p2pSession;
}
return null;
}
private void P2PSessionClosed(object sender, ContactEventArgs args)
{
P2PSession session = sender as P2PSession;
session.Closed -= P2PSessionClosed;
Trace.WriteLineIf(Settings.TraceSwitch.TraceVerbose,
String.Format("P2PSession {0} closed, removing", session.SessionId), GetType().Name);
if (session.Version == P2PVersion.P2PV2)
p2pV2Sessions.Remove(session);
else
p2pV1Sessions.Remove(session);
session.Dispose();
}
#endregion
#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 log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGAssetBroker")]
public class HGAssetBroker : ISharedRegionModule, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private IImprovedAssetCache m_Cache = null;
private IAssetService m_GridService;
private IAssetService m_HGService;
private Scene m_aScene;
private string m_LocalAssetServiceURI;
private bool m_Enabled = false;
private AssetPermissions m_AssetPerms;
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "HGAssetBroker"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("AssetServices", "");
if (name == Name)
{
IConfig assetConfig = source.Configs["AssetService"];
if (assetConfig == null)
{
m_log.Error("[HG ASSET CONNECTOR]: AssetService missing from OpenSim.ini");
return;
}
string localDll = assetConfig.GetString("LocalGridAssetService",
String.Empty);
string HGDll = assetConfig.GetString("HypergridAssetService",
String.Empty);
if (localDll == String.Empty)
{
m_log.Error("[HG ASSET CONNECTOR]: No LocalGridAssetService named in section AssetService");
return;
}
if (HGDll == String.Empty)
{
m_log.Error("[HG ASSET CONNECTOR]: No HypergridAssetService named in section AssetService");
return;
}
Object[] args = new Object[] { source };
m_GridService =
ServerUtils.LoadPlugin<IAssetService>(localDll,
args);
m_HGService =
ServerUtils.LoadPlugin<IAssetService>(HGDll,
args);
if (m_GridService == null)
{
m_log.Error("[HG ASSET CONNECTOR]: Can't load local asset service");
return;
}
if (m_HGService == null)
{
m_log.Error("[HG ASSET CONNECTOR]: Can't load hypergrid asset service");
return;
}
m_LocalAssetServiceURI = assetConfig.GetString("AssetServerURI", string.Empty);
if (m_LocalAssetServiceURI == string.Empty)
{
IConfig netConfig = source.Configs["Network"];
m_LocalAssetServiceURI = netConfig.GetString("asset_server_url", string.Empty);
}
if (m_LocalAssetServiceURI != string.Empty)
m_LocalAssetServiceURI = m_LocalAssetServiceURI.Trim('/');
IConfig hgConfig = source.Configs["HGAssetService"];
m_AssetPerms = new AssetPermissions(hgConfig); // it's ok if arg is null
m_Enabled = true;
m_log.Info("[HG ASSET CONNECTOR]: HG asset broker enabled");
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_aScene = scene;
m_aScene.RegisterModuleInterface<IAssetService>(this);
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
if (m_Cache == null)
{
m_Cache = scene.RequestModuleInterface<IImprovedAssetCache>();
if (!(m_Cache is ISharedRegionModule))
m_Cache = null;
}
m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled hypergrid asset broker for region {0}", scene.RegionInfo.RegionName);
if (m_Cache != null)
{
m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled asset caching for region {0}", scene.RegionInfo.RegionName);
}
}
private bool IsHG(string id)
{
Uri assetUri;
if (Uri.TryCreate(id, UriKind.Absolute, out assetUri) &&
assetUri.Scheme == Uri.UriSchemeHttp)
return true;
return false;
}
public AssetBase Get(string id)
{
//m_log.DebugFormat("[HG ASSET CONNECTOR]: Get {0}", id);
AssetBase asset = null;
if (m_Cache != null)
{
asset = m_Cache.Get(id);
if (asset != null)
return asset;
}
if (IsHG(id))
{
asset = m_HGService.Get(id);
if (asset != null)
{
// Now store it locally, if allowed
if (m_AssetPerms.AllowedImport(asset.Type))
m_GridService.Store(asset);
else
return null;
}
}
else
asset = m_GridService.Get(id);
if (m_Cache != null)
m_Cache.Cache(asset);
return asset;
}
public AssetBase GetCached(string id)
{
if (m_Cache != null)
return m_Cache.Get(id);
return null;
}
public AssetMetadata GetMetadata(string id)
{
AssetBase asset = null;
if (m_Cache != null)
{
if (m_Cache != null)
m_Cache.Get(id);
if (asset != null)
return asset.Metadata;
}
AssetMetadata metadata;
if (IsHG(id))
metadata = m_HGService.GetMetadata(id);
else
metadata = m_GridService.GetMetadata(id);
return metadata;
}
public byte[] GetData(string id)
{
AssetBase asset = null;
if (m_Cache != null)
{
if (m_Cache != null)
m_Cache.Get(id);
if (asset != null)
return asset.Data;
}
if (IsHG(id))
return m_HGService.GetData(id);
else
return m_GridService.GetData(id);
}
public bool Get(string id, Object sender, AssetRetrieved handler)
{
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset != null)
{
Util.FireAndForget(delegate { handler(id, sender, asset); });
return true;
}
if (IsHG(id))
{
return m_HGService.Get(id, sender, delegate (string assetID, Object s, AssetBase a)
{
if (m_Cache != null)
m_Cache.Cache(a);
handler(assetID, s, a);
});
}
else
{
return m_GridService.Get(id, sender, delegate (string assetID, Object s, AssetBase a)
{
if (m_Cache != null)
m_Cache.Cache(a);
handler(assetID, s, a);
});
}
}
public string Store(AssetBase asset)
{
bool isHG = IsHG(asset.ID);
if ((m_Cache != null) && !isHG)
// Don't store it in the cache if the asset is to
// be sent to the other grid, because this is already
// a copy of the local asset.
m_Cache.Cache(asset);
if (asset.Local)
{
if (m_Cache != null)
m_Cache.Cache(asset);
return asset.ID;
}
string id = string.Empty;
if (IsHG(asset.ID))
{
if (m_AssetPerms.AllowedExport(asset.Type))
id = m_HGService.Store(asset);
else
return String.Empty;
}
else
id = m_GridService.Store(asset);
if (id != String.Empty)
{
// Placing this here, so that this work with old asset servers that don't send any reply back
// SynchronousRestObjectRequester returns somethins that is not an empty string
if (id != null)
asset.ID = id;
if (m_Cache != null)
m_Cache.Cache(asset);
}
return id;
}
public bool UpdateContent(string id, byte[] data)
{
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset != null)
{
asset.Data = data;
m_Cache.Cache(asset);
}
if (IsHG(id))
return m_HGService.UpdateContent(id, data);
else
return m_GridService.UpdateContent(id, data);
}
public bool Delete(string id)
{
if (m_Cache != null)
m_Cache.Expire(id);
bool result = false;
if (IsHG(id))
result = m_HGService.Delete(id);
else
result = m_GridService.Delete(id);
if (result && m_Cache != null)
m_Cache.Expire(id);
return result;
}
}
}
| |
#if !UNITY_METRO && !UNITY_WEBPLAYER && (UNITY_PRO_LICENSE || !(UNITY_ANDROID || UNITY_IPHONE))
#define UTT_SOCKETS_SUPPORTED
#endif
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using UnityEngine;
using UnityTest.IntegrationTestRunner;
#if UTT_SOCKETS_SUPPORTED
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
#endif
#if UNITY_EDITOR
using UnityEditorInternal;
#endif
namespace UnityTest
{
public class TestRunnerConfigurator
{
public static string integrationTestsNetwork = "networkconfig.txt";
public static string batchRunFileMarker = "batchrun.txt";
public static string testScenesToRun = "testscenes.txt";
public static string previousScenes = "previousScenes.txt";
public bool isBatchRun { get; private set; }
public bool sendResultsOverNetwork { get; private set; }
#if UTT_SOCKETS_SUPPORTED
private readonly List<IPEndPoint> m_IPEndPointList = new List<IPEndPoint>();
#endif
public TestRunnerConfigurator()
{
CheckForBatchMode();
CheckForSendingResultsOverNetwork();
}
#if UNITY_EDITOR
public UnityEditor.EditorBuildSettingsScene[] GetPreviousScenesToRestore()
{
string text = null;
if (Application.isEditor)
{
text = GetTextFromTempFile(previousScenes);
}
if(text != null)
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(UnityEditor.EditorBuildSettingsScene[]));
using(var textReader = new StringReader(text))
{
try
{
return (UnityEditor.EditorBuildSettingsScene[] )serializer.Deserialize(textReader);
}
catch
{
return null;
}
}
}
return null;
}
#endif
public string GetIntegrationTestScenes(int testSceneNum)
{
string text;
if (Application.isEditor)
text = GetTextFromTempFile(testScenesToRun);
else
text = GetTextFromTextAsset(testScenesToRun);
List<string> sceneList = new List<string>();
foreach (var line in text.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries))
{
sceneList.Add(line.ToString());
}
if (testSceneNum < sceneList.Count)
return sceneList.ElementAt(testSceneNum);
else
return null;
}
private void CheckForSendingResultsOverNetwork()
{
#if UTT_SOCKETS_SUPPORTED
string text;
if (Application.isEditor)
text = GetTextFromTempFile(integrationTestsNetwork);
else
text = GetTextFromTextAsset(integrationTestsNetwork);
if (text == null) return;
sendResultsOverNetwork = true;
m_IPEndPointList.Clear();
foreach (var line in text.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries))
{
var idx = line.IndexOf(':');
if (idx == -1) throw new Exception(line);
var ip = line.Substring(0, idx);
var port = line.Substring(idx + 1);
m_IPEndPointList.Add(new IPEndPoint(IPAddress.Parse(ip), Int32.Parse(port)));
}
#endif // if UTT_SOCKETS_SUPPORTED
}
private static string GetTextFromTextAsset(string fileName)
{
var nameWithoutExtension = fileName.Substring(0, fileName.LastIndexOf('.'));
var resultpathFile = Resources.Load(nameWithoutExtension) as TextAsset;
return resultpathFile != null ? resultpathFile.text : null;
}
private static string GetTextFromTempFile(string fileName)
{
string text = null;
try
{
#if UNITY_EDITOR && !UNITY_WEBPLAYER
text = File.ReadAllText(Path.Combine("Temp", fileName));
#endif
}
catch
{
return null;
}
return text;
}
private void CheckForBatchMode()
{
#if IMITATE_BATCH_MODE
isBatchRun = true;
#elif UNITY_EDITOR
if (Application.isEditor && InternalEditorUtility.inBatchMode)
isBatchRun = true;
#else
if (GetTextFromTextAsset(batchRunFileMarker) != null) isBatchRun = true;
#endif
}
public static List<string> GetAvailableNetworkIPs()
{
#if UTT_SOCKETS_SUPPORTED
if (!NetworkInterface.GetIsNetworkAvailable())
return new List<String>{IPAddress.Loopback.ToString()};
var ipList = new List<UnicastIPAddressInformation>();
var allIpsList = new List<UnicastIPAddressInformation>();
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
if (netInterface.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 &&
netInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet)
continue;
var ipAdresses = netInterface.GetIPProperties().UnicastAddresses
.Where(a => a.Address.AddressFamily == AddressFamily.InterNetwork);
allIpsList.AddRange(ipAdresses);
if (netInterface.OperationalStatus != OperationalStatus.Up) continue;
ipList.AddRange(ipAdresses);
}
//On Mac 10.10 all interfaces return OperationalStatus.Unknown, thus this workaround
if(!ipList.Any()) return allIpsList.Select(i => i.Address.ToString()).ToList();
// sort ip list by their masks to predict which ip belongs to lan network
ipList.Sort((ip1, ip2) =>
{
var mask1 = BitConverter.ToInt32(ip1.IPv4Mask.GetAddressBytes().Reverse().ToArray(), 0);
var mask2 = BitConverter.ToInt32(ip2.IPv4Mask.GetAddressBytes().Reverse().ToArray(), 0);
return mask2.CompareTo(mask1);
});
if (ipList.Count == 0)
return new List<String> { IPAddress.Loopback.ToString() };
return ipList.Select(i => i.Address.ToString()).ToList();
#else
return new List<string>();
#endif // if UTT_SOCKETS_SUPPORTED
}
public ITestRunnerCallback ResolveNetworkConnection()
{
#if UTT_SOCKETS_SUPPORTED
var nrsList = m_IPEndPointList.Select(ipEndPoint => new NetworkResultSender(ipEndPoint.Address.ToString(), ipEndPoint.Port)).ToList();
var timeout = TimeSpan.FromSeconds(30);
DateTime startTime = DateTime.Now;
while ((DateTime.Now - startTime) < timeout)
{
foreach (var networkResultSender in nrsList)
{
try
{
if (!networkResultSender.Ping()) continue;
}
catch (Exception e)
{
Debug.LogException(e);
sendResultsOverNetwork = false;
return null;
}
return networkResultSender;
}
Thread.Sleep(500);
}
Debug.LogError("Couldn't connect to the server: " + string.Join(", ", m_IPEndPointList.Select(ipep => ipep.Address + ":" + ipep.Port).ToArray()));
sendResultsOverNetwork = false;
#endif // if UTT_SOCKETS_SUPPORTED
return null;
}
}
}
| |
/*
* Copyright 2014, 2015 James Geall
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using IdentityServer3.Core.Models;
namespace Core.MongoDb.Tests
{
public static class TestData
{
public static Client ClientAllProperties()
{
return new Client
{
AbsoluteRefreshTokenLifetime = 10,
AccessTokenLifetime = 20,
AccessTokenType = AccessTokenType.Reference,
EnableLocalLogin = false,
AllowRememberConsent = true,
AlwaysSendClientClaims = true,
AuthorizationCodeLifetime = 30,
ClientId = "123",
ClientName = "TEST",
ClientSecrets = new List<Secret>()
{
new Secret("secret","secret", WellKnownTime){Type = "secret type"},
new Secret("newsecret"),
},
ClientUri = "clientUri",
AllowedCustomGrantTypes = new List<string>()
{
"Restriction1",
"Restriction2"
},
Enabled = true,
Flow = Flows.AuthorizationCode,
IdentityProviderRestrictions = new[] { "idpr" }.ToList(),
IdentityTokenLifetime = 40,
LogoUri = "uri:logo",
PostLogoutRedirectUris = { "uri:logout" },
RedirectUris = { "uri:redirect" },
RefreshTokenExpiration = TokenExpiration.Sliding,
RefreshTokenUsage = TokenUsage.ReUse,
RequireConsent = true,
AllowedScopes = { "restriction1", "restriction2", "restriction3" },
SlidingRefreshTokenLifetime = 50,
IncludeJwtId = true,
PrefixClientClaims = true,
Claims = new List<Claim>
{
new Claim("client1", "value1"),
new Claim("client2", "value2"),
new Claim("client3", "value3"),
new Claim("withType", "value", "typeOfValue")
},
AllowClientCredentialsOnly = true,
UpdateAccessTokenClaimsOnRefresh = true,
AllowedCorsOrigins = new List<string> { "CorsOrigin1", "CorsOrigin2", "CorsOrigin3", },
AllowAccessToAllScopes = true,
AllowAccessToAllCustomGrantTypes = true,
AllowAccessTokensViaBrowser = false,
LogoutSessionRequired = false,
RequireSignOutPrompt = false,
LogoutUri = "somelogouturi"
};
}
public static Scope ScopeAllProperties()
{
return new Scope
{
Name = "all",
DisplayName = "displayName",
Claims = new List<ScopeClaim>
{
new ScopeClaim
{
Name = "claim1",
AlwaysIncludeInIdToken = false,
Description = "claim1 description"
},
new ScopeClaim
{
Name = "claim2",
AlwaysIncludeInIdToken = true,
Description = "claim2 description"
},
},
ClaimsRule = "claimsRule",
Description = "Description",
Emphasize = true,
Enabled = false,
IncludeAllClaimsForUser = true,
Required = true,
ShowInDiscoveryDocument = false,
Type = ScopeType.Identity,
AllowUnrestrictedIntrospection = true,
ScopeSecrets = new List<Secret>() {
new Secret("secret1"),
new Secret("secret2", "description", new DateTimeOffset(2000, 1, 1, 1, 1, 1, 1, TimeSpan.Zero))}
};
}
public static Scope ScopeMandatoryProperties()
{
return new Scope
{
Name = "mandatory",
DisplayName = "displayName"
};
}
public static AuthorizationCode AuthorizationCode(string subjectId = null)
{
var ac = AuthorizationCodeWithoutNonce(subjectId);
ac.Nonce = "test";
return ac;
}
public static AuthorizationCode AuthorizationCodeWithoutNonce(string subjectId = null)
{
return new AuthorizationCode
{
IsOpenId = true,
CreationTime = WellKnownTime,
Client = Client(),
RedirectUri = "uri:redirect",
RequestedScopes = Scopes(),
Subject = Subject(subjectId),
WasConsentShown = true,
CodeChallenge = "codeChallenge",
CodeChallengeMethod = "challengeMethod",
SessionId = "sessionId"
};
}
private static DateTimeOffset WellKnownTime
{
get { return new DateTimeOffset(2000, 1, 1, 1, 1, 1, 0, TimeSpan.Zero); }
}
private static Client Client()
{
return ClientAllProperties();
}
public static IEnumerable<Scope> Scopes()
{
yield return ScopeAllProperties();
yield return ScopeMandatoryProperties();
}
private static ClaimsPrincipal Subject(string subjectId)
{
return new ClaimsPrincipal(
new ClaimsIdentity(
Claims(subjectId), "authtype"
));
}
private static List<Claim> Claims(string subjectId)
{
return new List<Claim>
{
new Claim("sub", subjectId ?? "foo"),
new Claim("name", "bar"),
new Claim("email", "baz@qux.com"),
new Claim("scope", "scope1"),
new Claim("scope", "scope2"),
new Claim("guid", "561E12FE7BC24F5E8CAC029B91E8ADE8"),
new Claim("valueType", "value", "typeOfValue")
};
}
private static List<Claim> ClientCredentialClaims(string subjectId)
{
return new List<Claim>
{
new Claim("client_id", subjectId ?? "foo"),
new Claim("scope", "scope1"),
new Claim("scope", "scope2"),
new Claim("guid", "561E12FE7BC24F5E8CAC029B91E8ADE8"),
new Claim("valueType", "value", "typeOfValue")
};
}
public static RefreshToken RefreshToken(string subject = null)
{
return new RefreshToken
{
AccessToken = Token(subject),
CreationTime = new DateTimeOffset(2000, 1, 1, 1, 1, 1, 0, TimeSpan.Zero),
LifeTime = 100,
Version = 10,
Subject = new ClaimsPrincipal(new ClaimsIdentity(Claims(subject)))
};
}
public static Token Token(string subject = null)
{
return new Token
{
Audience = "audience",
Claims = Claims(subject),
Client = ClientAllProperties(),
CreationTime = new DateTimeOffset(2000, 1, 1, 1, 1, 1, 0, TimeSpan.Zero),
Issuer = "issuer",
Lifetime = 200,
Type = "tokenType",
Version = 10
};
}
public static Token ClientCredentialsToken(string client = null)
{
return new Token
{
Audience = "audience",
Claims = ClientCredentialClaims(client),
Client = ClientAllProperties(),
CreationTime = new DateTimeOffset(2000, 1, 1, 1, 1, 1, 0, TimeSpan.Zero),
Issuer = "issuer",
Lifetime = 200,
Type = "tokenType",
Version = 10
};
}
private static readonly JsonSerializer Serializer = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
public static string ToTestableString<T>(T subject)
{
return JObject.FromObject(subject, Serializer).ToString();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedConversionCustomVariableServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetConversionCustomVariableRequestObject()
{
moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient> mockGrpcClient = new moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient>(moq::MockBehavior.Strict);
GetConversionCustomVariableRequest request = new GetConversionCustomVariableRequest
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
};
gagvr::ConversionCustomVariable expectedResponse = new gagvr::ConversionCustomVariable
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Id = -6774108720365892680L,
ConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Tag = "tag843ed2e4",
Status = gagve::ConversionCustomVariableStatusEnum.Types.ConversionCustomVariableStatus.Paused,
OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
mockGrpcClient.Setup(x => x.GetConversionCustomVariable(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversionCustomVariableServiceClient client = new ConversionCustomVariableServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ConversionCustomVariable response = client.GetConversionCustomVariable(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetConversionCustomVariableRequestObjectAsync()
{
moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient> mockGrpcClient = new moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient>(moq::MockBehavior.Strict);
GetConversionCustomVariableRequest request = new GetConversionCustomVariableRequest
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
};
gagvr::ConversionCustomVariable expectedResponse = new gagvr::ConversionCustomVariable
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Id = -6774108720365892680L,
ConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Tag = "tag843ed2e4",
Status = gagve::ConversionCustomVariableStatusEnum.Types.ConversionCustomVariableStatus.Paused,
OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
mockGrpcClient.Setup(x => x.GetConversionCustomVariableAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ConversionCustomVariable>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversionCustomVariableServiceClient client = new ConversionCustomVariableServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ConversionCustomVariable responseCallSettings = await client.GetConversionCustomVariableAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::ConversionCustomVariable responseCancellationToken = await client.GetConversionCustomVariableAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetConversionCustomVariable()
{
moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient> mockGrpcClient = new moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient>(moq::MockBehavior.Strict);
GetConversionCustomVariableRequest request = new GetConversionCustomVariableRequest
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
};
gagvr::ConversionCustomVariable expectedResponse = new gagvr::ConversionCustomVariable
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Id = -6774108720365892680L,
ConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Tag = "tag843ed2e4",
Status = gagve::ConversionCustomVariableStatusEnum.Types.ConversionCustomVariableStatus.Paused,
OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
mockGrpcClient.Setup(x => x.GetConversionCustomVariable(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversionCustomVariableServiceClient client = new ConversionCustomVariableServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ConversionCustomVariable response = client.GetConversionCustomVariable(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetConversionCustomVariableAsync()
{
moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient> mockGrpcClient = new moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient>(moq::MockBehavior.Strict);
GetConversionCustomVariableRequest request = new GetConversionCustomVariableRequest
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
};
gagvr::ConversionCustomVariable expectedResponse = new gagvr::ConversionCustomVariable
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Id = -6774108720365892680L,
ConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Tag = "tag843ed2e4",
Status = gagve::ConversionCustomVariableStatusEnum.Types.ConversionCustomVariableStatus.Paused,
OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
mockGrpcClient.Setup(x => x.GetConversionCustomVariableAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ConversionCustomVariable>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversionCustomVariableServiceClient client = new ConversionCustomVariableServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ConversionCustomVariable responseCallSettings = await client.GetConversionCustomVariableAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::ConversionCustomVariable responseCancellationToken = await client.GetConversionCustomVariableAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetConversionCustomVariableResourceNames()
{
moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient> mockGrpcClient = new moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient>(moq::MockBehavior.Strict);
GetConversionCustomVariableRequest request = new GetConversionCustomVariableRequest
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
};
gagvr::ConversionCustomVariable expectedResponse = new gagvr::ConversionCustomVariable
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Id = -6774108720365892680L,
ConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Tag = "tag843ed2e4",
Status = gagve::ConversionCustomVariableStatusEnum.Types.ConversionCustomVariableStatus.Paused,
OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
mockGrpcClient.Setup(x => x.GetConversionCustomVariable(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversionCustomVariableServiceClient client = new ConversionCustomVariableServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ConversionCustomVariable response = client.GetConversionCustomVariable(request.ResourceNameAsConversionCustomVariableName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetConversionCustomVariableResourceNamesAsync()
{
moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient> mockGrpcClient = new moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient>(moq::MockBehavior.Strict);
GetConversionCustomVariableRequest request = new GetConversionCustomVariableRequest
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
};
gagvr::ConversionCustomVariable expectedResponse = new gagvr::ConversionCustomVariable
{
ResourceNameAsConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Id = -6774108720365892680L,
ConversionCustomVariableName = gagvr::ConversionCustomVariableName.FromCustomerConversionCustomVariable("[CUSTOMER_ID]", "[CONVERSION_CUSTOM_VARIABLE_ID]"),
Tag = "tag843ed2e4",
Status = gagve::ConversionCustomVariableStatusEnum.Types.ConversionCustomVariableStatus.Paused,
OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
mockGrpcClient.Setup(x => x.GetConversionCustomVariableAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ConversionCustomVariable>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversionCustomVariableServiceClient client = new ConversionCustomVariableServiceClientImpl(mockGrpcClient.Object, null);
gagvr::ConversionCustomVariable responseCallSettings = await client.GetConversionCustomVariableAsync(request.ResourceNameAsConversionCustomVariableName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::ConversionCustomVariable responseCancellationToken = await client.GetConversionCustomVariableAsync(request.ResourceNameAsConversionCustomVariableName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateConversionCustomVariablesRequestObject()
{
moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient> mockGrpcClient = new moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient>(moq::MockBehavior.Strict);
MutateConversionCustomVariablesRequest request = new MutateConversionCustomVariablesRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new ConversionCustomVariableOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateConversionCustomVariablesResponse expectedResponse = new MutateConversionCustomVariablesResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateConversionCustomVariableResult(),
},
};
mockGrpcClient.Setup(x => x.MutateConversionCustomVariables(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversionCustomVariableServiceClient client = new ConversionCustomVariableServiceClientImpl(mockGrpcClient.Object, null);
MutateConversionCustomVariablesResponse response = client.MutateConversionCustomVariables(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateConversionCustomVariablesRequestObjectAsync()
{
moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient> mockGrpcClient = new moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient>(moq::MockBehavior.Strict);
MutateConversionCustomVariablesRequest request = new MutateConversionCustomVariablesRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new ConversionCustomVariableOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateConversionCustomVariablesResponse expectedResponse = new MutateConversionCustomVariablesResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateConversionCustomVariableResult(),
},
};
mockGrpcClient.Setup(x => x.MutateConversionCustomVariablesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateConversionCustomVariablesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversionCustomVariableServiceClient client = new ConversionCustomVariableServiceClientImpl(mockGrpcClient.Object, null);
MutateConversionCustomVariablesResponse responseCallSettings = await client.MutateConversionCustomVariablesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateConversionCustomVariablesResponse responseCancellationToken = await client.MutateConversionCustomVariablesAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateConversionCustomVariables()
{
moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient> mockGrpcClient = new moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient>(moq::MockBehavior.Strict);
MutateConversionCustomVariablesRequest request = new MutateConversionCustomVariablesRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new ConversionCustomVariableOperation(),
},
};
MutateConversionCustomVariablesResponse expectedResponse = new MutateConversionCustomVariablesResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateConversionCustomVariableResult(),
},
};
mockGrpcClient.Setup(x => x.MutateConversionCustomVariables(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ConversionCustomVariableServiceClient client = new ConversionCustomVariableServiceClientImpl(mockGrpcClient.Object, null);
MutateConversionCustomVariablesResponse response = client.MutateConversionCustomVariables(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateConversionCustomVariablesAsync()
{
moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient> mockGrpcClient = new moq::Mock<ConversionCustomVariableService.ConversionCustomVariableServiceClient>(moq::MockBehavior.Strict);
MutateConversionCustomVariablesRequest request = new MutateConversionCustomVariablesRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new ConversionCustomVariableOperation(),
},
};
MutateConversionCustomVariablesResponse expectedResponse = new MutateConversionCustomVariablesResponse
{
PartialFailureError = new gr::Status(),
Results =
{
new MutateConversionCustomVariableResult(),
},
};
mockGrpcClient.Setup(x => x.MutateConversionCustomVariablesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateConversionCustomVariablesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ConversionCustomVariableServiceClient client = new ConversionCustomVariableServiceClientImpl(mockGrpcClient.Object, null);
MutateConversionCustomVariablesResponse responseCallSettings = await client.MutateConversionCustomVariablesAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateConversionCustomVariablesResponse responseCancellationToken = await client.MutateConversionCustomVariablesAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.UserInterface;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.Chat;
using osu.Game.Users;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays.Chat
{
public class ChatLine : CompositeDrawable
{
public const float LEFT_PADDING = default_message_padding + default_horizontal_padding * 2;
private const float default_message_padding = 200;
protected virtual float MessagePadding => default_message_padding;
private const float default_horizontal_padding = 15;
protected virtual float HorizontalPadding => default_horizontal_padding;
protected virtual float TextSize => 20;
private Color4 customUsernameColour;
private OsuSpriteText timestamp;
public ChatLine(Message message)
{
Message = message;
Padding = new MarginPadding { Left = HorizontalPadding, Right = HorizontalPadding };
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
}
[Resolved(CanBeNull = true)]
private ChannelManager chatManager { get; set; }
private Message message;
private OsuSpriteText username;
private LinkFlowContainer contentFlow;
public LinkFlowContainer ContentFlow => contentFlow;
public Message Message
{
get => message;
set
{
if (message == value) return;
message = MessageFormatter.FormatMessage(value);
if (!IsLoaded)
return;
updateMessageContent();
}
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
customUsernameColour = colours.ChatBlue;
}
private bool senderHasBackground => !string.IsNullOrEmpty(message.Sender.Colour);
protected override void LoadComplete()
{
base.LoadComplete();
bool hasBackground = senderHasBackground;
Drawable effectedUsername = username = new OsuSpriteText
{
Colour = hasBackground ? customUsernameColour : username_colours[message.Sender.Id % username_colours.Length],
Font = OsuFont.GetFont(size: TextSize, weight: FontWeight.Bold, italics: true)
};
if (hasBackground)
{
// Background effect
effectedUsername = new Container
{
AutoSizeAxes = Axes.Both,
Masking = true,
CornerRadius = 4,
EdgeEffect = new EdgeEffectParameters
{
Roundness = 1,
Offset = new Vector2(0, 3),
Radius = 3,
Colour = Color4.Black.Opacity(0.3f),
Type = EdgeEffectType.Shadow,
},
// Drop shadow effect
Child = new Container
{
AutoSizeAxes = Axes.Both,
Masking = true,
CornerRadius = 4,
EdgeEffect = new EdgeEffectParameters
{
Radius = 1,
Colour = OsuColour.FromHex(message.Sender.Colour),
Type = EdgeEffectType.Shadow,
},
Padding = new MarginPadding { Left = 3, Right = 3, Bottom = 1, Top = -3 },
Y = 3,
Child = username,
}
};
}
InternalChildren = new Drawable[]
{
new Container
{
Size = new Vector2(MessagePadding, TextSize),
Children = new Drawable[]
{
timestamp = new OsuSpriteText
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Font = OsuFont.GetFont(size: TextSize * 0.75f, weight: FontWeight.SemiBold, fixedWidth: true)
},
new MessageSender(message.Sender)
{
AutoSizeAxes = Axes.Both,
Origin = Anchor.TopRight,
Anchor = Anchor.TopRight,
Child = effectedUsername,
},
}
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding { Left = MessagePadding + HorizontalPadding },
Children = new Drawable[]
{
contentFlow = new LinkFlowContainer(t =>
{
if (Message.IsAction)
{
t.Font = OsuFont.GetFont(italics: true);
if (senderHasBackground)
t.Colour = OsuColour.FromHex(message.Sender.Colour);
}
t.Font = t.Font.With(size: TextSize);
})
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
}
}
}
};
updateMessageContent();
FinishTransforms(true);
}
private void updateMessageContent()
{
this.FadeTo(message is LocalEchoMessage ? 0.4f : 1.0f, 500, Easing.OutQuint);
timestamp.FadeTo(message is LocalEchoMessage ? 0 : 1, 500, Easing.OutQuint);
timestamp.Text = $@"{message.Timestamp.LocalDateTime:HH:mm:ss}";
username.Text = $@"{message.Sender.Username}" + (senderHasBackground || message.IsAction ? "" : ":");
// remove non-existent channels from the link list
message.Links.RemoveAll(link => link.Action == LinkAction.OpenChannel && chatManager?.AvailableChannels.Any(c => c.Name == link.Argument) != true);
contentFlow.Clear();
contentFlow.AddLinks(message.DisplayContent, message.Links);
}
private class MessageSender : OsuClickableContainer, IHasContextMenu
{
private readonly User sender;
private Action startChatAction;
public MessageSender(User sender)
{
this.sender = sender;
}
[BackgroundDependencyLoader(true)]
private void load(UserProfileOverlay profile, ChannelManager chatManager)
{
Action = () => profile?.ShowUser(sender);
startChatAction = () => chatManager?.OpenPrivateChannel(sender);
}
public MenuItem[] ContextMenuItems => new MenuItem[]
{
new OsuMenuItem("View Profile", MenuItemType.Highlighted, Action),
new OsuMenuItem("Start Chat", MenuItemType.Standard, startChatAction),
};
}
private static readonly Color4[] username_colours =
{
OsuColour.FromHex("588c7e"),
OsuColour.FromHex("b2a367"),
OsuColour.FromHex("c98f65"),
OsuColour.FromHex("bc5151"),
OsuColour.FromHex("5c8bd6"),
OsuColour.FromHex("7f6ab7"),
OsuColour.FromHex("a368ad"),
OsuColour.FromHex("aa6880"),
OsuColour.FromHex("6fad9b"),
OsuColour.FromHex("f2e394"),
OsuColour.FromHex("f2ae72"),
OsuColour.FromHex("f98f8a"),
OsuColour.FromHex("7daef4"),
OsuColour.FromHex("a691f2"),
OsuColour.FromHex("c894d3"),
OsuColour.FromHex("d895b0"),
OsuColour.FromHex("53c4a1"),
OsuColour.FromHex("eace5c"),
OsuColour.FromHex("ea8c47"),
OsuColour.FromHex("fc4f4f"),
OsuColour.FromHex("3d94ea"),
OsuColour.FromHex("7760ea"),
OsuColour.FromHex("af52c6"),
OsuColour.FromHex("e25696"),
OsuColour.FromHex("677c66"),
OsuColour.FromHex("9b8732"),
OsuColour.FromHex("8c5129"),
OsuColour.FromHex("8c3030"),
OsuColour.FromHex("1f5d91"),
OsuColour.FromHex("4335a5"),
OsuColour.FromHex("812a96"),
OsuColour.FromHex("992861"),
};
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Serialize and deserialize scene objects.
/// </summary>
/// This should really be in OpenSim.Framework.Serialization but this would mean circular dependency problems
/// right now - hopefully this isn't forever.
public class SceneObjectSerializer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static IUserManagement m_UserManagement;
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name="xmlData"></param>
/// <returns>The scene object deserialized. Null on failure.</returns>
public static SceneObjectGroup FromOriginalXmlFormat(string xmlData)
{
String fixedData = ExternalRepresentationUtils.SanitizeXml(xmlData);
using (XmlTextReader wrappedReader = new XmlTextReader(fixedData, XmlNodeType.Element, null))
{
using (XmlReader reader = XmlReader.Create(wrappedReader, new XmlReaderSettings() { IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Fragment }))
{
try {
return FromOriginalXmlFormat(reader);
}
catch (Exception e)
{
m_log.Error("[SERIALIZER]: Deserialization of xml failed ", e);
Util.LogFailedXML("[SERIALIZER]:", fixedData);
return null;
}
}
}
}
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name="xmlData"></param>
/// <returns>The scene object deserialized. Null on failure.</returns>
public static SceneObjectGroup FromOriginalXmlFormat(XmlReader reader)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
int linkNum;
reader.ReadToFollowing("RootPart");
reader.ReadToFollowing("SceneObjectPart");
SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(reader));
reader.ReadToFollowing("OtherParts");
if (reader.ReadToDescendant("Part"))
{
do
{
if (reader.ReadToDescendant("SceneObjectPart"))
{
SceneObjectPart part = SceneObjectPart.FromXml(reader);
linkNum = part.LinkNum;
sceneObject.AddPart(part);
part.LinkNum = linkNum;
part.TrimPermissions();
}
}
while (reader.ReadToNextSibling("Part"));
}
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(reader);
return sceneObject;
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject)
{
return ToOriginalXmlFormat(sceneObject, true);
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <param name="doScriptStates">Control whether script states are also serialized.</para>
/// <returns></returns>
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject, bool doScriptStates)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
ToOriginalXmlFormat(sceneObject, writer, doScriptStates);
}
return sw.ToString();
}
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer, bool doScriptStates)
{
ToOriginalXmlFormat(sceneObject, writer, doScriptStates, false);
}
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject, string scriptedState)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
ToOriginalXmlFormat(sceneObject, writer, false, true);
writer.WriteRaw(scriptedState);
writer.WriteEndElement();
}
return sw.ToString();
}
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <param name="writer"></param>
/// <param name="noRootElement">If false, don't write the enclosing SceneObjectGroup element</param>
/// <returns></returns>
public static void ToOriginalXmlFormat(
SceneObjectGroup sceneObject, XmlTextWriter writer, bool doScriptStates, bool noRootElement)
{
// m_log.DebugFormat("[SERIALIZER]: Starting serialization of {0}", sceneObject.Name);
// int time = System.Environment.TickCount;
if (!noRootElement)
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
writer.WriteStartElement(String.Empty, "RootPart", String.Empty);
ToXmlFormat(sceneObject.RootPart, writer);
writer.WriteEndElement();
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
SceneObjectPart[] parts = sceneObject.Parts;
for (int i = 0; i < parts.Length; i++)
{
SceneObjectPart part = parts[i];
if (part.UUID != sceneObject.RootPart.UUID)
{
writer.WriteStartElement(String.Empty, "Part", String.Empty);
ToXmlFormat(part, writer);
writer.WriteEndElement();
}
}
writer.WriteEndElement(); // OtherParts
if (doScriptStates)
sceneObject.SaveScriptedState(writer);
if (!noRootElement)
writer.WriteEndElement(); // SceneObjectGroup
// m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0}, {1}ms", sceneObject.Name, System.Environment.TickCount - time);
}
protected static void ToXmlFormat(SceneObjectPart part, XmlTextWriter writer)
{
SOPToXml2(writer, part, new Dictionary<string, object>());
}
public static SceneObjectGroup FromXml2Format(string xmlData)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlData);
XmlNodeList parts = doc.GetElementsByTagName("SceneObjectPart");
if (parts.Count == 0)
{
m_log.Error("[SERIALIZER]: Deserialization of xml failed: No SceneObjectPart nodes");
Util.LogFailedXML("[SERIALIZER]:", xmlData);
return null;
}
StringReader sr = new StringReader(parts[0].OuterXml);
XmlTextReader reader = new XmlTextReader(sr);
SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(reader));
reader.Close();
sr.Close();
// Then deal with the rest
for (int i = 1; i < parts.Count; i++)
{
sr = new StringReader(parts[i].OuterXml);
reader = new XmlTextReader(sr);
SceneObjectPart part = SceneObjectPart.FromXml(reader);
int originalLinkNum = part.LinkNum;
sceneObject.AddPart(part);
// SceneObjectGroup.AddPart() tries to be smart and automatically set the LinkNum.
// We override that here
if (originalLinkNum != 0)
part.LinkNum = originalLinkNum;
reader.Close();
sr.Close();
}
XmlNodeList keymotion = doc.GetElementsByTagName("KeyframeMotion");
if (keymotion.Count > 0)
sceneObject.RootPart.KeyframeMotion = KeyframeMotion.FromData(sceneObject, Convert.FromBase64String(keymotion[0].InnerText));
else
sceneObject.RootPart.KeyframeMotion = null;
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(doc);
return sceneObject;
}
catch (Exception e)
{
m_log.Error("[SERIALIZER]: Deserialization of xml failed ", e);
Util.LogFailedXML("[SERIALIZER]:", xmlData);
return null;
}
}
/// <summary>
/// Serialize a scene object to the 'xml2' format.
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static string ToXml2Format(SceneObjectGroup sceneObject)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
SOGToXml2(writer, sceneObject, new Dictionary<string,object>());
}
return sw.ToString();
}
}
/// <summary>
/// Modifies a SceneObjectGroup.
/// </summary>
/// <param name="sog">The object</param>
/// <returns>Whether the object was actually modified</returns>
public delegate bool SceneObjectModifier(SceneObjectGroup sog);
/// <summary>
/// Modifies an object by deserializing it; applying 'modifier' to each SceneObjectGroup; and reserializing.
/// </summary>
/// <param name="assetId">The object's UUID</param>
/// <param name="data">Serialized data</param>
/// <param name="modifier">The function to run on each SceneObjectGroup</param>
/// <returns>The new serialized object's data, or null if an error occurred</returns>
public static byte[] ModifySerializedObject(UUID assetId, byte[] data, SceneObjectModifier modifier)
{
List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
CoalescedSceneObjects coa = null;
string xmlData = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(data));
if (CoalescedSceneObjectsSerializer.TryFromXml(xmlData, out coa))
{
// m_log.DebugFormat("[SERIALIZER]: Loaded coalescence {0} has {1} objects", assetId, coa.Count);
if (coa.Objects.Count == 0)
{
m_log.WarnFormat("[SERIALIZER]: Aborting load of coalesced object from asset {0} as it has zero loaded components", assetId);
return null;
}
sceneObjects.AddRange(coa.Objects);
}
else
{
SceneObjectGroup deserializedObject = FromOriginalXmlFormat(xmlData);
if (deserializedObject != null)
{
sceneObjects.Add(deserializedObject);
}
else
{
m_log.WarnFormat("[SERIALIZER]: Aborting load of object from asset {0} as deserialization failed", assetId);
return null;
}
}
bool modified = false;
foreach (SceneObjectGroup sog in sceneObjects)
{
if (modifier(sog))
modified = true;
}
if (modified)
{
if (coa != null)
data = Utils.StringToBytes(CoalescedSceneObjectsSerializer.ToXml(coa));
else
data = Utils.StringToBytes(ToOriginalXmlFormat(sceneObjects[0]));
}
return data;
}
#region manual serialization
private static Dictionary<string, Action<SceneObjectPart, XmlReader>> m_SOPXmlProcessors
= new Dictionary<string, Action<SceneObjectPart, XmlReader>>();
private static Dictionary<string, Action<TaskInventoryItem, XmlReader>> m_TaskInventoryXmlProcessors
= new Dictionary<string, Action<TaskInventoryItem, XmlReader>>();
private static Dictionary<string, Action<PrimitiveBaseShape, XmlReader>> m_ShapeXmlProcessors
= new Dictionary<string, Action<PrimitiveBaseShape, XmlReader>>();
static SceneObjectSerializer()
{
#region SOPXmlProcessors initialization
m_SOPXmlProcessors.Add("AllowedDrop", ProcessAllowedDrop);
m_SOPXmlProcessors.Add("CreatorID", ProcessCreatorID);
m_SOPXmlProcessors.Add("CreatorData", ProcessCreatorData);
m_SOPXmlProcessors.Add("FolderID", ProcessFolderID);
m_SOPXmlProcessors.Add("InventorySerial", ProcessInventorySerial);
m_SOPXmlProcessors.Add("TaskInventory", ProcessTaskInventory);
m_SOPXmlProcessors.Add("UUID", ProcessUUID);
m_SOPXmlProcessors.Add("LocalId", ProcessLocalId);
m_SOPXmlProcessors.Add("Name", ProcessName);
m_SOPXmlProcessors.Add("Material", ProcessMaterial);
m_SOPXmlProcessors.Add("PassTouches", ProcessPassTouches);
m_SOPXmlProcessors.Add("PassCollisions", ProcessPassCollisions);
m_SOPXmlProcessors.Add("RegionHandle", ProcessRegionHandle);
m_SOPXmlProcessors.Add("ScriptAccessPin", ProcessScriptAccessPin);
m_SOPXmlProcessors.Add("GroupPosition", ProcessGroupPosition);
m_SOPXmlProcessors.Add("OffsetPosition", ProcessOffsetPosition);
m_SOPXmlProcessors.Add("RotationOffset", ProcessRotationOffset);
m_SOPXmlProcessors.Add("Velocity", ProcessVelocity);
m_SOPXmlProcessors.Add("AngularVelocity", ProcessAngularVelocity);
m_SOPXmlProcessors.Add("Acceleration", ProcessAcceleration);
m_SOPXmlProcessors.Add("Description", ProcessDescription);
m_SOPXmlProcessors.Add("Color", ProcessColor);
m_SOPXmlProcessors.Add("Text", ProcessText);
m_SOPXmlProcessors.Add("SitName", ProcessSitName);
m_SOPXmlProcessors.Add("TouchName", ProcessTouchName);
m_SOPXmlProcessors.Add("LinkNum", ProcessLinkNum);
m_SOPXmlProcessors.Add("ClickAction", ProcessClickAction);
m_SOPXmlProcessors.Add("Shape", ProcessShape);
m_SOPXmlProcessors.Add("Scale", ProcessScale);
m_SOPXmlProcessors.Add("SitTargetOrientation", ProcessSitTargetOrientation);
m_SOPXmlProcessors.Add("SitTargetPosition", ProcessSitTargetPosition);
m_SOPXmlProcessors.Add("SitTargetPositionLL", ProcessSitTargetPositionLL);
m_SOPXmlProcessors.Add("SitTargetOrientationLL", ProcessSitTargetOrientationLL);
m_SOPXmlProcessors.Add("ParentID", ProcessParentID);
m_SOPXmlProcessors.Add("CreationDate", ProcessCreationDate);
m_SOPXmlProcessors.Add("Category", ProcessCategory);
m_SOPXmlProcessors.Add("SalePrice", ProcessSalePrice);
m_SOPXmlProcessors.Add("ObjectSaleType", ProcessObjectSaleType);
m_SOPXmlProcessors.Add("OwnershipCost", ProcessOwnershipCost);
m_SOPXmlProcessors.Add("GroupID", ProcessGroupID);
m_SOPXmlProcessors.Add("OwnerID", ProcessOwnerID);
m_SOPXmlProcessors.Add("LastOwnerID", ProcessLastOwnerID);
m_SOPXmlProcessors.Add("BaseMask", ProcessBaseMask);
m_SOPXmlProcessors.Add("OwnerMask", ProcessOwnerMask);
m_SOPXmlProcessors.Add("GroupMask", ProcessGroupMask);
m_SOPXmlProcessors.Add("EveryoneMask", ProcessEveryoneMask);
m_SOPXmlProcessors.Add("NextOwnerMask", ProcessNextOwnerMask);
m_SOPXmlProcessors.Add("Flags", ProcessFlags);
m_SOPXmlProcessors.Add("CollisionSound", ProcessCollisionSound);
m_SOPXmlProcessors.Add("CollisionSoundVolume", ProcessCollisionSoundVolume);
m_SOPXmlProcessors.Add("MediaUrl", ProcessMediaUrl);
m_SOPXmlProcessors.Add("AttachedPos", ProcessAttachedPos);
m_SOPXmlProcessors.Add("DynAttrs", ProcessDynAttrs);
m_SOPXmlProcessors.Add("TextureAnimation", ProcessTextureAnimation);
m_SOPXmlProcessors.Add("ParticleSystem", ProcessParticleSystem);
m_SOPXmlProcessors.Add("PayPrice0", ProcessPayPrice0);
m_SOPXmlProcessors.Add("PayPrice1", ProcessPayPrice1);
m_SOPXmlProcessors.Add("PayPrice2", ProcessPayPrice2);
m_SOPXmlProcessors.Add("PayPrice3", ProcessPayPrice3);
m_SOPXmlProcessors.Add("PayPrice4", ProcessPayPrice4);
m_SOPXmlProcessors.Add("Buoyancy", ProcessBuoyancy);
m_SOPXmlProcessors.Add("Force", ProcessForce);
m_SOPXmlProcessors.Add("Torque", ProcessTorque);
m_SOPXmlProcessors.Add("VolumeDetectActive", ProcessVolumeDetectActive);
m_SOPXmlProcessors.Add("Vehicle", ProcessVehicle);
m_SOPXmlProcessors.Add("RotationAxisLocks", ProcessRotationAxisLocks);
m_SOPXmlProcessors.Add("PhysicsShapeType", ProcessPhysicsShapeType);
m_SOPXmlProcessors.Add("Density", ProcessDensity);
m_SOPXmlProcessors.Add("Friction", ProcessFriction);
m_SOPXmlProcessors.Add("Bounce", ProcessBounce);
m_SOPXmlProcessors.Add("GravityModifier", ProcessGravityModifier);
m_SOPXmlProcessors.Add("CameraEyeOffset", ProcessCameraEyeOffset);
m_SOPXmlProcessors.Add("CameraAtOffset", ProcessCameraAtOffset);
m_SOPXmlProcessors.Add("SoundID", ProcessSoundID);
m_SOPXmlProcessors.Add("SoundGain", ProcessSoundGain);
m_SOPXmlProcessors.Add("SoundFlags", ProcessSoundFlags);
m_SOPXmlProcessors.Add("SoundRadius", ProcessSoundRadius);
m_SOPXmlProcessors.Add("SoundQueueing", ProcessSoundQueueing);
#endregion
#region TaskInventoryXmlProcessors initialization
m_TaskInventoryXmlProcessors.Add("AssetID", ProcessTIAssetID);
m_TaskInventoryXmlProcessors.Add("BasePermissions", ProcessTIBasePermissions);
m_TaskInventoryXmlProcessors.Add("CreationDate", ProcessTICreationDate);
m_TaskInventoryXmlProcessors.Add("CreatorID", ProcessTICreatorID);
m_TaskInventoryXmlProcessors.Add("CreatorData", ProcessTICreatorData);
m_TaskInventoryXmlProcessors.Add("Description", ProcessTIDescription);
m_TaskInventoryXmlProcessors.Add("EveryonePermissions", ProcessTIEveryonePermissions);
m_TaskInventoryXmlProcessors.Add("Flags", ProcessTIFlags);
m_TaskInventoryXmlProcessors.Add("GroupID", ProcessTIGroupID);
m_TaskInventoryXmlProcessors.Add("GroupPermissions", ProcessTIGroupPermissions);
m_TaskInventoryXmlProcessors.Add("InvType", ProcessTIInvType);
m_TaskInventoryXmlProcessors.Add("ItemID", ProcessTIItemID);
m_TaskInventoryXmlProcessors.Add("OldItemID", ProcessTIOldItemID);
m_TaskInventoryXmlProcessors.Add("LastOwnerID", ProcessTILastOwnerID);
m_TaskInventoryXmlProcessors.Add("Name", ProcessTIName);
m_TaskInventoryXmlProcessors.Add("NextPermissions", ProcessTINextPermissions);
m_TaskInventoryXmlProcessors.Add("OwnerID", ProcessTIOwnerID);
m_TaskInventoryXmlProcessors.Add("CurrentPermissions", ProcessTICurrentPermissions);
m_TaskInventoryXmlProcessors.Add("ParentID", ProcessTIParentID);
m_TaskInventoryXmlProcessors.Add("ParentPartID", ProcessTIParentPartID);
m_TaskInventoryXmlProcessors.Add("PermsGranter", ProcessTIPermsGranter);
m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask);
m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType);
m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged);
#endregion
#region ShapeXmlProcessors initialization
m_ShapeXmlProcessors.Add("ProfileCurve", ProcessShpProfileCurve);
m_ShapeXmlProcessors.Add("TextureEntry", ProcessShpTextureEntry);
m_ShapeXmlProcessors.Add("ExtraParams", ProcessShpExtraParams);
m_ShapeXmlProcessors.Add("PathBegin", ProcessShpPathBegin);
m_ShapeXmlProcessors.Add("PathCurve", ProcessShpPathCurve);
m_ShapeXmlProcessors.Add("PathEnd", ProcessShpPathEnd);
m_ShapeXmlProcessors.Add("PathRadiusOffset", ProcessShpPathRadiusOffset);
m_ShapeXmlProcessors.Add("PathRevolutions", ProcessShpPathRevolutions);
m_ShapeXmlProcessors.Add("PathScaleX", ProcessShpPathScaleX);
m_ShapeXmlProcessors.Add("PathScaleY", ProcessShpPathScaleY);
m_ShapeXmlProcessors.Add("PathShearX", ProcessShpPathShearX);
m_ShapeXmlProcessors.Add("PathShearY", ProcessShpPathShearY);
m_ShapeXmlProcessors.Add("PathSkew", ProcessShpPathSkew);
m_ShapeXmlProcessors.Add("PathTaperX", ProcessShpPathTaperX);
m_ShapeXmlProcessors.Add("PathTaperY", ProcessShpPathTaperY);
m_ShapeXmlProcessors.Add("PathTwist", ProcessShpPathTwist);
m_ShapeXmlProcessors.Add("PathTwistBegin", ProcessShpPathTwistBegin);
m_ShapeXmlProcessors.Add("PCode", ProcessShpPCode);
m_ShapeXmlProcessors.Add("ProfileBegin", ProcessShpProfileBegin);
m_ShapeXmlProcessors.Add("ProfileEnd", ProcessShpProfileEnd);
m_ShapeXmlProcessors.Add("ProfileHollow", ProcessShpProfileHollow);
m_ShapeXmlProcessors.Add("Scale", ProcessShpScale);
m_ShapeXmlProcessors.Add("LastAttachPoint", ProcessShpLastAttach);
m_ShapeXmlProcessors.Add("State", ProcessShpState);
m_ShapeXmlProcessors.Add("ProfileShape", ProcessShpProfileShape);
m_ShapeXmlProcessors.Add("HollowShape", ProcessShpHollowShape);
m_ShapeXmlProcessors.Add("SculptTexture", ProcessShpSculptTexture);
m_ShapeXmlProcessors.Add("SculptType", ProcessShpSculptType);
// Ignore "SculptData"; this element is deprecated
m_ShapeXmlProcessors.Add("FlexiSoftness", ProcessShpFlexiSoftness);
m_ShapeXmlProcessors.Add("FlexiTension", ProcessShpFlexiTension);
m_ShapeXmlProcessors.Add("FlexiDrag", ProcessShpFlexiDrag);
m_ShapeXmlProcessors.Add("FlexiGravity", ProcessShpFlexiGravity);
m_ShapeXmlProcessors.Add("FlexiWind", ProcessShpFlexiWind);
m_ShapeXmlProcessors.Add("FlexiForceX", ProcessShpFlexiForceX);
m_ShapeXmlProcessors.Add("FlexiForceY", ProcessShpFlexiForceY);
m_ShapeXmlProcessors.Add("FlexiForceZ", ProcessShpFlexiForceZ);
m_ShapeXmlProcessors.Add("LightColorR", ProcessShpLightColorR);
m_ShapeXmlProcessors.Add("LightColorG", ProcessShpLightColorG);
m_ShapeXmlProcessors.Add("LightColorB", ProcessShpLightColorB);
m_ShapeXmlProcessors.Add("LightColorA", ProcessShpLightColorA);
m_ShapeXmlProcessors.Add("LightRadius", ProcessShpLightRadius);
m_ShapeXmlProcessors.Add("LightCutoff", ProcessShpLightCutoff);
m_ShapeXmlProcessors.Add("LightFalloff", ProcessShpLightFalloff);
m_ShapeXmlProcessors.Add("LightIntensity", ProcessShpLightIntensity);
m_ShapeXmlProcessors.Add("FlexiEntry", ProcessShpFlexiEntry);
m_ShapeXmlProcessors.Add("LightEntry", ProcessShpLightEntry);
m_ShapeXmlProcessors.Add("SculptEntry", ProcessShpSculptEntry);
m_ShapeXmlProcessors.Add("Media", ProcessShpMedia);
#endregion
}
#region SOPXmlProcessors
private static void ProcessAllowedDrop(SceneObjectPart obj, XmlReader reader)
{
obj.AllowedDrop = Util.ReadBoolean(reader);
}
private static void ProcessCreatorID(SceneObjectPart obj, XmlReader reader)
{
obj.CreatorID = Util.ReadUUID(reader, "CreatorID");
}
private static void ProcessCreatorData(SceneObjectPart obj, XmlReader reader)
{
obj.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty);
}
private static void ProcessFolderID(SceneObjectPart obj, XmlReader reader)
{
obj.FolderID = Util.ReadUUID(reader, "FolderID");
}
private static void ProcessInventorySerial(SceneObjectPart obj, XmlReader reader)
{
obj.InventorySerial = (uint)reader.ReadElementContentAsInt("InventorySerial", String.Empty);
}
private static void ProcessTaskInventory(SceneObjectPart obj, XmlReader reader)
{
obj.TaskInventory = ReadTaskInventory(reader, "TaskInventory");
}
private static void ProcessUUID(SceneObjectPart obj, XmlReader reader)
{
obj.UUID = Util.ReadUUID(reader, "UUID");
}
private static void ProcessLocalId(SceneObjectPart obj, XmlReader reader)
{
obj.LocalId = (uint)reader.ReadElementContentAsLong("LocalId", String.Empty);
}
private static void ProcessName(SceneObjectPart obj, XmlReader reader)
{
obj.Name = reader.ReadElementString("Name");
}
private static void ProcessMaterial(SceneObjectPart obj, XmlReader reader)
{
obj.Material = (byte)reader.ReadElementContentAsInt("Material", String.Empty);
}
private static void ProcessPassTouches(SceneObjectPart obj, XmlReader reader)
{
obj.PassTouches = Util.ReadBoolean(reader);
}
private static void ProcessPassCollisions(SceneObjectPart obj, XmlReader reader)
{
obj.PassCollisions = Util.ReadBoolean(reader);
}
private static void ProcessRegionHandle(SceneObjectPart obj, XmlReader reader)
{
obj.RegionHandle = (ulong)reader.ReadElementContentAsLong("RegionHandle", String.Empty);
}
private static void ProcessScriptAccessPin(SceneObjectPart obj, XmlReader reader)
{
obj.ScriptAccessPin = reader.ReadElementContentAsInt("ScriptAccessPin", String.Empty);
}
private static void ProcessGroupPosition(SceneObjectPart obj, XmlReader reader)
{
obj.GroupPosition = Util.ReadVector(reader, "GroupPosition");
}
private static void ProcessOffsetPosition(SceneObjectPart obj, XmlReader reader)
{
obj.OffsetPosition = Util.ReadVector(reader, "OffsetPosition"); ;
}
private static void ProcessRotationOffset(SceneObjectPart obj, XmlReader reader)
{
obj.RotationOffset = Util.ReadQuaternion(reader, "RotationOffset");
}
private static void ProcessVelocity(SceneObjectPart obj, XmlReader reader)
{
obj.Velocity = Util.ReadVector(reader, "Velocity");
}
private static void ProcessAngularVelocity(SceneObjectPart obj, XmlReader reader)
{
obj.AngularVelocity = Util.ReadVector(reader, "AngularVelocity");
}
private static void ProcessAcceleration(SceneObjectPart obj, XmlReader reader)
{
obj.Acceleration = Util.ReadVector(reader, "Acceleration");
}
private static void ProcessDescription(SceneObjectPart obj, XmlReader reader)
{
obj.Description = reader.ReadElementString("Description");
}
private static void ProcessColor(SceneObjectPart obj, XmlReader reader)
{
reader.ReadStartElement("Color");
if (reader.Name == "R")
{
float r = reader.ReadElementContentAsFloat("R", String.Empty);
float g = reader.ReadElementContentAsFloat("G", String.Empty);
float b = reader.ReadElementContentAsFloat("B", String.Empty);
float a = reader.ReadElementContentAsFloat("A", String.Empty);
obj.Color = Color.FromArgb((int)a, (int)r, (int)g, (int)b);
reader.ReadEndElement();
}
}
private static void ProcessText(SceneObjectPart obj, XmlReader reader)
{
obj.Text = reader.ReadElementString("Text", String.Empty);
}
private static void ProcessSitName(SceneObjectPart obj, XmlReader reader)
{
obj.SitName = reader.ReadElementString("SitName", String.Empty);
}
private static void ProcessTouchName(SceneObjectPart obj, XmlReader reader)
{
obj.TouchName = reader.ReadElementString("TouchName", String.Empty);
}
private static void ProcessLinkNum(SceneObjectPart obj, XmlReader reader)
{
obj.LinkNum = reader.ReadElementContentAsInt("LinkNum", String.Empty);
}
private static void ProcessClickAction(SceneObjectPart obj, XmlReader reader)
{
obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty);
}
private static void ProcessRotationAxisLocks(SceneObjectPart obj, XmlReader reader)
{
obj.RotationAxisLocks = (byte)reader.ReadElementContentAsInt("RotationAxisLocks", String.Empty);
}
private static void ProcessPhysicsShapeType(SceneObjectPart obj, XmlReader reader)
{
obj.PhysicsShapeType = (byte)reader.ReadElementContentAsInt("PhysicsShapeType", String.Empty);
}
private static void ProcessDensity(SceneObjectPart obj, XmlReader reader)
{
obj.Density = reader.ReadElementContentAsFloat("Density", String.Empty);
}
private static void ProcessFriction(SceneObjectPart obj, XmlReader reader)
{
obj.Friction = reader.ReadElementContentAsFloat("Friction", String.Empty);
}
private static void ProcessBounce(SceneObjectPart obj, XmlReader reader)
{
obj.Restitution = reader.ReadElementContentAsFloat("Bounce", String.Empty);
}
private static void ProcessGravityModifier(SceneObjectPart obj, XmlReader reader)
{
obj.GravityModifier = reader.ReadElementContentAsFloat("GravityModifier", String.Empty);
}
private static void ProcessCameraEyeOffset(SceneObjectPart obj, XmlReader reader)
{
obj.SetCameraEyeOffset(Util.ReadVector(reader, "CameraEyeOffset"));
}
private static void ProcessCameraAtOffset(SceneObjectPart obj, XmlReader reader)
{
obj.SetCameraAtOffset(Util.ReadVector(reader, "CameraAtOffset"));
}
private static void ProcessSoundID(SceneObjectPart obj, XmlReader reader)
{
obj.Sound = Util.ReadUUID(reader, "SoundID");
}
private static void ProcessSoundGain(SceneObjectPart obj, XmlReader reader)
{
obj.SoundGain = reader.ReadElementContentAsDouble("SoundGain", String.Empty);
}
private static void ProcessSoundFlags(SceneObjectPart obj, XmlReader reader)
{
obj.SoundFlags = (byte)reader.ReadElementContentAsInt("SoundFlags", String.Empty);
}
private static void ProcessSoundRadius(SceneObjectPart obj, XmlReader reader)
{
obj.SoundRadius = reader.ReadElementContentAsDouble("SoundRadius", String.Empty);
}
private static void ProcessSoundQueueing(SceneObjectPart obj, XmlReader reader)
{
obj.SoundQueueing = Util.ReadBoolean(reader);
}
private static void ProcessVehicle(SceneObjectPart obj, XmlReader reader)
{
SOPVehicle vehicle = SOPVehicle.FromXml2(reader);
if (vehicle == null)
{
obj.VehicleParams = null;
m_log.DebugFormat(
"[SceneObjectSerializer]: Parsing Vehicle for object part {0} {1} encountered errors. Please see earlier log entries.",
obj.Name, obj.UUID);
}
else
{
obj.VehicleParams = vehicle;
}
}
private static void ProcessShape(SceneObjectPart obj, XmlReader reader)
{
List<string> errorNodeNames;
obj.Shape = ReadShape(reader, "Shape", out errorNodeNames, obj);
if (errorNodeNames != null)
{
m_log.DebugFormat(
"[SceneObjectSerializer]: Parsing PrimitiveBaseShape for object part {0} {1} encountered errors in properties {2}.",
obj.Name, obj.UUID, string.Join(", ", errorNodeNames.ToArray()));
}
}
private static void ProcessScale(SceneObjectPart obj, XmlReader reader)
{
obj.Scale = Util.ReadVector(reader, "Scale");
}
private static void ProcessSitTargetOrientation(SceneObjectPart obj, XmlReader reader)
{
obj.SitTargetOrientation = Util.ReadQuaternion(reader, "SitTargetOrientation");
}
private static void ProcessSitTargetPosition(SceneObjectPart obj, XmlReader reader)
{
obj.SitTargetPosition = Util.ReadVector(reader, "SitTargetPosition");
}
private static void ProcessSitTargetPositionLL(SceneObjectPart obj, XmlReader reader)
{
obj.SitTargetPositionLL = Util.ReadVector(reader, "SitTargetPositionLL");
}
private static void ProcessSitTargetOrientationLL(SceneObjectPart obj, XmlReader reader)
{
obj.SitTargetOrientationLL = Util.ReadQuaternion(reader, "SitTargetOrientationLL");
}
private static void ProcessParentID(SceneObjectPart obj, XmlReader reader)
{
string str = reader.ReadElementContentAsString("ParentID", String.Empty);
obj.ParentID = Convert.ToUInt32(str);
}
private static void ProcessCreationDate(SceneObjectPart obj, XmlReader reader)
{
obj.CreationDate = reader.ReadElementContentAsInt("CreationDate", String.Empty);
}
private static void ProcessCategory(SceneObjectPart obj, XmlReader reader)
{
obj.Category = (uint)reader.ReadElementContentAsInt("Category", String.Empty);
}
private static void ProcessSalePrice(SceneObjectPart obj, XmlReader reader)
{
obj.SalePrice = reader.ReadElementContentAsInt("SalePrice", String.Empty);
}
private static void ProcessObjectSaleType(SceneObjectPart obj, XmlReader reader)
{
obj.ObjectSaleType = (byte)reader.ReadElementContentAsInt("ObjectSaleType", String.Empty);
}
private static void ProcessOwnershipCost(SceneObjectPart obj, XmlReader reader)
{
obj.OwnershipCost = reader.ReadElementContentAsInt("OwnershipCost", String.Empty);
}
private static void ProcessGroupID(SceneObjectPart obj, XmlReader reader)
{
obj.GroupID = Util.ReadUUID(reader, "GroupID");
}
private static void ProcessOwnerID(SceneObjectPart obj, XmlReader reader)
{
obj.OwnerID = Util.ReadUUID(reader, "OwnerID");
}
private static void ProcessLastOwnerID(SceneObjectPart obj, XmlReader reader)
{
obj.LastOwnerID = Util.ReadUUID(reader, "LastOwnerID");
}
private static void ProcessBaseMask(SceneObjectPart obj, XmlReader reader)
{
obj.BaseMask = (uint)reader.ReadElementContentAsInt("BaseMask", String.Empty);
}
private static void ProcessOwnerMask(SceneObjectPart obj, XmlReader reader)
{
obj.OwnerMask = (uint)reader.ReadElementContentAsInt("OwnerMask", String.Empty);
}
private static void ProcessGroupMask(SceneObjectPart obj, XmlReader reader)
{
obj.GroupMask = (uint)reader.ReadElementContentAsInt("GroupMask", String.Empty);
}
private static void ProcessEveryoneMask(SceneObjectPart obj, XmlReader reader)
{
obj.EveryoneMask = (uint)reader.ReadElementContentAsInt("EveryoneMask", String.Empty);
}
private static void ProcessNextOwnerMask(SceneObjectPart obj, XmlReader reader)
{
obj.NextOwnerMask = (uint)reader.ReadElementContentAsInt("NextOwnerMask", String.Empty);
}
private static void ProcessFlags(SceneObjectPart obj, XmlReader reader)
{
obj.Flags = Util.ReadEnum<PrimFlags>(reader, "Flags");
}
private static void ProcessCollisionSound(SceneObjectPart obj, XmlReader reader)
{
obj.CollisionSound = Util.ReadUUID(reader, "CollisionSound");
}
private static void ProcessCollisionSoundVolume(SceneObjectPart obj, XmlReader reader)
{
obj.CollisionSoundVolume = reader.ReadElementContentAsFloat("CollisionSoundVolume", String.Empty);
}
private static void ProcessMediaUrl(SceneObjectPart obj, XmlReader reader)
{
obj.MediaUrl = reader.ReadElementContentAsString("MediaUrl", String.Empty);
}
private static void ProcessAttachedPos(SceneObjectPart obj, XmlReader reader)
{
obj.AttachedPos = Util.ReadVector(reader, "AttachedPos");
}
private static void ProcessDynAttrs(SceneObjectPart obj, XmlReader reader)
{
obj.DynAttrs.ReadXml(reader);
}
private static void ProcessTextureAnimation(SceneObjectPart obj, XmlReader reader)
{
obj.TextureAnimation = Convert.FromBase64String(reader.ReadElementContentAsString("TextureAnimation", String.Empty));
}
private static void ProcessParticleSystem(SceneObjectPart obj, XmlReader reader)
{
obj.ParticleSystem = Convert.FromBase64String(reader.ReadElementContentAsString("ParticleSystem", String.Empty));
}
private static void ProcessPayPrice0(SceneObjectPart obj, XmlReader reader)
{
obj.PayPrice[0] = (int)reader.ReadElementContentAsInt("PayPrice0", String.Empty);
}
private static void ProcessPayPrice1(SceneObjectPart obj, XmlReader reader)
{
obj.PayPrice[1] = (int)reader.ReadElementContentAsInt("PayPrice1", String.Empty);
}
private static void ProcessPayPrice2(SceneObjectPart obj, XmlReader reader)
{
obj.PayPrice[2] = (int)reader.ReadElementContentAsInt("PayPrice2", String.Empty);
}
private static void ProcessPayPrice3(SceneObjectPart obj, XmlReader reader)
{
obj.PayPrice[3] = (int)reader.ReadElementContentAsInt("PayPrice3", String.Empty);
}
private static void ProcessPayPrice4(SceneObjectPart obj, XmlReader reader)
{
obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty);
}
private static void ProcessBuoyancy(SceneObjectPart obj, XmlReader reader)
{
obj.Buoyancy = (float)reader.ReadElementContentAsFloat("Buoyancy", String.Empty);
}
private static void ProcessForce(SceneObjectPart obj, XmlReader reader)
{
obj.Force = Util.ReadVector(reader, "Force");
}
private static void ProcessTorque(SceneObjectPart obj, XmlReader reader)
{
obj.Torque = Util.ReadVector(reader, "Torque");
}
private static void ProcessVolumeDetectActive(SceneObjectPart obj, XmlReader reader)
{
obj.VolumeDetectActive = Util.ReadBoolean(reader);
}
#endregion
#region TaskInventoryXmlProcessors
private static void ProcessTIAssetID(TaskInventoryItem item, XmlReader reader)
{
item.AssetID = Util.ReadUUID(reader, "AssetID");
}
private static void ProcessTIBasePermissions(TaskInventoryItem item, XmlReader reader)
{
item.BasePermissions = (uint)reader.ReadElementContentAsInt("BasePermissions", String.Empty);
}
private static void ProcessTICreationDate(TaskInventoryItem item, XmlReader reader)
{
item.CreationDate = (uint)reader.ReadElementContentAsInt("CreationDate", String.Empty);
}
private static void ProcessTICreatorID(TaskInventoryItem item, XmlReader reader)
{
item.CreatorID = Util.ReadUUID(reader, "CreatorID");
}
private static void ProcessTICreatorData(TaskInventoryItem item, XmlReader reader)
{
item.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty);
}
private static void ProcessTIDescription(TaskInventoryItem item, XmlReader reader)
{
item.Description = reader.ReadElementContentAsString("Description", String.Empty);
}
private static void ProcessTIEveryonePermissions(TaskInventoryItem item, XmlReader reader)
{
item.EveryonePermissions = (uint)reader.ReadElementContentAsInt("EveryonePermissions", String.Empty);
}
private static void ProcessTIFlags(TaskInventoryItem item, XmlReader reader)
{
item.Flags = (uint)reader.ReadElementContentAsInt("Flags", String.Empty);
}
private static void ProcessTIGroupID(TaskInventoryItem item, XmlReader reader)
{
item.GroupID = Util.ReadUUID(reader, "GroupID");
}
private static void ProcessTIGroupPermissions(TaskInventoryItem item, XmlReader reader)
{
item.GroupPermissions = (uint)reader.ReadElementContentAsInt("GroupPermissions", String.Empty);
}
private static void ProcessTIInvType(TaskInventoryItem item, XmlReader reader)
{
item.InvType = reader.ReadElementContentAsInt("InvType", String.Empty);
}
private static void ProcessTIItemID(TaskInventoryItem item, XmlReader reader)
{
item.ItemID = Util.ReadUUID(reader, "ItemID");
}
private static void ProcessTIOldItemID(TaskInventoryItem item, XmlReader reader)
{
item.OldItemID = Util.ReadUUID(reader, "OldItemID");
}
private static void ProcessTILastOwnerID(TaskInventoryItem item, XmlReader reader)
{
item.LastOwnerID = Util.ReadUUID(reader, "LastOwnerID");
}
private static void ProcessTIName(TaskInventoryItem item, XmlReader reader)
{
item.Name = reader.ReadElementContentAsString("Name", String.Empty);
}
private static void ProcessTINextPermissions(TaskInventoryItem item, XmlReader reader)
{
item.NextPermissions = (uint)reader.ReadElementContentAsInt("NextPermissions", String.Empty);
}
private static void ProcessTIOwnerID(TaskInventoryItem item, XmlReader reader)
{
item.OwnerID = Util.ReadUUID(reader, "OwnerID");
}
private static void ProcessTICurrentPermissions(TaskInventoryItem item, XmlReader reader)
{
item.CurrentPermissions = (uint)reader.ReadElementContentAsInt("CurrentPermissions", String.Empty);
}
private static void ProcessTIParentID(TaskInventoryItem item, XmlReader reader)
{
item.ParentID = Util.ReadUUID(reader, "ParentID");
}
private static void ProcessTIParentPartID(TaskInventoryItem item, XmlReader reader)
{
item.ParentPartID = Util.ReadUUID(reader, "ParentPartID");
}
private static void ProcessTIPermsGranter(TaskInventoryItem item, XmlReader reader)
{
item.PermsGranter = Util.ReadUUID(reader, "PermsGranter");
}
private static void ProcessTIPermsMask(TaskInventoryItem item, XmlReader reader)
{
item.PermsMask = reader.ReadElementContentAsInt("PermsMask", String.Empty);
}
private static void ProcessTIType(TaskInventoryItem item, XmlReader reader)
{
item.Type = reader.ReadElementContentAsInt("Type", String.Empty);
}
private static void ProcessTIOwnerChanged(TaskInventoryItem item, XmlReader reader)
{
item.OwnerChanged = Util.ReadBoolean(reader);
}
#endregion
#region ShapeXmlProcessors
private static void ProcessShpProfileCurve(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ProfileCurve = (byte)reader.ReadElementContentAsInt("ProfileCurve", String.Empty);
}
private static void ProcessShpTextureEntry(PrimitiveBaseShape shp, XmlReader reader)
{
byte[] teData = Convert.FromBase64String(reader.ReadElementString("TextureEntry"));
shp.Textures = new Primitive.TextureEntry(teData, 0, teData.Length);
}
private static void ProcessShpExtraParams(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ExtraParams = Convert.FromBase64String(reader.ReadElementString("ExtraParams"));
}
private static void ProcessShpPathBegin(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathBegin = (ushort)reader.ReadElementContentAsInt("PathBegin", String.Empty);
}
private static void ProcessShpPathCurve(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathCurve = (byte)reader.ReadElementContentAsInt("PathCurve", String.Empty);
}
private static void ProcessShpPathEnd(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathEnd = (ushort)reader.ReadElementContentAsInt("PathEnd", String.Empty);
}
private static void ProcessShpPathRadiusOffset(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathRadiusOffset = (sbyte)reader.ReadElementContentAsInt("PathRadiusOffset", String.Empty);
}
private static void ProcessShpPathRevolutions(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathRevolutions = (byte)reader.ReadElementContentAsInt("PathRevolutions", String.Empty);
}
private static void ProcessShpPathScaleX(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathScaleX = (byte)reader.ReadElementContentAsInt("PathScaleX", String.Empty);
}
private static void ProcessShpPathScaleY(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathScaleY = (byte)reader.ReadElementContentAsInt("PathScaleY", String.Empty);
}
private static void ProcessShpPathShearX(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathShearX = (byte)reader.ReadElementContentAsInt("PathShearX", String.Empty);
}
private static void ProcessShpPathShearY(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathShearY = (byte)reader.ReadElementContentAsInt("PathShearY", String.Empty);
}
private static void ProcessShpPathSkew(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathSkew = (sbyte)reader.ReadElementContentAsInt("PathSkew", String.Empty);
}
private static void ProcessShpPathTaperX(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathTaperX = (sbyte)reader.ReadElementContentAsInt("PathTaperX", String.Empty);
}
private static void ProcessShpPathTaperY(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathTaperY = (sbyte)reader.ReadElementContentAsInt("PathTaperY", String.Empty);
}
private static void ProcessShpPathTwist(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathTwist = (sbyte)reader.ReadElementContentAsInt("PathTwist", String.Empty);
}
private static void ProcessShpPathTwistBegin(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathTwistBegin = (sbyte)reader.ReadElementContentAsInt("PathTwistBegin", String.Empty);
}
private static void ProcessShpPCode(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PCode = (byte)reader.ReadElementContentAsInt("PCode", String.Empty);
}
private static void ProcessShpProfileBegin(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ProfileBegin = (ushort)reader.ReadElementContentAsInt("ProfileBegin", String.Empty);
}
private static void ProcessShpProfileEnd(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ProfileEnd = (ushort)reader.ReadElementContentAsInt("ProfileEnd", String.Empty);
}
private static void ProcessShpProfileHollow(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ProfileHollow = (ushort)reader.ReadElementContentAsInt("ProfileHollow", String.Empty);
}
private static void ProcessShpScale(PrimitiveBaseShape shp, XmlReader reader)
{
shp.Scale = Util.ReadVector(reader, "Scale");
}
private static void ProcessShpState(PrimitiveBaseShape shp, XmlReader reader)
{
shp.State = (byte)reader.ReadElementContentAsInt("State", String.Empty);
}
private static void ProcessShpLastAttach(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LastAttachPoint = (byte)reader.ReadElementContentAsInt("LastAttachPoint", String.Empty);
}
private static void ProcessShpProfileShape(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ProfileShape = Util.ReadEnum<ProfileShape>(reader, "ProfileShape");
}
private static void ProcessShpHollowShape(PrimitiveBaseShape shp, XmlReader reader)
{
shp.HollowShape = Util.ReadEnum<HollowShape>(reader, "HollowShape");
}
private static void ProcessShpSculptTexture(PrimitiveBaseShape shp, XmlReader reader)
{
shp.SculptTexture = Util.ReadUUID(reader, "SculptTexture");
}
private static void ProcessShpSculptType(PrimitiveBaseShape shp, XmlReader reader)
{
shp.SculptType = (byte)reader.ReadElementContentAsInt("SculptType", String.Empty);
}
private static void ProcessShpFlexiSoftness(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiSoftness = reader.ReadElementContentAsInt("FlexiSoftness", String.Empty);
}
private static void ProcessShpFlexiTension(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiTension = reader.ReadElementContentAsFloat("FlexiTension", String.Empty);
}
private static void ProcessShpFlexiDrag(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiDrag = reader.ReadElementContentAsFloat("FlexiDrag", String.Empty);
}
private static void ProcessShpFlexiGravity(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiGravity = reader.ReadElementContentAsFloat("FlexiGravity", String.Empty);
}
private static void ProcessShpFlexiWind(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiWind = reader.ReadElementContentAsFloat("FlexiWind", String.Empty);
}
private static void ProcessShpFlexiForceX(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiForceX = reader.ReadElementContentAsFloat("FlexiForceX", String.Empty);
}
private static void ProcessShpFlexiForceY(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiForceY = reader.ReadElementContentAsFloat("FlexiForceY", String.Empty);
}
private static void ProcessShpFlexiForceZ(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiForceZ = reader.ReadElementContentAsFloat("FlexiForceZ", String.Empty);
}
private static void ProcessShpLightColorR(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightColorR = reader.ReadElementContentAsFloat("LightColorR", String.Empty);
}
private static void ProcessShpLightColorG(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightColorG = reader.ReadElementContentAsFloat("LightColorG", String.Empty);
}
private static void ProcessShpLightColorB(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightColorB = reader.ReadElementContentAsFloat("LightColorB", String.Empty);
}
private static void ProcessShpLightColorA(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightColorA = reader.ReadElementContentAsFloat("LightColorA", String.Empty);
}
private static void ProcessShpLightRadius(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightRadius = reader.ReadElementContentAsFloat("LightRadius", String.Empty);
}
private static void ProcessShpLightCutoff(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightCutoff = reader.ReadElementContentAsFloat("LightCutoff", String.Empty);
}
private static void ProcessShpLightFalloff(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightFalloff = reader.ReadElementContentAsFloat("LightFalloff", String.Empty);
}
private static void ProcessShpLightIntensity(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightIntensity = reader.ReadElementContentAsFloat("LightIntensity", String.Empty);
}
private static void ProcessShpFlexiEntry(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiEntry = Util.ReadBoolean(reader);
}
private static void ProcessShpLightEntry(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightEntry = Util.ReadBoolean(reader);
}
private static void ProcessShpSculptEntry(PrimitiveBaseShape shp, XmlReader reader)
{
shp.SculptEntry = Util.ReadBoolean(reader);
}
private static void ProcessShpMedia(PrimitiveBaseShape shp, XmlReader reader)
{
string value = reader.ReadElementContentAsString("Media", String.Empty);
shp.Media = PrimitiveBaseShape.MediaList.FromXml(value);
}
#endregion
////////// Write /////////
public static void SOGToXml2(XmlTextWriter writer, SceneObjectGroup sog, Dictionary<string, object>options)
{
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
SOPToXml2(writer, sog.RootPart, options);
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
sog.ForEachPart(delegate(SceneObjectPart sop)
{
if (sop.UUID != sog.RootPart.UUID)
SOPToXml2(writer, sop, options);
});
writer.WriteEndElement();
if (sog.RootPart.KeyframeMotion != null)
{
Byte[] data = sog.RootPart.KeyframeMotion.Serialize();
writer.WriteStartElement(String.Empty, "KeyframeMotion", String.Empty);
writer.WriteBase64(data, 0, data.Length);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
public static void SOPToXml2(XmlTextWriter writer, SceneObjectPart sop, Dictionary<string, object> options)
{
writer.WriteStartElement("SceneObjectPart");
writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
writer.WriteElementString("AllowedDrop", sop.AllowedDrop.ToString().ToLower());
WriteUUID(writer, "CreatorID", sop.CreatorID, options);
if (!string.IsNullOrEmpty(sop.CreatorData))
writer.WriteElementString("CreatorData", sop.CreatorData);
else if (options.ContainsKey("home"))
{
if (m_UserManagement == null)
m_UserManagement = sop.ParentGroup.Scene.RequestModuleInterface<IUserManagement>();
string name = m_UserManagement.GetUserName(sop.CreatorID);
writer.WriteElementString("CreatorData", ExternalRepresentationUtils.CalcCreatorData((string)options["home"], name));
}
WriteUUID(writer, "FolderID", sop.FolderID, options);
writer.WriteElementString("InventorySerial", sop.InventorySerial.ToString());
WriteTaskInventory(writer, sop.TaskInventory, options, sop.ParentGroup.Scene);
WriteUUID(writer, "UUID", sop.UUID, options);
writer.WriteElementString("LocalId", sop.LocalId.ToString());
writer.WriteElementString("Name", sop.Name);
writer.WriteElementString("Material", sop.Material.ToString());
writer.WriteElementString("PassTouches", sop.PassTouches.ToString().ToLower());
writer.WriteElementString("PassCollisions", sop.PassCollisions.ToString().ToLower());
writer.WriteElementString("RegionHandle", sop.RegionHandle.ToString());
writer.WriteElementString("ScriptAccessPin", sop.ScriptAccessPin.ToString());
WriteVector(writer, "GroupPosition", sop.GroupPosition);
WriteVector(writer, "OffsetPosition", sop.OffsetPosition);
WriteQuaternion(writer, "RotationOffset", sop.RotationOffset);
WriteVector(writer, "Velocity", sop.Velocity);
WriteVector(writer, "AngularVelocity", sop.AngularVelocity);
WriteVector(writer, "Acceleration", sop.Acceleration);
writer.WriteElementString("Description", sop.Description);
writer.WriteStartElement("Color");
writer.WriteElementString("R", sop.Color.R.ToString(Utils.EnUsCulture));
writer.WriteElementString("G", sop.Color.G.ToString(Utils.EnUsCulture));
writer.WriteElementString("B", sop.Color.B.ToString(Utils.EnUsCulture));
writer.WriteElementString("A", sop.Color.A.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
writer.WriteElementString("Text", sop.Text);
writer.WriteElementString("SitName", sop.SitName);
writer.WriteElementString("TouchName", sop.TouchName);
writer.WriteElementString("LinkNum", sop.LinkNum.ToString());
writer.WriteElementString("ClickAction", sop.ClickAction.ToString());
WriteShape(writer, sop.Shape, options);
WriteVector(writer, "Scale", sop.Scale);
WriteQuaternion(writer, "SitTargetOrientation", sop.SitTargetOrientation);
WriteVector(writer, "SitTargetPosition", sop.SitTargetPosition);
WriteVector(writer, "SitTargetPositionLL", sop.SitTargetPositionLL);
WriteQuaternion(writer, "SitTargetOrientationLL", sop.SitTargetOrientationLL);
writer.WriteElementString("ParentID", sop.ParentID.ToString());
writer.WriteElementString("CreationDate", sop.CreationDate.ToString());
writer.WriteElementString("Category", sop.Category.ToString());
writer.WriteElementString("SalePrice", sop.SalePrice.ToString());
writer.WriteElementString("ObjectSaleType", sop.ObjectSaleType.ToString());
writer.WriteElementString("OwnershipCost", sop.OwnershipCost.ToString());
UUID groupID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.GroupID;
WriteUUID(writer, "GroupID", groupID, options);
UUID ownerID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.OwnerID;
WriteUUID(writer, "OwnerID", ownerID, options);
UUID lastOwnerID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.LastOwnerID;
WriteUUID(writer, "LastOwnerID", lastOwnerID, options);
writer.WriteElementString("BaseMask", sop.BaseMask.ToString());
writer.WriteElementString("OwnerMask", sop.OwnerMask.ToString());
writer.WriteElementString("GroupMask", sop.GroupMask.ToString());
writer.WriteElementString("EveryoneMask", sop.EveryoneMask.ToString());
writer.WriteElementString("NextOwnerMask", sop.NextOwnerMask.ToString());
WriteFlags(writer, "Flags", sop.Flags.ToString(), options);
WriteUUID(writer, "CollisionSound", sop.CollisionSound, options);
writer.WriteElementString("CollisionSoundVolume", sop.CollisionSoundVolume.ToString());
if (sop.MediaUrl != null)
writer.WriteElementString("MediaUrl", sop.MediaUrl.ToString());
WriteVector(writer, "AttachedPos", sop.AttachedPos);
if (sop.DynAttrs.CountNamespaces > 0)
{
writer.WriteStartElement("DynAttrs");
sop.DynAttrs.WriteXml(writer);
writer.WriteEndElement();
}
WriteBytes(writer, "TextureAnimation", sop.TextureAnimation);
WriteBytes(writer, "ParticleSystem", sop.ParticleSystem);
writer.WriteElementString("PayPrice0", sop.PayPrice[0].ToString());
writer.WriteElementString("PayPrice1", sop.PayPrice[1].ToString());
writer.WriteElementString("PayPrice2", sop.PayPrice[2].ToString());
writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString());
writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString());
writer.WriteElementString("Buoyancy", sop.Buoyancy.ToString());
WriteVector(writer, "Force", sop.Force);
WriteVector(writer, "Torque", sop.Torque);
writer.WriteElementString("VolumeDetectActive", sop.VolumeDetectActive.ToString().ToLower());
if (sop.VehicleParams != null)
sop.VehicleParams.ToXml2(writer);
if(sop.RotationAxisLocks != 0)
writer.WriteElementString("RotationAxisLocks", sop.RotationAxisLocks.ToString().ToLower());
writer.WriteElementString("PhysicsShapeType", sop.PhysicsShapeType.ToString().ToLower());
if (sop.Density != 1000.0f)
writer.WriteElementString("Density", sop.Density.ToString().ToLower());
if (sop.Friction != 0.6f)
writer.WriteElementString("Friction", sop.Friction.ToString().ToLower());
if (sop.Restitution != 0.5f)
writer.WriteElementString("Bounce", sop.Restitution.ToString().ToLower());
if (sop.GravityModifier != 1.0f)
writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString().ToLower());
WriteVector(writer, "CameraEyeOffset", sop.GetCameraEyeOffset());
WriteVector(writer, "CameraAtOffset", sop.GetCameraAtOffset());
// if (sop.Sound != UUID.Zero) force it till sop crossing does clear it on child prim
{
WriteUUID(writer, "SoundID", sop.Sound, options);
writer.WriteElementString("SoundGain", sop.SoundGain.ToString().ToLower());
writer.WriteElementString("SoundFlags", sop.SoundFlags.ToString().ToLower());
writer.WriteElementString("SoundRadius", sop.SoundRadius.ToString().ToLower());
}
writer.WriteElementString("SoundQueueing", sop.SoundQueueing.ToString().ToLower());
writer.WriteEndElement();
}
static void WriteUUID(XmlTextWriter writer, string name, UUID id, Dictionary<string, object> options)
{
writer.WriteStartElement(name);
if (options.ContainsKey("old-guids"))
writer.WriteElementString("Guid", id.ToString());
else
writer.WriteElementString("UUID", id.ToString());
writer.WriteEndElement();
}
static void WriteVector(XmlTextWriter writer, string name, Vector3 vec)
{
writer.WriteStartElement(name);
writer.WriteElementString("X", vec.X.ToString(Utils.EnUsCulture));
writer.WriteElementString("Y", vec.Y.ToString(Utils.EnUsCulture));
writer.WriteElementString("Z", vec.Z.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
}
static void WriteQuaternion(XmlTextWriter writer, string name, Quaternion quat)
{
writer.WriteStartElement(name);
writer.WriteElementString("X", quat.X.ToString(Utils.EnUsCulture));
writer.WriteElementString("Y", quat.Y.ToString(Utils.EnUsCulture));
writer.WriteElementString("Z", quat.Z.ToString(Utils.EnUsCulture));
writer.WriteElementString("W", quat.W.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
}
static void WriteBytes(XmlTextWriter writer, string name, byte[] data)
{
writer.WriteStartElement(name);
byte[] d;
if (data != null)
d = data;
else
d = Utils.EmptyBytes;
writer.WriteBase64(d, 0, d.Length);
writer.WriteEndElement(); // name
}
static void WriteFlags(XmlTextWriter writer, string name, string flagsStr, Dictionary<string, object> options)
{
// Older versions of serialization can't cope with commas, so we eliminate the commas
writer.WriteElementString(name, flagsStr.Replace(",", ""));
}
public static void WriteTaskInventory(XmlTextWriter writer, TaskInventoryDictionary tinv, Dictionary<string, object> options, Scene scene)
{
if (tinv.Count > 0) // otherwise skip this
{
writer.WriteStartElement("TaskInventory");
foreach (TaskInventoryItem item in tinv.Values)
{
writer.WriteStartElement("TaskInventoryItem");
WriteUUID(writer, "AssetID", item.AssetID, options);
writer.WriteElementString("BasePermissions", item.BasePermissions.ToString());
writer.WriteElementString("CreationDate", item.CreationDate.ToString());
WriteUUID(writer, "CreatorID", item.CreatorID, options);
if (!string.IsNullOrEmpty(item.CreatorData))
writer.WriteElementString("CreatorData", item.CreatorData);
else if (options.ContainsKey("home"))
{
if (m_UserManagement == null)
m_UserManagement = scene.RequestModuleInterface<IUserManagement>();
string name = m_UserManagement.GetUserName(item.CreatorID);
writer.WriteElementString("CreatorData", ExternalRepresentationUtils.CalcCreatorData((string)options["home"], name));
}
writer.WriteElementString("Description", item.Description);
writer.WriteElementString("EveryonePermissions", item.EveryonePermissions.ToString());
writer.WriteElementString("Flags", item.Flags.ToString());
UUID groupID = options.ContainsKey("wipe-owners") ? UUID.Zero : item.GroupID;
WriteUUID(writer, "GroupID", groupID, options);
writer.WriteElementString("GroupPermissions", item.GroupPermissions.ToString());
writer.WriteElementString("InvType", item.InvType.ToString());
WriteUUID(writer, "ItemID", item.ItemID, options);
WriteUUID(writer, "OldItemID", item.OldItemID, options);
UUID lastOwnerID = options.ContainsKey("wipe-owners") ? UUID.Zero : item.LastOwnerID;
WriteUUID(writer, "LastOwnerID", lastOwnerID, options);
writer.WriteElementString("Name", item.Name);
writer.WriteElementString("NextPermissions", item.NextPermissions.ToString());
UUID ownerID = options.ContainsKey("wipe-owners") ? UUID.Zero : item.OwnerID;
WriteUUID(writer, "OwnerID", ownerID, options);
writer.WriteElementString("CurrentPermissions", item.CurrentPermissions.ToString());
WriteUUID(writer, "ParentID", item.ParentID, options);
WriteUUID(writer, "ParentPartID", item.ParentPartID, options);
WriteUUID(writer, "PermsGranter", item.PermsGranter, options);
writer.WriteElementString("PermsMask", item.PermsMask.ToString());
writer.WriteElementString("Type", item.Type.ToString());
bool ownerChanged = options.ContainsKey("wipe-owners") ? false : item.OwnerChanged;
writer.WriteElementString("OwnerChanged", ownerChanged.ToString().ToLower());
writer.WriteEndElement(); // TaskInventoryItem
}
writer.WriteEndElement(); // TaskInventory
}
}
public static void WriteShape(XmlTextWriter writer, PrimitiveBaseShape shp, Dictionary<string, object> options)
{
if (shp != null)
{
writer.WriteStartElement("Shape");
writer.WriteElementString("ProfileCurve", shp.ProfileCurve.ToString());
writer.WriteStartElement("TextureEntry");
byte[] te;
if (shp.TextureEntry != null)
te = shp.TextureEntry;
else
te = Utils.EmptyBytes;
writer.WriteBase64(te, 0, te.Length);
writer.WriteEndElement(); // TextureEntry
writer.WriteStartElement("ExtraParams");
byte[] ep;
if (shp.ExtraParams != null)
ep = shp.ExtraParams;
else
ep = Utils.EmptyBytes;
writer.WriteBase64(ep, 0, ep.Length);
writer.WriteEndElement(); // ExtraParams
writer.WriteElementString("PathBegin", shp.PathBegin.ToString());
writer.WriteElementString("PathCurve", shp.PathCurve.ToString());
writer.WriteElementString("PathEnd", shp.PathEnd.ToString());
writer.WriteElementString("PathRadiusOffset", shp.PathRadiusOffset.ToString());
writer.WriteElementString("PathRevolutions", shp.PathRevolutions.ToString());
writer.WriteElementString("PathScaleX", shp.PathScaleX.ToString());
writer.WriteElementString("PathScaleY", shp.PathScaleY.ToString());
writer.WriteElementString("PathShearX", shp.PathShearX.ToString());
writer.WriteElementString("PathShearY", shp.PathShearY.ToString());
writer.WriteElementString("PathSkew", shp.PathSkew.ToString());
writer.WriteElementString("PathTaperX", shp.PathTaperX.ToString());
writer.WriteElementString("PathTaperY", shp.PathTaperY.ToString());
writer.WriteElementString("PathTwist", shp.PathTwist.ToString());
writer.WriteElementString("PathTwistBegin", shp.PathTwistBegin.ToString());
writer.WriteElementString("PCode", shp.PCode.ToString());
writer.WriteElementString("ProfileBegin", shp.ProfileBegin.ToString());
writer.WriteElementString("ProfileEnd", shp.ProfileEnd.ToString());
writer.WriteElementString("ProfileHollow", shp.ProfileHollow.ToString());
writer.WriteElementString("State", shp.State.ToString());
writer.WriteElementString("LastAttachPoint", shp.LastAttachPoint.ToString());
WriteFlags(writer, "ProfileShape", shp.ProfileShape.ToString(), options);
WriteFlags(writer, "HollowShape", shp.HollowShape.ToString(), options);
WriteUUID(writer, "SculptTexture", shp.SculptTexture, options);
writer.WriteElementString("SculptType", shp.SculptType.ToString());
// Don't serialize SculptData. It's just a copy of the asset, which can be loaded separately using 'SculptTexture'.
writer.WriteElementString("FlexiSoftness", shp.FlexiSoftness.ToString());
writer.WriteElementString("FlexiTension", shp.FlexiTension.ToString());
writer.WriteElementString("FlexiDrag", shp.FlexiDrag.ToString());
writer.WriteElementString("FlexiGravity", shp.FlexiGravity.ToString());
writer.WriteElementString("FlexiWind", shp.FlexiWind.ToString());
writer.WriteElementString("FlexiForceX", shp.FlexiForceX.ToString());
writer.WriteElementString("FlexiForceY", shp.FlexiForceY.ToString());
writer.WriteElementString("FlexiForceZ", shp.FlexiForceZ.ToString());
writer.WriteElementString("LightColorR", shp.LightColorR.ToString());
writer.WriteElementString("LightColorG", shp.LightColorG.ToString());
writer.WriteElementString("LightColorB", shp.LightColorB.ToString());
writer.WriteElementString("LightColorA", shp.LightColorA.ToString());
writer.WriteElementString("LightRadius", shp.LightRadius.ToString());
writer.WriteElementString("LightCutoff", shp.LightCutoff.ToString());
writer.WriteElementString("LightFalloff", shp.LightFalloff.ToString());
writer.WriteElementString("LightIntensity", shp.LightIntensity.ToString());
writer.WriteElementString("FlexiEntry", shp.FlexiEntry.ToString().ToLower());
writer.WriteElementString("LightEntry", shp.LightEntry.ToString().ToLower());
writer.WriteElementString("SculptEntry", shp.SculptEntry.ToString().ToLower());
if (shp.Media != null)
writer.WriteElementString("Media", shp.Media.ToXml());
writer.WriteEndElement(); // Shape
}
}
public static SceneObjectPart Xml2ToSOP(XmlReader reader)
{
SceneObjectPart obj = new SceneObjectPart();
reader.ReadStartElement("SceneObjectPart");
bool errors = ExternalRepresentationUtils.ExecuteReadProcessors(
obj,
m_SOPXmlProcessors,
reader,
(o, nodeName, e) => {
m_log.Debug(string.Format("[SceneObjectSerializer]: Error while parsing element {0} in object {1} {2} ",
nodeName, ((SceneObjectPart)o).Name, ((SceneObjectPart)o).UUID), e);
});
if (errors)
throw new XmlException(string.Format("Error parsing object {0} {1}", obj.Name, obj.UUID));
reader.ReadEndElement(); // SceneObjectPart
// m_log.DebugFormat("[SceneObjectSerializer]: parsed SOP {0} {1}", obj.Name, obj.UUID);
return obj;
}
public static TaskInventoryDictionary ReadTaskInventory(XmlReader reader, string name)
{
TaskInventoryDictionary tinv = new TaskInventoryDictionary();
reader.ReadStartElement(name, String.Empty);
while (reader.Name == "TaskInventoryItem")
{
reader.ReadStartElement("TaskInventoryItem", String.Empty); // TaskInventory
TaskInventoryItem item = new TaskInventoryItem();
ExternalRepresentationUtils.ExecuteReadProcessors(
item,
m_TaskInventoryXmlProcessors,
reader);
reader.ReadEndElement(); // TaskInventoryItem
tinv.Add(item.ItemID, item);
}
if (reader.NodeType == XmlNodeType.EndElement)
reader.ReadEndElement(); // TaskInventory
return tinv;
}
/// <summary>
/// Read a shape from xml input
/// </summary>
/// <param name="reader"></param>
/// <param name="name">The name of the xml element containing the shape</param>
/// <param name="errors">a list containing the failing node names. If no failures then null.</param>
/// <returns>The shape parsed</returns>
public static PrimitiveBaseShape ReadShape(XmlReader reader, string name, out List<string> errorNodeNames, SceneObjectPart obj)
{
List<string> internalErrorNodeNames = null;
PrimitiveBaseShape shape = new PrimitiveBaseShape();
if (reader.IsEmptyElement)
{
reader.Read();
errorNodeNames = null;
return shape;
}
reader.ReadStartElement(name, String.Empty); // Shape
ExternalRepresentationUtils.ExecuteReadProcessors(
shape,
m_ShapeXmlProcessors,
reader,
(o, nodeName, e) => {
m_log.Debug(string.Format("[SceneObjectSerializer]: Error while parsing element {0} in Shape property of object {1} {2} ",
nodeName, obj.Name, obj.UUID), e);
if (internalErrorNodeNames == null)
internalErrorNodeNames = new List<string>();
internalErrorNodeNames.Add(nodeName);
});
reader.ReadEndElement(); // Shape
errorNodeNames = internalErrorNodeNames;
return shape;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using IfacesEnumsStructsClasses;
using System.IO;
namespace DemoApp
{
#region AllForms class
/// <summary>
/// Simple class to encapsulate global forms, controls, consts, and methods
/// </summary>
public sealed class AllForms
{
public const string COOKIE = "Cookie:";
public const string VISITED = "Visited:";
public const string DLG_HTMLS_FILTER = "Html files (*.html)|*.html|Htm files (*.htm)|*.htm|Text files (*.txt)|*.txt|All files (*.*)|*.*";
public const string DLG_XMLS_FILTER = "XML files (*.xml)|*.xml";
public const string DLG_TEXTFILES_FILTER = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
public const string DLG_IMAGES_FILTER = "Bmp files (*.bmp)|*.bmp" +
"|Gif files (*.gif)|*.gif" +
"|Jpeg files (*.Jpeg)|*.Jpeg" +
"|Png files (*.png)|*.png" +
"|Wmf files (*.wmf)|*.wmf" +
"|Tiff files (*.tiff)|*.tiff" +
"|Emf files (*.emf)|*.emf";
public static frmLog m_frmLog = new frmLog();
public static frmDynamicConfirm m_frmDynamicConfirm = new frmDynamicConfirm();
public static frmInput m_frmInput = new frmInput();
public static ImageList m_imgListMain = new ImageList();
public static SaveFileDialog m_dlgSave = new SaveFileDialog();
public static OpenFileDialog m_dlgOpen = new OpenFileDialog();
public static Icon BitmapToIcon(Image orgImage)
{
Icon icoRet = null;
if (orgImage == null)
return icoRet;
Bitmap bmp = new Bitmap(orgImage);
icoRet = Icon.FromHandle(bmp.GetHicon());
bmp.Dispose();
return icoRet;
}
//Using m_imgListMain static member
public static Icon BitmapToIcon(int orgImage)
{
Icon icoRet = null;
if (AllForms.m_imgListMain.Images.Count > 0)
{
Bitmap bmp = new Bitmap(AllForms.m_imgListMain.Images[orgImage]);
icoRet = Icon.FromHandle(bmp.GetHicon());
bmp.Dispose();
}
return icoRet;
}
//replace = visited: or cookie:
public static string SetupCookieCachePattern(string pattern, string replace)
{
const string COOKIECACHEPATTERN = ".*";
const string DOT = ".";
const string BACKSLASHDOT = "\\.";
string url = pattern;
if (url.Length > 0)
{
Uri curUri = new Uri(url);
url = curUri.Host;
//Replace "." with "\\."
url = url.Replace(DOT, BACKSLASHDOT);
url = replace + COOKIECACHEPATTERN + url;
//www.google.com
//visited:.*www\\.google\\.com
//login.live.com
//cookie:.*login\\.live\\.com
}
return url;
}
/// <summary>
/// A little shortcut when asking for yes or no type of confirmation
/// </summary>
/// <param name="Msg"></param>
/// <param name="Win"></param>
/// <returns></returns>
public static bool AskForConfirmation(string Msg, IWin32Window Win)
{
const string CONFIRMATIONREQUESTED = "Confirmation Requested";
DialogResult result = MessageBox.Show(Win, Msg, CONFIRMATIONREQUESTED, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
return (result == DialogResult.Yes) ? true : false;
}
/// <summary>
/// To display a save dialog from any form within this project
/// </summary>
/// <param name="defaultext">If empty, "txt" is used.</param>
/// <param name="filename">Name or Name.ext</param>
/// <param name="filter">If empty, Textual filter is used.</param>
/// <param name="title">if empty, "Save File" is used.</param>
/// <param name="initialdir">If empty, current directory is used.</param>
/// <returns></returns>
public static DialogResult ShowStaticSaveDialog(IWin32Window Win,
string defaultext, string filename,
string filter, string title, string initialdir)
{
if (string.IsNullOrEmpty(defaultext))
AllForms.m_dlgSave.DefaultExt = "txt";
else
AllForms.m_dlgSave.DefaultExt = defaultext;
if (string.IsNullOrEmpty(filename))
AllForms.m_dlgSave.FileName = "FileName";
else
AllForms.m_dlgSave.FileName = filename;
if (string.IsNullOrEmpty(filter))
AllForms.m_dlgSave.Filter = DLG_TEXTFILES_FILTER;
else
AllForms.m_dlgSave.Filter = filter;
if (string.IsNullOrEmpty(title))
AllForms.m_dlgSave.Title = "Save File";
else
AllForms.m_dlgSave.Title = title;
if (string.IsNullOrEmpty(initialdir))
AllForms.m_dlgSave.InitialDirectory = Environment.CurrentDirectory;
else
AllForms.m_dlgSave.InitialDirectory = initialdir;
return AllForms.m_dlgSave.ShowDialog(Win);
}
public static DialogResult ShowStaticSaveDialogForHTML(IWin32Window Win)
{
return ShowStaticSaveDialog(Win, string.Empty, string.Empty, DLG_HTMLS_FILTER, string.Empty, string.Empty);
}
public static DialogResult ShowStaticSaveDialogForText(IWin32Window Win)
{
return ShowStaticSaveDialog(Win, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
}
public static DialogResult ShowStaticSaveDialogForImage(IWin32Window Win)
{
return ShowStaticSaveDialog(Win, "bmp", "ImageFileName", DLG_IMAGES_FILTER, "Save Image", string.Empty);
}
public static DialogResult ShowStaticSaveDialogForXML(IWin32Window Win)
{
return ShowStaticSaveDialog(Win, "xml", "XMLFileName", DLG_XMLS_FILTER, "Save XML", string.Empty);
}
public static DialogResult ShowStaticOpenDialog(IWin32Window Win,
string filter, string title, string initialdir, bool showreadonly)
{
AllForms.m_dlgOpen.Filter = filter;
if (string.IsNullOrEmpty(title))
AllForms.m_dlgOpen.Title = "Open File";
else
AllForms.m_dlgOpen.Title = title;
if (string.IsNullOrEmpty(initialdir))
AllForms.m_dlgOpen.InitialDirectory = Environment.CurrentDirectory;
else
AllForms.m_dlgOpen.InitialDirectory = initialdir;
AllForms.m_dlgOpen.ShowReadOnly = showreadonly;
return AllForms.m_dlgOpen.ShowDialog(Win);
}
public static void LoadWebColors(ComboBox combo)
{
Array knownColors = Enum.GetValues(typeof(System.Drawing.KnownColor));
//First add an empty color
combo.Items.Add(Color.Empty);
//Then the rest
foreach (KnownColor k in knownColors)
{
Color c = Color.FromKnownColor(k);
if (!c.IsSystemColor && (c.A > 0))
{
combo.Items.Add(c);
}
}
//Select default
combo.SelectedIndex = 0;
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
#pragma warning disable 279 //"doesn't implement collection pattern..." yes, I know.
namespace Imms.Abstract {
/// <summary>
/// Parent class of all list-like collections, where elements appear in a certain order and may be indexed.
/// </summary>
/// <typeparam name="TList"> The type of the underlying collection. </typeparam>
/// <typeparam name="TElem"> The type of element stored in the collection. </typeparam>
public abstract partial class AbstractSequential<TElem, TList>
: AbstractIterable<TElem, TList, ISequentialBuilder<TElem, TList>>,
IEquatable<TList> where TList : AbstractSequential<TElem, TList> {
static readonly IEqualityComparer<TElem> DefaultEquality = FastEquality<TElem>.Default;
/// <summary>
/// Returns a new collection containing a slice of the current collection, from index to index. The indexes may be
/// negative.
/// </summary>
/// <param name="from"> The initial index. </param>
/// <param name="to"> The end index. </param>
/// <returns> </returns>
public TList this[int from, int to] {
get {
var len = Length;
from.CheckIsBetween("from", -len, len - 1);
to.CheckIsBetween("to", -len, len - 1);
to = to < 0 ? to + len : to;
@from = @from < 0 ? @from + len : @from;
to.CheckIsBetween("to", from, message:"The value of the index was converted to its positive form.");
return GetRange(from, to - from + 1);
}
}
internal virtual Tuple<TList, TList> Split(int atIndex) {
atIndex.CheckIsBetween("atIndex", -Length, Length);
if (atIndex == 0) {
return Tuple.Create(Empty, (TList) this);
}
if (atIndex == Length) {
return Tuple.Create((TList) this, Empty);
}
return Tuple.Create(Take(atIndex), Skip(atIndex));
}
/// <summary>
/// Returns the element at the specified index.
/// </summary>
/// <param name="index"> </param>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the specified index doesn't exist.</exception>
/// <returns> </returns>
public TElem this[int index] {
get {
index.CheckIsBetween("index", -Length, Length - 1);
index = index < 0 ? index + Length : index;
return GetItem(index);
}
}
/// <summary>
/// Returns the element at the specified index, or None if no element was found.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
public Optional<TElem> TryGet(int index) {
index = index < 0 ? index + Length : index;
if (index >= Length || index < 0) return Optional.None;
return GetItem(index);
}
/// <summary>
/// Returns the first element in the collection.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the collection is empty.</exception>
public virtual TElem First {
get {
var v = Find(x => true);
if (v.IsNone) throw Errors.Is_empty;
return v.Value;
}
}
/// <summary>
/// Gets the last element in the collection.
/// </summary>
/// <value> The last. </value>
/// <exception cref="InvalidOperationException">Thrown if the collection is empty.</exception>
public virtual TElem Last {
get {
var v = FindLast(x => true);
if (v.IsNone) throw Errors.Is_empty;
return v.Value;
}
}
/// <summary>
/// Returns the first element or None.
/// </summary>
/// <value> The first element, or None if the collection is empty.</value>
public Optional<TElem> TryFirst {
get { return IsEmpty ? Optional.None : Optional.Some(First); }
}
/// <summary>
/// Gets the last element or None.
/// </summary>
/// <value> The last element, or None if the collection is empty. </value>
public Optional<TElem> TryLast {
get { return IsEmpty ? Optional.None : Optional.Some(Last); }
}
/// <summary>
/// Copies a range of elements from the collection to the specified array.
/// </summary>
/// <param name="arr"> The array. </param>
/// <param name="myStart"> The index of the collection at which to start copying. May be negative.</param>
/// <param name="arrStart">The index of the array at which to start copying. May be negative.</param>
/// <param name="count"> The number of items to copy. Must be non-negative.</param>
/// <exception cref="ArgumentNullException">Thrown if the array is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if the array isn't long enough, or one of the parameters is
/// invalid.
/// </exception>
public virtual void CopyTo(TElem[] arr, int myStart, int arrStart, int count) {
arr.CheckNotNull("arr");
if (count != 0 || (myStart != 0 && myStart != -1)) {
myStart.CheckIsBetween("myStart", -Length, Length - 1);
}
if (count != 0 || (arrStart != 0 && arrStart != -1)) {
arrStart.CheckIsBetween("arrStart", -arr.Length, arr.Length - 1);
}
if (count == 0) {
return;
}
myStart = myStart < 0 ? myStart + Length : myStart;
arrStart = arrStart < 0 ? arrStart + arr.Length : arrStart;
count.CheckIsBetween("count", 0, Length - myStart, "It was out of bounds of this collection.");
count.CheckIsBetween("count", 0, arr.Length - arrStart, "It was out of bounds of the array.");
var ix = 0;
ForEachWhileI((v, i) => {
if (i < myStart) return true;
if (ix >= count) return false;
arr[myStart + ix] = v;
ix++;
return true;
});
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(TList other) {
return SequenceEquals(other, DefaultEquality);
}
/// <summary>
/// Determines structural equality between the sequential collections.
/// </summary>
/// <param name="a">The first collection</param>
/// <param name="b">The second collection.</param>
/// <returns>
/// Whether the two collections are equal.
/// </returns>
public static bool operator ==(AbstractSequential<TElem, TList> a, AbstractSequential<TElem, TList> b) {
var boiler = EqualityHelper.BoilerEquality(a, b);
if (boiler.IsSome) return boiler.Value;
return
a.Equals(b);
}
/// <summary>
/// Determines structural inequality.
/// </summary>
/// <param name="a">The first collection</param>
/// <param name="b">The second collection.</param>
/// <returns>
/// Whether the two collections are unequal.
/// </returns>
public static bool operator !=(AbstractSequential<TElem, TList> a, AbstractSequential<TElem, TList> b) {
return !(a == b);
}
/// <summary>
/// Determines structural inequality with obj. Two sequential collections are equal if they contain the same sequence of elements, and are of the same type.
/// </summary>
/// <param name="obj">Another object (a sequential collection) to compare with this instance.</param>
public override bool Equals(object obj) {
var elems = obj as AbstractSequential<TElem, TList>;
return elems != null && elems.Equals(this);
}
/// <summary>
/// Returns a structural hash code for this collection. Uses the default hash function of the elements.
/// </summary>
public override int GetHashCode() {
return this.CompuateSeqHashCode(DefaultEquality);
}
/// <summary>
/// Returns the element at the specified index. Doesn't support negative indexing.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
protected virtual TElem GetItem(int index) {
return Pick((v, i) => i == index ? Optional.Some(v) : Optional.None).Value;
}
/// <summary>
/// Returns a range of elements. Doesn't support negative indexing.
/// </summary>
/// <param name="from"></param>
/// <param name="count"></param>
/// <returns></returns>
protected virtual TList GetRange(int from, int count) {
using (var builder = EmptyBuilder)
{
ForEachWhileI((v, i) => {
if (i >= from + count) return false;
if (i < from) return true;
builder.Add(v);
return true;
});
return builder.Produce();
}
}
/// <summary>
/// Applies an accumulator on every item in the sequence, from last to first.
/// </summary>
/// <typeparam name="TResult"> The type of the result. </typeparam>
/// <param name="initial"> The initial value. </param>
/// <param name="fold"> The accumulator. </param>
/// <exception cref="ArgumentNullException">Thrown if the accumulator is null.</exception>
/// <returns> </returns>
public TResult AggregateBack<TResult>(TResult initial, Func<TResult, TElem, TResult> fold) {
fold.CheckNotNull("fold");
ForEachBack(v => initial = fold(initial, v));
return initial;
}
/// <summary>
/// Finds the index of the first item that matches the specified predicate.
/// </summary>
/// <param name="predicate"> The predicate. </param>
/// <exception cref="ArgumentNullException">Thrown if the predicate is null.</exception>
/// <returns> </returns>
public Optional<int> FindIndex(Func<TElem, bool> predicate) {
predicate.CheckNotNull("predicate");
return Pick((v, i) => predicate(v) ? Optional.Some(i) : Optional.None);
}
/// <summary>
/// Returns the first index of the specified element using the default equality comparer.
/// </summary>
/// <param name="elem">The element to find.</param>
/// <returns>The index of the element, or None if it wasn't found.</returns>
public virtual Optional<int> FindIndex(TElem elem) {
return FindIndex(v => Equals(v, elem));
}
/// <summary>
/// Returns true if this sequence is equal to the other sequence, using an optional value equality comparer.
/// </summary>
/// <param name="other"></param>
/// <param name="eq"></param>
/// <returns></returns>
public virtual bool SequenceEquals(IEnumerable<TElem> other, IEqualityComparer<TElem> eq = null) {
other.CheckNotNull("other");
TList list = other as TList;
if (list != null) return SequenceEquals(list, eq);
return EqualityHelper.SeqEquals(this, other, eq);
}
/// <summary>
/// Override this to provide an efficient implementation for the operation.
/// </summary>
/// <param name="other"></param>
/// <param name="eq"></param>
/// <returns></returns>
protected virtual bool SequenceEquals(TList other, IEqualityComparer<TElem> eq = null) {
other.CheckNotNull("other");
return EqualityHelper.SeqEquals(this, other, eq);
}
/// <summary>
/// Returns the index of the last element that satisfies the given predicate.
/// </summary>
/// <param name="predicate">The predicate.</param>
/// <returns></returns>
public Optional<int> FindLastIndex(Func<TElem, bool> predicate) {
predicate.CheckNotNull("predicate");
Optional<int> found = Optional.None;
var i = 0;
ForEachBackWhile(v => {
if (predicate(v)) {
found = i++;
return false;
}
i++;
return true;
});
return found.Map(ix => Length - 1 - ix);
}
/// <summary>
/// Tries to find the last item that matches the specified predicate, returning None if no such item was found.
/// </summary>
/// <param name="predicate"> The predicate. </param>
/// <exception cref="ArgumentNullException">Thrown if the predicate is null.</exception>
/// <returns> </returns>
public Optional<TElem> FindLast(Func<TElem, bool> predicate) {
predicate.CheckNotNull("predicate");
Optional<TElem> found = Optional.None;
ForEachBackWhile(x => {
if (predicate(x)) {
found = x;
return false;
}
return true;
});
return found;
}
/// <summary>
/// Applies the specified delegate on every item in the collection, from last to first.
/// </summary>
/// <param name="action"> The action. </param>
/// <exception cref="ArgumentNullException">Thrown if the delegate is null.</exception>
public virtual void ForEachBack(Action<TElem> action) {
action.CheckNotNull("action");
ForEachBackWhile(v => {
action(v);
return true;
});
}
/// <summary>
/// Applies the specified delegate on every item in the collection, from last to first, until it returns false.
/// </summary>
/// <param name="function"> The function. </param>
/// <returns> </returns>
/// <exception cref="ArgumentNullException">Thrown if the function null.</exception>
public virtual bool ForEachBackWhile(Func<TElem, bool> function) {
function.CheckNotNull("function");
var list = new List<TElem>(Length);
list.AddRange(this);
for (var i = list.Count - 1; i >= 0; i--) if (!function(list[i])) return false;
return true;
}
/// <summary>
/// Applies an function over each element-index pair in the collection, from first to last, and stops if the function
/// returns false.
/// </summary>
/// <param name="function"> The function. </param>
/// <exception cref="ArgumentNullException">Thrown if the argument null.</exception>
/// <returns> </returns>
private bool ForEachWhileI(Func<TElem, int, bool> function) {
function.CheckNotNull("function");
return ForEachWhile(function.HideIndex());
}
/// <summary>
/// Orders the elements in this collection using the specified ordering.
/// </summary>
/// <param name="ordering">The ordering to use.</param>
/// <returns></returns>
public virtual TList OrderBy(IComparer<TElem> ordering) {
return _OrderBy(this, ordering);
}
/// <summary>
/// Orders the sequence using the specified key selector.
/// </summary>
/// <typeparam name="TKey1">The type of the key.</typeparam>
/// <param name="selector1">The selector</param>
/// <returns></returns>
public TList OrderBy<TKey1>(Func<TElem, TKey1> selector1) {
var comparer1 = Comparer<TKey1>.Default;
return OrderBy(comparer1.BySelector(selector1));
}
/// <summary>
/// Orders the sequence using the specified key selector.
/// </summary>
/// <typeparam name="TKey1">The type of the key.</typeparam>
/// <param name="selector1">The selector</param>
/// <returns></returns>
public TList OrderByDescending<TKey1>(Func<TElem, TKey1> selector1) {
var comparer1 = Comparer<TKey1>.Default;
return OrderBy(comparer1.BySelector(selector1).Invert());
}
/// <summary>
/// Orders the sequence using the specified orderings, in order of precedence.
/// </summary>
/// <param name="orderings">The orderings.</param>
/// <returns></returns>
public TList OrderBy(params IComparer<TElem>[] orderings) {
return OrderBy(orderings.Combine());
}
/// <summary>
/// Applies an accumulator on each element in the sequence. Begins by applying the accumulator on the first two
/// elements. Runs from last to first.
/// </summary>
/// <param name="fold"> The accumulator </param>
/// <returns> The final result of the accumulator </returns>
/// <exception cref="ArgumentNullException">Thrown if the argument null.</exception>
public TElem AggregateBack(Func<TElem, TElem, TElem> fold) {
fold.CheckNotNull("fold");
return
AggregateBack(Optional.NoneOf<TElem>(), (r, v) => r.IsSome ? fold(r.Value, v).AsSome() : v.AsSome())
.ValueOrError(Errors.Is_empty);
}
/// <summary>
/// Returns a reversed collection.
/// </summary>
/// <returns> </returns>
public virtual TList Reverse() {
if (Length <= 1) return this;
using (var builder = EmptyBuilder) {
ForEachBack(v => builder.Add(v));
return builder.Produce();
}
}
/// <summary>
/// Returns a new collection without the specified initial number of elements. Returns empty if
/// <paramref name="count" /> is equal or greater than Length.
/// </summary>
/// <param name="count"> The number of elements to skip. </param>
/// <exception cref="ArgumentException">Thrown if the argument is smaller than 0.</exception>
/// <returns> </returns>
public virtual TList Skip(int count) {
count.CheckIsBetween("count", 0);
if (count >= Length) return Empty;
if (count == 0) return this;
return GetRange(count, Length - count);
}
/// <summary>
/// Discards the initial elements in the collection until the predicate returns false.
/// </summary>
/// <param name="predicate"> The predicate. </param>
/// <exception cref="ArgumentNullException">Thrown if the argument is null.</exception>
/// <returns> </returns>
public TList SkipWhile(Func<TElem, bool> predicate) {
predicate.CheckNotNull("predicate");
var index = FindIndex(x => !predicate(x));
return index.IsNone ? Empty : Skip(index.Value);
}
/// <summary>
/// Copies the first several elements (according to order of iteration) of the collection to an array, starting at the
/// specified array index.
/// </summary>
/// <param name="arr">The array to copy to.</param>
/// <param name="arrStart">The array index at which to begin copying.</param>
/// <param name="count">The number of elements to copy.</param>
public sealed override void CopyTo(TElem[] arr, int arrStart, int count) {
CopyTo(arr, 0, arrStart, count);
}
/// <summary>
/// Returns a subsequence consisting of the specified number of elements. Returns empty if <paramref name="count" /> is
/// greater than Length.
/// </summary>
/// <param name="count"> The number of elements.. </param>
/// <exception cref="ArgumentException">Thrown if the argument is smaller than 0.</exception>
/// <returns> </returns>
public virtual TList Take(int count) {
count.CheckIsBetween("count", 0);
if (count == 0) return Empty;
if (count >= Length) return this;
return GetRange(0, count);
}
/// <summary>
/// Returns the first items until the predicate returns false.
/// </summary>
/// <param name="predicate"> The predicate. </param>
/// <exception cref="ArgumentNullException">Thrown if the argument null.</exception>
/// <returns> </returns>
public TList TakeWhile(Func<TElem, bool> predicate) {
predicate.CheckNotNull("predicate");
var index = FindIndex(x => !predicate(x));
return index.IsNone ? (TList)this : Take(index.Value);
}
/// <summary>
/// Implementation for a method that incrementally applies an accumulator over the collection, and returns a sequence of partial results. Runs from last to first.
/// </summary>
/// <typeparam name="TElem2"> The type of the element in the return collection. </typeparam>
/// <typeparam name="TRSeq"> The type of the return provider. </typeparam>
/// <param name="bFactory"> A prototype instance of the resulting collection provider, used as a builder factory. </param>
/// <param name="initial"> The initial value for the accumulator. </param>
/// <param name="accumulator"> The accumulator. </param>
/// <exception cref="ArgumentNullException">Thrown if the argument null.</exception>
/// <returns> </returns>
protected virtual TRSeq _ScanBack<TElem2, TRSeq>(TRSeq bFactory, TElem2 initial, Func<TElem2, TElem, TElem2> accumulator)
where TRSeq : IBuilderFactory<ISequentialBuilder<TElem2, TRSeq>>
{
bFactory.CheckNotNull("bFactory");
if (accumulator == null) throw Errors.Argument_null("accumulator");
using (var builder = bFactory.EmptyBuilder)
{
AggregateBack(initial, (r, v) =>
{
r = accumulator(r, v);
builder.Add(r);
return r;
});
return builder.Produce();
}
}
/// <summary>
/// Implementation for a method that joins the elements of this collection with those of a sequence by index, and uses a result selector to construct a return collection.
/// </summary>
/// <typeparam name="TRElem"> The type of the R elem. </typeparam>
/// <typeparam name="TRSeq"> The type of the R provider. </typeparam>
/// <typeparam name="TInner"> The type of the inner. </typeparam>
/// <param name="bFactory"> A prototype instance of the resulting collection provider, used as a builder factory. </param>
/// <param name="o"> The o. </param>
/// <param name="selector"> The selector. </param>
/// <returns> </returns>
protected virtual TRSeq _Zip<TRElem, TRSeq, TInner>(TRSeq bFactory, IEnumerable<TInner> o, Func<TElem, TInner, TRElem> selector)
where TRSeq : IBuilderFactory<ISequentialBuilder<TRElem, TRSeq>>
{
using (var builder = bFactory.EmptyBuilder)
using (var iterator = o.GetEnumerator())
{
ForEachWhile(otr =>
{
if (!iterator.MoveNext()) return false;
var inr = iterator.Current;
builder.Add(selector(otr, inr));
return true;
});
return builder.Produce();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
namespace ClosedXML.Excel
{
public enum XLDataType { Text, Number, Boolean, DateTime, TimeSpan }
public enum XLTableCellType { None, Header, Data, Total }
public interface IXLCell
{
/// <summary>
/// Gets or sets the cell's value. To get or set a strongly typed value, use the GetValue<T> and SetValue methods.
/// <para>ClosedXML will try to detect the data type through parsing. If it can't then the value will be left as a string.</para>
/// <para>If the object is an IEnumerable, ClosedXML will copy the collection's data into a table starting from this cell.</para>
/// <para>If the object is a range, ClosedXML will copy the range starting from this cell.</para>
/// <para>Setting the value to an object (not IEnumerable/range) will call the object's ToString() method.</para>
/// </summary>
/// <value>
/// The object containing the value(s) to set.
/// </value>
Object Value { get; set; }
/// <summary>Gets this cell's address, relative to the worksheet.</summary>
/// <value>The cell's address.</value>
IXLAddress Address { get; }
/// <summary>
/// Returns the current region. The current region is a range bounded by any combination of blank rows and blank columns
/// </summary>
/// <value>
/// The current region.
/// </value>
IXLRange CurrentRegion { get; }
/// <summary>
/// Gets or sets the type of this cell's data.
/// <para>Changing the data type will cause ClosedXML to covert the current value to the new data type.</para>
/// <para>An exception will be thrown if the current value cannot be converted to the new data type.</para>
/// </summary>
/// <value>
/// The type of the cell's data.
/// </value>
/// <exception cref="ArgumentException"></exception>
XLDataType DataType { get; set; }
/// <summary>
/// Sets the type of this cell's data.
/// <para>Changing the data type will cause ClosedXML to covert the current value to the new data type.</para>
/// <para>An exception will be thrown if the current value cannot be converted to the new data type.</para>
/// </summary>
/// <param name="dataType">Type of the data.</param>
/// <returns></returns>
IXLCell SetDataType(XLDataType dataType);
/// <summary>
/// Sets the cell's value.
/// <para>If the object is an IEnumerable ClosedXML will copy the collection's data into a table starting from this cell.</para>
/// <para>If the object is a range ClosedXML will copy the range starting from this cell.</para>
/// <para>Setting the value to an object (not IEnumerable/range) will call the object's ToString() method.</para>
/// <para>ClosedXML will try to translate it to the corresponding type, if it can't then the value will be left as a string.</para>
/// </summary>
/// <value>
/// The object containing the value(s) to set.
/// </value>
IXLCell SetValue<T>(T value);
/// <summary>
/// Gets the cell's value converted to the T type.
/// <para>ClosedXML will try to covert the current value to the T type.</para>
/// <para>An exception will be thrown if the current value cannot be converted to the T type.</para>
/// </summary>
/// <typeparam name="T">The return type.</typeparam>
/// <exception cref="ArgumentException"></exception>
T GetValue<T>();
/// <summary>
/// Gets the cell's value converted to a String.
/// </summary>
String GetString();
/// <summary>
/// Gets the cell's value formatted depending on the cell's data type and style.
/// </summary>
String GetFormattedString();
/// <summary>
/// Gets the cell's value converted to Double.
/// <para>ClosedXML will try to covert the current value to Double.</para>
/// <para>An exception will be thrown if the current value cannot be converted to Double.</para>
/// </summary>
Double GetDouble();
/// <summary>
/// Gets the cell's value converted to Boolean.
/// <para>ClosedXML will try to covert the current value to Boolean.</para>
/// <para>An exception will be thrown if the current value cannot be converted to Boolean.</para>
/// </summary>
Boolean GetBoolean();
/// <summary>
/// Gets the cell's value converted to DateTime.
/// <para>ClosedXML will try to covert the current value to DateTime.</para>
/// <para>An exception will be thrown if the current value cannot be converted to DateTime.</para>
/// </summary>
DateTime GetDateTime();
/// <summary>
/// Gets the cell's value converted to TimeSpan.
/// <para>ClosedXML will try to covert the current value to TimeSpan.</para>
/// <para>An exception will be thrown if the current value cannot be converted to TimeSpan.</para>
/// </summary>
TimeSpan GetTimeSpan();
XLHyperlink GetHyperlink();
Boolean TryGetValue<T>(out T value);
Boolean HasHyperlink { get; }
/// <summary>
/// Clears the contents of this cell.
/// </summary>
/// <param name="clearOptions">Specify what you want to clear.</param>
IXLCell Clear(XLClearOptions clearOptions = XLClearOptions.All);
/// <summary>
/// Deletes the current cell and shifts the surrounding cells according to the shiftDeleteCells parameter.
/// </summary>
/// <param name="shiftDeleteCells">How to shift the surrounding cells.</param>
void Delete(XLShiftDeletedCells shiftDeleteCells);
/// <summary>
/// Gets or sets the cell's formula with A1 references.
/// </summary>
/// <value>The formula with A1 references.</value>
String FormulaA1 { get; set; }
IXLCell SetFormulaA1(String formula);
/// <summary>
/// Gets or sets the cell's formula with R1C1 references.
/// </summary>
/// <value>The formula with R1C1 references.</value>
String FormulaR1C1 { get; set; }
IXLCell SetFormulaR1C1(String formula);
/// <summary>
/// Returns this cell as an IXLRange.
/// </summary>
IXLRange AsRange();
/// <summary>
/// Gets or sets the cell's style.
/// </summary>
IXLStyle Style { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this cell's text should be shared or not.
/// </summary>
/// <value>
/// If false the cell's text will not be shared and stored as an inline value.
/// </value>
Boolean ShareString { get; set; }
/// <summary>
/// Inserts the IEnumerable data elements and returns the range it occupies.
/// </summary>
/// <param name="data">The IEnumerable data.</param>
IXLRange InsertData(IEnumerable data);
/// <summary>
/// Inserts the IEnumerable data elements and returns the range it occupies.
/// </summary>
/// <param name="data">The IEnumerable data.</param>
/// <param name="tranpose">if set to <c>true</c> the data will be transposed before inserting.</param>
/// <returns></returns>
IXLRange InsertData(IEnumerable data, Boolean tranpose);
/// <summary>
/// Inserts the data of a data table.
/// </summary>
/// <param name="dataTable">The data table.</param>
/// <returns>The range occupied by the inserted data</returns>
IXLRange InsertData(DataTable dataTable);
/// <summary>
/// Inserts the IEnumerable data elements as a table and returns it.
/// <para>The new table will receive a generic name: Table#</para>
/// </summary>
/// <param name="data">The table data.</param>
IXLTable InsertTable<T>(IEnumerable<T> data);
/// <summary>
/// Inserts the IEnumerable data elements as a table and returns it.
/// <para>The new table will receive a generic name: Table#</para>
/// </summary>
/// <param name="data">The table data.</param>
/// <param name="createTable">
/// if set to <c>true</c> it will create an Excel table.
/// <para>if set to <c>false</c> the table will be created in memory.</para>
/// </param>
IXLTable InsertTable<T>(IEnumerable<T> data, Boolean createTable);
/// <summary>
/// Creates an Excel table from the given IEnumerable data elements.
/// </summary>
/// <param name="data">The table data.</param>
/// <param name="tableName">Name of the table.</param>
IXLTable InsertTable<T>(IEnumerable<T> data, String tableName);
/// <summary>
/// Inserts the IEnumerable data elements as a table and returns it.
/// </summary>
/// <param name="data">The table data.</param>
/// <param name="tableName">Name of the table.</param>
/// <param name="createTable">
/// if set to <c>true</c> it will create an Excel table.
/// <para>if set to <c>false</c> the table will be created in memory.</para>
/// </param>
IXLTable InsertTable<T>(IEnumerable<T> data, String tableName, Boolean createTable);
/// <summary>
/// Inserts the DataTable data elements as a table and returns it.
/// <para>The new table will receive a generic name: Table#</para>
/// </summary>
/// <param name="data">The table data.</param>
IXLTable InsertTable(DataTable data);
/// <summary>
/// Inserts the DataTable data elements as a table and returns it.
/// <para>The new table will receive a generic name: Table#</para>
/// </summary>
/// <param name="data">The table data.</param>
/// <param name="createTable">
/// if set to <c>true</c> it will create an Excel table.
/// <para>if set to <c>false</c> the table will be created in memory.</para>
/// </param>
IXLTable InsertTable(DataTable data, Boolean createTable);
/// <summary>
/// Creates an Excel table from the given DataTable data elements.
/// </summary>
/// <param name="data">The table data.</param>
/// <param name="tableName">Name of the table.</param>
IXLTable InsertTable(DataTable data, String tableName);
/// <summary>
/// Inserts the DataTable data elements as a table and returns it.
/// </summary>
/// <param name="data">The table data.</param>
/// <param name="tableName">Name of the table.</param>
/// <param name="createTable">
/// if set to <c>true</c> it will create an Excel table.
/// <para>if set to <c>false</c> the table will be created in memory.</para>
/// </param>
IXLTable InsertTable(DataTable data, String tableName, Boolean createTable);
XLTableCellType TableCellType();
XLHyperlink Hyperlink { get; set; }
IXLWorksheet Worksheet { get; }
IXLDataValidation DataValidation { get; }
IXLDataValidation NewDataValidation { get; }
IXLDataValidation SetDataValidation();
IXLCells InsertCellsAbove(int numberOfRows);
IXLCells InsertCellsBelow(int numberOfRows);
IXLCells InsertCellsAfter(int numberOfColumns);
IXLCells InsertCellsBefore(int numberOfColumns);
/// <summary>
/// Creates a named range out of this cell.
/// <para>If the named range exists, it will add this range to that named range.</para>
/// <para>The default scope for the named range is Workbook.</para>
/// </summary>
/// <param name="rangeName">Name of the range.</param>
IXLCell AddToNamed(String rangeName);
/// <summary>
/// Creates a named range out of this cell.
/// <para>If the named range exists, it will add this range to that named range.</para>
/// <param name="rangeName">Name of the range.</param>
/// <param name="scope">The scope for the named range.</param>
/// </summary>
IXLCell AddToNamed(String rangeName, XLScope scope);
/// <summary>
/// Creates a named range out of this cell.
/// <para>If the named range exists, it will add this range to that named range.</para>
/// <param name="rangeName">Name of the range.</param>
/// <param name="scope">The scope for the named range.</param>
/// <param name="comment">The comments for the named range.</param>
/// </summary>
IXLCell AddToNamed(String rangeName, XLScope scope, String comment);
IXLCell CopyFrom(IXLCell otherCell);
IXLCell CopyFrom(String otherCell);
IXLCell CopyTo(IXLCell target);
IXLCell CopyTo(String target);
/// <summary>
/// Textual representation of cell calculated value (as it is saved to a workbook or read from it)
/// </summary>
[Obsolete("Use CachedValue instead")]
String ValueCached { get; }
/// <summary>
/// Calculated value of cell formula. Is used for decreasing number of computations perfromed.
/// May hold invalid value when <see cref="NeedsRecalculation"/> flag is True.
/// </summary>
Object CachedValue { get; }
/// <summary>
/// Flag indicating that previously calculated cell value may be not valid anymore and has to be re-evaluated.
/// </summary>
Boolean NeedsRecalculation { get; }
/// <summary>
/// Invalidate <see cref="CachedValue"/> so the formula will be re-evaluated next time <see cref="Value"/> is accessed.
/// If cell does not contain formula nothing happens.
/// </summary>
void InvalidateFormula();
IXLRichText RichText { get; }
Boolean HasRichText { get; }
IXLComment Comment { get; }
Boolean HasComment { get; }
Boolean IsMerged();
IXLRange MergedRange();
Boolean IsEmpty();
Boolean IsEmpty(Boolean includeFormats);
IXLCell CellAbove();
IXLCell CellAbove(Int32 step);
IXLCell CellBelow();
IXLCell CellBelow(Int32 step);
IXLCell CellLeft();
IXLCell CellLeft(Int32 step);
IXLCell CellRight();
IXLCell CellRight(Int32 step);
IXLColumn WorksheetColumn();
IXLRow WorksheetRow();
Boolean HasDataValidation { get; }
IXLConditionalFormat AddConditionalFormat();
void Select();
Boolean Active { get; set; }
IXLCell SetActive(Boolean value = true);
Boolean HasFormula { get; }
Boolean HasArrayFormula { get; }
IXLRangeAddress FormulaReference { get; set; }
}
}
| |
using Frankfort.Threading.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
namespace Frankfort.Threading
{
public delegate void MultithreadedWorkloadComplete<T>(T[] workLoad);
public delegate void MultithreadedWorkloadPackageComplete<T>(T[] workLoad, int firstIndex, int lastIndex);
public delegate void ThreadDispatchDelegate();
public delegate void ThreadDispatchDelegateArg(object arg);
public delegate object ThreadDispatchDelegateArgReturn(object arg);
public delegate object ThreadDispatchDelegateReturn();
public delegate void ThreadedWorkCompleteEvent(IThreadWorkerObject finishedObject);
public delegate void ThreadPoolSchedulerEvent(IThreadWorkerObject[] finishedObjects);
public class ThreadPoolScheduler : MonoBehaviour
{
public bool DebugMode = false;
public bool ForceToMainThread = false;
public float WaitForSecondsTime = 0.001f;
private bool _providerThreadBusy;
private bool _shedularBusy;
private bool _isAborted;
private ASyncThreadWorkData workData;
private Thread providerThread;
private int workObjectIndex;
private ThreadPoolSchedulerEvent onCompleteCallBack;
private ThreadedWorkCompleteEvent onWorkerObjectDoneCallBack;
private bool safeMode;
public bool isBusy
{
get
{
return this._shedularBusy;
}
}
public float Progress
{
get
{
bool flag = this.workData == null || this.workData.workerPackages == null || this.workData.workerPackages.Length == 0;
float result;
if (flag)
{
result = 1f;
}
else
{
int num = 0;
int num2 = this.workData.workerPackages.Length;
while (true)
{
int num3 = num2 - 1;
num2 = num3;
if (num3 <= -1)
{
break;
}
bool finishedWorking = this.workData.workerPackages[num2].finishedWorking;
if (finishedWorking)
{
num3 = num;
num = num3 + 1;
}
}
result = (float)num / (float)this.workData.workerPackages.Length;
}
return result;
}
}
protected virtual void Awake()
{
MainThreadWatchdog.Init();
MainThreadDispatcher.Init();
UnityActivityWatchdog.Init();
}
protected virtual void OnApplicationQuit()
{
Debug.Log("ThreadPoolScheduler.OnApplicationQuit!");
this.AbortASyncThreads();
}
protected virtual void OnDestroy()
{
Debug.Log("ThreadPoolScheduler.OnDestroy!");
this.AbortASyncThreads();
}
public void StartASyncThreads(IThreadWorkerObject[] workerObjects, ThreadPoolSchedulerEvent onCompleteCallBack, ThreadedWorkCompleteEvent onPackageExecuted = null, int maxThreads = -1, bool safeMode = true)
{
bool shedularBusy = this._shedularBusy;
if (shedularBusy)
{
Debug.LogError("You are trying the start a new ASync threading-process, but is still Busy!");
}
else
{
bool flag = workerObjects == null || workerObjects.Length == 0;
if (flag)
{
Debug.LogError("Please provide an Array with atleast \"IThreadWorkerObject\"-object!");
}
else
{
this._isAborted = false;
this._shedularBusy = true;
this._providerThreadBusy = true;
this.onCompleteCallBack = onCompleteCallBack;
this.onWorkerObjectDoneCallBack = onPackageExecuted;
bool flag2 = !this.ForceToMainThread;
if (flag2)
{
base.StartCoroutine("WaitForCompletion");
this.workData = new ASyncThreadWorkData(workerObjects, safeMode, maxThreads);
this.providerThread = new Thread(new ThreadStart(this.InvokeASyncThreadPoolWork));
this.providerThread.Start();
}
else
{
base.StartCoroutine(this.WaitAndExecuteWorkerObjects(workerObjects));
}
}
}
}
private IEnumerator WaitAndExecuteWorkerObjects(IThreadWorkerObject[] workerObjects)
{
int num = 0;
while (num == 0)
{
num++;
yield return new WaitForEndOfFrame();
}
if (num != 1)
{
yield break;
}
int num2;
for (int i = 0; i < workerObjects.Length; i = num2 + 1)
{
workerObjects[i].ExecuteThreadedWork();
bool flag = this.onWorkerObjectDoneCallBack != null;
if (flag)
{
this.onWorkerObjectDoneCallBack(workerObjects[i]);
}
num2 = i;
}
this._shedularBusy = false;
this._providerThreadBusy = false;
bool flag2 = this.onCompleteCallBack != null;
if (flag2)
{
this.onCompleteCallBack(workerObjects);
}
yield break;
}
private IEnumerator WaitForCompletion()
{
while (true)
{
int num = 0;
if (num != 0)
{
if (num != 1)
{
break;
}
bool isAborted = this._isAborted;
if (isAborted)
{
goto Block_4;
}
int finishedPackagesCount = this.GetFinishedPackagesCount();
bool flag = finishedPackagesCount == this.workData.workerPackages.Length;
if (flag)
{
goto Block_5;
}
int unhandledFinishedPackagesCount = this.GetUnhandledFinishedPackagesCount();
bool debugMode = this.DebugMode;
if (debugMode)
{
Debug.Log(string.Concat(new object[]
{
" ----- unhandledPackages: ",
unhandledFinishedPackagesCount,
" ( out of: ",
finishedPackagesCount,
" completed so far...)"
}));
}
bool flag2 = unhandledFinishedPackagesCount > 0;
if (flag2)
{
ThreadWorkStatePackage[] array = this.workData.workerPackages;
for (int i = 0; i < array.Length; i++)
{
ThreadWorkStatePackage threadWorkStatePackage = array[i];
bool flag3 = threadWorkStatePackage.finishedWorking && !threadWorkStatePackage.eventFired;
if (flag3)
{
bool flag4 = this.onWorkerObjectDoneCallBack != null;
if (flag4)
{
this.onWorkerObjectDoneCallBack(threadWorkStatePackage.workerObject);
}
threadWorkStatePackage.eventFired = true;
}
threadWorkStatePackage = null;
}
array = null;
}
}
else
{
bool debugMode2 = this.DebugMode;
if (debugMode2)
{
num++;
Debug.Log(" ----- WaitForCompletion: " + Thread.CurrentThread.ManagedThreadId);
}
}
if (this._isAborted)
{
goto IL_21E;
}
yield return new WaitForSeconds(this.WaitForSecondsTime);
}
yield break;
Block_4:
Block_5:
IL_21E:
bool flag5 = !this._isAborted;
if (flag5)
{
bool debugMode3 = this.DebugMode;
if (debugMode3)
{
Debug.Log(" ----- Coroutine knows its done!");
}
IThreadWorkerObject[] finishedObjects = this.GetWorkerObjectsFromPackages();
this.workData.Dispose();
this.workData = null;
this._shedularBusy = false;
bool flag6 = this.onCompleteCallBack != null;
if (flag6)
{
this.onCompleteCallBack(finishedObjects);
}
finishedObjects = null;
}
yield break;
}
public void AbortASyncThreads()
{
bool flag = !this._providerThreadBusy;
if (!flag)
{
this._isAborted = true;
base.StopCoroutine("WaitForCompletion");
bool flag2 = this.workData != null && this.workData.workerPackages != null;
if (flag2)
{
ThreadWorkStatePackage[] workerPackages = this.workData.workerPackages;
Monitor.Enter(workerPackages);
try
{
ThreadWorkStatePackage[] workerPackages2 = this.workData.workerPackages;
for (int i = 0; i < workerPackages2.Length; i++)
{
ThreadWorkStatePackage threadWorkStatePackage = workerPackages2[i];
bool flag3 = threadWorkStatePackage.running && !threadWorkStatePackage.finishedWorking;
if (flag3)
{
threadWorkStatePackage.workerObject.AbortThreadedWork();
}
}
}
finally
{
Monitor.Exit(workerPackages);
}
}
bool flag4 = this.providerThread != null && this.providerThread.IsAlive;
if (flag4)
{
Debug.Log("ThreadPoolScheduler.AbortASyncThreads - Interrupt!");
this.providerThread.Interrupt();
this.providerThread.Join();
}
else
{
Debug.Log("ThreadPoolScheduler.AbortASyncThreads!");
}
this._providerThreadBusy = false;
}
}
public void InvokeASyncThreadPoolWork()
{
UnityActivityWatchdog.SleepOrAbortIfUnityInactive();
int num = this.workData.workerPackages.Length;
int num2 = Mathf.Clamp(this.workData.maxWorkingThreads, 1, num);
bool debugMode = this.DebugMode;
if (debugMode)
{
Debug.Log(string.Concat(new object[]
{
" ----- InvokeASyncThreadPoolWork. startBurst: ",
num2,
", totalWork: ",
num
}));
}
int num3 = 0;
while (num3 < num2 && !this._isAborted)
{
bool flag = this.workData.workerPackages[num3] != null;
if (flag)
{
this.workData.workerPackages[num3].started = true;
ThreadPool.QueueUserWorkItem(new WaitCallback(this.workData.workerPackages[num3].ExecuteThreadWork), num3);
}
int num4 = num3;
num3 = num4 + 1;
}
bool debugMode2 = this.DebugMode;
if (debugMode2)
{
Debug.Log(" ----- Burst with WorkerObjects being processed!");
}
this.workObjectIndex = num2;
while (this.workObjectIndex < num && !this._isAborted)
{
UnityActivityWatchdog.SleepOrAbortIfUnityInactive();
AutoResetEvent[] startedPackageEvents = this.GetStartedPackageEvents();
bool flag2 = startedPackageEvents.Length > 0;
if (flag2)
{
WaitHandle.WaitAny(startedPackageEvents);
}
this.workData.workerPackages[this.workObjectIndex].started = true;
ThreadPool.QueueUserWorkItem(new WaitCallback(this.workData.workerPackages[this.workObjectIndex].ExecuteThreadWork), this.workObjectIndex);
int num4 = this.workObjectIndex;
this.workObjectIndex = num4 + 1;
}
bool debugMode3 = this.DebugMode;
if (debugMode3)
{
Debug.Log(" ----- all packages fed to the pool!");
}
AutoResetEvent[] startedPackageEvents2 = this.GetStartedPackageEvents();
bool flag3 = startedPackageEvents2.Length > 0;
if (flag3)
{
UnityActivityWatchdog.SleepOrAbortIfUnityInactive();
WaitHandle.WaitAll(startedPackageEvents2);
}
bool debugMode4 = this.DebugMode;
if (debugMode4)
{
Debug.Log(" ----- PROVIDER THREAD DONE");
}
this._providerThreadBusy = false;
}
private AutoResetEvent[] GetStartedPackageEvents()
{
List<AutoResetEvent> list = new List<AutoResetEvent>();
int num;
for (int i = 0; i < this.workData.workerPackages.Length; i = num + 1)
{
ThreadWorkStatePackage threadWorkStatePackage = this.workData.workerPackages[i];
bool flag = threadWorkStatePackage.started && !threadWorkStatePackage.finishedWorking;
if (flag)
{
list.Add(threadWorkStatePackage.waitHandle);
}
num = i;
}
return list.ToArray();
}
private IThreadWorkerObject[] GetWorkerObjectsFromPackages()
{
bool flag = this.workData == null || this.workData.workerPackages == null;
IThreadWorkerObject[] result;
if (flag)
{
result = new IThreadWorkerObject[0];
}
else
{
IThreadWorkerObject[] array = new IThreadWorkerObject[this.workData.workerPackages.Length];
int num = this.workData.workerPackages.Length;
while (true)
{
int num2 = num - 1;
num = num2;
if (num2 <= -1)
{
break;
}
array[num] = this.workData.workerPackages[num].workerObject;
}
result = array;
}
return result;
}
public int GetFinishedPackagesCount()
{
bool flag = this.workData == null || this.workData.workerPackages == null;
int result;
if (flag)
{
result = 0;
}
else
{
int num = 0;
int num2 = this.workData.workerPackages.Length;
while (true)
{
int num3 = num2 - 1;
num2 = num3;
if (num3 <= -1)
{
break;
}
bool finishedWorking = this.workData.workerPackages[num2].finishedWorking;
if (finishedWorking)
{
num3 = num;
num = num3 + 1;
}
}
result = num;
}
return result;
}
public int GetUnhandledFinishedPackagesCount()
{
bool flag = this.workData == null || this.workData.workerPackages == null;
int result;
if (flag)
{
result = 0;
}
else
{
int num = 0;
int num2 = this.workData.workerPackages.Length;
while (true)
{
int num3 = num2 - 1;
num2 = num3;
if (num3 <= -1)
{
break;
}
bool flag2 = this.workData.workerPackages[num2].finishedWorking && !this.workData.workerPackages[num2].eventFired;
if (flag2)
{
num3 = num;
num = num3 + 1;
}
}
result = num;
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using fNbt;
using fNbt.Serialization;
using Craft.Net.Common;
namespace Craft.Net.Anvil
{
/// <summary>
/// Represents a Minecraft level
/// </summary>
public class Level : IDisposable
{
public const int TickLength = 1000 / 20;
[NbtIgnore]
private IWorldGenerator WorldGenerator { get; set; }
[NbtIgnore]
private string DatFile { get; set; }
[NbtIgnore]
public string BaseDirectory { get; private set; }
[NbtIgnore]
public List<World> Worlds { get; set; }
[NbtIgnore]
public World DefaultWorld
{
get
{
if (Worlds.Count == 0)
throw new InvalidOperationException("This level is associated with no worlds.");
return Worlds[0];
}
}
#region NBT Fields
/// <summary>
/// Always set to 19133.
/// </summary>
[TagName("version")]
public int Version { get; private set; }
/// <summary>
/// True if this level has been initialized with a world.
/// </summary>
[TagName("initialized")]
public bool Initialized { get; private set; }
/// <summary>
/// The name of this level.
/// </summary>
public string LevelName { get; set; }
/// <summary>
/// The name of the world generator to use. Corresponds to IWorldGenerator.GeneratorName.
/// </summary>
[TagName("generatorName")]
public string GeneratorName { get; set; }
/// <summary>
/// The version number of the world generator to use.
/// </summary>
[TagName("generatorVersion")]
public int GeneratorVersion { get; set; }
/// <summary>
/// The options to pass to the world generator.
/// </summary>
[TagName("generatorOptions")]
public string GeneratorOptions { get; set; }
/// <summary>
/// The level's randomly generated seed.
/// </summary>
public long RandomSeed { get; set; }
/// <summary>
/// If true, structures like villages and strongholds will generate (depending on the IWorldGenerator).
/// </summary>
public bool MapFeatures { get; set; }
/// <summary>
/// Unix timestamp of last time this level was played.
/// </summary>
public long LastPlayed { get; set; }
/// <summary>
/// If true, single player users will be allowed to issue commands.
/// </summary>
[TagName("allowCommands")]
public bool AllowCommands { get; set; }
/// <summary>
/// If true, the world is to be deleted upon the death of the user (singleplayer only).
/// </summary>
[TagName("hardcore")]
public bool Hardcore { get; set; }
private int GameType { get; set; }
/// <summary>
/// The default game mode for new players.
/// </summary>
[NbtIgnore]
public GameMode GameMode
{
get { return (GameMode)GameType; }
set { GameType = (int)value; }
}
/// <summary>
/// The number of ticks since this level was created.
/// </summary>
public long Time { get; set; }
/// <summary>
/// The number of ticks in the current day.
/// </summary>
public long DayTime
{
get { return _DayTime; }
set { _DayTime = value % 24000; }
}
private long _DayTime;
/// <summary>
/// This level's spawn point in the overworld.
/// </summary>
[NbtIgnore]
public Vector3 Spawn
{
get
{
return new Vector3(SpawnX, SpawnY, SpawnZ);
}
set
{
SpawnX = (int)value.X;
SpawnY = (int)value.Y;
SpawnZ = (int)value.Z;
}
}
private int SpawnX { get; set; }
private int SpawnY { get; set; }
private int SpawnZ { get; set; }
/// <summary>
/// True if the level is currently raining.
/// </summary>
[TagName("raining")]
public bool Raining { get; set; }
/// <summary>
/// The number of ticks until the next weather cycle.
/// </summary>
[TagName("rainTime")]
public int RainTime { get; set; }
/// <summary>
/// True if it is currently thundering.
/// </summary>
[TagName("thundering")]
public bool Thundering { get; set; }
/// <summary>
/// The number of ticks until the next thunder cycle.
/// </summary>
[TagName("thunderTime")]
public int ThunderTime { get; set; }
/// <summary>
/// The rules for this level.
/// </summary>
public GameRules GameRules { get; set; }
#endregion
/// <summary>
/// An in-memory level, with all defaults set as such.
/// </summary>
public Level()
{
Version = 19133;
Initialized = true;
LevelName = "Level";
GeneratorVersion = 1;
GeneratorOptions = string.Empty;
double seed = MathHelper.Random.NextDouble();
unsafe { RandomSeed = *((long*)&seed); }
MapFeatures = true;
LastPlayed = DateTime.UtcNow.Ticks;
AllowCommands = true;
Hardcore = false;
GameMode = GameMode.Survival;
Time = 0;
DayTime = 0;
Spawn = Vector3.Zero;
Raining = false;
RainTime = MathHelper.Random.Next(0, 100000);
Thundering = false;
ThunderTime = MathHelper.Random.Next(0, 100000);
GameRules = new GameRules();
Worlds = new List<World>();
}
/// <summary>
/// Creates an in-memory world with a given world generator.
/// </summary>
public Level(IWorldGenerator generator) : this()
{
GeneratorName = generator.GeneratorName;
generator.Seed = RandomSeed;
generator.Initialize(this);
WorldGenerator = generator;
Spawn = WorldGenerator.SpawnPoint;
}
/// <summary>
/// Creates a named in-memory world.
/// </summary>
public Level(string levelName) : this()
{
LevelName = levelName;
}
/// <summary>
/// Creates a named in-memory world with a given world generator.
/// </summary>
public Level(IWorldGenerator generator, string levelName) : this(generator)
{
LevelName = levelName;
}
/// <summary>
/// Adds a world to this level.
/// </summary>
public void AddWorld(World world)
{
if (Worlds.Any(w => w.Name.ToUpper() == world.Name.ToUpper()))
throw new InvalidOperationException("A world with the same name already exists in this level.");
Worlds.Add(world);
}
/// <summary>
/// Creates and adds a world to this level, with the given name.
/// </summary>
public void AddWorld(string name, IWorldGenerator worldGenerator = null)
{
if (Worlds.Any(w => w.Name.ToUpper() == name.ToUpper()))
throw new InvalidOperationException("A world with the same name already exists in this level.");
var world = new World(name);
if (worldGenerator == null)
world.WorldGenerator = WorldGenerator;
else
world.WorldGenerator = worldGenerator;
Worlds.Add(world);
}
/// <summary>
/// Saves this level to a directory.
/// </summary>
public void SaveTo(string directory)
{
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
Save(Path.Combine(directory, "level.dat"));
}
/// <summary>
/// Saves this level to a file, and the worlds to the same directory.
/// </summary>
public void Save(string file)
{
DatFile = file;
if (!Path.IsPathRooted(file))
file = Path.Combine(Directory.GetCurrentDirectory(), file);
BaseDirectory = Path.GetDirectoryName(file);
Save();
}
/// <summary>
/// Saves this level. This will not work with an in-memory world.
/// </summary>
public void Save()
{
if (DatFile == null)
throw new InvalidOperationException("This level exists only in memory. Use Save(string).");
LastPlayed = DateTime.UtcNow.Ticks;
var serializer = new NbtSerializer(typeof(Level));
var tag = serializer.Serialize(this, "Data") as NbtCompound;
var file = new NbtFile();
file.RootTag.Add(tag);
file.SaveToFile(DatFile, NbtCompression.GZip);
// Save worlds
foreach (var world in Worlds)
{
if (world.BaseDirectory == null)
world.Save(Path.Combine(BaseDirectory, world.Name));
else
world.Save();
}
}
/// <summary>
/// Loads a level by directory name from the .minecraft saves folder.
/// </summary>
public static Level LoadSavedLevel(string world)
{
return LoadFrom(Path.Combine(GetDotMinecraftPath(), "saves", world));
}
private static string GetDotMinecraftPath()
{
if (RuntimeInfo.IsLinux)
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".minecraft");
if (RuntimeInfo.IsMacOSX)
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Library", "Application Support", ".minecraft");
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ".minecraft");
}
/// <summary>
/// Loads a level from the given directory.
/// </summary>
public static Level LoadFrom(string directory)
{
return Load(Path.Combine(directory, "level.dat"));
}
/// <summary>
/// Loads a level from the given level.dat file.
/// </summary>
public static Level Load(string file)
{
if (!Path.IsPathRooted(file))
file = Path.Combine(Directory.GetCurrentDirectory(), file);
var serializer = new NbtSerializer(typeof(Level));
var nbtFile = new NbtFile(file);
var level = (Level)serializer.Deserialize(nbtFile.RootTag["Data"]);
level.DatFile = file;
level.BaseDirectory = Path.GetDirectoryName(file);
level.WorldGenerator = GetGenerator(level.GeneratorName);
level.WorldGenerator.Initialize(level);
var worlds = Directory.GetDirectories(level.BaseDirectory).Where(
d => Directory.GetFiles(d).Any(f => f.EndsWith(".mca") || f.EndsWith(".mcr")));
foreach (var world in worlds)
{
var w = World.LoadWorld(world);
w.WorldGenerator = level.WorldGenerator;
level.AddWorld(w);
}
return level;
}
/// <summary>
/// Gets a world generator for the given world generator name.
/// </summary>
public static IWorldGenerator GetGenerator(string generatorName)
{
IWorldGenerator worldGenerator = null;
Type generatorType;
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var types = assembly.GetTypes().Where(t =>
!t.IsAbstract && t.IsClass && typeof(IWorldGenerator).IsAssignableFrom(t) &&
t.GetConstructors().Any(c => c.IsPublic && !c.GetParameters().Any())).ToArray();
generatorType = types.FirstOrDefault(t =>
(worldGenerator = (IWorldGenerator)Activator.CreateInstance(t)).GeneratorName == generatorName);
if (generatorType != null)
break;
}
return worldGenerator;
}
// Internally, we use network slots everywhere, but on disk, we need to use data slots
// Maybe someday we can use the Window classes to remap these around or something
// Or better yet, Mojang can stop making terrible design decisions
public static int DataSlotToNetworkSlot(int index)
{
if (index <= 8)
index += 36;
else if (index == 100)
index = 8;
else if (index == 101)
index = 7;
else if (index == 102)
index = 6;
else if (index == 103)
index = 5;
else if (index >= 80 && index <= 83)
index -= 79;
return index;
}
public static int NetworkSlotToDataSlot(int index)
{
if (index >= 36 && index <= 44)
index -= 36;
else if (index == 8)
index = 100;
else if (index == 7)
index = 101;
else if (index == 6)
index = 102;
else if (index == 5)
index = 103;
else if (index >= 1 && index <= 4)
index += 79;
return index;
}
public void Dispose()
{
foreach (var world in Worlds)
world.Dispose();
}
}
}
| |
#region License
/*
* HttpRequest.cs
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contributors
/*
* Contributors:
* - David Burhans
*/
#endregion
using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using CustomWebSocketSharp.Net;
namespace CustomWebSocketSharp
{
internal class HttpRequest : HttpBase
{
#region Private Fields
private string _method;
private string _uri;
private bool _websocketRequest;
private bool _websocketRequestSet;
#endregion
#region Private Constructors
private HttpRequest (string method, string uri, Version version, NameValueCollection headers)
: base (version, headers)
{
_method = method;
_uri = uri;
}
#endregion
#region Internal Constructors
internal HttpRequest (string method, string uri)
: this (method, uri, HttpVersion.Version11, new NameValueCollection ())
{
Headers["User-Agent"] = "websocket-sharp/1.0";
}
#endregion
#region Public Properties
public AuthenticationResponse AuthenticationResponse {
get {
var res = Headers["Authorization"];
return res != null && res.Length > 0
? AuthenticationResponse.Parse (res)
: null;
}
}
public CookieCollection Cookies {
get {
return Headers.GetCookies (false);
}
}
public string HttpMethod {
get {
return _method;
}
}
public bool IsWebSocketRequest {
get {
if (!_websocketRequestSet) {
var headers = Headers;
_websocketRequest = _method == "GET" &&
ProtocolVersion > HttpVersion.Version10 &&
headers.Contains ("Upgrade", "websocket") &&
headers.Contains ("Connection", "Upgrade");
_websocketRequestSet = true;
}
return _websocketRequest;
}
}
public string RequestUri {
get {
return _uri;
}
}
#endregion
#region Internal Methods
internal static HttpRequest CreateConnectRequest (Uri uri)
{
var host = uri.DnsSafeHost;
var port = uri.Port;
var authority = String.Format ("{0}:{1}", host, port);
var req = new HttpRequest ("CONNECT", authority);
req.Headers["Host"] = port == 80 ? host : authority;
return req;
}
internal static HttpRequest CreateWebSocketRequest (Uri uri)
{
var req = new HttpRequest ("GET", uri.PathAndQuery);
var headers = req.Headers;
// Only includes a port number in the Host header value if it's non-default.
// See: https://tools.ietf.org/html/rfc6455#page-17
var port = uri.Port;
var schm = uri.Scheme;
headers["Host"] = (port == 80 && schm == "ws") || (port == 443 && schm == "wss")
? uri.DnsSafeHost
: uri.Authority;
headers["Upgrade"] = "websocket";
headers["Connection"] = "Upgrade";
return req;
}
internal HttpResponse GetResponse (Stream stream, int millisecondsTimeout)
{
var buff = ToByteArray ();
stream.Write (buff, 0, buff.Length);
return Read<HttpResponse> (stream, HttpResponse.Parse, millisecondsTimeout);
}
internal static HttpRequest Parse (string[] headerParts)
{
var requestLine = headerParts[0].Split (new[] { ' ' }, 3);
if (requestLine.Length != 3)
throw new ArgumentException ("Invalid request line: " + headerParts[0]);
var headers = new WebHeaderCollection ();
for (int i = 1; i < headerParts.Length; i++)
headers.InternalSet (headerParts[i], false);
return new HttpRequest (
requestLine[0], requestLine[1], new Version (requestLine[2].Substring (5)), headers);
}
internal static HttpRequest Read (Stream stream, int millisecondsTimeout)
{
return Read<HttpRequest> (stream, Parse, millisecondsTimeout);
}
#endregion
#region Public Methods
public void SetCookies (CookieCollection cookies)
{
if (cookies == null || cookies.Count == 0)
return;
var buff = new StringBuilder (64);
foreach (var cookie in cookies.Sorted)
if (!cookie.Expired)
buff.AppendFormat ("{0}; ", cookie.ToString ());
var len = buff.Length;
if (len > 2) {
buff.Length = len - 2;
Headers["Cookie"] = buff.ToString ();
}
}
public override string ToString ()
{
var output = new StringBuilder (64);
output.AppendFormat ("{0} {1} HTTP/{2}{3}", _method, _uri, ProtocolVersion, CrLf);
var headers = Headers;
foreach (var key in headers.AllKeys)
output.AppendFormat ("{0}: {1}{2}", key, headers[key], CrLf);
output.Append (CrLf);
var entity = EntityBody;
if (entity.Length > 0)
output.Append (entity);
return output.ToString ();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using Gwen.Input;
using Newtonsoft.Json;
namespace Gwen.Control
{
[JsonObject(MemberSerialization.OptIn)]
[JsonConverter(typeof(Serialization.GwenConverter))]
public class MultilineTextBox : Label
{
private readonly ScrollControl scrollControl;
private bool selectAll;
private Point cursorPos;
private Point cursorEnd;
protected Rectangle caretBounds;
private float lastInputTime;
private List<string> textLines = new List<string>();
private Point startPoint {
get {
if (CursorPosition.Y == cursorEnd.Y) {
return CursorPosition.X < CursorEnd.X ? CursorPosition : CursorEnd;
} else {
return CursorPosition.Y < CursorEnd.Y ? CursorPosition : CursorEnd;
}
}
}
private Point endPoint {
get {
if (CursorPosition.Y == cursorEnd.Y) {
return CursorPosition.X > CursorEnd.X ? CursorPosition : CursorEnd;
} else {
return CursorPosition.Y > CursorEnd.Y ? CursorPosition : CursorEnd;
}
}
}
/// <summary>
/// Indicates whether the text has active selection.
/// </summary>
public bool HasSelection { get { return cursorPos != cursorEnd; } }
/// <summary>
/// Invoked when the text has changed.
/// </summary>
public event GwenEventHandler<EventArgs> TextChanged;
/// <summary>
/// Get a point representing where the cursor physically appears on the screen.
/// Y is line number, X is character position on that line.
/// </summary>
public Point CursorPosition {
get {
if (textLines == null || textLines.Count() == 0)
return new Point(0, 0);
int Y = cursorPos.Y;
Y = Math.Max(Y, 0);
Y = Math.Min(Y, textLines.Count() - 1);
int X = cursorPos.X; //X may be beyond the last character, but we will want to draw it at the end of line.
X = Math.Max(X, 0);
X = Math.Min(X, textLines[Y].Length);
return new Point(X, Y);
}
set {
cursorPos.X = value.X;
cursorPos.Y = value.Y;
refreshCursorBounds();
}
}
/// <summary>
/// Get a point representing where the endpoint of text selection.
/// Y is line number, X is character position on that line.
/// </summary>
public Point CursorEnd {
get {
if (textLines == null || textLines.Count() == 0)
return new Point(0, 0);
int Y = cursorEnd.Y;
Y = Math.Max(Y, 0);
Y = Math.Min(Y, textLines.Count() - 1);
int X = cursorEnd.X; //X may be beyond the last character, but we will want to draw it at the end of line.
X = Math.Max(X, 0);
X = Math.Min(X, textLines[Y].Length);
return new Point(X, Y);
}
set {
cursorEnd.X = value.X;
cursorEnd.Y = value.Y;
refreshCursorBounds();
}
}
/// <summary>
/// Indicates whether the control will accept Tab characters as input.
/// </summary>
public bool AcceptTabs { get; set; }
/// <summary>
/// Returns the number of lines that are in the Multiline Text Box.
/// </summary>
public int TotalLines
{
get
{
return textLines.Count;
}
}
/// <summary>
/// Gets and sets the text to display to the user. Each line is seperated by
/// an Environment.NetLine character.
/// </summary>
public override string Text {
get {
string ret = "";
for (int i = 0; i < TotalLines; i++){
ret += textLines[i];
if (i != TotalLines - 1) {
ret += Environment.NewLine;
}
}
return ret;
}
set {
//Label (base) calls SetText.
//SetText is overloaded to dump value into TextLines.
//We're cool.
base.Text = value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="TextBox"/> class.
/// </summary>
/// <param name="parent">Parent control.</param>
public MultilineTextBox(ControlBase parent) : base(parent)
{
AutoSizeToContents = false;
SetSize(200, 20);
MouseInputEnabled = true;
KeyboardInputEnabled = true;
Alignment = Pos.Left | Pos.Top;
TextPadding = new Padding(4, 2, 4, 2);
cursorPos = new Point(0, 0);
cursorEnd = new Point(0, 0);
selectAll = false;
TextColor = Color.FromArgb(255, 50, 50, 50); // TODO: From Skin
IsTabable = false;
AcceptTabs = true;
scrollControl = new ScrollControl(this);
scrollControl.Dock = Pos.Fill;
scrollControl.EnableScroll(true, true);
scrollControl.AutoHideBars = true;
scrollControl.Margin = Margin.One;
innerPanel = scrollControl;
text.Parent = innerPanel;
scrollControl.InnerPanel.BoundsChanged += new GwenEventHandler<EventArgs>(scrollChanged);
textLines.Add(String.Empty);
// [halfofastaple] TODO Figure out where these numbers come from. See if we can remove the magic numbers.
// This should be as simple as 'm_ScrollControl.AutoSizeToContents = true' or 'm_ScrollControl.NoBounds()'
scrollControl.SetInnerSize(1000, 1000);
AddAccelerator("Ctrl + C", onCopy);
AddAccelerator("Ctrl + X", onCut);
AddAccelerator("Ctrl + V", onPaste);
AddAccelerator("Ctrl + A", onSelectAll);
}
public string GetTextLine(int index) {
return textLines[index];
}
public void SetTextLine(int index, string value) {
textLines[index] = value;
}
/// <summary>
/// Refreshes the cursor location and selected area when the inner panel scrolls
/// </summary>
/// <param name="control">The inner panel the text is embedded in</param>
private void scrollChanged(ControlBase control, EventArgs args)
{
refreshCursorBounds();
}
/// <summary>
/// Handler for text changed event.
/// </summary>
protected override void onTextChanged() {
base.onTextChanged();
if (TextChanged != null)
TextChanged.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Handler for character input event.
/// </summary>
/// <param name="chr">Character typed.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool onChar(char chr) {
//base.onChar(chr);
if (chr == '\t' && !AcceptTabs) return false;
insertText(chr.ToString());
return true;
}
/// <summary>
/// Inserts text at current cursor position, erasing selection if any.
/// </summary>
/// <param name="text">Text to insert.</param>
protected void insertText(string text) {
// TODO: Make sure fits (implement maxlength)
if (HasSelection) {
EraseSelection();
}
string str = textLines[cursorPos.Y];
str = str.Insert(CursorPosition.X, text);
textLines[cursorPos.Y] = str;
cursorPos.X = CursorPosition.X + text.Length;
cursorEnd = cursorPos;
Invalidate();
refreshCursorBounds();
}
/// <summary>
/// Renders the control using specified skin.
/// </summary>
/// <param name="skin">Skin to use.</param>
protected override void render(Skin.SkinBase skin) {
base.render(skin);
if (ShouldDrawBackground)
skin.DrawTextBox(this);
if (!HasFocus) return;
int VerticalOffset = 2 - scrollControl.VerticalScroll;
int VerticalSize = Font.Size + 6;
// Draw selection.. if selected..
if (cursorPos != cursorEnd) {
if (startPoint.Y == endPoint.Y) {
Point pA = getCharacterPosition(startPoint);
Point pB = getCharacterPosition(endPoint);
Rectangle SelectionBounds = new Rectangle();
SelectionBounds.X = Math.Min(pA.X, pB.X);
SelectionBounds.Y = pA.Y - VerticalOffset;
SelectionBounds.Width = Math.Max(pA.X, pB.X) - SelectionBounds.X;
SelectionBounds.Height = VerticalSize;
skin.Renderer.DrawColor = Color.FromArgb(200, 50, 170, 255);
skin.Renderer.DrawFilledRect(SelectionBounds);
} else {
/* Start */
Point pA = getCharacterPosition(startPoint);
Point pB = getCharacterPosition(new Point(textLines[startPoint.Y].Length, startPoint.Y));
Rectangle SelectionBounds = new Rectangle();
SelectionBounds.X = Math.Min(pA.X, pB.X);
SelectionBounds.Y = pA.Y - VerticalOffset;
SelectionBounds.Width = Math.Max(pA.X, pB.X) - SelectionBounds.X;
SelectionBounds.Height = VerticalSize;
skin.Renderer.DrawColor = Color.FromArgb(200, 50, 170, 255);
skin.Renderer.DrawFilledRect(SelectionBounds);
/* Middle */
for (int i = 1; i < endPoint.Y - startPoint.Y; i++) {
pA = getCharacterPosition(new Point(0, startPoint.Y + i));
pB = getCharacterPosition(new Point(textLines[startPoint.Y + i].Length, startPoint.Y + i));
SelectionBounds = new Rectangle();
SelectionBounds.X = Math.Min(pA.X, pB.X);
SelectionBounds.Y = pA.Y - VerticalOffset;
SelectionBounds.Width = Math.Max(pA.X, pB.X) - SelectionBounds.X;
SelectionBounds.Height = VerticalSize;
skin.Renderer.DrawColor = Color.FromArgb(200, 50, 170, 255);
skin.Renderer.DrawFilledRect(SelectionBounds);
}
/* End */
pA = getCharacterPosition(new Point(0, endPoint.Y));
pB = getCharacterPosition(endPoint);
SelectionBounds = new Rectangle();
SelectionBounds.X = Math.Min(pA.X, pB.X);
SelectionBounds.Y = pA.Y - VerticalOffset;
SelectionBounds.Width = Math.Max(pA.X, pB.X) - SelectionBounds.X;
SelectionBounds.Height = VerticalSize;
skin.Renderer.DrawColor = Color.FromArgb(200, 50, 170, 255);
skin.Renderer.DrawFilledRect(SelectionBounds);
}
}
// Draw caret
float time = Platform.Neutral.GetTimeInSeconds() - lastInputTime;
if ((time % 1.0f) <= 0.5f) {
skin.Renderer.DrawColor = Color.Black;
skin.Renderer.DrawFilledRect(caretBounds);
}
}
protected void refreshCursorBounds() {
lastInputTime = Platform.Neutral.GetTimeInSeconds();
makeCaretVisible();
Point pA = getCharacterPosition(CursorPosition);
//Point pB = getCharacterPosition(cursorEnd);
//m_SelectionBounds.X = Math.Min(pA.X, pB.X);
//m_SelectionBounds.Y = TextY - 1;
//m_SelectionBounds.Width = Math.Max(pA.X, pB.X) - m_SelectionBounds.X;
//m_SelectionBounds.Height = TextHeight + 2;
caretBounds.X = pA.X;
caretBounds.Y = (pA.Y + 1);
caretBounds.Y += scrollControl.VerticalScroll;
caretBounds.Width = 1;
caretBounds.Height = Font.Size + 2;
Redraw();
}
/// <summary>
/// Handler for Paste event.
/// </summary>
/// <param name="from">Source control.</param>
protected override void onPaste(ControlBase from, EventArgs args) {
base.onPaste(from, args);
insertText(Platform.Neutral.GetClipboardText());
}
/// <summary>
/// Handler for Copy event.
/// </summary>
/// <param name="from">Source control.</param>
protected override void onCopy(ControlBase from, EventArgs args) {
if (!HasSelection) return;
base.onCopy(from, args);
Platform.Neutral.SetClipboardText(GetSelection());
}
/// <summary>
/// Handler for Cut event.
/// </summary>
/// <param name="from">Source control.</param>
protected override void onCut(ControlBase from, EventArgs args) {
if (!HasSelection) return;
base.onCut(from, args);
Platform.Neutral.SetClipboardText(GetSelection());
EraseSelection();
}
/// <summary>
/// Handler for Select All event.
/// </summary>
/// <param name="from">Source control.</param>
protected override void onSelectAll(ControlBase from, EventArgs args) {
//base.onSelectAll(from);
cursorEnd = new Point(0, 0);
cursorPos = new Point(textLines.Last().Length, textLines.Count());
refreshCursorBounds();
}
/// <summary>
/// Handler invoked on mouse double click (left) event.
/// </summary>
/// <param name="x">X coordinate.</param>
/// <param name="y">Y coordinate.</param>
protected override void onMouseDoubleClickedLeft(int x, int y) {
//base.onMouseDoubleClickedLeft(x, y);
onSelectAll(this, EventArgs.Empty);
}
/// <summary>
/// Handler for Return keyboard event.
/// </summary>
/// <param name="down">Indicates whether the key was pressed or released.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool onKeyReturn(bool down) {
if (down) return true;
//Split current string, putting the rhs on a new line
string CurrentLine = textLines[cursorPos.Y];
string lhs = CurrentLine.Substring(0, CursorPosition.X);
string rhs = CurrentLine.Substring(CursorPosition.X);
textLines[cursorPos.Y] = lhs;
textLines.Insert(cursorPos.Y + 1, rhs);
onKeyDown(true);
onKeyHome(true);
if (cursorPos.Y == TotalLines - 1) {
scrollControl.ScrollToBottom();
}
Invalidate();
refreshCursorBounds();
return true;
}
/// <summary>
/// Handler for Backspace keyboard event.
/// </summary>
/// <param name="down">Indicates whether the key was pressed or released.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool onKeyBackspace(bool down) {
if (!down) return true;
if (HasSelection) {
EraseSelection();
return true;
}
if (cursorPos.X == 0) {
if (cursorPos.Y == 0) {
return true; //Nothing left to delete
} else {
string lhs = textLines[cursorPos.Y - 1];
string rhs = textLines[cursorPos.Y];
textLines.RemoveAt(cursorPos.Y);
onKeyUp(true);
onKeyEnd(true);
textLines[cursorPos.Y] = lhs + rhs;
}
} else {
string CurrentLine = textLines[cursorPos.Y];
string lhs = CurrentLine.Substring(0, CursorPosition.X - 1);
string rhs = CurrentLine.Substring(CursorPosition.X);
textLines[cursorPos.Y] = lhs + rhs;
onKeyLeft(true);
}
Invalidate();
refreshCursorBounds();
return true;
}
/// <summary>
/// Handler for Delete keyboard event.
/// </summary>
/// <param name="down">Indicates whether the key was pressed or released.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool onKeyDelete(bool down) {
if (!down) return true;
if (HasSelection) {
EraseSelection();
return true;
}
if (cursorPos.X == textLines[cursorPos.Y].Length) {
if (cursorPos.Y == textLines.Count - 1) {
return true; //Nothing left to delete
} else {
string lhs = textLines[cursorPos.Y];
string rhs = textLines[cursorPos.Y + 1];
textLines.RemoveAt(cursorPos.Y + 1);
onKeyEnd(true);
textLines[cursorPos.Y] = lhs + rhs;
}
} else {
string CurrentLine = textLines[cursorPos.Y];
string lhs = CurrentLine.Substring(0, CursorPosition.X);
string rhs = CurrentLine.Substring(CursorPosition.X + 1);
textLines[cursorPos.Y] = lhs + rhs;
}
Invalidate();
refreshCursorBounds();
return true;
}
/// <summary>
/// Handler for Up Arrow keyboard event.
/// </summary>
/// <param name="down">Indicates whether the key was pressed or released.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool onKeyUp(bool down) {
if (!down) return true;
if (cursorPos.Y > 0) {
cursorPos.Y -= 1;
}
if (!Input.InputHandler.IsShiftDown) {
cursorEnd = cursorPos;
}
Invalidate();
refreshCursorBounds();
return true;
}
/// <summary>
/// Handler for Down Arrow keyboard event.
/// </summary>
/// <param name="down">Indicates whether the key was pressed or released.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool onKeyDown(bool down) {
if (!down) return true;
if (cursorPos.Y < TotalLines - 1) {
cursorPos.Y += 1;
}
if (!Input.InputHandler.IsShiftDown) {
cursorEnd = cursorPos;
}
Invalidate();
refreshCursorBounds();
return true;
}
/// <summary>
/// Handler for Left Arrow keyboard event.
/// </summary>
/// <param name="down">Indicates whether the key was pressed or released.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool onKeyLeft(bool down) {
if (!down) return true;
if (cursorPos.X > 0) {
cursorPos.X = Math.Min(cursorPos.X - 1, textLines[cursorPos.Y].Length);
} else {
if (cursorPos.Y > 0) {
onKeyUp(down);
onKeyEnd(down);
}
}
if (!Input.InputHandler.IsShiftDown) {
cursorEnd = cursorPos;
}
Invalidate();
refreshCursorBounds();
return true;
}
/// <summary>
/// Handler for Right Arrow keyboard event.
/// </summary>
/// <param name="down">Indicates whether the key was pressed or released.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool onKeyRight(bool down) {
if (!down) return true;
if (cursorPos.X < textLines[cursorPos.Y].Length) {
cursorPos.X = Math.Min(cursorPos.X + 1, textLines[cursorPos.Y].Length);
} else {
if (cursorPos.Y < textLines.Count - 1) {
onKeyDown(down);
onKeyHome(down);
}
}
if (!Input.InputHandler.IsShiftDown) {
cursorEnd = cursorPos;
}
Invalidate();
refreshCursorBounds();
return true;
}
/// <summary>
/// Handler for Home Key keyboard event.
/// </summary>
/// <param name="down">Indicates whether the key was pressed or released.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool onKeyHome(bool down) {
if (!down) return true;
cursorPos.X = 0;
if (!Input.InputHandler.IsShiftDown) {
cursorEnd = cursorPos;
}
Invalidate();
refreshCursorBounds();
return true;
}
/// <summary>
/// Handler for End Key keyboard event.
/// </summary>
/// <param name="down">Indicates whether the key was pressed or released.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool onKeyEnd(bool down) {
if (!down) return true;
cursorPos.X = textLines[cursorPos.Y].Length;
if (!Input.InputHandler.IsShiftDown) {
cursorEnd = cursorPos;
}
Invalidate();
refreshCursorBounds();
return true;
}
/// <summary>
/// Handler for Tab Key keyboard event.
/// </summary>
/// <param name="down">Indicates whether the key was pressed or released.</param>
/// <returns>
/// True if handled.
/// </returns>
protected override bool onKeyTab(bool down) {
if (!AcceptTabs) return base.onKeyTab(down);
if (!down) return false;
onChar('\t');
return true;
}
/// <summary>
/// Returns currently selected text.
/// </summary>
/// <returns>Current selection.</returns>
public string GetSelection() {
if (!HasSelection) return String.Empty;
string str = String.Empty;
if (startPoint.Y == endPoint.Y) {
int start = startPoint.X;
int end = endPoint.X;
str = textLines[cursorPos.Y];
str = str.Substring(start, end - start);
} else {
str = String.Empty;
str += textLines[startPoint.Y].Substring(startPoint.X); //Copy start
for (int i = 1; i < endPoint.Y - startPoint.Y; i++) {
str += textLines[startPoint.Y + i]; //Copy middle
}
str += textLines[endPoint.Y].Substring(0, endPoint.X); //Copy end
}
return str;
}
//[halfofastaple] TODO Implement this and use it. The end user can work around not having it, but it is terribly convenient.
// See the delete key handler for help. Eventually, the delete key should use this.
///// <summary>
///// Deletes text.
///// </summary>
///// <param name="startPos">Starting cursor position.</param>
///// <param name="length">Length in characters.</param>
//public void DeleteText(Point StartPos, int length) {
// /* Single Line Delete */
// if (StartPos.X + length <= m_TextLines[StartPos.Y].Length) {
// string str = m_TextLines[StartPos.Y];
// str = str.Remove(StartPos.X, length);
// m_TextLines[StartPos.Y] = str;
// if (CursorPosition.X > StartPos.X) {
// m_CursorPos.X = CursorPosition.X - length;
// }
// m_CursorEnd = m_CursorPos;
// /* Multiline Delete */
// } else {
// }
//}
/// <summary>
/// Deletes selected text.
/// </summary>
public void EraseSelection() {
if (startPoint.Y == endPoint.Y) {
int start = startPoint.X;
int end = endPoint.X;
textLines[startPoint.Y] = textLines[startPoint.Y].Remove(start, end - start);
} else {
/* Remove Start */
if (startPoint.X < textLines[startPoint.Y].Length) {
textLines[startPoint.Y] = textLines[startPoint.Y].Remove(startPoint.X);
}
/* Remove Middle */
for (int i = 1; i < endPoint.Y - startPoint.Y; i++) {
textLines.RemoveAt(startPoint.Y + 1);
}
/* Remove End */
if (endPoint.X < textLines[startPoint.Y + 1].Length) {
textLines[startPoint.Y] += textLines[startPoint.Y + 1].Substring(endPoint.X);
}
textLines.RemoveAt(startPoint.Y + 1);
}
// Move the cursor to the start of the selection,
// since the end is probably outside of the string now.
cursorPos = startPoint;
cursorEnd = startPoint;
Invalidate();
refreshCursorBounds();
}
/// <summary>
/// Handler invoked on mouse click (left) event.
/// </summary>
/// <param name="x">X coordinate.</param>
/// <param name="y">Y coordinate.</param>
/// <param name="down">If set to <c>true</c> mouse button is down.</param>
protected override void onMouseClickedLeft(int x, int y, bool down) {
base.onMouseClickedLeft(x, y, down);
if (selectAll) {
onSelectAll(this, EventArgs.Empty);
//m_SelectAll = false;
return;
}
Point coords = getClosestCharacter(x, y);
if (down) {
CursorPosition = coords;
if (!Input.InputHandler.IsShiftDown)
CursorEnd = coords;
InputHandler.MouseFocus = this;
} else {
if (InputHandler.MouseFocus == this) {
CursorPosition = coords;
InputHandler.MouseFocus = null;
}
}
Invalidate();
refreshCursorBounds();
}
/// <summary>
/// Returns index of the character closest to specified point (in canvas coordinates).
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
protected override Point getClosestCharacter(int px, int py) {
Point p = CanvasPosToLocal(new Point(px, py));
double distance = Double.MaxValue;
Point Best = new Point(0, 0);
string sub = String.Empty;
/* Find the appropriate Y row (always pick whichever y the mouse currently is on) */
for (int y = 0; y < textLines.Count(); y++) {
sub += textLines[y] + Environment.NewLine;
Point cp = Skin.Renderer.MeasureText(Font, sub);
double YDist = Math.Abs(cp.Y - p.Y);
if (YDist < distance) {
distance = YDist;
Best.Y = y;
}
}
/* Find the best X row, closest char */
sub = String.Empty;
distance = Double.MaxValue;
for (int x = 0; x <= textLines[Best.Y].Count(); x++) {
if (x < textLines[Best.Y].Count()) {
sub += textLines[Best.Y][x];
} else {
sub += " ";
}
Point cp = Skin.Renderer.MeasureText(Font, sub);
double XDiff = Math.Abs(cp.X - p.X);
if (XDiff < distance){
distance = XDiff;
Best.X = x;
}
}
return Best;
}
/// <summary>
/// Handler invoked on mouse moved event.
/// </summary>
/// <param name="x">X coordinate.</param>
/// <param name="y">Y coordinate.</param>
/// <param name="dx">X change.</param>
/// <param name="dy">Y change.</param>
protected override void onMouseMoved(int x, int y, int dx, int dy) {
base.onMouseMoved(x, y, dx, dy);
if (InputHandler.MouseFocus != this) return;
Point c = getClosestCharacter(x, y);
CursorPosition = c;
Invalidate();
refreshCursorBounds();
}
protected virtual void makeCaretVisible() {
int caretPos = getCharacterPosition(CursorPosition).X - TextX;
// If the caret is already in a semi-good position, leave it.
{
int realCaretPos = caretPos + TextX;
if (realCaretPos > Width * 0.1f && realCaretPos < Width * 0.9f)
return;
}
// The ideal position is for the caret to be right in the middle
int idealx = (int)(-caretPos + Width * 0.5f);
// Don't show too much whitespace to the right
if (idealx + TextWidth < Width - TextPadding.Right)
idealx = -TextWidth + (Width - TextPadding.Right);
// Or the left
if (idealx > TextPadding.Left)
idealx = TextPadding.Left;
setTextPosition(idealx, TextY);
}
/// <summary>
/// Handler invoked when control children's bounds change.
/// </summary>
/// <param name="oldChildBounds"></param>
/// <param name="child"></param>
protected override void onChildBoundsChanged(System.Drawing.Rectangle oldChildBounds, ControlBase child)
{
if (scrollControl != null)
{
scrollControl.UpdateScrollBars();
}
}
/// <summary>
/// Sets the label text.
/// </summary>
/// <param name="str">Text to set.</param>
/// <param name="doEvents">Determines whether to invoke "text changed" event.</param>
public override void SetText(string str, bool doEvents = true) {
string EasySplit = str.Replace("\r\n", "\n").Replace("\r", "\n");
string[] Lines = EasySplit.Split('\n');
textLines = new List<string>(Lines);
Invalidate();
refreshCursorBounds();
}
/// <summary>
/// Invalidates the control.
/// </summary>
/// <remarks>
/// Causes layout, repaint, invalidates cached texture.
/// </remarks>
public override void Invalidate() {
if (text != null) {
text.Text = Text;
}
if (AutoSizeToContents)
SizeToContents();
base.Invalidate();
InvalidateParent();
onTextChanged();
}
private Point getCharacterPosition(Point CursorPosition) {
if (textLines.Count == 0) {
return new Point(0, 0);
}
string CurrLine = textLines[CursorPosition.Y].Substring(0, Math.Min(CursorPosition.X, textLines[CursorPosition.Y].Length));
string sub = "";
for (int i = 0; i < CursorPosition.Y; i++) {
sub += textLines[i] + "\n";
}
Point p = new Point(Skin.Renderer.MeasureText(Font, CurrLine).X, Skin.Renderer.MeasureText(Font, sub).Y);
return new Point(p.X + text.X, p.Y + text.Y + TextPadding.Top);
}
protected override bool onMouseWheeled(int delta) {
return scrollControl.InputMouseWheeled(delta);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Crypto
{
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaCreate")]
internal static extern SafeRsaHandle RsaCreate();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaUpRef")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool RsaUpRef(IntPtr rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaDestroy")]
internal static extern void RsaDestroy(IntPtr rsa);
internal static SafeRsaHandle DecodeRsaPublicKey(ReadOnlySpan<byte> buf) =>
DecodeRsaPublicKey(ref MemoryMarshal.GetReference(buf), buf.Length);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeRsaPublicKey")]
private static extern SafeRsaHandle DecodeRsaPublicKey(ref byte buf, int len);
internal static int RsaPublicEncrypt(
int flen,
ReadOnlySpan<byte> from,
Span<byte> to,
SafeRsaHandle rsa,
RsaPadding padding) =>
RsaPublicEncrypt(flen, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa, padding);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaPublicEncrypt")]
private extern static int RsaPublicEncrypt(
int flen,
ref byte from,
ref byte to,
SafeRsaHandle rsa,
RsaPadding padding);
internal static int RsaPrivateDecrypt(
int flen,
ReadOnlySpan<byte> from,
Span<byte> to,
SafeRsaHandle rsa,
RsaPadding padding) =>
RsaPrivateDecrypt(flen, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa, padding);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaPrivateDecrypt")]
private extern static int RsaPrivateDecrypt(
int flen,
ref byte from,
ref byte to,
SafeRsaHandle rsa,
RsaPadding padding);
internal static int RsaSignPrimitive(
ReadOnlySpan<byte> from,
Span<byte> to,
SafeRsaHandle rsa) =>
RsaSignPrimitive(from.Length, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaSignPrimitive")]
private static extern int RsaSignPrimitive(
int flen,
ref byte from,
ref byte to,
SafeRsaHandle rsa);
internal static int RsaVerificationPrimitive(
ReadOnlySpan<byte> from,
Span<byte> to,
SafeRsaHandle rsa) =>
RsaVerificationPrimitive(from.Length, ref MemoryMarshal.GetReference(from), ref MemoryMarshal.GetReference(to), rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaVerificationPrimitive")]
private static extern int RsaVerificationPrimitive(
int flen,
ref byte from,
ref byte to,
SafeRsaHandle rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaSize")]
internal static extern int RsaSize(SafeRsaHandle rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaGenerateKeyEx")]
internal static extern int RsaGenerateKeyEx(SafeRsaHandle rsa, int bits, SafeBignumHandle e);
internal static bool RsaSign(int type, ReadOnlySpan<byte> m, int m_len, Span<byte> sigret, out int siglen, SafeRsaHandle rsa) =>
RsaSign(type, ref MemoryMarshal.GetReference(m), m_len, ref MemoryMarshal.GetReference(sigret), out siglen, rsa);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaSign")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool RsaSign(int type, ref byte m, int m_len, ref byte sigret, out int siglen, SafeRsaHandle rsa);
internal static bool RsaVerify(int type, ReadOnlySpan<byte> m, ReadOnlySpan<byte> sigbuf, SafeRsaHandle rsa)
{
bool ret = RsaVerify(
type,
ref MemoryMarshal.GetReference(m),
m.Length,
ref MemoryMarshal.GetReference(sigbuf),
sigbuf.Length,
rsa);
if (!ret)
{
ErrClearError();
}
return ret;
}
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_RsaVerify")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool RsaVerify(int type, ref byte m, int m_len, ref byte sigbuf, int siglen, SafeRsaHandle rsa);
internal static RSAParameters ExportRsaParameters(SafeRsaHandle key, bool includePrivateParameters)
{
Debug.Assert(
key != null && !key.IsInvalid,
"Callers should check the key is invalid and throw an exception with a message");
if (key == null || key.IsInvalid)
{
throw new CryptographicException();
}
bool addedRef = false;
try
{
key.DangerousAddRef(ref addedRef);
IntPtr n, e, d, p, dmp1, q, dmq1, iqmp;
if (!GetRsaParameters(key, out n, out e, out d, out p, out dmp1, out q, out dmq1, out iqmp))
{
throw new CryptographicException();
}
int modulusSize = Crypto.RsaSize(key);
// RSACryptoServiceProvider expects P, DP, Q, DQ, and InverseQ to all
// be padded up to half the modulus size.
int halfModulus = modulusSize / 2;
RSAParameters rsaParameters = new RSAParameters
{
Modulus = Crypto.ExtractBignum(n, modulusSize),
Exponent = Crypto.ExtractBignum(e, 0),
};
if (includePrivateParameters)
{
rsaParameters.D = Crypto.ExtractBignum(d, modulusSize);
rsaParameters.P = Crypto.ExtractBignum(p, halfModulus);
rsaParameters.DP = Crypto.ExtractBignum(dmp1, halfModulus);
rsaParameters.Q = Crypto.ExtractBignum(q, halfModulus);
rsaParameters.DQ = Crypto.ExtractBignum(dmq1, halfModulus);
rsaParameters.InverseQ = Crypto.ExtractBignum(iqmp, halfModulus);
}
return rsaParameters;
}
finally
{
if (addedRef)
key.DangerousRelease();
}
}
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetRsaParameters")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetRsaParameters(
SafeRsaHandle key,
out IntPtr n,
out IntPtr e,
out IntPtr d,
out IntPtr p,
out IntPtr dmp1,
out IntPtr q,
out IntPtr dmq1,
out IntPtr iqmp);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SetRsaParameters")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetRsaParameters(
SafeRsaHandle key,
byte[] n,
int nLength,
byte[] e,
int eLength,
byte[] d,
int dLength,
byte[] p,
int pLength,
byte[] dmp1,
int dmp1Length,
byte[] q,
int qLength,
byte[] dmq1,
int dmq1Length,
byte[] iqmp,
int iqmpLength);
internal enum RsaPadding : int
{
Pkcs1 = 0,
OaepSHA1 = 1,
NoPadding = 2,
}
}
}
| |
$pref::Player::Name = "Visitor";
$pref::Player::defaultFov = 75;
$pref::Player::zoomSpeed = 0;
$pref::Net::LagThreshold = 400;
$pref::Net::Port = 28000;
$pref::HudMessageLogSize = 40;
$pref::ChatHudLength = 1;
$pref::Input::LinkMouseSensitivity = 1;
// DInput keyboard, mouse, and joystick prefs
$pref::Input::KeyboardEnabled = 1;
$pref::Input::MouseEnabled = 1;
$pref::Input::JoystickEnabled = 0;
$pref::Input::KeyboardTurnSpeed = 0.1;
$pref::Input::invertVerticalMouse = false;
$pref::Input::VertMouseSensitivity = 1;
$pref::Input::HorzMouseSensitivity = 1;
$pref::Input::RollMouseSensitivity = 1;
$pref::Input::ZoomVertMouseSensitivity = 0.3;
$pref::Input::ZoomHorzMouseSensitivity = 0.3;
$sceneLighting::cacheSize = 20000;
$sceneLighting::purgeMethod = "lastCreated";
$sceneLighting::cacheLighting = 1;
$pref::Video::displayDevice = "D3D9";
$pref::Video::disableVerticalSync = 1;
$pref::Video::Resolution = "1024 768";
$pref::Video::FullScreen = false;
$pref::Video::BitDepth = "32";
$pref::Video::RefreshRate = "60";
$pref::Video::AA = "4";
$pref::Video::defaultFenceCount = 0;
$pref::Video::screenShotSession = 0;
$pref::Video::screenShotFormat = "PNG";
/// This disables the hardware FSAA/MSAA so that
/// we depend completely on the FXAA post effect
/// which works on all cards and in deferred mode.
///
/// Note the new Intel Hybrid graphics on laptops
/// will fail to initialize when hardware AA is
/// enabled... so you've been warned.
///
$pref::Video::disableHardwareAA = true;
$pref::Video::disableNormalmapping = false;
$pref::Video::disablePixSpecular = false;
$pref::Video::disableCubemapping = false;
///
$pref::Video::disableParallaxMapping = false;
$pref::Video::Gamma = 2.2;
$pref::Video::Contrast = 1.0;
$pref::Video::Brightness = 0;
/// The perfered light manager to use at startup. If blank
/// or if the selected one doesn't work on this platfom it
/// will try the defaults below.
$pref::lightManager = "";
/// This is the default list of light managers ordered from
/// most to least desirable for initialization.
$lightManager::defaults = "Advanced Lighting";
/// A scale to apply to the camera view distance
/// typically used for tuning performance.
$pref::camera::distanceScale = 1.0;
/// Causes the system to do a one time autodetect
/// of an SFX provider and device at startup if the
/// provider is unset.
$pref::SFX::autoDetect = true;
/// The sound provider to select at startup. Typically
/// this is DirectSound, OpenAL, or XACT. There is also
/// a special Null provider which acts normally, but
/// plays no sound.
$pref::SFX::provider = "";
/// The sound device to select from the provider. Each
/// provider may have several different devices.
$pref::SFX::device = "OpenAL";
/// If true the device will try to use hardware buffers
/// and sound mixing. If not it will use software.
$pref::SFX::useHardware = false;
/// If you have a software device you have a
/// choice of how many software buffers to
/// allow at any one time. More buffers cost
/// more CPU time to process and mix.
$pref::SFX::maxSoftwareBuffers = 16;
/// This is the playback frequency for the primary
/// sound buffer used for mixing. Although most
/// providers will reformat on the fly, for best
/// quality and performance match your sound files
/// to this setting.
$pref::SFX::frequency = 44100;
/// This is the playback bitrate for the primary
/// sound buffer used for mixing. Although most
/// providers will reformat on the fly, for best
/// quality and performance match your sound files
/// to this setting.
$pref::SFX::bitrate = 32;
/// The overall system volume at startup. Note that
/// you can only scale volume down, volume does not
/// get louder than 1.
$pref::SFX::masterVolume = 0.8;
/// The startup sound channel volumes. These are
/// used to control the overall volume of different
/// classes of sounds.
$pref::SFX::channelVolume1 = 1;
$pref::SFX::channelVolume2 = 1;
$pref::SFX::channelVolume3 = 1;
$pref::SFX::channelVolume4 = 1;
$pref::SFX::channelVolume5 = 1;
$pref::SFX::channelVolume6 = 1;
$pref::SFX::channelVolume7 = 1;
$pref::SFX::channelVolume8 = 1;
$pref::SFX::channelVolume[1] = 1;
$pref::SFX::channelVolume[2] = 1;
$pref::SFX::channelVolume[3] = 1;
$pref::SFX::channelVolume[4] = 1;
$pref::PostEffect::PreferedHDRFormat = "GFXFormatR8G8B8A8";
/// This is an scalar which can be used to reduce the
/// reflection textures on all objects to save fillrate.
$pref::Reflect::refractTexScale = 1.0;
/// This is the total frame in milliseconds to budget for
/// reflection rendering. If your CPU bound and have alot
/// of smaller reflection surfaces try reducing this time.
$pref::Reflect::frameLimitMS = 10;
/// Set true to force all water objects to use static cubemap reflections.
$pref::Water::disableTrueReflections = false;
// A global LOD scalar which can reduce the overall density of placed GroundCover.
$pref::GroundCover::densityScale = 1.0;
/// An overall scaler on the lod switching between DTS models.
/// Smaller numbers makes the lod switch sooner.
$pref::TS::detailAdjust = 1.0;
///
$pref::Decals::enabled = true;
///
$pref::Decals::lifeTimeScale = "1";
/// The number of mipmap levels to drop on loaded textures
/// to reduce video memory usage.
///
/// It will skip any textures that have been defined as not
/// allowing down scaling.
///
$pref::Video::textureReductionLevel = 0;
///
$pref::Shadows::textureScalar = 1.0;
///
$pref::Shadows::disable = false;
/// Sets the shadow filtering mode.
///
/// None - Disables filtering.
///
/// SoftShadow - Does a simple soft shadow
///
/// SoftShadowHighQuality
///
$pref::Shadows::filterMode = "SoftShadow";
///
$pref::Video::defaultAnisotropy = 1;
/// Radius in meters around the camera that ForestItems are affected by wind.
/// Note that a very large number with a large number of items is not cheap.
$pref::windEffectRadius = 25;
/// AutoDetect graphics quality levels the next startup.
$pref::Video::autoDetect = 1;
$PostFXManager::Settings::EnableDOF = "0";
$PostFXManager::Settings::DOF::BlurCurveFar = "";
$PostFXManager::Settings::DOF::BlurCurveNear = "";
$PostFXManager::Settings::DOF::BlurMax = "";
$PostFXManager::Settings::DOF::BlurMin = "";
$PostFXManager::Settings::DOF::EnableAutoFocus = "";
$PostFXManager::Settings::DOF::EnableDOF = "";
$PostFXManager::Settings::DOF::FocusRangeMax = "";
$PostFXManager::Settings::DOF::FocusRangeMin = "";
$PostFXManager::Settings::EnableLightRays = "0";
$PostFXManager::Settings::LightRays::brightScalar = "0.75";
$PostFXManager::Settings::LightRays::decay = "1.0";
$PostFXManager::Settings::LightRays::density = "0.94";
$PostFXManager::Settings::LightRays::numSamples = "40";
$PostFXManager::Settings::LightRays::weight = "5.65";
$PostFXManager::Settings::EnableDOF = 1;
$pref::PostFX::EnableVignette = 1;
$pref::PostFX::EnableLightRays = 1;
$pref::PostFX::EnableHDR = 1;
$pref::PostFX::EnableSSAO = 1;
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Voxalia.Shared;
using Voxalia.Shared.Collision;
namespace Voxalia.ServerGame.WorldSystem.SimpleGenerator
{
public class SimpleGeneratorCore: BlockPopulator
{
public SimpleBiomeGenerator Biomes = new SimpleBiomeGenerator();
public const double GlobalHeightMapSize = 400;
public const double LocalHeightMapSize = 40;
public const double SolidityMapSize = 100;
public const double OreMapSize = 70;
public const double OreTypeMapSize = 150;
public const double OreMapTolerance = 0.90f;
public const double OreMapThickTolerance = 0.94f;
public Material GetMatType(int seed2, int seed3, int seed4, int seed5, int x, int y, int z)
{
// TODO: better non-simplex code!
double val = SimplexNoise.Generate((double)seed2 + (x / OreMapSize), (double)seed5 + (y / OreMapSize), (double)seed4 + (z / OreMapSize));
if (val < OreMapTolerance)
{
return Material.AIR;
}
bool thick = val > OreMapThickTolerance;
double tval = SimplexNoise.Generate((double)seed5 + (x / OreTypeMapSize), (double)seed3 + (y / OreTypeMapSize), (double)seed2 + (z / OreTypeMapSize));
if (thick)
{
if (tval > 0.66f)
{
return Material.TIN_ORE;
}
else if (tval > 0.33f)
{
return Material.COAL_ORE;
}
else
{
return Material.COPPER_ORE;
}
}
else
{
if (tval > 0.66f)
{
return Material.TIN_ORE_SPARSE;
}
else if (tval > 0.33f)
{
return Material.COAL_ORE_SPARSE;
}
else
{
return Material.COPPER_ORE_SPARSE;
}
}
}
public override void ClearTimings()
{
#if TIMINGS
Timings_Height = 0;
Timings_Chunk = 0;
Timings_Entities = 0;
#endif
}
#if TIMINGS
public double Timings_Height = 0;
public double Timings_Chunk = 0;
public double Timings_Entities = 0;
#endif
public override List<Tuple<string, double>> GetTimings()
{
List<Tuple<string, double>> res = new List<Tuple<string, double>>();
#if TIMINGS
res.Add(new Tuple<string, double>("Height", Timings_Height));
res.Add(new Tuple<string, double>("Chunk", Timings_Chunk));
res.Add(new Tuple<string, double>("Entities", Timings_Entities));
#endif
return res;
}
public bool CanBeSolid(int seed3, int seed4, int seed5, int x, int y, int z, SimpleBiome biome)
{
// TODO: better non-simplex code?!
double val = SimplexNoise.Generate((double)seed3 + (x / SolidityMapSize), (double)seed4 + (y / SolidityMapSize), (double)seed5 + (z / SolidityMapSize));
//SysConsole.Output(OutputType.INFO, seed3 + "," + seed4 + "," + seed5 + " -> " + x + ", " + y + ", " + z + " -> " + val);
return val < biome.AirDensity();
}
public double GetHeightQuick(int Seed, int seed2, double x, double y)
{
double lheight = SimplexNoise.Generate((double)seed2 + (x / GlobalHeightMapSize), (double)Seed + (y / GlobalHeightMapSize)) * 50f - 10f;
double height = SimplexNoise.Generate((double)Seed + (x / LocalHeightMapSize), (double)seed2 + (y / LocalHeightMapSize)) * 6f - 3f;
return lheight + height;
}
// TODO: Clean, reduce to only what's necessary. Every entry in this list makes things that much more expensive.
/*public static Vector3i[] Rels = new Vector3i[] { new Vector3i(-10, 10, 0), new Vector3i(-10, -10, 0), new Vector3i(10, 10, 0), new Vector3i(10, -10, 0),
new Vector3i(-15, 15, 0), new Vector3i(-15, -15, 0), new Vector3i(15, 15, 0), new Vector3i(15, -15, 0),
new Vector3i(-20, 20, 0), new Vector3i(-20, -20, 0), new Vector3i(20, 20, 0), new Vector3i(20, -20, 0),
new Vector3i(-5, 5, 0), new Vector3i(-5, -5, 0), new Vector3i(5, 5, 0), new Vector3i(5, -5, 0),
new Vector3i(-10, 0, 0), new Vector3i(0, -10, 0), new Vector3i(10, 0, 0), new Vector3i(0, 10, 0),
new Vector3i(-20, 0, 0), new Vector3i(0, -20, 0), new Vector3i(20, 0, 0), new Vector3i(0, 20, 0),
new Vector3i(-15, 0, 0), new Vector3i(0, -15, 0), new Vector3i(15, 0, 0), new Vector3i(0, 15, 0),
new Vector3i(-5, 0, 0), new Vector3i(0, -5, 0), new Vector3i(5, 0, 0), new Vector3i(0, 5, 0)};
double relmod = 1f;*/
public override double GetHeight(int Seed, int seed2, int seed3, int seed4, int seed5, double x, double y, double z, out Biome biome)
{
#if TIMINGS
Stopwatch sw = new Stopwatch();
sw.Start();
try
#endif
{
double valBasic = GetHeightQuick(Seed, seed2, x, y);
//if (z < -50 || z > 50)
{
biome = Biomes.BiomeFor(seed2, seed3, seed4, x, y, z, valBasic);
return valBasic;
}
/*Biome b = Biomes.BiomeFor(seed2, seed3, seed4, x, y, z, valBasic);
double total = valBasic; * ((SimpleBiome)b).HeightMod();
foreach (Vector3i vecer in Rels)
{
double valt = GetHeightQuick(Seed, seed2, x + vecer.X * relmod, y + vecer.Y * relmod);
Biome bt = Biomes.BiomeFor(seed2, seed3, seed4, x + vecer.X * relmod, y + vecer.Y * relmod, z, valt);
total += valt * ((SimpleBiome)bt).HeightMod();
}
biome = b;
return total / (Rels.Length + 1);
*/
}
#if TIMINGS
finally
{
sw.Stop();
Timings_Height += sw.ElapsedTicks / (double)Stopwatch.Frequency;
}
#endif
}
void SpecialSetBlockAt(Chunk chunk, int X, int Y, int Z, BlockInternal bi)
{
if (X < 0 || Y < 0 || Z < 0 || X >= Chunk.CHUNK_SIZE || Y >= Chunk.CHUNK_SIZE || Z >= Chunk.CHUNK_SIZE)
{
Vector3i chloc = chunk.OwningRegion.ChunkLocFor(new Location(X, Y, Z));
Chunk ch = chunk.OwningRegion.LoadChunkNoPopulate(chunk.WorldPosition + chloc);
int x = (int)(X - chloc.X * Chunk.CHUNK_SIZE);
int y = (int)(Y - chloc.Y * Chunk.CHUNK_SIZE);
int z = (int)(Z - chloc.Z * Chunk.CHUNK_SIZE);
BlockInternal orig = ch.GetBlockAt(x, y, z);
BlockFlags flags = ((BlockFlags)orig.BlockLocalData);
if (!flags.HasFlag(BlockFlags.EDITED) && !flags.HasFlag(BlockFlags.PROTECTED))
{
// TODO: lock?
ch.BlocksInternal[chunk.BlockIndex(x, y, z)] = bi;
}
}
else
{
BlockInternal orig = chunk.GetBlockAt(X, Y, Z);
BlockFlags flags = ((BlockFlags)orig.BlockLocalData);
if (!flags.HasFlag(BlockFlags.EDITED) && !flags.HasFlag(BlockFlags.PROTECTED))
{
chunk.BlocksInternal[chunk.BlockIndex(X, Y, Z)] = bi;
}
}
}
public byte[] OreShapes = new byte[] { 0, 64, 65, 66, 67, 68 };
public int MaxNonAirHeight = 2;
public override void Populate(int Seed, int seed2, int seed3, int seed4, int seed5, Chunk chunk)
{
#if TIMINGS
Stopwatch sw = new Stopwatch();
sw.Start();
PopulateInternal(Seed, seed2, seed3, seed4, seed5, chunk);
sw.Stop();
Timings_Chunk += sw.ElapsedTicks / (double)Stopwatch.Frequency;
}
private void PopulateInternal(int Seed, int seed2, int seed3, int seed4, int seed5, Chunk chunk)
{
#endif
if (chunk.OwningRegion.TheWorld.Flat)
{
if (chunk.WorldPosition.Z == 0)
{
for (int i = 0; i < chunk.BlocksInternal.Length; i++)
{
chunk.BlocksInternal[i] = new BlockInternal((ushort)Material.STONE, 0, 0, 0);
}
for (int x = 0; x < Chunk.CHUNK_SIZE; x++)
{
for (int y = 0; y < Chunk.CHUNK_SIZE; y++)
{
chunk.BlocksInternal[chunk.BlockIndex(x, y, Chunk.CHUNK_SIZE - 1)] = new BlockInternal((ushort)Material.GRASS_PLAINS, 0, 0, 0);
chunk.BlocksInternal[chunk.BlockIndex(x, y, Chunk.CHUNK_SIZE - 2)] = new BlockInternal((ushort)Material.DIRT, 0, 0, 0);
chunk.BlocksInternal[chunk.BlockIndex(x, y, Chunk.CHUNK_SIZE - 3)] = new BlockInternal((ushort)Material.DIRT, 0, 0, 0);
}
}
}
else if (chunk.WorldPosition.Z < 0)
{
for (int i = 0; i < chunk.BlocksInternal.Length; i++)
{
chunk.BlocksInternal[i] = new BlockInternal((ushort)Material.STONE, 0, 0, 0);
}
}
else
{
for (int i = 0; i < chunk.BlocksInternal.Length; i++)
{
chunk.BlocksInternal[i] = BlockInternal.AIR;
}
}
return;
}
if (chunk.WorldPosition.Z > MaxNonAirHeight)
{
for (int i = 0; i < chunk.BlocksInternal.Length; i++)
{
chunk.BlocksInternal[i] = BlockInternal.AIR;
}
return;
}
// TODO: Special case for too far down as well.
for (int x = 0; x < Chunk.CHUNK_SIZE; x++)
{
for (int y = 0; y < Chunk.CHUNK_SIZE; y++)
{
Location cpos = chunk.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE;
// Prepare basics
int cx = (int)cpos.X + x;
int cy = (int)cpos.Y + y;
Biome biomeOrig;
double hheight = GetHeight(Seed, seed2, seed3, seed4, seed5, cx, cy, (double)cpos.Z, out biomeOrig);
SimpleBiome biome = (SimpleBiome)biomeOrig;
//Biome biomeOrig2;
/*double hheight2 = */
/*GetHeight(Seed, seed2, seed3, seed4, seed5, cx + 7, cy + 7, (double)cpos.Z + 7, out biomeOrig2);
SimpleBiome biome2 = (SimpleBiome)biomeOrig2;*/
Material surf = biome.SurfaceBlock();
Material seco = biome.SecondLayerBlock();
Material basb = biome.BaseBlock();
Material water = biome.WaterMaterial();
/*Material surf2 = biome2.SurfaceBlock();
Material seco2 = biome2.SecondLayerBlock();
Material basb2 = biome2.BaseBlock();*/
// TODO: Make this possible?: hheight = (hheight + hheight2) / 2f;
int hheightint = (int)Math.Round(hheight);
double topf = hheight - (double)(chunk.WorldPosition.Z * Chunk.CHUNK_SIZE);
int top = (int)Math.Round(topf);
// General natural ground
for (int z = 0; z < Math.Min(top - 5, Chunk.CHUNK_SIZE); z++)
{
if (CanBeSolid(seed3, seed4, seed5, cx, cy, (int)cpos.Z + z, biome))
{
Material typex = GetMatType(seed2, seed3, seed4, seed5, cx, cy, (int)cpos.Z + z);
byte shape = 0;
if (typex != Material.AIR)
{
shape = OreShapes[new Random((int)((hheight + cx + cy + cpos.Z + z) * 5)).Next(OreShapes.Length)];
}
//bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z + z) / 10f) >= 0.5f;
chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal((ushort)(typex == Material.AIR ? (/*choice ? basb2 : */basb) : typex), shape, 0, 0);
}
else if ((CanBeSolid(seed3, seed4, seed5, cx, cy, (int)cpos.Z + z - 1, biome) || (CanBeSolid(seed3, seed4, seed5, cx, cy, (int)cpos.Z + z + 1, biome))) &&
(CanBeSolid(seed3, seed4, seed5, cx + 1, cy, (int)cpos.Z + z, biome) || CanBeSolid(seed3, seed4, seed5, cx, cy + 1, (int)cpos.Z + z, biome)
|| CanBeSolid(seed3, seed4, seed5, cx - 1, cy, (int)cpos.Z + z, biome) || CanBeSolid(seed3, seed4, seed5, cx, cy - 1, (int)cpos.Z + z, biome)))
{
//bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z + z) / 10f) >= 0.5f;
chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal((ushort)(/*choice ? basb2 : */basb), 3, 0, 0);
}
}
for (int z = Math.Max(top - 5, 0); z < Math.Min(top - 1, Chunk.CHUNK_SIZE); z++)
{
if (CanBeSolid(seed3, seed4, seed5, cx, cy, (int)cpos.Z + z, biome))
{
//bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z + z) / 10f) >= 0.5f;
chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal((ushort)(/*choice ? seco2 :*/ seco), 0, 0, 0);
}
}
for (int z = Math.Max(top - 1, 0); z < Math.Min(top, Chunk.CHUNK_SIZE); z++)
{
//bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z + z) / 10f) >= 0.5f;
chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal((ushort)(/*choice ? surf2 : */surf), 0, 0, 0);
}
// Smooth terrain cap
Biome tempb;
double heightfxp = GetHeight(Seed, seed2, seed3, seed4, seed5, cx + 1, cy, (double)cpos.Z, out tempb);
double heightfxm = GetHeight(Seed, seed2, seed3, seed4, seed5, cx - 1, cy, (double)cpos.Z, out tempb);
double heightfyp = GetHeight(Seed, seed2, seed3, seed4, seed5, cx, cy + 1, (double)cpos.Z, out tempb);
double heightfym = GetHeight(Seed, seed2, seed3, seed4, seed5, cx, cy - 1, (double)cpos.Z, out tempb);
double topfxp = heightfxp - (double)chunk.WorldPosition.Z * Chunk.CHUNK_SIZE;
double topfxm = heightfxm - (double)chunk.WorldPosition.Z * Chunk.CHUNK_SIZE;
double topfyp = heightfyp - (double)chunk.WorldPosition.Z * Chunk.CHUNK_SIZE;
double topfym = heightfym - (double)chunk.WorldPosition.Z * Chunk.CHUNK_SIZE;
for (int z = Math.Max(top, 0); z < Math.Min(top + 1, Chunk.CHUNK_SIZE); z++)
{
//bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z + z) / 10f) >= 0.5f;
ushort tsf = (ushort)(/*choice ? surf2 : */surf);
if (topf - top > 0f)
{
bool xp = topfxp > topf && topfxp - Math.Round(topfxp) <= 0;
bool xm = topfxm > topf && topfxm - Math.Round(topfxm) <= 0;
bool yp = topfyp > topf && topfyp - Math.Round(topfyp) <= 0;
bool ym = topfym > topf && topfym - Math.Round(topfym) <= 0;
if (xm && xp) { /* Fine as-is */ }
else if (ym && yp) { /* Fine as-is */ }
else if (yp && xm) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 0, 0, 0); } // TODO: Shape
else if (yp && xp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 0, 0, 0); } // TODO: Shape
else if (xp && ym) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 0, 0, 0); } // TODO: Shape
else if (xp && yp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 0, 0, 0); } // TODO: Shape
else if (ym && xm) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 0, 0, 0); } // TODO: Shape
else if (ym && xp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 0, 0, 0); } // TODO: Shape
else if (xm && ym) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 0, 0, 0); } // TODO: Shape
else if (xm && yp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 0, 0, 0); } // TODO: Shape
else if (xp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 80, 0, 0); }
else if (xm) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 81, 0, 0); }
else if (yp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 82, 0, 0); }
else if (ym) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 83, 0, 0); }
else { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 3, 0, 0); }
if (z > 0)
{
chunk.BlocksInternal[chunk.BlockIndex(x, y, z - 1)] = new BlockInternal((ushort)(/*choice ? seco2 :*/ seco), 0, 0, 0);
}
}
else
{
bool xp = topfxp > topf && topfxp - Math.Round(topfxp) > 0;
bool xm = topfxm > topf && topfxm - Math.Round(topfxm) > 0;
bool yp = topfyp > topf && topfyp - Math.Round(topfyp) > 0;
bool ym = topfym > topf && topfym - Math.Round(topfym) > 0;
if (xm && xp) { /* Fine as-is */ }
else if (ym && yp) { /* Fine as-is */ }
else if (yp && xm) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 3, 0, 0); } // TODO: Shape
else if (yp && xp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 3, 0, 0); } // TODO: Shape
else if (xp && ym) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 3, 0, 0); } // TODO: Shape
else if (xp && yp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 3, 0, 0); } // TODO: Shape
else if (ym && xm) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 3, 0, 0); } // TODO: Shape
else if (ym && xp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 3, 0, 0); } // TODO: Shape
else if (xm && ym) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 3, 0, 0); } // TODO: Shape
else if (xm && yp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 3, 0, 0); } // TODO: Shape
else if (xp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 73, 0, 0); }
else if (xm) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 72, 0, 0); }
else if (yp) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 74, 0, 0); }
else if (ym) { chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(tsf, 75, 0, 0); }
else { /* Fine as-is */ }
}
}
// Water
int level = 0 - (int)(chunk.WorldPosition.Z * Chunk.CHUNK_SIZE);
if (hheightint <= 0)
{
// bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z) / 10f) >= 0.5f;
ushort sandmat = (ushort)(/*choice ? biome2 : */biome).SandMaterial();
for (int z = Math.Max(top, 0); z < Math.Min(top + 1, Chunk.CHUNK_SIZE); z++)
{
chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal(sandmat, 0, 0, 0);
}
for (int z = Math.Max(top + 1, 0); z <= Math.Min(level, Chunk.CHUNK_SIZE - 1); z++)
{
chunk.BlocksInternal[chunk.BlockIndex(x, y, z)] = new BlockInternal((ushort)water, 0, (byte)Colors.M_BLUR, 0);
}
}
else
{
if (level >= 0 && level < Chunk.CHUNK_SIZE)
{
if (Math.Round(heightfxp) <= 0 || Math.Round(heightfxm) <= 0 || Math.Round(heightfyp) <= 0 || Math.Round(heightfym) <= 0)
{
//bool choice = SimplexNoise.Generate(cx / 10f, cy / 10f, ((double)cpos.Z) / 10f) >= 0.5f;
chunk.BlocksInternal[chunk.BlockIndex(x, y, level)] = new BlockInternal((ushort)(/*choice ? biome2 : */biome).SandMaterial(), 0, 0, 0);
}
}
}
// Special case: trees.
if (hheight > 0 && top >= 0 && top < Chunk.CHUNK_SIZE)
{
#if TIMINGS
Stopwatch sw = new Stopwatch();
sw.Start();
#endif
// TODO: Scrap this or change the logic?
MTRandom spotr = new MTRandom(39, (ulong)(SimplexNoise.Generate(seed2 + cx, Seed + cy) * 1000 * 1000)); // TODO: Improve!
if (spotr.Next(300) == 1) // TODO: Efficiency! // TODO: Biome based chance!
{
// TODO: Different trees per biome!
chunk.OwningRegion.SpawnTree("treevox0" + (Utilities.UtilRandom.Next(2) + 1), new Location(cx + 0.5f, cy + 0.5f, hheight), chunk);
}
#if TIMINGS
sw.Stop();
Timings_Entities += sw.ElapsedTicks / (double)Stopwatch.Frequency;
#endif
}
}
}
}
}
}
| |
// LayoutPanelBase.cs
//
// Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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.
//
// Review documentation at http://www.yourothermind.com for updated implementation notes, license updates
// or other general information/
//
// Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW
// Full source code: https://github.com/BrentKnowles/YourOtherMind
//###
using System;
using System.Windows.Forms;
using CoreUtilities;
using System.Collections.Generic;
namespace Layout
{
public abstract class LayoutPanelBase : Panel
{
public const string SYSTEM_LAYOUT ="system";
public abstract void DisableLayout (bool off);
bool systemNote = false;
// set in NoteDataXML_SystemONy to true so I can use it to figure out if it deserves a findbar
public bool SystemNote {
get {
return systemNote;
}
set {
if (value == true)
{
//if (FindBar == null)
{
FindBar = new FindBarStatusStrip ();
FindBar.Dock = DockStyle.Bottom;
this.Controls.Add (FindBar);
}
}
systemNote = value;
}
}
// used for auto window assignment
public abstract int HeightOfToolbars ();
public LayoutPanelBase ()
{
}
#region delegates
// This delgate set in NoteDataXML_Panel, hooking the parent Layout up with the Child Layout, for the purposes of SettingCurrentTextNote accurately
public Action<NoteDataXML_RichText> SetParentLayoutCurrentNote;
// set in NoteDataXML_Panel so that a child Layout will tell a higher level to save, if needed
public Action<bool> SetSubNoteSaveRequired = null;
#endregion
#region variables
private string _guid = CoreUtilities.Constants.BLANK;
protected bool _saverequired = false;
private bool isDraggingANote=false;
/// <summary>
/// Is set to true if occupied by dragging a note around
/// </summary>
/// <value>
/// <c>true</c> if this instance is dragging A note; otherwise, <c>false</c>.
/// </value>
public bool IsDraggingANote {
get {
return isDraggingANote;
}
set {
isDraggingANote = value;
}
}
/// <summary>
/// Clears the drag. Called from ESC is presed
/// </summary>
public virtual void ClearDrag ()
{
IsDraggingANote = false;
}
public abstract void SetParentGuidForNotesFromExternal(string newGUID);
public abstract string ParentGuidFromNotes { get; }
public abstract string ParentGUID { get; set; }
public abstract void CopyNote (NoteDataInterface Note);
/// <summary>
/// Wraps the lookup to see if I am a child (by checking my parentGUID)
/// </summary>
/// <value>
/// <c>true</c> if get is child; otherwise, <c>false</c>.
/// </value>
public bool GetIsChild {
get {
if (ParentGUID == Constants.BLANK)
{
return false;
}
return true;
}
}
// storing reference to Interface, allowing a data swapout later
/// <summary>
/// The GUID associated with this LayoutPanel. If blank there is no Layout loaded.
/// </summary>
/// <value>
/// The GUI.
/// </value>
public string GUID {
get { return _guid;}
set { _guid = value;}
}
/// <summary>
/// If true this layout needs to be saved
/// </summary>
/// <value>
/// <c>true</c> if saved required; otherwise, <c>false</c>.
/// </value>
public bool GetSaveRequired {
get{
lg.Instance.Line("LayoutPanelBase->GetSaveRequired", ProblemType.MESSAGE, String.Format ("{0} GetSaveRequired for {1}",
_saverequired, this.GUID),Loud.CTRIVIAL);
return _saverequired;}
// set { _saverequired = value;} Must set this through function
}
/// <summary>
/// Wrapper around the show tab variable for access from individual notes (layoutpanel notes)
/// </summary>
/// <value>
/// <c>true</c> if show tabs; otherwise, <c>false</c>.
/// </value>
abstract public bool ShowTabs { get; set; }
abstract public bool GetIsSystemLayout { get; set; }
abstract public NoteDataXML_RichText CurrentTextNote{ get; set; }
abstract public string Caption {get;}
abstract public string Section { get; }
abstract public string Keywords { get; }
abstract public string Subtype { get; }
abstract public string Notebook { get; }
// set when a richtext box has been updated so that when the mainform update timer runs
// we know to update the word count and such on the findbar
private bool needsTextBoxUpdate = false;
public bool NeedsTextBoxUpdate {
get { return needsTextBoxUpdate;}
set { needsTextBoxUpdate = value;}
}
abstract public void SetParentFields (string section, string keywords, string subtype, string notebook);
private bool isLoaded=false;
/// <summary>
/// Gets or sets a value indicating whether this instance is loaded.
///
/// This is used when painting something expensive, or something that can't paint untl all the notes exist
///
/// re: Timeline
///
/// It is set to true in NewLayout and LoadLayout
/// </summary>
/// <value>
/// <c>true</c> if this instance is loaded; otherwise, <c>false</c>.
/// </value>
public bool IsLoaded {
get {
return isLoaded;
}
set {
isLoaded = value;
}
}
#endregion
#region gui
public virtual Panel NoteCanvas {get;set;}
// passed in front MainForm and then used by any text box
protected ContextMenuStrip TextEditContextStrip;
public ContextMenuStrip GetLayoutTextEditContextStrip()
{
return TextEditContextStrip;
}
public FindBarStatusStrip GetFindbar ()
{
if (GetIsChild) {
LayoutPanelBase absoluteParent = (LayoutPanelBase)GetAbsoluteParent ();
if (absoluteParent != null) {
return absoluteParent.GetFindbar () ;
}
}
return FindBar;
}
protected FindBarStatusStrip FindBar=null;
#endregion
public abstract void SaveLayout();
//public abstract void LoadLayout(string GUID);
public abstract void LoadLayout (string _GUID, bool IsSubPanel, ContextMenuStrip textEditorContextStrip);
public abstract void LoadLayout (string _GUID, bool IsSubPanel, ContextMenuStrip textEditorContextStrip, bool NoSaveMode);
// public abstract void AddNote();
public abstract void AddNote(NoteDataInterface note);
public abstract System.Collections.Generic.List<NoteDataInterface> GetAvailableFolders();
public abstract void MoveNote (string GUIDOfNoteToMove, string GUIDOfLayoutToMoveItTo);
//public abstract string Backup();
public abstract void SetSaveRequired(bool NeedSave);
public abstract void UpdateListOfNotes ();
public abstract void RefreshTabs ();
public abstract void DeleteNote(NoteDataInterface NoteToDelete);
public abstract System.Collections.ArrayList GetAllNotes();
public abstract NoteDataInterface FindNoteByName(string name);
public abstract NoteDataInterface FindNoteByName(string name, ref System.Collections.ArrayList notes_tmp);
public abstract NoteDataInterface FindNoteByGuid (string guid);
public abstract NoteDataInterface GoToNote(NoteDataInterface note);
public abstract NoteDataInterface GetNoteOnSameLayout(string GUID, bool GoTo);
public abstract NoteDataInterface GetNoteOnSameLayout (string GUID, bool GoTo, string TextToFindInRichEdit);
public abstract NoteDataInterface FindSubpanelNote (NoteDataInterface note);
public abstract void SetCurrentTextNote (NoteDataXML_RichText note);
public abstract List<string> GetListOfStringsFromSystemTable (string tableName, int Column, string filter, bool sort);
public abstract List<string> GetListOfStringsFromSystemTable (string tableName, int Column, string filter);
public abstract List<string> GetListOfStringsFromSystemTable (string tableName, int Column);
public abstract NoteDataXML_SystemOnly CreateSystemPanel ();
public abstract void NewLayout (string _GUID, bool AddDefaultNote, ContextMenuStrip textEditorContextStrip);
public abstract CoreUtilities.Links.LinkTable GetLinkTable ();
public abstract int CountNotes();
public abstract string[] GetListOfGroupEmNameMatching (string sStoryboardName, string sGroupMatch);
// public abstract void SystemNoteHasClosedDown (bool closed);
/// <summary>
/// Gets the absolute parent (the LayoutPanel that contains me or the subpanels I am inside)
/// </summary>
/// <returns>
/// The absolute parent.
/// </returns>
public LayoutPanelBase GetAbsoluteParent()
{
LayoutPanelBase layoutParent = null;
if (this.Parent != null) {
// NewMessage.Show (this.Parent.Name);
Control looker = this.Parent;
if (looker != null)
{
while ( (layoutParent == null || layoutParent.GetIsChild == true) && (looker != null) /*not sure&& (looker != null)*/)
{
if (looker is LayoutPanelBase )
{
layoutParent= (looker as LayoutPanelBase);
//NewMessage.Show ("Setting Absolute to " + layoutParent.GUID);
}
else
{
}
// because we want to go all the way to the top we keep looking
if (null == looker.Parent)
{
looker = null;
}
else
looker = looker.Parent;
}
}//if looker not null
} else {
NewMessage.Show (Loc.Instance.GetStringFmt("No parent for this layout {0} with ParentGUID = {1}", GUID, this.ParentGUID));
}
return layoutParent;
}
/// <summary>
/// Focuses the on find bar.
/// </summary>
public void FocusOnFindBar ()
{
if (FindBar != null) {
FindBar.FocusOnSearchEdit();
}
}
public virtual void BringNoteToFront(string guid)
{
}
public void DoFormatOnText (NoteDataXML_RichText.FormatText format)
{
if (CurrentTextNote != null) {
switch (format) {
case NoteDataXML_RichText.FormatText.BOLD:
CurrentTextNote.Bold();
break;
case NoteDataXML_RichText.FormatText.STRIKETHRU:
CurrentTextNote.Strike();
break;
case NoteDataXML_RichText.FormatText.ZOOM:
CurrentTextNote.ZoomToggle();
break;
case NoteDataXML_RichText.FormatText.LINE:
CurrentTextNote.GetRichTextBox().DrawBlackLine();
break;
case NoteDataXML_RichText.FormatText.BULLET:
CurrentTextNote.GetRichTextBox().Bullet(false);
break;
case NoteDataXML_RichText.FormatText.BULLETNUMBER:
CurrentTextNote.GetRichTextBox().Bullet(true);
break;
case NoteDataXML_RichText.FormatText.DEFAULTFONT:
if (LayoutDetails.Instance.GetDefaultFont != null)
{
CurrentTextNote.GetRichTextBox().SelectionFont = LayoutDetails.Instance.GetDefaultFont();
}
break;
case NoteDataXML_RichText.FormatText.DATE:
CurrentTextNote.GetRichTextBox().InsertDate();
break;
case NoteDataXML_RichText.FormatText.UNDERLINE:
CurrentTextNote.Underline();
break;
case NoteDataXML_RichText.FormatText.ITALIC:
CurrentTextNote.Italic();
break;
}
}
}
// looks for a notelist and will filter that notelist by the specified text
public abstract void FilterByKeyword (string text);
public abstract void ColorToolBars (AppearanceClass app);
public abstract void TestForceError();
}
}
| |
//
// System.Data.DataRowView.cs
//
// Author:
// Rodrigo Moya <rodrigo@ximian.com>
// Miguel de Icaza <miguel@ximian.com>
// Daniel Morgan <danmorg@sc.rr.com>
//
// (C) Ximian, Inc 2002
// (C) Daniel Morgan 2002
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
namespace System.Data
{
/// <summary>
/// Represents a customized view of a DataRow exposed as a fully featured Windows Forms control.
/// </summary>
// FIXME: correct exceptions in this[] methods
public class DataRowView : ICustomTypeDescriptor, IEditableObject, IDataErrorInfo
{
#region Fields
DataView _dataView;
DataRow _dataRow;
int _index = -1;
#endregion // Fields
#region Constructors
internal DataRowView (DataView dataView, DataRow row, int index) {
_dataView = dataView;
_dataRow = row;
_index = index;
}
#endregion // Constructors
#region Methods
public override bool Equals(object other)
{
return (other != null &&
other is DataRowView &&
((DataRowView)other)._dataRow != null &&
((DataRowView)other)._dataRow.Equals(_dataRow));
}
public void BeginEdit ()
{
_dataRow.BeginEdit();
}
public void CancelEdit ()
{
// FIXME:
if (this.Row == DataView._lastAdded) {
DataView.CompleteLastAdded(false);
}
else {
_dataRow.CancelEdit();
}
}
public DataView CreateChildView (DataRelation relation)
{
return DataView.CreateChildView(relation,_index);
}
public DataView CreateChildView (string name)
{
return CreateChildView (
Row.Table.ChildRelations [name]);
}
public void Delete ()
{
DataView.Delete(_index);
}
public void EndEdit ()
{
// FIXME:
if (this.Row == DataView._lastAdded) {
DataView.CompleteLastAdded(true);
}
else {
_dataRow.EndEdit();
}
}
private void CheckAllowEdit()
{
if (!DataView.AllowEdit && (Row != DataView._lastAdded))
throw new DataException("Cannot edit on a DataSource where AllowEdit is false.");
}
#endregion // Methods
#region Properties
public DataView DataView {
get { return _dataView; }
}
public bool IsEdit {
get { return _dataRow.HasVersion(DataRowVersion.Proposed); }
}
// It becomes true when this instance is created by
// DataView.AddNew(). If it is true, then the DataRow is
// "Detached", and when this.EndEdit() is invoked, the row
// will be added to the table.
public bool IsNew {
[MonoTODO]
get {
return Row == DataView._lastAdded;
}
}
[System.Runtime.CompilerServices.IndexerName("Item")]
public object this[string column] {
get {
DataColumn dc = _dataView.Table.Columns[column];
if (dc == null) {
string error = column + " is neither a DataColumn nor a DataRelation for table " + _dataView.Table.TableName;
throw new ArgumentException(error);
}
return _dataRow[dc, GetActualRowVersion ()];
}
set {
CheckAllowEdit();
DataColumn dc = _dataView.Table.Columns[column];
if (dc == null) {
string error = column + " is neither a DataColumn nor a DataRelation for table " + _dataView.Table.TableName;
throw new ArgumentException(error);
}
_dataRow[dc] = value;
}
}
// the compiler creates a DefaultMemeberAttribute from
// this IndexerNameAttribute
public object this[int column] {
get {
DataColumn dc = _dataView.Table.Columns[column];
if (dc == null) {
string error = column + " is neither a DataColumn nor a DataRelation for table " + _dataView.Table.TableName;
throw new ArgumentException(error);
}
return _dataRow[dc, GetActualRowVersion ()];
}
set {
CheckAllowEdit();
DataColumn dc = _dataView.Table.Columns[column];
if (dc == null) {
string error = column + " is neither a DataColumn nor a DataRelation for table " + _dataView.Table.TableName;
throw new ArgumentException(error);
}
_dataRow[dc] = value;
}
}
private DataRowVersion GetActualRowVersion ()
{
switch (_dataView.RowStateFilter) {
case DataViewRowState.Added:
return DataRowVersion.Proposed;
case DataViewRowState.ModifiedOriginal:
case DataViewRowState.Deleted:
case DataViewRowState.Unchanged:
case DataViewRowState.OriginalRows:
return DataRowVersion.Original;
case DataViewRowState.ModifiedCurrent:
return DataRowVersion.Current;
}
return DataRowVersion.Default;
}
public DataRow Row {
[MonoTODO]
get {
return _dataRow;
}
}
public DataRowVersion RowVersion {
[MonoTODO]
get {
DataRowVersion version = DataView.GetRowVersion(_index);
if (version != DataRowVersion.Original)
version = DataRowVersion.Current;
return version;
}
}
[MonoTODO]
public override int GetHashCode() {
return _dataRow.GetHashCode();
}
internal int Index {
get { return _index; }
}
#endregion // Properties
#region ICustomTypeDescriptor implementations
[MonoTODO]
AttributeCollection ICustomTypeDescriptor.GetAttributes ()
{
System.ComponentModel.AttributeCollection attributes;
attributes = AttributeCollection.Empty;
return attributes;
}
[MonoTODO]
string ICustomTypeDescriptor.GetClassName ()
{
return "";
}
[MonoTODO]
string ICustomTypeDescriptor.GetComponentName ()
{
return null;
}
[MonoTODO]
TypeConverter ICustomTypeDescriptor.GetConverter ()
{
return null;
}
[MonoTODO]
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent ()
{
return null;
}
[MonoTODO]
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty ()
{
return null;
}
[MonoTODO]
object ICustomTypeDescriptor.GetEditor (Type editorBaseType)
{
return null;
}
[MonoTODO]
EventDescriptorCollection ICustomTypeDescriptor.GetEvents ()
{
return new EventDescriptorCollection(null);
}
[MonoTODO]
EventDescriptorCollection ICustomTypeDescriptor.GetEvents (Attribute [] attributes)
{
return new EventDescriptorCollection(null);
}
[MonoTODO]
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties ()
{
if (DataView == null) {
ITypedList typedList = (ITypedList) _dataView;
return typedList.GetItemProperties(new PropertyDescriptor[0]);
}
else {
return DataView.Table.GetPropertyDescriptorCollection();
}
}
[MonoTODO]
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties (Attribute [] attributes)
{
PropertyDescriptorCollection descriptors;
descriptors = ((ICustomTypeDescriptor) this).GetProperties ();
// TODO: filter out descriptors which do not contain
// any of those attributes
// except, those descriptors
// that contain DefaultMemeberAttribute
return descriptors;
}
[MonoTODO]
object ICustomTypeDescriptor.GetPropertyOwner (PropertyDescriptor pd)
{
return this;
}
#endregion // ICustomTypeDescriptor implementations
#region IDataErrorInfo implementation
string IDataErrorInfo.Error {
[MonoTODO]
get {
return ""; // FIXME
}
}
string IDataErrorInfo.this[string columnName] {
[MonoTODO]
get {
return ""; // FIXME
}
}
#endregion // IDataErrorInfo implementation
}
}
| |
// 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 Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class ReturnKeywordRecommenderTests : KeywordRecommenderTests
{
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAtRoot_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"class C { }
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGlobalStatement_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterGlobalVariableDeclaration_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void EmptyStatement()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void BeforeStatement()
{
VerifyKeyword(AddInsideMethod(
@"$$
return true;"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStatement()
{
VerifyKeyword(AddInsideMethod(
@"return true;
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterBlock()
{
VerifyKeyword(AddInsideMethod(
@"if (true) {
}
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterReturn()
{
VerifyAbsence(AddInsideMethod(
@"return $$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterYield()
{
VerifyKeyword(AddInsideMethod(
@"yield $$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInClass()
{
VerifyAbsence(@"class C
{
$$
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InAttributeInsideClass()
{
VerifyKeyword(
@"class C {
[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InAttributeAfterAttributeInsideClass()
{
VerifyKeyword(
@"class C {
[Foo]
[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InAttributeAfterMethod()
{
VerifyKeyword(
@"class C {
void Foo() {
}
[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InAttributeAfterProperty()
{
VerifyKeyword(
@"class C {
int Foo {
get;
}
[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InAttributeAfterField()
{
VerifyKeyword(
@"class C {
int Foo;
[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InAttributeAfterEvent()
{
VerifyKeyword(
@"class C {
event Action<int> Foo;
[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInOuterAttribute()
{
VerifyAbsence(SourceCodeKind.Regular,
@"[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InOuterAttributeScripting()
{
VerifyKeyword(SourceCodeKind.Script,
@"[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInParameterAttribute()
{
VerifyAbsence(
@"class C {
void Foo([$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInPropertyAttribute()
{
VerifyAbsence(
@"class C {
int Foo { [$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInEventAttribute()
{
VerifyAbsence(
@"class C {
event Action<int> Foo { [$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInClassReturnParameters()
{
VerifyAbsence(
@"class C<[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInDelegateReturnParameters()
{
VerifyAbsence(
@"delegate void D<[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInMethodReturnParameters()
{
VerifyAbsence(
@"class C {
void M<[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InInterface()
{
VerifyKeyword(
@"interface I {
[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InStruct()
{
VerifyKeyword(
@"struct S {
[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInEnum()
{
VerifyAbsence(
@"enum E {
[$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterElse()
{
VerifyKeyword(AddInsideMethod(
@"if (foo) {
} else $$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterElseClause()
{
VerifyKeyword(AddInsideMethod(
@"if (foo) {
} else {
}
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterFixed()
{
VerifyKeyword(AddInsideMethod(
@"fixed (byte* pResult = result) {
}
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterSwitch()
{
VerifyKeyword(AddInsideMethod(
@"switch (foo) {
}
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterCatch()
{
VerifyKeyword(AddInsideMethod(
@"try {
} catch {
}
$$"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterFinally()
{
VerifyKeyword(AddInsideMethod(
@"try {
} finally {
}
$$"));
}
}
}
| |
namespace AngleSharp.Text
{
using AngleSharp.Dom;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
/// <summary>
/// Various HTML encoding helpers.
/// </summary>
public static class TextEncoding
{
#region Encodings
/// <summary>
/// Gets the UTF-8 encoding.
/// </summary>
public static readonly Encoding Utf8 = new UTF8Encoding(false);
/// <summary>
/// Gets the UTF-16 (Big Endian) encoding.
/// </summary>
public static readonly Encoding Utf16Be = new UnicodeEncoding(true, false);
/// <summary>
/// Gets the UTF-16 (Little Endian) encoding.
/// </summary>
public static readonly Encoding Utf16Le = new UnicodeEncoding(false, false);
/// <summary>
/// Gets the UTF-32 (Little Endian) encoding.
/// </summary>
public static readonly Encoding Utf32Le = GetEncoding("UTF-32LE");
/// <summary>
/// Gets the UTF-32 (Little Endian) encoding.
/// </summary>
public static readonly Encoding Utf32Be = GetEncoding("UTF-32BE");
/// <summary>
/// Gets the chinese government standard encoding.
/// </summary>
public static readonly Encoding Gb18030 = GetEncoding("GB18030");
/// <summary>
/// Gets the Big5 encoding.
/// </summary>
public static readonly Encoding Big5 = GetEncoding("big5");
/// <summary>
/// Gets the Windows-874 encoding.
/// </summary>
public static readonly Encoding Windows874 = GetEncoding("windows-874");
/// <summary>
/// Gets the Windows-1250 encoding.
/// </summary>
public static readonly Encoding Windows1250 = GetEncoding("windows-1250");
/// <summary>
/// Gets the Windows-1251 encoding.
/// </summary>
public static readonly Encoding Windows1251 = GetEncoding("windows-1251");
/// <summary>
/// Gets the Windows-1252 encoding.
/// </summary>
public static readonly Encoding Windows1252 = GetEncoding("windows-1252");
/// <summary>
/// Gets the Windows-1253 encoding.
/// </summary>
public static readonly Encoding Windows1253 = GetEncoding("windows-1253");
/// <summary>
/// Gets the Windows-1254 encoding.
/// </summary>
public static readonly Encoding Windows1254 = GetEncoding("windows-1254");
/// <summary>
/// Gets the Windows-1255 encoding.
/// </summary>
public static readonly Encoding Windows1255 = GetEncoding("windows-1255");
/// <summary>
/// Gets the Windows-1256 encoding.
/// </summary>
public static readonly Encoding Windows1256 = GetEncoding("windows-1256");
/// <summary>
/// Gets the Windows-1257 encoding.
/// </summary>
public static readonly Encoding Windows1257 = GetEncoding("windows-1257");
/// <summary>
/// Gets the Windows-1258 encoding.
/// </summary>
public static readonly Encoding Windows1258 = GetEncoding("windows-1258");
/// <summary>
/// Gets the iso-8859-2 encoding.
/// </summary>
public static readonly Encoding Latin2 = GetEncoding("iso-8859-2");
/// <summary>
/// Gets the iso-8859-53 encoding.
/// </summary>
public static readonly Encoding Latin3 = GetEncoding("iso-8859-3");
/// <summary>
/// Gets the iso-8859-4 encoding.
/// </summary>
public static readonly Encoding Latin4 = GetEncoding("iso-8859-4");
/// <summary>
/// Gets the iso-8859-5 encoding.
/// </summary>
public static readonly Encoding Latin5 = GetEncoding("iso-8859-5");
/// <summary>
/// Gets the iso-8859-13 encoding.
/// </summary>
public static readonly Encoding Latin13 = GetEncoding("iso-8859-13");
/// <summary>
/// Gets the US-ASCII encoding.
/// </summary>
public static readonly Encoding UsAscii = GetEncoding("us-ascii");
/// <summary>
/// Gets the ks_c_5601-1987 encoding.
/// </summary>
public static readonly Encoding Korean = GetEncoding("ks_c_5601-1987");
#endregion
#region Fields
private static readonly Dictionary<String, Encoding> encodings = CreateEncodings();
#endregion
#region Extensions
/// <summary>
/// Checks if the provided encoding is any UTF-16 encoding.
/// </summary>
/// <param name="encoding">The encoding to check.</param>
/// <returns>The result of the check (UTF-16BE, UTF-16LE).</returns>
public static Boolean IsUnicode(this Encoding encoding) => encoding == Utf16Be || encoding == Utf16Le;
#endregion
#region Methods
/// <summary>
/// Tries to extract the encoding from the given http-equiv content
/// string.
/// </summary>
/// <param name="content">The value of the attribute.</param>
/// <returns>
/// The extracted encoding or null if the encoding is invalid.
/// </returns>
public static Encoding? Parse(String content)
{
var encoding = String.Empty;
var position = 0;
for (var i = position; i < content.Length - 7; i++)
{
if (content.Substring(i).StartsWith(AttributeNames.Charset, StringComparison.OrdinalIgnoreCase))
{
position = i + 7;
break;
}
}
if (position > 0 && position < content.Length)
{
for (var i = position; i < content.Length - 1; i++)
{
if (content[i].IsSpaceCharacter())
{
position++;
}
else
{
break;
}
}
if (content[position] != Symbols.Equality)
{
return Parse(content.Substring(position));
}
position++;
for (var i = position; i < content.Length; i++)
{
if (content[i].IsSpaceCharacter())
{
position++;
}
else
{
break;
}
}
if (position < content.Length)
{
if (content[position] == Symbols.DoubleQuote)
{
content = content.Substring(position + 1);
var index = content.IndexOf(Symbols.DoubleQuote);
if (index != -1)
{
encoding = content.Substring(0, index);
}
}
else if (content[position] == Symbols.SingleQuote)
{
content = content.Substring(position + 1);
var index = content.IndexOf(Symbols.SingleQuote);
if (index != -1)
{
encoding = content.Substring(0, index);
}
}
else
{
content = content.Substring(position);
var index = 0;
for (var i = 0; i < content.Length; i++)
{
if (content[i].IsSpaceCharacter() || content[i] == Symbols.Semicolon)
{
break;
}
else
{
index++;
}
}
encoding = content.Substring(0, index);
}
}
}
if (!IsSupported(encoding))
{
return null;
}
return Resolve(encoding);
}
/// <summary>
/// Detects if a valid encoding has been found in the given charset
/// string.
/// </summary>
/// <param name="charset">The parsed charset string.</param>
/// <returns>
/// True if a valid encdoing has been found, otherwise false.
/// </returns>
public static Boolean IsSupported(String charset) => encodings.ContainsKey(charset);
/// <summary>
/// Resolves an Encoding instance given by the charset string.
/// If the desired encoding is not found (or supported), then
/// UTF-8 will be returned.
/// </summary>
/// <param name="charset">The charset string.</param>
/// <returns>An instance of the Encoding class or null.</returns>
public static Encoding Resolve(String? charset)
{
if (charset != null && encodings.TryGetValue(charset, out var encoding))
{
return encoding;
}
return Utf8;
}
#endregion
#region Helper
private static Encoding GetEncoding(String name, Encoding? fallback = default)
{
try
{
return Encoding.GetEncoding(name);
}
catch (Exception ex)
{
Debug.WriteLine("The platform does not allow using the '{0}' encoding: {1}", name, ex);
// We use a catch em all since WP8 does throw a different exception than W*.
return fallback ?? Utf8;
}
}
private static Dictionary<String, Encoding> CreateEncodings()
{
var encodings = new Dictionary<String, Encoding>(StringComparer.OrdinalIgnoreCase)
{
{ "unicode-1-1-utf-8", Utf8 },
{ "utf-8", Utf8 },
{ "utf8", Utf8 },
{ "utf-16be", Utf16Be },
{ "utf-16", Utf16Le },
{ "utf-16le", Utf16Le },
{ "dos-874", Windows874 },
{ "iso-8859-11", Windows874 },
{ "iso8859-11", Windows874 },
{ "iso885911", Windows874 },
{ "tis-620", Windows874 },
{ "windows-874", Windows874 },
{ "cp1250", Windows1250 },
{ "windows-1250", Windows1250 },
{ "x-cp1250", Windows1250 },
{ "cp1251", Windows1251 },
{ "windows-1251", Windows1251 },
{ "x-cp1251", Windows1251 },
{ "x-user-defined", Windows1252 },
{ "ansi_x3.4-1968", Windows1252 },
{ "ascii", Windows1252 },
{ "cp1252", Windows1252 },
{ "cp819", Windows1252 },
{ "csisolatin1", Windows1252 },
{ "ibm819", Windows1252 },
{ "iso-8859-1", Windows1252 },
{ "iso-ir-100", Windows1252 },
{ "iso8859-1", Windows1252 },
{ "iso88591", Windows1252 },
{ "iso_8859-1", Windows1252 },
{ "iso_8859-1:1987", Windows1252 },
{ "l1", Windows1252 },
{ "latin1", Windows1252 },
{ "us-ascii", Windows1252 },
{ "windows-1252", Windows1252 },
{ "x-cp1252", Windows1252 },
{ "cp1253", Windows1253 },
{ "windows-1253", Windows1253 },
{ "x-cp1253", Windows1253 },
{ "cp1254", Windows1254 },
{ "csisolatin5", Windows1254 },
{ "iso-8859-9", Windows1254 },
{ "iso-ir-148", Windows1254 },
{ "iso8859-9", Windows1254 },
{ "iso88599", Windows1254 },
{ "iso_8859-9", Windows1254 },
{ "iso_8859-9:1989", Windows1254 },
{ "l5", Windows1254 },
{ "latin5", Windows1254 },
{ "windows-1254", Windows1254 },
{ "x-cp1254", Windows1254 },
{ "cp1255", Windows1255 },
{ "windows-1255", Windows1255 },
{ "x-cp1255", Windows1255 },
{ "cp1256", Windows1256 },
{ "windows-1256", Windows1256 },
{ "x-cp1256", Windows1256 },
{ "cp1257", Windows1257 },
{ "windows-1257", Windows1257 },
{ "x-cp1257", Windows1257 },
{ "cp1258", Windows1258 },
{ "windows-1258", Windows1258 },
{ "x-cp1258", Windows1258 }
};
var macintosh = GetEncoding("macintosh");
encodings.Add("csmacintosh", macintosh);
encodings.Add("mac", macintosh);
encodings.Add("macintosh", macintosh);
encodings.Add("x-mac-roman", macintosh);
var maccyrillic = GetEncoding("x-mac-cyrillic"); ;
encodings.Add("x-mac-cyrillic", maccyrillic);
encodings.Add("x-mac-ukrainian", maccyrillic);
var i866 = GetEncoding("cp866");
encodings.Add("866", i866);
encodings.Add("cp866", i866);
encodings.Add("csibm866", i866);
encodings.Add("ibm866", i866);
encodings.Add("csisolatin2", Latin2);
encodings.Add("iso-8859-2", Latin2);
encodings.Add("iso-ir-101", Latin2);
encodings.Add("iso8859-2", Latin2);
encodings.Add("iso88592", Latin2);
encodings.Add("iso_8859-2", Latin2);
encodings.Add("iso_8859-2:1987", Latin2);
encodings.Add("l2", Latin2);
encodings.Add("latin2", Latin2);
encodings.Add("csisolatin3", Latin3);
encodings.Add("iso-8859-3", Latin3);
encodings.Add("iso-ir-109", Latin3);
encodings.Add("iso8859-3", Latin3);
encodings.Add("iso88593", Latin3);
encodings.Add("iso_8859-3", Latin3);
encodings.Add("iso_8859-3:1988", Latin3);
encodings.Add("l3", Latin3);
encodings.Add("latin3", Latin3);
encodings.Add("csisolatin4", Latin4);
encodings.Add("iso-8859-4", Latin4);
encodings.Add("iso-ir-110", Latin4);
encodings.Add("iso8859-4", Latin4);
encodings.Add("iso88594", Latin4);
encodings.Add("iso_8859-4", Latin4);
encodings.Add("iso_8859-4:1988", Latin4);
encodings.Add("l4", Latin4);
encodings.Add("latin4", Latin4);
encodings.Add("csisolatincyrillic", Latin5);
encodings.Add("cyrillic", Latin5);
encodings.Add("iso-8859-5", Latin5);
encodings.Add("iso-ir-144", Latin5);
encodings.Add("iso8859-5", Latin5);
encodings.Add("iso88595", Latin5);
encodings.Add("iso_8859-5", Latin5);
encodings.Add("iso_8859-5:1988", Latin5);
var latin6 = GetEncoding("iso-8859-6");
encodings.Add("arabic", latin6);
encodings.Add("asmo-708", latin6);
encodings.Add("csiso88596e", latin6);
encodings.Add("csiso88596i", latin6);
encodings.Add("csisolatinarabic", latin6);
encodings.Add("ecma-114", latin6);
encodings.Add("iso-8859-6", latin6);
encodings.Add("iso-8859-6-e", latin6);
encodings.Add("iso-8859-6-i", latin6);
encodings.Add("iso-ir-127", latin6);
encodings.Add("iso8859-6", latin6);
encodings.Add("iso88596", latin6);
encodings.Add("iso_8859-6", latin6);
encodings.Add("iso_8859-6:1987", latin6);
var latin7 = GetEncoding("iso-8859-7");
encodings.Add("csisolatingreek", latin7);
encodings.Add("ecma-118", latin7);
encodings.Add("elot_928", latin7);
encodings.Add("greek", latin7);
encodings.Add("greek8", latin7);
encodings.Add("iso-8859-7", latin7);
encodings.Add("iso-ir-126", latin7);
encodings.Add("iso8859-7", latin7);
encodings.Add("iso88597", latin7);
encodings.Add("iso_8859-7", latin7);
encodings.Add("iso_8859-7:1987", latin7);
encodings.Add("sun_eu_greek", latin7);
var latin8 = GetEncoding("iso-8859-8");
encodings.Add("csiso88598e", latin8);
encodings.Add("csisolatinhebrew", latin8);
encodings.Add("hebrew", latin8);
encodings.Add("iso-8859-8", latin8);
encodings.Add("iso-8859-8-e", latin8);
encodings.Add("iso-ir-138", latin8);
encodings.Add("iso8859-8", latin8);
encodings.Add("iso88598", latin8);
encodings.Add("iso_8859-8", latin8);
encodings.Add("iso_8859-8:1988", latin8);
encodings.Add("visual", latin8);
var latini = GetEncoding("iso-8859-8-i");
encodings.Add("csiso88598i", latini);
encodings.Add("iso-8859-8-i", latini);
encodings.Add("logical", latini);
var latin13 = GetEncoding("iso-8859-13");
encodings.Add("iso-8859-13", latin13);
encodings.Add("iso8859-13", latin13);
encodings.Add("iso885913", latin13);
var latin15 = GetEncoding("iso-8859-15");
encodings.Add("csisolatin9", latin15);
encodings.Add("iso-8859-15", latin15);
encodings.Add("iso8859-15", latin15);
encodings.Add("iso885915", latin15);
encodings.Add("iso_8859-15", latin15);
encodings.Add("l9", latin15);
var kr = GetEncoding("koi8-r");
encodings.Add("cskoi8r", kr);
encodings.Add("koi", kr);
encodings.Add("koi8", kr);
encodings.Add("koi8-r", kr);
encodings.Add("koi8_r", kr);
encodings.Add("koi8-u", GetEncoding("koi8-u"));
var chineseOfficial = GetEncoding("GB18030", GetEncoding("x-cp20936"));
encodings.Add("chinese", chineseOfficial);
encodings.Add("csgb2312", chineseOfficial);
encodings.Add("csiso58gb231280", chineseOfficial);
encodings.Add("gb2312", chineseOfficial);
encodings.Add("gb_2312", chineseOfficial);
encodings.Add("gb_2312-80", chineseOfficial);
encodings.Add("gbk", chineseOfficial);
encodings.Add("iso-ir-58", chineseOfficial);
encodings.Add("x-gbk", chineseOfficial);
encodings.Add("hz-gb-2312", GetEncoding("hz-gb-2312"));
encodings.Add("gb18030", Gb18030);
var chineseSimplified = GetEncoding("x-cp50227");
encodings.Add("x-cp50227", chineseSimplified);
encodings.Add("iso-22-cn", chineseSimplified);
encodings.Add("big5", Big5);
encodings.Add("big5-hkscs", Big5);
encodings.Add("cn-big5", Big5);
encodings.Add("csbig5", Big5);
encodings.Add("x-x-big5", Big5);
var isojp = GetEncoding("iso-2022-jp");
encodings.Add("csiso2022jp", isojp);
encodings.Add("iso-2022-jp", isojp);
var isokr = GetEncoding("iso-2022-kr");
encodings.Add("csiso2022kr", isokr);
encodings.Add("iso-2022-kr", isokr);
var isocn = GetEncoding("iso-2022-cn");
encodings.Add("iso-2022-cn", isocn);
encodings.Add("iso-2022-cn-ext", isocn);
encodings.Add("shift_jis", GetEncoding("shift_jis"));
var eucjp = GetEncoding("euc-jp");
encodings.Add("euc-jp", eucjp);
var euckr = GetEncoding("euc-kr");
encodings.Add("euc-kr", euckr);
return encodings;
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Represents logging target.
/// </summary>
[NLogConfigurationItem]
public abstract class Target : ISupportsInitialize, IDisposable
{
private object lockObject = new object();
private List<Layout> allLayouts;
private Exception initializeException;
/// <summary>
/// Gets or sets the name of the target.
/// </summary>
/// <docgen category='General Options' order='10' />
public string Name { get; set; }
/// <summary>
/// Gets the object which can be used to synchronize asynchronous operations that must rely on the .
/// </summary>
protected object SyncRoot
{
get { return this.lockObject; }
}
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
/// <summary>
/// Gets a value indicating whether the target has been initialized.
/// </summary>
protected bool IsInitialized { get; private set; }
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
this.Initialize(configuration);
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
this.Close();
}
/// <summary>
/// Closes the target.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Flush(AsyncContinuation asyncContinuation)
{
if (asyncContinuation == null)
{
throw new ArgumentNullException("asyncContinuation");
}
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
asyncContinuation(null);
return;
}
asyncContinuation = AsyncHelpers.PreventMultipleCalls(asyncContinuation);
try
{
this.FlushAsync(asyncContinuation);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
asyncContinuation(exception);
}
}
}
/// <summary>
/// Calls the <see cref="Layout.Precalculate"/> on each volatile layout
/// used by this target.
/// </summary>
/// <param name="logEvent">
/// The log event.
/// </param>
public void PrecalculateVolatileLayouts(LogEventInfo logEvent)
{
lock (this.SyncRoot)
{
if (this.IsInitialized)
{
if (this.allLayouts != null)
{
foreach (Layout l in this.allLayouts)
{
l.Precalculate(logEvent);
}
}
}
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var targetAttribute = (TargetAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(TargetAttribute));
if (targetAttribute != null)
{
return targetAttribute.Name + " Target[" + (this.Name ?? "(unnamed)") + "]";
}
return this.GetType().Name;
}
/// <summary>
/// Writes the log to the target.
/// </summary>
/// <param name="logEvent">Log event to write.</param>
public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent)
{
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
logEvent.Continuation(null);
return;
}
if (this.initializeException != null)
{
logEvent.Continuation(this.CreateInitException());
return;
}
var wrappedContinuation = AsyncHelpers.PreventMultipleCalls(logEvent.Continuation);
try
{
this.Write(logEvent.LogEvent.WithContinuation(wrappedContinuation));
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
wrappedContinuation(exception);
}
}
}
/// <summary>
/// Writes the array of log events.
/// </summary>
/// <param name="logEvents">The log events.</param>
public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents)
{
if (logEvents == null || logEvents.Length == 0)
{
return;
}
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
foreach (var ev in logEvents)
{
ev.Continuation(null);
}
return;
}
if (this.initializeException != null)
{
foreach (var ev in logEvents)
{
ev.Continuation(this.CreateInitException());
}
return;
}
var wrappedEvents = new AsyncLogEventInfo[logEvents.Length];
for (int i = 0; i < logEvents.Length; ++i)
{
wrappedEvents[i] = logEvents[i].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(logEvents[i].Continuation));
}
try
{
this.Write(wrappedEvents);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
// in case of synchronous failure, assume that nothing is running asynchronously
foreach (var ev in wrappedEvents)
{
ev.Continuation(exception);
}
}
}
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
lock (this.SyncRoot)
{
this.LoggingConfiguration = configuration;
if (!this.IsInitialized)
{
PropertyHelper.CheckRequiredParameters(this);
this.IsInitialized = true;
try
{
this.InitializeTarget();
this.initializeException = null;
if (this.allLayouts == null)
{
throw new NLogRuntimeException("{0}.allLayouts is null. Call base.InitializeTarget() in {0}", this.GetType());
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error initializing target '{0}'.", this);
this.initializeException = exception;
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
lock (this.SyncRoot)
{
this.LoggingConfiguration = null;
if (this.IsInitialized)
{
this.IsInitialized = false;
try
{
if (this.initializeException == null)
{
// if Init succeeded, call Close()
this.CloseTarget();
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error closing target '{0}'.", this);
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
}
internal void WriteAsyncLogEvents(AsyncLogEventInfo[] logEventInfos, AsyncContinuation continuation)
{
if (logEventInfos.Length == 0)
{
continuation(null);
}
else
{
var wrappedLogEventInfos = new AsyncLogEventInfo[logEventInfos.Length];
int remaining = logEventInfos.Length;
for (int i = 0; i < logEventInfos.Length; ++i)
{
AsyncContinuation originalContinuation = logEventInfos[i].Continuation;
AsyncContinuation wrappedContinuation = ex =>
{
originalContinuation(ex);
if (0 == Interlocked.Decrement(ref remaining))
{
continuation(null);
}
};
wrappedLogEventInfos[i] = logEventInfos[i].LogEvent.WithContinuation(wrappedContinuation);
}
this.WriteAsyncLogEvents(wrappedLogEventInfos);
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.CloseTarget();
}
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
protected virtual void InitializeTarget()
{
this.allLayouts = new List<Layout>(ObjectGraphScanner.FindReachableObjects<Layout>(this));
InternalLogger.Trace("{0} has {1} layouts", this, this.allLayouts.Count);
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected virtual void CloseTarget()
{
}
/// <summary>
/// Flush any pending log messages asynchronously (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected virtual void FlushAsync(AsyncContinuation asyncContinuation)
{
asyncContinuation(null);
}
/// <summary>
/// Writes logging event to the log target.
/// classes.
/// </summary>
/// <param name="logEvent">
/// Logging event to be written out.
/// </param>
protected virtual void Write(LogEventInfo logEvent)
{
// do nothing
}
/// <summary>
/// Writes log event to the log target. Must be overridden in inheriting
/// classes.
/// </summary>
/// <param name="logEvent">Log event to be written out.</param>
protected virtual void Write(AsyncLogEventInfo logEvent)
{
try
{
this.MergeEventProperties(logEvent.LogEvent);
this.Write(logEvent.LogEvent);
logEvent.Continuation(null);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
logEvent.Continuation(exception);
}
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected virtual void Write(AsyncLogEventInfo[] logEvents)
{
for (int i = 0; i < logEvents.Length; ++i)
{
this.Write(logEvents[i]);
}
}
private Exception CreateInitException()
{
return new NLogRuntimeException("Target " + this + " failed to initialize.", this.initializeException);
}
/// <summary>
/// Merges (copies) the event context properties from any event info object stored in
/// parameters of the given event info object.
/// </summary>
/// <param name="logEvent">The event info object to perform the merge to.</param>
protected void MergeEventProperties(LogEventInfo logEvent)
{
if (logEvent.Parameters == null)
{
return;
}
foreach (var item in logEvent.Parameters)
{
var logEventParameter = item as LogEventInfo;
if (logEventParameter != null)
{
foreach (var key in logEventParameter.Properties.Keys)
{
logEvent.Properties.Add(key, logEventParameter.Properties[key]);
}
logEventParameter.Properties.Clear();
}
}
}
}
}
| |
namespace RAGENativeUI.Elements
{
using System;
using System.Linq;
using System.Collections.Generic;
using Rage;
using System.Drawing;
using RAGENativeUI.Internals;
using System.ComponentModel;
public class InstructionalButtons
{
private const string ScaleformName = "instructional_buttons";
public static readonly Color DefaultBackgroundColor = Color.FromArgb(80, 0, 0, 0);
private bool needsUpdate = true;
public Scaleform Scaleform { get; }
public InstructionalButtonsCollection Buttons { get; }
public Color BackgroundColor { get; set; } = DefaultBackgroundColor;
public float MaxWidth { get; set; } = 1.0f;
public bool MouseButtonsEnabled { get; set; }
public InstructionalButtons()
{
Scaleform = new Scaleform();
Buttons = new InstructionalButtonsCollection();
Buttons.ItemAdded += (c, i) => Update();
Buttons.ItemRemoved += (c, i) => Update();
Buttons.ItemModified += (c, o, n) => Update();
Buttons.Cleared += (c) => Update();
}
public void Draw()
{
if (needsUpdate ||
N.HasInputJustChanged(2)) // check so the correct keys or controller buttons are displayed when the user switches between keyboard and controller
{
DoUpdate();
}
if (ScriptGlobals.TimerBarsInstructionButtonsNumRowsAvailable)
{
ScriptGlobals.TimerBarsInstructionButtonsNumRows = NumberOfRows;
}
Scaleform.Render2D();
}
public void Update() => needsUpdate = true;
private void DoUpdate()
{
if (!Scaleform.IsLoaded)
{
Scaleform.Load(ScaleformName);
return;
}
Scaleform.CallFunction("CLEAR_ALL");
Scaleform.CallFunction("TOGGLE_MOUSE_BUTTONS", MouseButtonsEnabled);
Scaleform.CallFunction("SET_MAX_WIDTH", MaxWidth);
for (int i = 0, slot = 0; i < Buttons.Count; i++)
{
IInstructionalButtonSlot b = Buttons[i];
if (b.CanBeDisplayed == null || b.CanBeDisplayed(b))
{
if (MouseButtonsEnabled)
{
Scaleform.CallFunction("SET_DATA_SLOT", slot++,
b.GetButtonId() ?? string.Empty,
b.Text ?? string.Empty,
b.BindedControl.HasValue, // clickable?
b.BindedControl.HasValue ? (int)b.BindedControl.Value : -1); // control binded to click
}
else
{
Scaleform.CallFunction("SET_DATA_SLOT", slot++,
b.GetButtonId() ?? string.Empty,
b.Text ?? string.Empty);
}
}
}
Scaleform.CallFunction("SET_BACKGROUND_COLOUR", (int)BackgroundColor.R, (int)BackgroundColor.G, (int)BackgroundColor.B, (int)BackgroundColor.A);
Scaleform.CallFunction("DRAW_INSTRUCTIONAL_BUTTONS", 0);
needsUpdate = false;
}
private static int numberOfRowsReturnValueId = 0;
private static uint numberOfRowsReturnValueFrame = 0;
internal static int NumberOfRows // TODO: make NumberOfRows public?
{
get
{
static unsafe int GetInstructionalButtonsRows(uint frame)
{
if (CBusySpinner.Available && CScaleformMgr.Available)
{
if (numberOfRowsReturnValueId != 0)
{
if (N.IsScaleformMovieMethodReturnValueReady(numberOfRowsReturnValueId))
{
int rows = N.GetScaleformMovieMethodReturnValueInt(numberOfRowsReturnValueId);
numberOfRowsReturnValueId = 0;
return rows;
}
if ((frame - numberOfRowsReturnValueFrame) >= 2) // if the return value is not ready after 2 frames, call the method again
{
numberOfRowsReturnValueId = 0;
}
return Shared.NumInstructionalButtonsRows; // return the previous number of rows until the return value is ready
}
else
{
foreach (int sf in CBusySpinner.InstructionalButtons)
{
if (CScaleformMgr.IsMovieRendering(sf))
{
if (CScaleformMgr.BeginMethod(sf, 1, "GET_NUMBER_OF_ROWS")) // not using the native because we don't have scaleform script handle
{
numberOfRowsReturnValueId = N.EndScaleformMovieMethodReturnValue();
numberOfRowsReturnValueFrame = frame;
return Shared.NumInstructionalButtonsRows; // return the previous number of rows until the return value is ready
}
}
}
}
}
return N.BusySpinnerIsOn() ? 1 : 0;
}
uint frame = Game.FrameCount;
if (Shared.NumInstructionalButtonsRowsLastFrame != frame)
{
Shared.NumInstructionalButtonsRowsLastFrame = frame;
Shared.NumInstructionalButtonsRows = GetInstructionalButtonsRows(frame);
}
return Shared.NumInstructionalButtonsRows;
}
}
public class InstructionalButtonsCollection : BaseCollection<IInstructionalButtonSlot>, IEnumerable<InstructionalButton>
{
#region Backwards Compatibility
// Implement IEnumerable<InstructionalButton> for backwards compatibilty (mainly when using Linq, broken when BaseCollection<InstructionalButton> was changed to BaseCollection<IInstructionalButtonSlot>)
// Other methods like Add or Remove still work because InstructionalButton implements IInstructionalButtonSlot and the runtime can still find them
// This doesn't make it fully backwards compatible (like BaseCollection events are still incompatible), but improves the situation a bit
[EditorBrowsable(EditorBrowsableState.Never)]
IEnumerator<InstructionalButton> IEnumerable<InstructionalButton>.GetEnumerator()
=> InternalList.Where(slot => slot is InstructionalButton).Cast<InstructionalButton>().GetEnumerator();
#endregion
}
}
public interface IInstructionalButtonSlot
{
/// <summary>
/// Gets or sets the text displayed next to the button.
/// <para>
/// If this <see cref="IInstructionalButtonSlot"/> is contained in a <see cref="InstructionalButtons"/> scaleform,
/// <see cref="InstructionalButtons.Update"/> needs to be called to reflect the changes made.
/// </para>
/// </summary>
/// <value>
/// A <see cref="string"/> representing the text displayed next to the button.
/// </value>
public string Text { get; set; }
/// <summary>
/// Gets or sets the <see cref="Predicate{T}"/> that defines the conditions for this <see cref="IInstructionalButtonSlot"/> to be visible.
/// <para>
/// If this <see cref="IInstructionalButtonSlot"/> is contained in a <see cref="InstructionalButtons"/> scaleform,
/// this predicate is only evaluated when <see cref="InstructionalButtons.Update"/> is called.
/// </para>
/// </summary>
/// <value>
/// A <see cref="Predicate{T}"/> delegate that defines the conditions for this <see cref="InstructionalButton"/> to be visible.
/// </value>
public Predicate<IInstructionalButtonSlot> CanBeDisplayed { get; set; }
/// <summary>
/// Gets or sets the <see cref="GameControl"/> triggered when the button is clicked. If <c>null</c>, the button cannot be clicked.
/// </summary>
/// <remarks>
/// When the user clicks the button, the specified control will be pressed for one frame so it can be checked with methods such as <see cref="Game.IsControlJustPressed(int, GameControl)"/>.
/// </remarks>
public GameControl? BindedControl { get; set; }
/// <summary>
/// Gets a <see cref="string"/> that represents the contents of this <see cref="IInstructionalButtonSlot"/>.
/// </summary>
/// <returns>A <see cref="string"/> that represents the contents of this <see cref="IInstructionalButtonSlot"/>.</returns>
public string GetButtonId();
}
public class InstructionalButton : IInstructionalButtonSlot
{
/// <inheritdoc/>
public string Text { get; set; }
/// <summary>
/// Gets or sets the contents of the button.
/// <para>
/// If this <see cref="InstructionalButton"/> is contained in a <see cref="InstructionalButtons"/> scaleform,
/// <see cref="InstructionalButtons.Update"/> needs to be called to reflect the changes made.
/// </para>
/// </summary>
public InstructionalButtonId Button { get; set; }
/// <inheritdoc/>
public Predicate<IInstructionalButtonSlot> CanBeDisplayed { get; set; }
/// <inheritdoc/>
public GameControl? BindedControl { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButton"/> class.
/// </summary>
/// <param name="button">The button to be displayed.</param>
/// <param name="text">The text displayed next to the button.</param>
public InstructionalButton(InstructionalButtonId button, string text)
{
Text = text;
Button = button;
}
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButton"/> class. This overload sets <see cref="BindedControl"/> to <paramref name="control"/>.
/// </summary>
/// <param name="control">The <see cref="GameControl"/> displayed inside the button, it changes depending on keybinds and whether the user is using the controller or the keyboard and mouse.</param>
/// <param name="text">The text displayed next to the button.</param>
public InstructionalButton(GameControl control, string text) : this((InstructionalButtonId)control, text) { BindedControl = control; }
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButton"/> class.
/// </summary>
/// <param name="buttonText">The text displayed inside the button, mainly for displaying custom keyboard bindings, like "I", or "O", or "F5".</param>
/// <param name="text">The text displayed next to the button.</param>
public InstructionalButton(string buttonText, string text) : this((InstructionalButtonId)buttonText, text) { }
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButton"/> class.
/// </summary>
/// <param name="rawId">The raw identifier of the symbol to be displayed.</param>
/// <param name="text">The text displayed next to the button.</param>
public InstructionalButton(uint rawId, string text) : this((InstructionalButtonId)rawId, text) { }
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButton"/> class.
/// </summary>
/// <param name="key">The symbol to be displayed.</param>
/// <param name="text">The text displayed next to the button.</param>
public InstructionalButton(InstructionalKey key, string text) : this((InstructionalButtonId)key, text) { }
/// <inheritdoc/>
public string GetButtonId() => Button.Id;
public static string GetButtonId(GameControl control) => new InstructionalButtonId(control).Id;
public static string GetButtonId(string keyString) => new InstructionalButtonId(keyString).Id;
public static string GetButtonId(uint rawId) => new InstructionalButtonId(rawId).Id;
public static string GetButtonId(InstructionalKey key) => new InstructionalButtonId(key).Id;
}
public class InstructionalButtonGroup : IInstructionalButtonSlot
{
private IList<InstructionalButtonId> buttons;
/// <inheritdoc/>
public string Text { get; set; }
/// <inheritdoc/>
public Predicate<IInstructionalButtonSlot> CanBeDisplayed { get; set; }
/// <inheritdoc/>
public GameControl? BindedControl { get; set; }
/// <summary>
/// Gets or sets the list containing the buttons of this group.
/// <para>
/// If this <see cref="InstructionalButtonGroup"/> is contained in a <see cref="InstructionalButtons"/> scaleform,
/// <see cref="InstructionalButtons.Update"/> needs to be called to reflect the changes made.
/// </para>
/// </summary>
/// <exception cref="ArgumentNullException">
/// <c>value</c> is null.
/// </exception>
public IList<InstructionalButtonId> Buttons
{
get => buttons;
set => buttons = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButtonGroup"/> class.
/// </summary>
/// <param name="text">The text displayed next to the buttons.</param>
/// <param name="buttons">The buttons to be displayed.</param>
public InstructionalButtonGroup(string text, IEnumerable<InstructionalButtonId> buttons)
{
Text = text;
Buttons = new List<InstructionalButtonId>(buttons);
}
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButtonGroup"/> class.
/// </summary>
/// <param name="text">The text displayed next to the buttons.</param>
/// <param name="buttons">The buttons to be displayed.</param>
public InstructionalButtonGroup(string text, params InstructionalButtonId[] buttons) : this(text, (IEnumerable<InstructionalButtonId>)buttons) { }
/// <inheritdoc/>
public string GetButtonId() => GetButtonId(Buttons);
public static string GetButtonId(IEnumerable<InstructionalButtonId> buttons)
=> string.Join("%", buttons.Reverse().Select(btn => btn.Id));
}
public class InstructionalButtonDynamic : IInstructionalButtonSlot
{
private IList<InstructionalButtonId> buttonsForKeyboard, buttonsForController;
/// <inheritdoc/>
public string Text { get; set; }
public IList<InstructionalButtonId> ButtonsForKeyboard
{
get => buttonsForKeyboard;
set => buttonsForKeyboard = value ?? throw new ArgumentNullException(nameof(value));
}
public IList<InstructionalButtonId> ButtonsForController
{
get => buttonsForController;
set => buttonsForController = value ?? throw new ArgumentNullException(nameof(value));
}
/// <inheritdoc/>
public Predicate<IInstructionalButtonSlot> CanBeDisplayed { get; set; }
/// <inheritdoc/>
public GameControl? BindedControl { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButtonDynamic"/> class.
/// </summary>
/// <param name="text">The text displayed next to the button.</param>
/// <param name="forKeyboard">The button to be displayed when using keyboard and mouse.</param>
/// <param name="forController">The button to be displayed when using a controller.</param>
public InstructionalButtonDynamic(string text, InstructionalButtonId forKeyboard, InstructionalButtonId forController)
{
Text = text;
ButtonsForKeyboard = new List<InstructionalButtonId>(1) { forKeyboard };
ButtonsForController = new List<InstructionalButtonId>(1) { forController };
}
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButtonDynamic"/> class.
/// </summary>
/// <param name="text">The text displayed next to the button.</param>
/// <param name="forKeyboard">The buttons to be displayed when using keyboard and mouse.</param>
/// <param name="forController">The buttons to be displayed when using a controller.</param>
public InstructionalButtonDynamic(string text, IEnumerable<InstructionalButtonId> forKeyboard, IEnumerable<InstructionalButtonId> forController)
{
Text = text;
ButtonsForKeyboard = new List<InstructionalButtonId>(forKeyboard);
ButtonsForController = new List<InstructionalButtonId>(forController);
}
/// <inheritdoc/>
public string GetButtonId() => UIMenu.IsUsingController ? InstructionalButtonGroup.GetButtonId(ButtonsForController) :
InstructionalButtonGroup.GetButtonId(ButtonsForKeyboard);
}
public readonly struct InstructionalButtonId
{
/// <summary>
/// A blank button. Used when this struct is created with the default constructor or <c>default</c> value.
/// </summary>
private const string EmptyButtonId = "t_";
// need to store the control because the string returned by GET_CONTROL_INSTRUCTIONAL_BUTTON may change
// if the user switches between keyboard and controller
private readonly GameControl? control;
private readonly string id;
/// <summary>
/// Gets the <see cref="string"/> that represents the button contents.
/// </summary>
public string Id => id ?? (control.HasValue ? N.GetControlInstructionalButton(2, control.Value) : EmptyButtonId);
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButtonId"/> structure.
/// </summary>
/// <param name="control">The <see cref="GameControl"/> displayed inside the button, it changes depending on keybinds and whether the user is using the controller or the keyboard and mouse.</param>
public InstructionalButtonId(GameControl control) : this() => this.control = control;
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButtonId"/> structure.
/// </summary>
/// <param name="str">The text displayed inside the button, mainly for displaying custom keyboard bindings, like "I", or "O", or "F5".</param>
public InstructionalButtonId(string str) : this()
=> id = str.Length switch
{
int n when n <= 2 => "t_",
int n when n <= 4 => "T_",
_ => "w_"
} + str;
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButtonId"/> structure.
/// </summary>
/// <param name="rawId">The raw identifier of the symbol to be displayed.</param>
public InstructionalButtonId(uint rawId) : this() => id = "b_" + rawId;
/// <summary>
/// Initializes a new instance of the <see cref="InstructionalButtonId"/> structure.
/// </summary>
/// <param name="key">The symbol to be displayed.</param>
public InstructionalButtonId(InstructionalKey key) : this() => id = key.GetId();
public static implicit operator InstructionalButtonId(GameControl control) => new InstructionalButtonId(control);
public static implicit operator InstructionalButtonId(string str) => new InstructionalButtonId(str);
public static implicit operator InstructionalButtonId(uint rawId) => new InstructionalButtonId(rawId);
public static implicit operator InstructionalButtonId(InstructionalKey key) => new InstructionalButtonId(key);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
using System.Collections.Generic;
using System;
namespace HoloToolkit.Unity.Collections
{
/// <summary>
/// An Object Collection is simply a set of child objects organized with some
/// layout parameters. The object collection can be used to quickly create
/// control panels or sets of prefab/objects.
/// </summary>
public class ObjectCollection : MonoBehaviour
{
#region public members
/// <summary>
/// Action called when collection is updated
/// </summary>
public Action<ObjectCollection> OnCollectionUpdated;
/// <summary>
/// List of objects with generated data on the object.
/// </summary>
[SerializeField]
public List<CollectionNode> NodeList = new List<CollectionNode>();
/// <summary>
/// Type of surface to map the collection to.
/// </summary>
[Tooltip("Type of surface to map the collection to")]
public SurfaceTypeEnum SurfaceType = SurfaceTypeEnum.Plane;
/// <summary>
/// Type of sorting to use.
/// </summary>
[Tooltip("Type of sorting to use")]
public SortTypeEnum SortType = SortTypeEnum.None;
/// <summary>
/// Should the objects in the collection face the origin of the collection
/// </summary>
[Tooltip("Should the objects in the collection be rotated / how should they be rotated")]
public OrientTypeEnum OrientType = OrientTypeEnum.FaceOrigin;
/// <summary>
/// Whether to sort objects by row first or by column first
/// </summary>
[Tooltip("Whether to sort objects by row first or by column first")]
public LayoutTypeEnum LayoutType = LayoutTypeEnum.ColumnThenRow;
/// <summary>
/// Whether to treat inactive transforms as 'invisible'
/// </summary>
public bool IgnoreInactiveTransforms = true;
/// <summary>
/// This is the radius of either the Cylinder or Sphere mapping and is ignored when using the plane mapping.
/// </summary>
[Range(0.05f, 5.0f)]
[Tooltip("Radius for the sphere or cylinder")]
public float Radius = 2f;
/// <summary>
/// Number of rows per column, column number is automatically determined
/// </summary>
[Tooltip("Number of rows per column")]
public int Rows = 3;
/// <summary>
/// Width of the cell per object in the collection.
/// </summary>
[Tooltip("Width of cell per object")]
public float CellWidth = 0.5f;
/// <summary>
/// Height of the cell per object in the collection.
/// </summary>
[Tooltip("Height of cell per object")]
public float CellHeight = 0.5f;
/// <summary>
/// Reference mesh to use for rendering the sphere layout
/// </summary>
[HideInInspector]
public Mesh SphereMesh;
/// <summary>
/// Reference mesh to use for rendering the cylinder layout
/// </summary>
[HideInInspector]
public Mesh CylinderMesh;
#endregion
#region private variables
private int _columns;
private float _width;
private float _height;
private float _circumference;
private Vector2 _halfCell;
#endregion
public float Width
{
get { return _width; }
}
public float Height
{
get { return _height; }
}
/// <summary>
/// Update collection is called from the editor button on the inspector.
/// This function rebuilds / updates the layout.
/// </summary>
public void UpdateCollection()
{
// Check for empty nodes and remove them
List<CollectionNode> emptyNodes = new List<CollectionNode>();
for (int i = 0; i < NodeList.Count; i++)
{
if (NodeList[i].transform == null || (IgnoreInactiveTransforms && !NodeList[i].transform.gameObject.activeSelf))
{
emptyNodes.Add(NodeList[i]);
}
}
// Now delete the empty nodes
for (int i = 0; i < emptyNodes.Count; i++)
{
NodeList.Remove(emptyNodes[i]);
}
emptyNodes.Clear();
// Check when children change and adjust
for (int i = 0; i < this.transform.childCount; i++)
{
Transform child = this.transform.GetChild(i);
if (!ContainsNode(child) && (child.gameObject.activeSelf || !IgnoreInactiveTransforms))
{
CollectionNode node = new CollectionNode();
node.Name = child.name;
node.transform = child;
NodeList.Add(node);
}
}
switch (SortType)
{
case SortTypeEnum.None:
break;
case SortTypeEnum.Transform:
NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.transform.GetSiblingIndex().CompareTo(c2.transform.GetSiblingIndex()); });
break;
case SortTypeEnum.Alphabetical:
NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.Name.CompareTo(c2.Name); });
break;
case SortTypeEnum.AlphabeticalReversed:
NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.Name.CompareTo(c2.Name); });
NodeList.Reverse();
break;
case SortTypeEnum.TransformReversed:
NodeList.Sort(delegate (CollectionNode c1, CollectionNode c2) { return c1.transform.GetSiblingIndex().CompareTo(c2.transform.GetSiblingIndex()); });
NodeList.Reverse();
break;
}
_columns = Mathf.CeilToInt((float)NodeList.Count / Rows);
_width = _columns * CellWidth;
_height = Rows * CellHeight;
_halfCell = new Vector2(CellWidth / 2f, CellHeight / 2f);
_circumference = 2f * Mathf.PI * Radius;
LayoutChildren();
if (OnCollectionUpdated != null)
{
OnCollectionUpdated.Invoke(this);
}
}
/// <summary>
/// Internal function for laying out all the children when UpdateCollection is called.
/// </summary>
private void LayoutChildren() {
int cellCounter = 0;
float startOffsetX;
float startOffsetY;
Vector3[] nodeGrid = new Vector3[NodeList.Count];
Vector3 newPos = Vector3.zero;
Vector3 newRot = Vector3.zero;
// Now lets lay out the grid
startOffsetX = (_columns * 0.5f) * CellWidth;
startOffsetY = (Rows * 0.5f) * CellHeight;
cellCounter = 0;
// First start with a grid then project onto surface
switch (LayoutType)
{
case LayoutTypeEnum.ColumnThenRow:
default:
for (int c = 0; c < _columns; c++)
{
for (int r = 0; r < Rows; r++)
{
if (cellCounter < NodeList.Count)
{
nodeGrid[cellCounter] = new Vector3((c * CellWidth) - startOffsetX + _halfCell.x, -(r * CellHeight) + startOffsetY - _halfCell.y, 0f) + (Vector3)((NodeList[cellCounter])).Offset;
}
cellCounter++;
}
}
break;
case LayoutTypeEnum.RowThenColumn:
for (int r = 0; r < Rows; r++)
{
for (int c = 0; c < _columns; c++)
{
if (cellCounter < NodeList.Count)
{
nodeGrid[cellCounter] = new Vector3((c * CellWidth) - startOffsetX + _halfCell.x, -(r * CellHeight) + startOffsetY - _halfCell.y, 0f) + (Vector3)((NodeList[cellCounter])).Offset;
}
cellCounter++;
}
}
break;
}
switch (SurfaceType) {
case SurfaceTypeEnum.Plane:
for (int i = 0; i < NodeList.Count; i++)
{
newPos = nodeGrid[i];
NodeList[i].transform.localPosition = newPos;
switch (OrientType)
{
case OrientTypeEnum.FaceOrigin:
case OrientTypeEnum.FaceFoward:
NodeList[i].transform.forward = transform.forward;
break;
case OrientTypeEnum.FaceOriginReversed:
case OrientTypeEnum.FaceForwardReversed:
newRot = Vector3.zero;
NodeList[i].transform.forward = transform.forward;
NodeList[i].transform.Rotate(0f, 180f, 0f);
break;
case OrientTypeEnum.None:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
break;
case SurfaceTypeEnum.Cylinder:
for (int i = 0; i < NodeList.Count; i++)
{
newPos = CylindricalMapping(nodeGrid[i], Radius);
switch (OrientType)
{
case OrientTypeEnum.FaceOrigin:
newRot = new Vector3(newPos.x, 0.0f, newPos.z);
NodeList[i].transform.rotation = Quaternion.LookRotation(newRot);
break;
case OrientTypeEnum.FaceOriginReversed:
newRot = new Vector3(newPos.x, 0f, newPos.z);
NodeList[i].transform.rotation = Quaternion.LookRotation(newRot);
NodeList[i].transform.Rotate(0f, 180f, 0f);
break;
case OrientTypeEnum.FaceFoward:
NodeList[i].transform.forward = transform.forward;
break;
case OrientTypeEnum.FaceForwardReversed:
NodeList[i].transform.forward = transform.forward;
NodeList[i].transform.Rotate(0f, 180f, 0f);
break;
case OrientTypeEnum.None:
break;
default:
throw new ArgumentOutOfRangeException();
}
NodeList[i].transform.localPosition = newPos;
}
break;
case SurfaceTypeEnum.Sphere:
for (int i = 0; i < NodeList.Count; i++)
{
newPos = SphericalMapping(nodeGrid[i], Radius);
switch (OrientType)
{
case OrientTypeEnum.FaceOrigin:
newRot = newPos;
NodeList[i].transform.rotation = Quaternion.LookRotation(newRot);
break;
case OrientTypeEnum.FaceOriginReversed:
newRot = newPos;
NodeList[i].transform.rotation = Quaternion.LookRotation(newRot);
NodeList[i].transform.Rotate(0f, 180f, 0f);
break;
case OrientTypeEnum.FaceFoward:
NodeList[i].transform.forward = transform.forward;
break;
case OrientTypeEnum.FaceForwardReversed:
NodeList[i].transform.forward = transform.forward;
NodeList[i].transform.Rotate(0f, 180f, 0f);
break;
case OrientTypeEnum.None:
break;
default:
throw new ArgumentOutOfRangeException();
}
NodeList[i].transform.localPosition = newPos;
}
break;
case SurfaceTypeEnum.Scatter:
// Get randomized planar mapping
// Calculate radius of each node while we're here
// Then use the packer function to shift them into place
for (int i = 0; i < NodeList.Count; i++)
{
newPos = ScatterMapping (nodeGrid[i], Radius);
Collider nodeCollider = NodeList[i].transform.GetComponentInChildren<Collider>();
if (nodeCollider != null)
{
// Make the radius the largest of the object's dimensions to avoid overlap
Bounds bounds = nodeCollider.bounds;
NodeList[i].Radius = Mathf.Max (Mathf.Max(bounds.size.x, bounds.size.y), bounds.size.z) / 2;
}
else
{
// Make the radius a default value
// TODO move this into a public field ?
NodeList[i].Radius = 1f;
}
NodeList[i].transform.localPosition = newPos;
switch (OrientType)
{
case OrientTypeEnum.FaceOrigin:
case OrientTypeEnum.FaceFoward:
NodeList[i].transform.rotation = Quaternion.LookRotation(newRot);
break;
case OrientTypeEnum.FaceOriginReversed:
case OrientTypeEnum.FaceForwardReversed:
NodeList[i].transform.rotation = Quaternion.LookRotation(newRot);
NodeList[i].transform.Rotate(0f, 180f, 0f);
break;
case OrientTypeEnum.None:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
// Iterate [x] times
// TODO move center, iterations and padding into a public field
for (int i = 0; i < 100; i++)
{
IterateScatterPacking (NodeList, Radius);
}
break;
}
}
/// <summary>
/// Internal function for getting the relative mapping based on a source Vec3 and a radius for spherical mapping.
/// </summary>
/// <param name="source">The source <see cref="Vector3"/> to be mapped to sphere</param>
/// <param name="radius">This is a <see cref="float"/> for the radius of the sphere</param>
/// <returns></returns>
private Vector3 SphericalMapping(Vector3 source, float radius)
{
Radius = radius >= 0 ? Radius : radius;
Vector3 newPos = new Vector3(0f, 0f, Radius);
float xAngle = (source.x / _circumference) * 360f;
float yAngle = -(source.y / _circumference) * 360f;
Quaternion rot = Quaternion.Euler(yAngle, xAngle, 0.0f);
newPos = rot * newPos;
return newPos;
}
/// <summary>
/// Internal function for getting the relative mapping based on a source Vec3 and a radius for cylinder mapping.
/// </summary>
/// <param name="source">The source <see cref="Vector3"/> to be mapped to cylinder</param>
/// <param name="radius">This is a <see cref="float"/> for the radius of the cylinder</param>
/// <returns></returns>
private Vector3 CylindricalMapping(Vector3 source, float radius)
{
Radius = radius >= 0 ? Radius : radius;
Vector3 newPos = new Vector3(0f, source.y, Radius);
float xAngle = (source.x / _circumference) * 360f;
Quaternion rot = Quaternion.Euler(0.0f, xAngle, 0.0f);
newPos = rot * newPos;
return newPos;
}
/// <summary>
/// Internal function to check if a node exists in the NodeList.
/// </summary>
/// <param name="node">A <see cref="Transform"/> of the node to see if it's in the NodeList</param>
/// <returns></returns>
private bool ContainsNode(Transform node)
{
for (int i = 0; i < NodeList.Count; i++)
{
if (NodeList[i] != null)
{
if (NodeList[i].transform == node)
{
return true;
}
}
}
return false;
}
/// <summary>
/// Internal function for randomized mapping based on a source Vec3 and a radius for randomization distance.
/// </summary>
/// <param name="source">The source <see cref="Vector3"/> to be mapped to cylinder</param>
/// <param name="radius">This is a <see cref="float"/> for the radius of the cylinder</param>
/// <returns></returns>
private Vector3 ScatterMapping(Vector3 source, float radius)
{
source.x = UnityEngine.Random.Range(-radius, radius);
source.y = UnityEngine.Random.Range(-radius, radius);
return source;
}
/// <summary>
/// Internal function to pack randomly spaced nodes so they don't overlap
/// Usually requires about 25 iterations for decent packing
/// </summary>
/// <returns></returns>
private void IterateScatterPacking(List<CollectionNode> nodes, float radiusPadding)
{
// Sort by closest to center (don't worry about z axis)
// Use the position of the collection as the packing center
nodes.Sort(delegate (CollectionNode circle1, CollectionNode circle2) {
float distance1 = (circle1.transform.localPosition).sqrMagnitude;
float distance2 = (circle2.transform.localPosition).sqrMagnitude;
return distance1.CompareTo(distance2);
});
Vector3 difference;
Vector2 difference2D;
// Move them closer together
float radiusPaddingSquared = Mathf.Pow(radiusPadding, 2f);
for (int i = 0; i < nodes.Count - 1; i++)
{
for (int j = i + 1; j < nodes.Count; j++)
{
if (i != j)
{
difference = nodes[j].transform.localPosition - nodes[i].transform.localPosition;
// Ignore Z axis
difference2D.x = difference.x;
difference2D.y = difference.y;
float combinedRadius = nodes[i].Radius + nodes[j].Radius;
float distance = difference2D.SqrMagnitude() - radiusPaddingSquared;
float minSeparation = Mathf.Min(distance, radiusPaddingSquared);
distance -= minSeparation;
if (distance < (Mathf.Pow(combinedRadius, 2)))
{
difference2D.Normalize();
difference *= ((combinedRadius - Mathf.Sqrt(distance)) * 0.5f);
nodes[j].transform.localPosition += difference;
nodes[i].transform.localPosition -= difference;
}
}
}
}
}
/// <summary>
/// Gizmos to draw when the Collection is selected.
/// </summary>
protected virtual void OnDrawGizmosSelected()
{
Vector3 scale = (2f * Radius) * Vector3.one;
switch (SurfaceType)
{
case SurfaceTypeEnum.Plane:
break;
case SurfaceTypeEnum.Cylinder:
Gizmos.color = Color.green;
Gizmos.DrawWireMesh(CylinderMesh, transform.position, transform.rotation, scale);
break;
case SurfaceTypeEnum.Sphere:
Gizmos.color = Color.green;
Gizmos.DrawWireMesh(SphereMesh, transform.position, transform.rotation, scale);
break;
}
}
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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 SharpDX.Direct3D9
{
public partial class CubeTexture
{
/// <summary>
/// Initializes a new instance of the <see cref="CubeTexture"/> class.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="edgeLength">Length of the edge.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
public CubeTexture(Device device, int edgeLength, int levelCount, Usage usage, Format format, Pool pool = Pool.Managed) : base(IntPtr.Zero)
{
device.CreateCubeTexture(edgeLength, levelCount, (int)usage, format, pool, this, IntPtr.Zero);
}
/// <summary>
/// Initializes a new instance of the <see cref="CubeTexture"/> class.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="edgeLength">Length of the edge.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="sharedHandle">The shared handle.</param>
public CubeTexture(Device device, int edgeLength, int levelCount, Usage usage, Format format, Pool pool, ref IntPtr sharedHandle) : base(IntPtr.Zero)
{
unsafe
{
fixed (void* pSharedHandle = &sharedHandle)
device.CreateCubeTexture(edgeLength, levelCount, (int)usage, format, pool, this, (IntPtr)pSharedHandle);
}
}
/// <summary>
/// Checks texture-creation parameters.
/// </summary>
/// <param name="device">Device associated with the texture.</param>
/// <param name="size">Requested size of the texture. Null if </param>
/// <param name="mipLevelCount">Requested number of mipmap levels for the texture.</param>
/// <param name="usage">The requested usage for the texture.</param>
/// <param name="format">Requested format for the texture.</param>
/// <param name="pool">Memory class where the resource will be placed.</param>
/// <returns>A value type containing the proposed values to pass to the texture creation functions.</returns>
/// <unmanaged>HRESULT D3DXCheckCubeTextureRequirements([In] IDirect3DDevice9* pDevice,[InOut] unsigned int* pSize,[InOut] unsigned int* pNumMipLevels,[In] unsigned int Usage,[InOut] D3DFORMAT* pFormat,[In] D3DPOOL Pool)</unmanaged>
public static CubeTextureRequirements CheckRequirements(Device device, int size, int mipLevelCount, Usage usage, Format format, Pool pool)
{
var result = new CubeTextureRequirements
{
Size = size,
MipLevelCount = mipLevelCount,
Format = format
};
D3DX9.CheckCubeTextureRequirements(device, ref result.Size, ref result.MipLevelCount, (int)usage, ref result.Format, pool);
return result;
}
/// <summary>
/// Uses a user-provided function to fill each texel of each mip level of a given cube texture.
/// </summary>
/// <param name="callback">A function that is used to fill the texture.</param>
/// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns>
public void Fill(Fill3DCallback callback)
{
var handle = GCHandle.Alloc(callback);
try
{
D3DX9.FillCubeTexture(this, FillCallbackHelper.Native3DCallbackPtr, GCHandle.ToIntPtr(handle));
}
finally
{
handle.Free();
}
}
/// <summary>
/// Uses a compiled high-level shader language (HLSL) function to fill each texel of each mipmap level of a texture.
/// </summary>
/// <param name="shader">A texture shader object that is used to fill the texture.</param>
/// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns>
public void Fill(TextureShader shader)
{
D3DX9.FillCubeTextureTX(this, shader);
}
/// <summary>
/// Locks a rectangle on a cube texture resource.
/// </summary>
/// <param name="faceType">Type of the face.</param>
/// <param name="level">The level.</param>
/// <param name="flags">The flags.</param>
/// <returns>
/// A <see cref="DataRectangle"/> describing the region locked.
/// </returns>
/// <unmanaged>HRESULT IDirect3DCubeTexture9::LockRect([In] D3DCUBEMAP_FACES FaceType,[In] unsigned int Level,[In] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged>
public DataRectangle LockRectangle(SharpDX.Direct3D9.CubeMapFace faceType, int level, SharpDX.Direct3D9.LockFlags flags)
{
LockedRectangle lockedRect;
LockRectangle(faceType, level, out lockedRect, IntPtr.Zero, flags);
return new DataRectangle(lockedRect.PBits, lockedRect.Pitch);
}
/// <summary>
/// Locks a rectangle on a cube texture resource.
/// </summary>
/// <param name="faceType">Type of the face.</param>
/// <param name="level">The level.</param>
/// <param name="flags">The flags.</param>
/// <param name="stream">The stream pointing to the locked region.</param>
/// <returns>
/// A <see cref="DataRectangle"/> describing the region locked.
/// </returns>
/// <unmanaged>HRESULT IDirect3DCubeTexture9::LockRect([In] D3DCUBEMAP_FACES FaceType,[In] unsigned int Level,[In] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged>
public DataRectangle LockRectangle(SharpDX.Direct3D9.CubeMapFace faceType, int level, SharpDX.Direct3D9.LockFlags flags, out DataStream stream)
{
LockedRectangle lockedRect;
LockRectangle(faceType, level, out lockedRect, IntPtr.Zero, flags);
stream = new DataStream(lockedRect.PBits, lockedRect.Pitch * GetLevelDescription(level).Height, true, (flags & LockFlags.ReadOnly) == 0);
return new DataRectangle(lockedRect.PBits, lockedRect.Pitch);
}
/// <summary>
/// Locks a rectangle on a cube texture resource.
/// </summary>
/// <param name="faceType">Type of the face.</param>
/// <param name="level">The level.</param>
/// <param name="rectangle">The rectangle.</param>
/// <param name="flags">The flags.</param>
/// <returns>
/// A <see cref="DataRectangle"/> describing the region locked.
/// </returns>
/// <unmanaged>HRESULT IDirect3DCubeTexture9::LockRect([In] D3DCUBEMAP_FACES FaceType,[In] unsigned int Level,[In] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged>
public DataRectangle LockRectangle(SharpDX.Direct3D9.CubeMapFace faceType, int level, Rectangle rectangle, SharpDX.Direct3D9.LockFlags flags) {
unsafe
{
LockedRectangle lockedRect;
LockRectangle(faceType, level, out lockedRect, new IntPtr(&rectangle), flags);
return new DataRectangle(lockedRect.PBits, lockedRect.Pitch);
}
}
/// <summary>
/// Locks a rectangle on a cube texture resource.
/// </summary>
/// <param name="faceType">Type of the face.</param>
/// <param name="level">The level.</param>
/// <param name="rectangle">The rectangle.</param>
/// <param name="flags">The flags.</param>
/// <param name="stream">The stream pointing to the locked region.</param>
/// <returns>
/// A <see cref="DataRectangle"/> describing the region locked.
/// </returns>
/// <unmanaged>HRESULT IDirect3DCubeTexture9::LockRect([In] D3DCUBEMAP_FACES FaceType,[In] unsigned int Level,[In] D3DLOCKED_RECT* pLockedRect,[In] const void* pRect,[In] D3DLOCK Flags)</unmanaged>
public DataRectangle LockRectangle(SharpDX.Direct3D9.CubeMapFace faceType, int level, Rectangle rectangle, SharpDX.Direct3D9.LockFlags flags, out DataStream stream)
{
unsafe
{
LockedRectangle lockedRect;
LockRectangle(faceType, level, out lockedRect, new IntPtr(&rectangle), flags);
stream = new DataStream(lockedRect.PBits, lockedRect.Pitch * GetLevelDescription(level).Height, true, (flags & LockFlags.ReadOnly) == 0);
return new DataRectangle(lockedRect.PBits, lockedRect.Pitch);
}
}
/// <summary>
/// Adds a dirty region to a cube texture resource.
/// </summary>
/// <param name="faceType">Type of the face.</param>
/// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns>
/// <unmanaged>HRESULT IDirect3DCubeTexture9::AddDirtyRect([In] D3DCUBEMAP_FACES FaceType,[In] const void* pDirtyRect)</unmanaged>
public void AddDirtyRectangle(SharpDX.Direct3D9.CubeMapFace faceType)
{
AddDirtyRectangle(faceType, IntPtr.Zero);
}
/// <summary>
/// Adds a dirty region to a cube texture resource.
/// </summary>
/// <param name="faceType">Type of the face.</param>
/// <param name="dirtyRectRef">The dirty rect ref.</param>
/// <returns>A <see cref="SharpDX.Result" /> object describing the result of the operation.</returns>
/// <unmanaged>HRESULT IDirect3DCubeTexture9::AddDirtyRect([In] D3DCUBEMAP_FACES FaceType,[In] const void* pDirtyRect)</unmanaged>
public void AddDirtyRectangle(SharpDX.Direct3D9.CubeMapFace faceType, Rectangle dirtyRectRef)
{
unsafe
{
AddDirtyRectangle(faceType, new IntPtr(&dirtyRectRef));
}
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a file
/// </summary>
/// <param name="device">The device.</param>
/// <param name="filename">The filename.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static CubeTexture FromFile(Device device, string filename)
{
CubeTexture cubeTexture;
D3DX9.CreateCubeTextureFromFileW(device, filename, out cubeTexture);
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a file
/// </summary>
/// <param name="device">The device.</param>
/// <param name="filename">The filename.</param>
/// <param name="usage">The usage.</param>
/// <param name="pool">The pool.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static CubeTexture FromFile(Device device, string filename, Usage usage, Pool pool)
{
return FromFile(device, filename, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a file
/// </summary>
/// <param name="device">The device.</param>
/// <param name="filename">The filename.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static CubeTexture FromFile(Device device, string filename, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey)
{
return CreateFromFile(device, filename, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a file
/// </summary>
/// <param name="device">The device.</param>
/// <param name="filename">The filename.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static unsafe CubeTexture FromFile(Device device, string filename, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation)
{
fixed (void* pImageInfo = &imageInformation)
return CreateFromFile(device, filename, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a file
/// </summary>
/// <param name="device">The device.</param>
/// <param name="filename">The filename.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileExW([In] IDirect3DDevice9* pDevice,[In] const wchar_t* pSrcFile,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[In] void* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static unsafe CubeTexture FromFile(Device device, string filename, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette)
{
palette = new PaletteEntry[256];
fixed (void* pImageInfo = &imageInformation)
return CreateFromFile(device, filename, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a memory buffer.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemory([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static CubeTexture FromMemory(Device device, byte[] buffer)
{
CubeTexture cubeTexture;
unsafe
{
fixed (void* pData = buffer)
D3DX9.CreateCubeTextureFromFileInMemory(device, (IntPtr)pData, buffer.Length, out cubeTexture);
}
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a memory buffer.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="usage">The usage.</param>
/// <param name="pool">The pool.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static CubeTexture FromMemory(Device device, byte[] buffer, Usage usage, Pool pool)
{
return FromMemory(device, buffer, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a memory buffer.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static CubeTexture FromMemory(Device device, byte[] buffer, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey)
{
return CreateFromMemory(device, buffer, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a memory buffer.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static unsafe CubeTexture FromMemory(Device device, byte[] buffer, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation)
{
fixed (void* pImageInfo = &imageInformation)
return CreateFromMemory(device, buffer, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a memory buffer.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static unsafe CubeTexture FromMemory(Device device, byte[] buffer, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette)
{
palette = new PaletteEntry[256];
fixed (void* pImageInfo = &imageInformation)
return CreateFromMemory(device, buffer, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <returns>A <see cref="CubeTexture"/></returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemory([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static CubeTexture FromStream(Device device, Stream stream)
{
CubeTexture cubeTexture;
if (stream is DataStream)
{
D3DX9.CreateCubeTextureFromFileInMemory(device, ((DataStream)stream).PositionPointer, (int)(stream.Length - stream.Position), out cubeTexture);
}
else
{
unsafe
{
var data = Utilities.ReadStream(stream);
fixed (void* pData = data)
D3DX9.CreateCubeTextureFromFileInMemory(device, (IntPtr)pData, data.Length, out cubeTexture);
}
}
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="usage">The usage.</param>
/// <param name="pool">The pool.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static CubeTexture FromStream(Device device, Stream stream, Usage usage, Pool pool)
{
return FromStream(device, stream, 0, -1, -1, usage, Format.Unknown, pool, Filter.Default, Filter.Default, 0);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static CubeTexture FromStream(Device device, Stream stream, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey)
{
return FromStream(device, stream, 0, size, levelCount, usage, format, pool, filter, mipFilter, colorKey);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="sizeBytes">The size bytes.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static CubeTexture FromStream(Device device, Stream stream, int sizeBytes, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey)
{
return CreateFromStream(device, stream, sizeBytes, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, IntPtr.Zero, null);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="sizeBytes">The size bytes.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static unsafe CubeTexture FromStream(Device device, Stream stream, int sizeBytes, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation)
{
fixed (void* pImageInfo = &imageInformation)
return CreateFromStream(device, stream, sizeBytes, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, null);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="sizeBytes">The size bytes.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
public static unsafe CubeTexture FromStream(Device device, Stream stream, int sizeBytes, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, out ImageInformation imageInformation, out PaletteEntry[] palette)
{
palette = new PaletteEntry[256];
fixed (void* pImageInfo = &imageInformation)
return CreateFromStream(device, stream, sizeBytes, size, levelCount, usage, format, pool, filter, mipFilter, colorKey, (IntPtr)pImageInfo, palette);
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
private static unsafe CubeTexture CreateFromMemory(Device device, byte[] buffer, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette)
{
CubeTexture cubeTexture;
fixed (void* pBuffer = buffer)
cubeTexture = CreateFromPointer(
device,
(IntPtr)pBuffer,
buffer.Length,
size,
levelCount,
usage,
format,
pool,
filter,
mipFilter,
colorKey,
imageInformation,
palette
);
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="stream">The stream.</param>
/// <param name="sizeBytes">The size bytes.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>A <see cref="CubeTexture"/></returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
private static unsafe CubeTexture CreateFromStream(Device device, Stream stream, int sizeBytes, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette)
{
CubeTexture cubeTexture;
sizeBytes = sizeBytes == 0 ? (int)(stream.Length - stream.Position) : sizeBytes;
if (stream is DataStream)
{
cubeTexture = CreateFromPointer(
device,
((DataStream)stream).PositionPointer,
sizeBytes,
size,
levelCount,
usage,
format,
pool,
filter,
mipFilter,
colorKey,
imageInformation,
palette
);
}
else
{
var data = Utilities.ReadStream(stream);
fixed (void* pData = data)
cubeTexture = CreateFromPointer(
device,
(IntPtr)pData,
data.Length,
size,
levelCount,
usage,
format,
pool,
filter,
mipFilter,
colorKey,
imageInformation,
palette
);
}
stream.Position = sizeBytes;
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="pointer">The pointer.</param>
/// <param name="sizeInBytes">The size in bytes.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
private static unsafe CubeTexture CreateFromPointer(Device device, IntPtr pointer, int sizeInBytes, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette)
{
CubeTexture cubeTexture;
D3DX9.CreateCubeTextureFromFileInMemoryEx(
device,
pointer,
sizeInBytes,
size,
levelCount,
(int)usage,
format,
pool,
(int)filter,
(int)mipFilter,
(Color)colorKey,
imageInformation,
palette,
out cubeTexture);
return cubeTexture;
}
/// <summary>
/// Creates a <see cref="CubeTexture"/> from a stream.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="fileName">Name of the file.</param>
/// <param name="size">The size.</param>
/// <param name="levelCount">The level count.</param>
/// <param name="usage">The usage.</param>
/// <param name="format">The format.</param>
/// <param name="pool">The pool.</param>
/// <param name="filter">The filter.</param>
/// <param name="mipFilter">The mip filter.</param>
/// <param name="colorKey">The color key.</param>
/// <param name="imageInformation">The image information.</param>
/// <param name="palette">The palette.</param>
/// <returns>
/// A <see cref="CubeTexture"/>
/// </returns>
/// <unmanaged>HRESULT D3DXCreateCubeTextureFromFileInMemoryEx([In] IDirect3DDevice9* pDevice,[In] const void* pSrcData,[In] unsigned int SrcDataSize,[In] unsigned int Size,[In] unsigned int MipLevels,[In] unsigned int Usage,[In] D3DFORMAT Format,[In] D3DPOOL Pool,[In] unsigned int Filter,[In] unsigned int MipFilter,[In] D3DCOLOR ColorKey,[Out] D3DXIMAGE_INFO* pSrcInfo,[Out, Buffer] PALETTEENTRY* pPalette,[In] IDirect3DCubeTexture9** ppCubeTexture)</unmanaged>
private static CubeTexture CreateFromFile(Device device, string fileName, int size, int levelCount, Usage usage, Format format, Pool pool, Filter filter, Filter mipFilter, int colorKey, IntPtr imageInformation, PaletteEntry[] palette)
{
CubeTexture cubeTexture;
D3DX9.CreateCubeTextureFromFileExW(
device,
fileName,
size,
levelCount,
(int)usage,
format,
pool,
(int)filter,
(int)mipFilter,
(Color)colorKey,
imageInformation,
palette,
out cubeTexture);
return cubeTexture;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Data;
using System.Collections;
namespace fyiReporting.Data
{
/// <summary>
/// LogCommand allows specifying the command for the web log.
/// </summary>
public class LogCommand : IDbCommand
{
LogConnection _lc; // connection we're running under
string _cmd; // command to execute
// parsed constituents of the command
string _Url; // url of the file
string _Domain; // Domain for the log's web site; e.g. www.fyireporting.com
string _IndexFile; // name of the index file; e.g. what's the default page when none (e.g. index.html)
DataParameterCollection _Parameters = new DataParameterCollection();
public LogCommand(LogConnection conn)
{
_lc = conn;
}
internal string Url
{
get
{
// Check to see if "Url" or "@Url" is a parameter
IDbDataParameter dp= _Parameters["Url"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@Url"] as IDbDataParameter;
// Then check to see if the Url value is a parameter?
if (dp == null)
dp = _Parameters[_Url] as IDbDataParameter;
if (dp != null)
return dp.Value != null? dp.Value.ToString(): _Url; // don't pass null; pass existing value
return _Url; // the value must be a constant
}
set {_Url = value;}
}
internal string Domain
{
get
{
// Check to see if "Domain" or "@Domain" is a parameter
IDbDataParameter dp= _Parameters["Domain"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@Domain"] as IDbDataParameter;
// Then check to see if the Domain value is a parameter?
if (dp == null)
dp = _Parameters[_Domain] as IDbDataParameter;
return (dp == null || dp.Value == null)? _Domain: dp.Value.ToString();
}
set {_Domain = value;}
}
internal string IndexFile
{
get
{
// Check to see if "IndexFile" or "@IndexFile" is a parameter
IDbDataParameter dp= _Parameters["IndexFile"] as IDbDataParameter;
if (dp == null)
dp= _Parameters["@IndexFile"] as IDbDataParameter;
// Then check to see if the IndexFile value is a parameter?
if (dp == null)
dp = _Parameters[_IndexFile] as IDbDataParameter;
return (dp == null || dp.Value == null)? _IndexFile: dp.Value.ToString();
}
set {_IndexFile = value;}
}
#region IDbCommand Members
public void Cancel()
{
throw new NotImplementedException("Cancel not implemented");
}
public void Prepare()
{
return; // Prepare is a noop
}
public System.Data.CommandType CommandType
{
get
{
throw new NotImplementedException("CommandType not implemented");
}
set
{
throw new NotImplementedException("CommandType not implemented");
}
}
public IDataReader ExecuteReader(System.Data.CommandBehavior behavior)
{
if (!(behavior == CommandBehavior.SingleResult ||
behavior == CommandBehavior.SchemaOnly))
throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only.");
return new LogDataReader(behavior, _lc, this);
}
IDataReader System.Data.IDbCommand.ExecuteReader()
{
return ExecuteReader(System.Data.CommandBehavior.SingleResult);
}
public object ExecuteScalar()
{
throw new NotImplementedException("ExecuteScalar not implemented");
}
public int ExecuteNonQuery()
{
throw new NotImplementedException("ExecuteNonQuery not implemented");
}
public int CommandTimeout
{
get
{
return 0;
}
set
{
throw new NotImplementedException("CommandTimeout not implemented");
}
}
public IDbDataParameter CreateParameter()
{
return new LogDataParameter();
}
public IDbConnection Connection
{
get
{
return this._lc;
}
set
{
throw new NotImplementedException("Setting Connection not implemented");
}
}
public System.Data.UpdateRowSource UpdatedRowSource
{
get
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
set
{
throw new NotImplementedException("UpdatedRowSource not implemented");
}
}
public string CommandText
{
get
{
return this._cmd;
}
set
{
// Parse the command string for keyword value pairs separated by ';'
string[] args = value.Split(';');
string url=null;
string domain=null;
string indexfile=null;
foreach(string arg in args)
{
string[] param = arg.Trim().Split('=');
if (param == null || param.Length != 2)
continue;
string key = param[0].Trim().ToLower();
string val = param[1];
switch (key)
{
case "url":
case "file":
url = val;
break;
case "domain":
domain = val;
break;
case "indexfile":
indexfile = val;
break;
default:
throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0]));
}
}
// User must specify both the url and the RowsXPath
if (url == null)
throw new ArgumentException("CommandText requires a 'Url=' parameter.");
_cmd = value;
_Url = url;
_Domain = domain;
_IndexFile = indexfile;
}
}
public IDataParameterCollection Parameters
{
get
{
return _Parameters;
}
}
public IDbTransaction Transaction
{
get
{
throw new NotImplementedException("Transaction not implemented");
}
set
{
throw new NotImplementedException("Transaction not implemented");
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
// nothing to dispose of
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Security;
using System.Runtime.CompilerServices;
#if !NET_NATIVE
using ExtensionDataObject = System.Object;
#endif
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || NET_NATIVE
public class XmlObjectSerializerWriteContext : XmlObjectSerializerContext
#else
internal class XmlObjectSerializerWriteContext : XmlObjectSerializerContext
#endif
{
private ObjectReferenceStack _byValObjectsInScope = new ObjectReferenceStack();
private XmlSerializableWriter _xmlSerializableWriter;
private const int depthToCheckCyclicReference = 512;
private ObjectToIdCache _serializedObjects;
private bool _isGetOnlyCollection;
private readonly bool _unsafeTypeForwardingEnabled;
protected bool serializeReadOnlyTypes;
protected bool preserveObjectReferences;
internal static XmlObjectSerializerWriteContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver)
{
return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null)
? new XmlObjectSerializerWriteContextComplex(serializer, rootTypeDataContract, dataContractResolver)
: new XmlObjectSerializerWriteContext(serializer, rootTypeDataContract, dataContractResolver);
}
protected XmlObjectSerializerWriteContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver resolver)
: base(serializer, rootTypeDataContract, resolver)
{
this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes;
// Known types restricts the set of types that can be deserialized
_unsafeTypeForwardingEnabled = true;
}
internal XmlObjectSerializerWriteContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject)
: base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject)
{
// Known types restricts the set of types that can be deserialized
_unsafeTypeForwardingEnabled = true;
}
#if USE_REFEMIT || NET_NATIVE
internal ObjectToIdCache SerializedObjects
#else
protected ObjectToIdCache SerializedObjects
#endif
{
get
{
if (_serializedObjects == null)
_serializedObjects = new ObjectToIdCache();
return _serializedObjects;
}
}
internal override bool IsGetOnlyCollection
{
get { return _isGetOnlyCollection; }
set { _isGetOnlyCollection = value; }
}
internal bool SerializeReadOnlyTypes
{
get { return this.serializeReadOnlyTypes; }
}
internal bool UnsafeTypeForwardingEnabled
{
get { return _unsafeTypeForwardingEnabled; }
}
#if USE_REFEMIT
public void StoreIsGetOnlyCollection()
#else
internal void StoreIsGetOnlyCollection()
#endif
{
_isGetOnlyCollection = true;
}
#if USE_REFEMIT
public void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#else
internal void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#endif
{
if (!OnHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/))
InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle);
OnEndHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/);
}
#if USE_REFEMIT
public virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#else
internal virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
#endif
{
if (writeXsiType)
{
Type declaredType = Globals.TypeOfObject;
SerializeWithXsiType(xmlWriter, obj, obj.GetType().TypeHandle, null/*type*/, -1, declaredType.TypeHandle, declaredType);
}
else if (isDeclaredType)
{
DataContract contract = GetDataContract(declaredTypeID, declaredTypeHandle);
SerializeWithoutXsiType(contract, xmlWriter, obj, declaredTypeHandle);
}
else
{
RuntimeTypeHandle objTypeHandle = obj.GetType().TypeHandle;
if (declaredTypeHandle.GetHashCode() == objTypeHandle.GetHashCode()) // semantically the same as Value == Value; Value is not available in SL
{
DataContract dataContract = (declaredTypeID >= 0)
? GetDataContract(declaredTypeID, declaredTypeHandle)
: GetDataContract(declaredTypeHandle, null /*type*/);
SerializeWithoutXsiType(dataContract, xmlWriter, obj, declaredTypeHandle);
}
else
{
SerializeWithXsiType(xmlWriter, obj, objTypeHandle, null /*type*/, declaredTypeID, declaredTypeHandle, Type.GetTypeFromHandle(declaredTypeHandle));
}
}
}
internal void SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
{
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
if (dataContract.KnownDataContracts != null)
{
scopedKnownTypes.Push(dataContract.KnownDataContracts);
WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle);
scopedKnownTypes.Pop();
}
else
{
WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle);
}
}
internal virtual void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
{
bool verifyKnownType = false;
Type declaredType = rootTypeDataContract.UnderlyingType;
if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
if (DataContractResolver != null)
{
WriteResolvedTypeInfo(xmlWriter, graphType, declaredType);
}
}
else if (!declaredType.IsArray) //Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item
{
verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract);
}
SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, originalDeclaredTypeHandle, declaredType);
}
protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
{
bool verifyKnownType = false;
#if !NET_NATIVE
DataContract dataContract;
if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
dataContract = GetDataContractSkipValidation(DataContract.GetId(objectTypeHandle), objectTypeHandle, objectType);
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
dataContract = GetDataContract(declaredTypeHandle, declaredType);
#else
DataContract dataContract = DataContract.GetDataContract(declaredType);
if (dataContract.TypeIsInterface && dataContract.TypeIsCollectionInterface)
{
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
if (this.Mode == SerializationMode.SharedType && dataContract.IsValidContract(this.Mode))
dataContract = dataContract.GetValidContract(this.Mode);
else
dataContract = GetDataContract(declaredTypeHandle, declaredType);
#endif
if (!WriteClrTypeInfo(xmlWriter, dataContract) && DataContractResolver != null)
{
if (objectType == null)
{
objectType = Type.GetTypeFromHandle(objectTypeHandle);
}
WriteResolvedTypeInfo(xmlWriter, objectType, declaredType);
}
}
else if (declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item
{
// A call to OnHandleIsReference is not necessary here -- arrays cannot be IsReference
dataContract = GetDataContract(objectTypeHandle, objectType);
WriteClrTypeInfo(xmlWriter, dataContract);
dataContract = GetDataContract(declaredTypeHandle, declaredType);
}
else
{
dataContract = GetDataContract(objectTypeHandle, objectType);
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
if (!WriteClrTypeInfo(xmlWriter, dataContract))
{
DataContract declaredTypeContract = (declaredTypeID >= 0)
? GetDataContract(declaredTypeID, declaredTypeHandle)
: GetDataContract(declaredTypeHandle, declaredType);
verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract);
}
}
SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredTypeHandle, declaredType);
}
internal bool OnHandleIsReference(XmlWriterDelegator xmlWriter, DataContract contract, object obj)
{
if (preserveObjectReferences || !contract.IsReference || _isGetOnlyCollection)
{
return false;
}
bool isNew = true;
int objectId = SerializedObjects.GetId(obj, ref isNew);
_byValObjectsInScope.EnsureSetAsIsReference(obj);
if (isNew)
{
xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.IdLocalName,
DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId));
return false;
}
else
{
xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId));
return true;
}
}
protected void SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, bool verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
{
bool knownTypesAddedInCurrentScope = false;
if (dataContract.KnownDataContracts != null)
{
scopedKnownTypes.Push(dataContract.KnownDataContracts);
knownTypesAddedInCurrentScope = true;
}
#if !NET_NATIVE
if (verifyKnownType)
{
if (!IsKnownType(dataContract, declaredType))
{
DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/);
if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)));
}
}
}
#endif
WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle);
if (knownTypesAddedInCurrentScope)
{
scopedKnownTypes.Pop();
}
}
internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract)
{
return false;
}
internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, string clrTypeName, string clrAssemblyName)
{
return false;
}
internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName)
{
return false;
}
internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, SerializationInfo serInfo)
{
return false;
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value)
#else
internal virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value)
#endif
{
xmlWriter.WriteAnyType(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteString(XmlWriterDelegator xmlWriter, string value)
#else
internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value)
#endif
{
xmlWriter.WriteString(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
xmlWriter.WriteString(value);
xmlWriter.WriteEndElementPrimitive();
}
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value)
#else
internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value)
#endif
{
xmlWriter.WriteBase64(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
xmlWriter.WriteBase64(value);
xmlWriter.WriteEndElementPrimitive();
}
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value)
#else
internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value)
#endif
{
xmlWriter.WriteUri(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns);
else
{
xmlWriter.WriteStartElementPrimitive(name, ns);
xmlWriter.WriteUri(value);
xmlWriter.WriteEndElementPrimitive();
}
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value)
#else
internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value)
#endif
{
xmlWriter.WriteQName(value);
}
#if USE_REFEMIT || NET_NATIVE
public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns)
#else
internal virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns)
#endif
{
if (value == null)
WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns);
else
{
if (ns != null && ns.Value != null && ns.Value.Length > 0)
xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns);
else
xmlWriter.WriteStartElement(name, ns);
xmlWriter.WriteQName(value);
xmlWriter.WriteEndElement();
}
}
internal void HandleGraphAtTopLevel(XmlWriterDelegator writer, object obj, DataContract contract)
{
writer.WriteXmlnsAttribute(Globals.XsiPrefix, DictionaryGlobals.SchemaInstanceNamespace);
if (contract.IsISerializable)
{
writer.WriteXmlnsAttribute(Globals.XsdPrefix, DictionaryGlobals.SchemaNamespace);
}
OnHandleReference(writer, obj, true /*canContainReferences*/);
}
internal virtual bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference)
{
if (xmlWriter.depth < depthToCheckCyclicReference)
return false;
if (canContainCyclicReference)
{
if (_byValObjectsInScope.Contains(obj))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotSerializeObjectWithCycles, DataContract.GetClrTypeFullName(obj.GetType()))));
_byValObjectsInScope.Push(obj);
}
return false;
}
internal virtual void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference)
{
if (xmlWriter.depth < depthToCheckCyclicReference)
return;
if (canContainCyclicReference)
{
_byValObjectsInScope.Pop(obj);
}
}
#if USE_REFEMIT
public void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable)
#else
internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable)
#endif
{
CheckIfTypeSerializable(memberType, isMemberTypeSerializable);
WriteNull(xmlWriter);
}
internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable, XmlDictionaryString name, XmlDictionaryString ns)
{
xmlWriter.WriteStartElement(name, ns);
WriteNull(xmlWriter, memberType, isMemberTypeSerializable);
xmlWriter.WriteEndElement();
}
#if USE_REFEMIT
public void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array)
#else
internal void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array)
#endif
{
IncrementCollectionCount(xmlWriter, array.GetLength(0));
}
#if USE_REFEMIT
public void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection)
#else
internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection)
#endif
{
IncrementCollectionCount(xmlWriter, collection.Count);
}
#if USE_REFEMIT
public void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection)
#else
internal void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection)
#endif
{
IncrementCollectionCount(xmlWriter, collection.Count);
}
private void IncrementCollectionCount(XmlWriterDelegator xmlWriter, int size)
{
IncrementItemCount(size);
WriteArraySize(xmlWriter, size);
}
internal virtual void WriteArraySize(XmlWriterDelegator xmlWriter, int size)
{
}
#if USE_REFEMIT
public static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType)
#else
internal static bool IsMemberTypeSameAsMemberValue(object obj, Type memberType)
#endif
{
if (obj == null || memberType == null)
return false;
return obj.GetType().TypeHandle.Equals(memberType.TypeHandle);
}
#if USE_REFEMIT
public static T GetDefaultValue<T>()
#else
internal static T GetDefaultValue<T>()
#endif
{
return default(T);
}
#if USE_REFEMIT
public static T GetNullableValue<T>(Nullable<T> value) where T : struct
#else
internal static T GetNullableValue<T>(Nullable<T> value) where T : struct
#endif
{
// value.Value will throw if hasValue is false
return value.Value;
}
#if USE_REFEMIT
public static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type)
#else
internal static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type)
#endif
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.RequiredMemberMustBeEmitted, memberName, type.FullName)));
}
#if USE_REFEMIT
public static bool GetHasValue<T>(Nullable<T> value) where T : struct
#else
internal static bool GetHasValue<T>(Nullable<T> value) where T : struct
#endif
{
return value.HasValue;
}
internal void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj)
{
if (_xmlSerializableWriter == null)
_xmlSerializableWriter = new XmlSerializableWriter();
WriteIXmlSerializable(xmlWriter, obj, _xmlSerializableWriter);
}
internal static void WriteRootIXmlSerializable(XmlWriterDelegator xmlWriter, object obj)
{
WriteIXmlSerializable(xmlWriter, obj, new XmlSerializableWriter());
}
private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj, XmlSerializableWriter xmlSerializableWriter)
{
xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj);
IXmlSerializable xmlSerializable = obj as IXmlSerializable;
if (xmlSerializable != null)
xmlSerializable.WriteXml(xmlSerializableWriter);
else
{
XmlElement xmlElement = obj as XmlElement;
if (xmlElement != null)
xmlElement.WriteTo(xmlSerializableWriter);
else
{
XmlNode[] xmlNodes = obj as XmlNode[];
if (xmlNodes != null)
foreach (XmlNode xmlNode in xmlNodes)
xmlNode.WriteTo(xmlSerializableWriter);
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnknownXmlType, DataContract.GetClrTypeFullName(obj.GetType()))));
}
}
xmlSerializableWriter.EndWrite();
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal void GetObjectData(ISerializable obj, SerializationInfo serInfo, StreamingContext context)
{
obj.GetObjectData(serInfo, context);
}
public void WriteISerializable(XmlWriterDelegator xmlWriter, ISerializable obj)
{
Type objType = obj.GetType();
var serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter /*!UnsafeTypeForwardingEnabled is always false*/);
GetObjectData(obj, serInfo, GetStreamingContext());
if (!UnsafeTypeForwardingEnabled && serInfo.AssemblyName == Globals.MscorlibAssemblyName)
{
// Throw if a malicious type tries to set its assembly name to "0" to get deserialized in mscorlib
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ISerializableAssemblyNameSetToZero, DataContract.GetClrTypeFullName(obj.GetType()))));
}
WriteSerializationInfo(xmlWriter, objType, serInfo);
}
internal void WriteSerializationInfo(XmlWriterDelegator xmlWriter, Type objType, SerializationInfo serInfo)
{
if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName)
{
if (DataContractResolver != null)
{
XmlDictionaryString typeName, typeNs;
if (ResolveType(serInfo.ObjectType, objType, out typeName, out typeNs))
{
xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, typeName, typeNs);
}
}
else
{
string typeName, typeNs;
DataContract.GetDefaultStableName(serInfo.FullTypeName, out typeName, out typeNs);
xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, DataContract.GetClrTypeString(typeName), DataContract.GetClrTypeString(typeNs));
}
}
WriteClrTypeInfo(xmlWriter, objType, serInfo);
IncrementItemCount(serInfo.MemberCount);
foreach (SerializationEntry serEntry in serInfo)
{
XmlDictionaryString name = DataContract.GetClrTypeString(DataContract.EncodeLocalName(serEntry.Name));
xmlWriter.WriteStartElement(name, DictionaryGlobals.EmptyString);
object obj = serEntry.Value;
if (obj == null)
{
WriteNull(xmlWriter);
}
else
{
InternalSerializeReference(xmlWriter, obj, false /*isDeclaredType*/, false /*writeXsiType*/, -1, Globals.TypeOfObject.TypeHandle);
}
xmlWriter.WriteEndElement();
}
}
protected virtual void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle)
{
dataContract.WriteXmlValue(xmlWriter, obj, this);
}
protected virtual void WriteNull(XmlWriterDelegator xmlWriter)
{
XmlObjectSerializer.WriteNull(xmlWriter);
}
private void WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType)
{
XmlDictionaryString typeName, typeNamespace;
if (ResolveType(objectType, declaredType, out typeName, out typeNamespace))
{
WriteTypeInfo(writer, typeName, typeNamespace);
}
}
private bool ResolveType(Type objectType, Type declaredType, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
{
if (!DataContractResolver.TryResolveType(objectType, declaredType, KnownTypeResolver, out typeName, out typeNamespace))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedFalse, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
}
if (typeName == null)
{
if (typeNamespace == null)
{
return false;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
}
}
if (typeNamespace == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType))));
}
return true;
}
protected virtual bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract)
{
if (!XmlObjectSerializer.IsContractDeclared(contract, declaredContract))
{
if (DataContractResolver == null)
{
WriteTypeInfo(writer, contract.Name, contract.Namespace);
return true;
}
else
{
WriteResolvedTypeInfo(writer, contract.OriginalUnderlyingType, declaredContract.OriginalUnderlyingType);
return false;
}
}
return false;
}
protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace)
{
writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace);
}
protected virtual void WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryString dataContractName, XmlDictionaryString dataContractNamespace)
{
writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace);
}
public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject extensionData, int memberIndex)
{
if (IgnoreExtensionDataObject || extensionData == null)
return;
IList<ExtensionDataMember> members = extensionData.Members;
if (members != null)
{
for (int i = 0; i < extensionData.Members.Count; i++)
{
ExtensionDataMember member = extensionData.Members[i];
if (member.MemberIndex == memberIndex)
{
WriteExtensionDataMember(xmlWriter, member);
}
}
}
}
private void WriteExtensionDataMember(XmlWriterDelegator xmlWriter, ExtensionDataMember member)
{
xmlWriter.WriteStartElement(member.Name, member.Namespace);
IDataNode dataNode = member.Value;
WriteExtensionDataValue(xmlWriter, dataNode);
xmlWriter.WriteEndElement();
}
internal virtual void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, IDataNode dataNode)
{
if (dataNode.DataContractName != null)
WriteTypeInfo(xmlWriter, dataNode.DataContractName, dataNode.DataContractNamespace);
WriteClrTypeInfo(xmlWriter, dataNode.DataType, dataNode.ClrTypeName, dataNode.ClrAssemblyName);
}
internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode dataNode)
{
IncrementItemCount(1);
if (dataNode == null)
{
WriteNull(xmlWriter);
return;
}
if (dataNode.PreservesReferences
&& OnHandleReference(xmlWriter, (dataNode.Value == null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/))
return;
Type dataType = dataNode.DataType;
if (dataType == Globals.TypeOfClassDataNode)
WriteExtensionClassData(xmlWriter, (ClassDataNode)dataNode);
else if (dataType == Globals.TypeOfCollectionDataNode)
WriteExtensionCollectionData(xmlWriter, (CollectionDataNode)dataNode);
else if (dataType == Globals.TypeOfXmlDataNode)
WriteExtensionXmlData(xmlWriter, (XmlDataNode)dataNode);
else if (dataType == Globals.TypeOfISerializableDataNode)
WriteExtensionISerializableData(xmlWriter, (ISerializableDataNode)dataNode);
else
{
WriteExtensionDataTypeInfo(xmlWriter, dataNode);
if (dataType == Globals.TypeOfObject)
{
// NOTE: serialize value in DataNode<object> since it may contain non-primitive
// deserialized object (ex. empty class)
object o = dataNode.Value;
if (o != null)
InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, o.GetType().TypeHandle);
}
else
xmlWriter.WriteExtensionData(dataNode);
}
if (dataNode.PreservesReferences)
OnEndHandleReference(xmlWriter, (dataNode.Value == null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/);
}
internal bool TryWriteDeserializedExtensionData(XmlWriterDelegator xmlWriter, IDataNode dataNode)
{
object o = dataNode.Value;
if (o == null)
return false;
Type declaredType = (dataNode.DataContractName == null) ? o.GetType() : Globals.TypeOfObject;
InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, declaredType.TypeHandle);
return true;
}
private void WriteExtensionClassData(XmlWriterDelegator xmlWriter, ClassDataNode dataNode)
{
if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode))
{
WriteExtensionDataTypeInfo(xmlWriter, dataNode);
IList<ExtensionDataMember> members = dataNode.Members;
if (members != null)
{
for (int i = 0; i < members.Count; i++)
{
WriteExtensionDataMember(xmlWriter, members[i]);
}
}
}
}
private void WriteExtensionCollectionData(XmlWriterDelegator xmlWriter, CollectionDataNode dataNode)
{
if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode))
{
WriteExtensionDataTypeInfo(xmlWriter, dataNode);
WriteArraySize(xmlWriter, dataNode.Size);
IList<IDataNode> items = dataNode.Items;
if (items != null)
{
for (int i = 0; i < items.Count; i++)
{
xmlWriter.WriteStartElement(dataNode.ItemName, dataNode.ItemNamespace);
WriteExtensionDataValue(xmlWriter, items[i]);
xmlWriter.WriteEndElement();
}
}
}
}
private void WriteExtensionISerializableData(XmlWriterDelegator xmlWriter, ISerializableDataNode dataNode)
{
if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode))
{
WriteExtensionDataTypeInfo(xmlWriter, dataNode);
if (dataNode.FactoryTypeName != null)
xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, dataNode.FactoryTypeName, dataNode.FactoryTypeNamespace);
IList<ISerializableDataMember> members = dataNode.Members;
if (members != null)
{
for (int i = 0; i < members.Count; i++)
{
ISerializableDataMember member = members[i];
xmlWriter.WriteStartElement(member.Name, String.Empty);
WriteExtensionDataValue(xmlWriter, member.Value);
xmlWriter.WriteEndElement();
}
}
}
}
private void WriteExtensionXmlData(XmlWriterDelegator xmlWriter, XmlDataNode dataNode)
{
if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode))
{
IList<XmlAttribute> xmlAttributes = dataNode.XmlAttributes;
if (xmlAttributes != null)
{
foreach (XmlAttribute attribute in xmlAttributes)
attribute.WriteTo(xmlWriter.Writer);
}
WriteExtensionDataTypeInfo(xmlWriter, dataNode);
IList<XmlNode> xmlChildNodes = dataNode.XmlChildNodes;
if (xmlChildNodes != null)
{
foreach (XmlNode node in xmlChildNodes)
node.WriteTo(xmlWriter.Writer);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using Xunit;
namespace System.Text.Tests
{
public class EncodingTest
{
private static byte[] s_UTF32LEBom = new byte[] { 0xFF, 0xFE, 0x0, 0x0 };
private static byte[] s_UTF32BEBom = new byte[] { 0x0, 0x0, 0xFE, 0xFF, };
private static byte[] s_UTF8Bom = new byte[] { 0xEF, 0xBB, 0xBF };
private static byte[] s_UTF16LEBom = new byte[] { 0xFF, 0xFE };
private static byte[] s_UTF8BEBom = new byte[] { 0xFE, 0xFF };
[Fact]
public static void TestGetEncoding()
{
Encoding encoding = Encoding.GetEncoding("UTF-32LE");
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF32LEBom);
encoding = Encoding.UTF32;
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF32LEBom);
encoding = Encoding.GetEncoding("UTF-32BE");
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF32BEBom);
encoding = Encoding.UTF8;
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF8Bom);
encoding = Encoding.GetEncoding("UTF-16BE");
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF8BEBom);
encoding = Encoding.GetEncoding("UTF-16LE");
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF16LEBom);
encoding = Encoding.Unicode;
Assert.Equal<byte>(encoding.GetPreamble(), s_UTF16LEBom);
}
private static byte[] s_asciiBytes = new byte[] { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', };
private static string s_asciiString = "ABCDEFGH";
[Fact]
public static void TestEncodingDecoding()
{
Encoding encoding = Encoding.ASCII;
byte[] bytes = encoding.GetBytes(s_asciiString);
Assert.Equal<byte>(bytes, s_asciiBytes);
string s = encoding.GetString(bytes, 0, bytes.Length);
Assert.True(s.Equals(s_asciiString));
s = encoding.GetString(bytes);
Assert.True(s.Equals(s_asciiString));
encoding = Encoding.GetEncoding("us-ascii");
bytes = encoding.GetBytes(s_asciiString);
Assert.Equal<byte>(bytes, s_asciiBytes);
s = encoding.GetString(bytes, 0, bytes.Length);
Assert.True(s.Equals(s_asciiString));
s = encoding.GetString(bytes);
Assert.True(s.Equals(s_asciiString));
encoding = Encoding.GetEncoding("latin1");
bytes = encoding.GetBytes(s_asciiString);
Assert.Equal<byte>(bytes, s_asciiBytes);
s = encoding.GetString(bytes, 0, bytes.Length);
Assert.True(s.Equals(s_asciiString));
s = encoding.GetString(bytes);
Assert.True(s.Equals(s_asciiString));
}
public class CodePageMapping
{
public CodePageMapping(string name, int codepage)
{
Name = name;
CodePage = codepage;
}
public string Name { set; get; }
public int CodePage { set; get; }
}
private static CodePageMapping[] s_mapping = new CodePageMapping[] {
new CodePageMapping("ANSI_X3.4-1968", 20127 ),
new CodePageMapping("ANSI_X3.4-1986", 20127 ),
new CodePageMapping("ascii", 20127 ),
new CodePageMapping("cp367", 20127 ),
new CodePageMapping("cp819", 28591 ),
new CodePageMapping("csASCII", 20127 ),
new CodePageMapping("csISOLatin1", 28591 ),
new CodePageMapping("csUnicode11UTF7", 65000 ),
new CodePageMapping("IBM367", 20127 ),
new CodePageMapping("ibm819", 28591 ),
new CodePageMapping("ISO-10646-UCS-2", 1200),
new CodePageMapping("iso-8859-1", 28591),
new CodePageMapping("iso-ir-100", 28591),
new CodePageMapping("iso-ir-6", 20127),
new CodePageMapping("ISO646-US", 20127),
new CodePageMapping("iso8859-1", 28591),
new CodePageMapping("ISO_646.irv:1991", 20127),
new CodePageMapping("iso_8859-1", 28591),
new CodePageMapping("iso_8859-1:1987", 28591),
new CodePageMapping("l1", 28591),
new CodePageMapping("latin1", 28591),
new CodePageMapping("ucs-2", 1200),
new CodePageMapping("unicode", 1200),
new CodePageMapping("unicode-1-1-utf-7", 65000),
new CodePageMapping("unicode-1-1-utf-8", 65001),
new CodePageMapping("unicode-2-0-utf-7", 65000),
new CodePageMapping("unicode-2-0-utf-8", 65001),
new CodePageMapping("unicodeFFFE", 1201),
new CodePageMapping("us", 20127),
new CodePageMapping("us-ascii", 20127),
new CodePageMapping("utf-16", 1200),
new CodePageMapping("UTF-16BE", 1201),
new CodePageMapping("UTF-16LE", 1200),
new CodePageMapping("utf-32", 12000),
new CodePageMapping("UTF-32BE", 12001),
new CodePageMapping("UTF-32LE", 12000),
new CodePageMapping("utf-7", 65000),
new CodePageMapping("utf-8", 65001),
new CodePageMapping("x-unicode-1-1-utf-7", 65000),
new CodePageMapping("x-unicode-1-1-utf-8", 65001),
new CodePageMapping("x-unicode-2-0-utf-7", 65000),
new CodePageMapping("x-unicode-2-0-utf-8", 65001)
};
[Fact]
public static void TestEncodingNameAndCopdepageNumber()
{
foreach (var map in s_mapping)
{
Encoding encoding = Encoding.GetEncoding(map.Name);
Assert.True(encoding.CodePage == map.CodePage);
}
}
[Fact]
public static void TestEncodingDisplayNames()
{
CultureInfo originalUICulture = CultureInfo.CurrentUICulture;
try
{
CultureInfo.CurrentCulture = new CultureInfo("en-US");
foreach (var map in s_mapping)
{
Encoding encoding = Encoding.GetEncoding(map.Name);
string name = encoding.EncodingName;
Assert.NotNull(name);
Assert.NotEqual(string.Empty, name);
Assert.All(name, ch => Assert.InRange(ch, 0, 127));
}
}
finally
{
CultureInfo.CurrentUICulture = originalUICulture;
}
}
[Fact]
public static void TestCodePageToWebNameMappings()
{
foreach (var mapping in s_codePageToWebNameMappings)
{
Encoding encoding = Encoding.GetEncoding(mapping.CodePage);
Assert.True(string.Equals(mapping.WebName, encoding.WebName, StringComparison.OrdinalIgnoreCase));
}
}
internal class CodePageToWebNameMapping
{
public CodePageToWebNameMapping(int codePage, string webName)
{
_codePage = codePage;
_webName = webName;
}
public int CodePage { get { return _codePage; } }
public string WebName { get { return _webName; } }
private int _codePage;
private string _webName;
}
private static readonly CodePageToWebNameMapping[] s_codePageToWebNameMappings = new[]
{
new CodePageToWebNameMapping(1200, "utf-16"),
new CodePageToWebNameMapping(1201, "utf-16be"),
new CodePageToWebNameMapping(12000, "utf-32"),
new CodePageToWebNameMapping(12001, "utf-32be"),
new CodePageToWebNameMapping(20127, "us-ascii"),
new CodePageToWebNameMapping(28591, "iso-8859-1"),
new CodePageToWebNameMapping(65000, "utf-7"),
new CodePageToWebNameMapping(65001, "utf-8")
};
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
namespace Apache.Geode.Client.FwkLib
{
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client.Tests;
using Apache.Geode.Client;
using NEWAPI = Apache.Geode.Client.Tests;
[Serializable]
struct HostInfo
{
public bool Started;
public string HostType;
public string HostName;
public string ExtraServerArgs;
public HostInfo(bool started, string hostType, string hostName,
string extraServerArgs)
{
Started = started;
HostType = hostType;
HostName = hostName;
ExtraServerArgs = extraServerArgs;
}
}
public class Utils<TKey, TVal> : FwkTest<TKey, TVal>
{
private const char PathSep = '/';
private const int MaxWaitMillis = 1800000;
private const string SetupJSName = "setupJavaServers";
private const string StartJSName = "startJavaServers";
private const string StopJSName = "stopJavaServers";
private const string KillJSName = "killJavaServers";
private const string SleepTime = "sleepTime";
private const string MinServers = "minServers";
private const string JavaServerCountKey = "ServerCount";
private const string JavaServerMapKey = "ServerMap";
private const string JavaServerName = "cacheserver.bat";
private const string JavaServerOtherArgs =
" statistic-sampling-enabled=true" +
" statistic-archive-file=statArchive.gfs mcast-port=0";
private const string JavaServerJavaArgs =
" -J-Xmx1280m -J-Xms512m -J-DCacheClientProxy.MESSAGE_QUEUE_SIZE=100000";
private const string JavaServerJavaArgsUnix =
" -J-Xmx2048m -J-Xms1024m -J-XX:+HeapDumpOnOutOfMemoryError " +
"-J-DCacheClientProxy.MESSAGE_QUEUE_SIZE=100000";
private static string TempDir = Util.GetEnvironmentVariable("TMP");
// Constants for status
private const int GFNoError = 0;
private const int GFError = 1;
private const int GFTimeout = 2;
private static Dictionary<string, HostInfo> m_javaServerHostMap =
new Dictionary<string, HostInfo>();
private static int m_numServers = 1;
private static int locCount = 0;
private static volatile bool m_exiting = false;
private static bool m_firstRun = true;
private static string m_locatorHost = null;
private static string m_locatorType = null;
#region Private methods
private string[] ParseJavaServerArgs(string argStr, ref int numServers,
out int argIndx, out string extraServerArgs)
{
argIndx = 0;
extraServerArgs = string.Empty;
if (argStr != null && argStr.Length > 0)
{
string[] args = argStr.Split(' ');
while (args.Length > argIndx && args[argIndx][0] == '-')
{
FwkAssert(args.Length > (argIndx + 1),
"JavaServer() value not provided after option '{0}'.",
args[argIndx]);
string argName = args[argIndx];
string argValue = args[argIndx + 1];
switch (argName)
{
case "-t":
// Ignore the tagname; we now use the hostGroup name as the tag
break;
case "-N":
break;
case "-M":
break;
case "-X":
break;
case "-c":
numServers = int.Parse(argValue);
break;
case "-e":
// @TODO: this is C++ specific environment variables -- ignored for now
break;
case "-p":
extraServerArgs += (" " + argValue.Replace("\\", "").
Replace("\"", "").Replace("'", ""));
break;
default:
FwkException("JavaServer() Unknown option '{0}'", argName);
break;
}
argIndx += 2;
}
extraServerArgs += " ";
return args;
}
return new string[0];
}
private string GetHostGroup()
{
string hostGroup;
try
{
hostGroup = Util.BBGet(Util.ClientId,
FwkReadData.HostGroupKey) as string;
}
catch
{
hostGroup = null;
}
return (hostGroup == null ? string.Empty : hostGroup);
}
private static HostInfo GetHostInfo(string serverId)
{
HostInfo hostInfo = new HostInfo();
lock (((ICollection)m_javaServerHostMap).SyncRoot)
{
if (m_javaServerHostMap.Count == 0)
{
try
{
m_javaServerHostMap = Util.BBGet(JavaServerBB, JavaServerMapKey)
as Dictionary<string, HostInfo>;
}
catch
{
}
}
if (m_javaServerHostMap.ContainsKey(serverId))
{
hostInfo = m_javaServerHostMap[serverId];
}
}
return hostInfo;
}
private static string GetJavaStartDir(string serverId, string hostType)
{
return Util.GetLogBaseDir(hostType) + PathSep + "GFECS_" + serverId;
}
private static string GetLocatorStartDir(string locatorId, string hostType)
{
return Util.GetLogBaseDir(hostType) + PathSep + "GFELOC_" + locatorId;
}
private string GetJavaLocator()
{
try
{
return (string)Util.BBGet(string.Empty, "LOCATOR_ADDRESS");
}
catch
{
return null;
}
}
private string GetJavaLocatorForPoolAttri()
{
try
{
return (string)Util.BBGet(string.Empty, "LOCATOR_ADDRESS_POOL");
}
catch
{
return null;
}
}
private bool GetSetJavaLocator(string locatorHost,
out int locatorPort)
{
locatorPort = 0;
string locatorAddress = GetJavaLocator();
string locatorAddressForPool = GetJavaLocatorForPoolAttri();
if (locatorAddress == null || locatorAddress.Length == 0)
{
locatorPort = Util.Rand(31124, 54343);
locatorAddress = locatorHost + '[' + locatorPort + ']';
locatorAddressForPool = locatorHost + ':' + locatorPort;
Util.BBSet(string.Empty, "LOCATOR_ADDRESS", locatorAddress);
Util.BBSet(string.Empty, "LOCATOR_ADDRESS_POOL", locatorAddressForPool);
locCount++;
return true;
}
if (locatorAddress != null && locatorAddress.Length > 0 && locCount > 0)
{
locatorPort = Util.Rand(31124, 54343);
locatorAddress += ',' + locatorHost + '[' + locatorPort + ']';
locatorAddressForPool += ',' + locatorHost + ':' + locatorPort;
Util.BBSet(string.Empty, "LOCATOR_ADDRESS", locatorAddress);
Util.BBSet(string.Empty, "LOCATOR_ADDRESS_POOL", locatorAddressForPool);
locCount++;
return true;
}
return false;
}
private static int StartLocalGFExe(string exeName, string gfeDir,
string exeArgs, out string outStr)
{
int status = GFNoError;
Process javaProc;
string javaExePath = gfeDir + PathSep + "bin" + PathSep + exeName;
Util.ServerLog("Executing local Geode command {0} {1}", javaExePath,
exeArgs);
if (!Util.StartProcess(javaExePath, exeArgs, false, TempDir,
true, false, false, out javaProc))
{
outStr = null;
return GFError;
}
StreamReader outSr = javaProc.StandardOutput;
// Wait for process to start
bool started = javaProc.WaitForExit(MaxWaitMillis);
outStr = outSr.ReadLine();
outSr.Close();
if (!started)
{
try
{
javaProc.Kill();
}
catch
{
}
status = GFTimeout;
}
else if (javaProc.ExitCode != 0)
{
status = GFError;
}
return status;
}
private static string StartRemoteGFExe(string host, string hostType,
string exeName, string exeArgs)
{
string gfJavaDir = Util.GetEnvironmentVariable("GFE_DIR", hostType);
string gfClassPath = Util.GetEnvironmentVariable("CLASSPATH", hostType);
string gfJava = Util.GetEnvironmentVariable("GF_JAVA", hostType);
string javaCmd = gfJavaDir + "/bin/" + exeName + ' ' + exeArgs;
Dictionary<string, string> envVars = new Dictionary<string, string>();
if (gfClassPath != null && gfClassPath.Length > 0)
{
envVars["CLASSPATH"] = gfClassPath;
}
if (gfJava != null && gfJava.Length > 0)
{
envVars["GF_JAVA"] = gfJava;
}
return Util.RunClientShellTask(Util.ClientId, host, javaCmd, envVars);
}
private string GetWorkerId(string serverNum)
{
return "worker." + serverNum;
}
private string CreateWorkerTaskSpecification(string progName,
string serverNum, string extraArgs)
{
extraArgs = (extraArgs == null ? string.Empty : ' ' + extraArgs);
return string.Format("<task name=\"Deleg{1}\" action=\"doRunProcess\" " +
"container=\"utils\" waitTime=\"25m\">{0}<data name=\"program\">" +
"{1}</data>{0}" + "<data name=\"arguments\">{2}{3}</data>{0}" +
"<client-set name=\"{4}\">{0}<client name=\"{5}\"/>{0}" +
"</client-set>{0}</task>", Environment.NewLine, progName, serverNum,
extraArgs, Util.ClientId, GetWorkerId(serverNum));
}
private string GetSslProperty(string hostType, bool forServer,string startDir)
{
string sslCmdStr = null;
//if (!File.Exists(startDir + PathSep + "geode.properties"))
//{
TextWriter sw = new StreamWriter(startDir + PathSep + "geode.properties", false);
String locatorAddress = GetJavaLocator();
sw.WriteLine("locators={0}", locatorAddress);
ResetKey("sslEnable");
bool isSslEnable = GetBoolValue("sslEnable");
if (!isSslEnable)
{
sw.Close();
return string.Empty;
}
FwkInfo("ssl is enable");
if (!forServer)
{
//StreamWriter sw = new StreamWriter("geode.properties",false);
sw.WriteLine("ssl-enabled=true");
sw.WriteLine("ssl-require-authentication=true");
sw.WriteLine("mcast-port=0");
sw.WriteLine("ssl-ciphers=SSL_RSA_WITH_NULL_SHA");
}
sw.Close();
string keyStorePath = Util.GetFwkLogDir(hostType) + "/data/keystore/sslcommon.jks";
string trustStorePath = Util.GetFwkLogDir(hostType) + "/data/keystore/server_truststore.jks";
sslCmdStr = " -Djavax.net.ssl.keyStore=" + keyStorePath +
" -Djavax.net.ssl.keyStorePassword=gemstone -Djavax.net.ssl.trustStore=" + trustStorePath +
" -Djavax.net.ssl.trustStorePassword=gemstone";
//string securityParams = GetStringValue(SecurityParams);
if (forServer)
{
sslCmdStr = " -J-Djavax.net.ssl.keyStore=" + keyStorePath +
" -J-Djavax.net.ssl.keyStorePassword=gemstone -J-Djavax.net.ssl.trustStore=" + trustStorePath +
" -J-Djavax.net.ssl.trustStorePassword=gemstone " +
" ssl-enabled=true ssl-require-authentication=true ssl-ciphers=SSL_RSA_WITH_NULL_SHA";
}
//}
return sslCmdStr;
}
private string GetServerSecurityArgs(string hostType)
{
string securityParams = GetStringValue(SecurityParams);
CredentialGenerator gen;
// no security means security params is not applicable
if (securityParams == null || securityParams.Length == 0 ||
(gen = GetCredentialGenerator()) == null)
{
FwkInfo("Security is DISABLED.");
return string.Empty;
}
string logDir = Util.GetFwkLogDir(hostType);
if (logDir == null || logDir.Length == 0)
{
logDir = Util.GetLogBaseDir(hostType);
logDir = logDir.Substring(0, logDir.LastIndexOf("/"));
logDir = logDir.Substring(0, logDir.LastIndexOf("/"));
}
string dataDir = logDir + "/data";
gen.Init(dataDir, dataDir);
Properties<string,string> extraProps = new Properties<string,string>();
if (gen.SystemProperties != null)
{
extraProps.AddAll(gen.SystemProperties);
}
// For now only XML based authorization is supported
AuthzCredentialGenerator authzGen = new XmlAuthzCredentialGenerator();
authzGen.Init(gen);
if (authzGen.SystemProperties != null)
{
extraProps.AddAll(authzGen.SystemProperties);
}
return Utility.GetServerArgs(gen.Authenticator,
authzGen.AccessControl, null, extraProps, gen.JavaProperties);
}
private void SetupJavaServers(string argStr)
{
int argIndx;
string endpoints = string.Empty;
m_numServers = 1;
string gfeDir = Util.GetEnvironmentVariable("GFE_DIR");
FwkAssert(gfeDir != null && gfeDir.Length != 0,
"SetupJavaServers() GFE_DIR is not set.");
string hostGroup = GetHostGroup();
Match mt;
if (argStr == "CPP")
{
// special string to denote that endpoints have to be obtained
// from C++ framework
string fwkBBPath = Util.AssemblyDir + "/../../bin/FwkBB";
string fwkBBArgs = "getInt GFE_BB EP_COUNT";
Process fwkBBProc;
if (!Util.StartProcess(fwkBBPath, fwkBBArgs, false, null,
true, false, false, out fwkBBProc))
{
FwkException("SetupJavaServers() Cannot start C++ FwkBB [{0}].",
fwkBBPath);
}
int numEndpoints = int.Parse(fwkBBProc.StandardOutput.ReadToEnd());
fwkBBProc.WaitForExit();
fwkBBProc.StandardOutput.Close();
for (int index = 1; index <= numEndpoints; index++)
{
fwkBBArgs = "get GFE_BB EndPoints_" + index;
if (!Util.StartProcess(fwkBBPath, fwkBBArgs, false, null,
true, false, false, out fwkBBProc))
{
FwkException("SetupJavaServers() Cannot start C++ FwkBB [{0}].",
fwkBBPath);
}
string endpoint = fwkBBProc.StandardOutput.ReadToEnd();
fwkBBProc.WaitForExit();
fwkBBProc.StandardOutput.Close();
if (endpoints.Length > 0)
{
endpoints += ',' + endpoint;
}
else
{
endpoints = endpoint;
}
}
}
else if ((mt = Regex.Match(gfeDir, "^[^:]+:[0-9]+(,[^:]+:[0-9]+)*$"))
!= null && mt.Length > 0)
{
// The GFE_DIR is for a remote server; contains an end-point list
endpoints = gfeDir;
}
else
{
string extraServerArgs;
string[] args = ParseJavaServerArgs(argStr, ref m_numServers,
out argIndx, out extraServerArgs);
Util.BBSet(JavaServerBB, FwkTest<TKey,TVal>.JavaServerEPCountKey, m_numServers);
FwkAssert(args.Length == argIndx + 1, "SetupJavaServers() cache XML argument not correct");
string cacheXml = args[argIndx];
FwkAssert(cacheXml.Length > 0, "SetupJavaServers() cacheXml argument is empty.");
string xmlDir = Util.GetEnvironmentVariable("GFBASE") + "/framework/xml";
if (xmlDir != null && xmlDir.Length > 0)
{
cacheXml = Util.NormalizePath(xmlDir + PathSep + cacheXml);
}
int javaServerPort = Util.RandPort(21321, 29789);
List<string> targetHosts = Util.BBGet(FwkReadData.HostGroupKey,
hostGroup) as List<string>;
for (int serverNum = 1; serverNum <= m_numServers; serverNum++)
{
if (m_exiting)
{
return;
}
string serverId = hostGroup + '_' + serverNum;
string startDir = GetJavaStartDir(serverId, Util.SystemType);
if (!Directory.Exists(startDir))
{
Directory.CreateDirectory(startDir);
}
string targetHost;
int numHosts = (targetHosts == null ? 0 : targetHosts.Count);
int lruMemSizeMb = 700;
if (numHosts == 0)
{
targetHost = Util.HostName;
lock (((IDictionary)m_javaServerHostMap).SyncRoot)
{
m_javaServerHostMap[serverId] = new HostInfo();
}
}
else
{
int hostIndex;
if (numHosts > 1)
{
hostIndex = ((serverNum - 1) % (numHosts - 1)) + 1;
}
else
{
hostIndex = 0;
}
targetHost = targetHosts[hostIndex];
FwkInfo("Checking the type of host {0}.", targetHost);
string hostType = Util.RunClientShellTask(Util.ClientId,
targetHost, "uname", null);
hostType = Util.GetHostType(hostType);
FwkInfo("The host {0} is: {1}", targetHost, hostType);
if (hostType != "WIN")
{
lruMemSizeMb = 1400;
}
lock (((IDictionary)m_javaServerHostMap).SyncRoot)
{
m_javaServerHostMap[serverId] = new HostInfo(false,
hostType, targetHost, extraServerArgs);
}
}
// Create the cache.xml with correct port
javaServerPort++;
StreamReader cacheXmlReader = new StreamReader(cacheXml);
string cacheXmlContent = cacheXmlReader.ReadToEnd();
cacheXmlReader.Close();
cacheXmlContent = cacheXmlContent.Replace("$PORT_NUM",
javaServerPort.ToString()).Replace("$LRU_MEM",
lruMemSizeMb.ToString());
StreamWriter cacheXmlWriter = new StreamWriter(startDir +
PathSep + "cache.xml");
cacheXmlWriter.Write(cacheXmlContent);
cacheXmlWriter.Close();
Util.ServerLog("SetupJavaServers() added '{0}' for host '{1}'",
serverId, targetHost);
FwkInfo("SetupJavaServers() added '{0}' for host '{1}'",
serverId, targetHost);
if (serverNum == 1)
{
endpoints = targetHost + ':' + javaServerPort;
}
else
{
endpoints += ',' + targetHost + ':' + javaServerPort;
}
Util.BBSet(JavaServerBB, FwkTest<TKey,TVal>.EndPoints + "_" + serverNum.ToString(), targetHost + ':' + javaServerPort);
}
int[] locatorPort = new int[2];
int locatorPort1;
HostInfo locatorInfo = GetHostInfo(hostGroup + "_1");
string locatorHost = locatorInfo.HostName;
string locatorType = locatorInfo.HostType;
if (locatorHost == null)
{
locatorHost = Util.HostName;
locatorType = Util.SystemType;
}
if (locatorType == Util.SystemType)
{
locatorHost = Util.HostName;
}
//ResetKey("multiLocator");
//bool isMultiLocator = GetBoolValue("multiLocator");
//if (isMultiLocator)
//{
for (int i = 0; i < 2; i++)
{
GetSetJavaLocator(locatorHost, out locatorPort1);
locatorPort[i] = locatorPort1;
}
for (int i = 0; i < 2; i++)
{
//if (GetSetJavaLocator(locatorHost, out locatorPort))
//{
FwkInfo("SetupJavaServers() starting locator on host {0}",
locatorHost);
string locatorDir = GetLocatorStartDir((i + 1).ToString(), Util.SystemType);
if (!Directory.Exists(locatorDir))
{
Directory.CreateDirectory(locatorDir);
}
ResetKey("sslEnable");
bool isSslEnable = GetBoolValue("sslEnable");
/*
if (isSslEnable)
{
locatorDir = locatorDir + "/..";
}
*/
string sslArg = GetSslProperty(locatorType, false, locatorDir);
locatorDir = GetLocatorStartDir((i + 1).ToString(), locatorType);
FwkInfo("ssl arguments: {0} {1}", sslArg, locatorDir);
string locatorArgs = "start-locator -port=" + locatorPort[i] +
" -dir=" + locatorDir + sslArg;
if (locatorType != Util.SystemType)
{
FwkInfo(StartRemoteGFExe(locatorHost, locatorType,
"geode", locatorArgs));
}
else
{
string outStr;
int status = StartLocalGFExe("geode.bat", gfeDir,
locatorArgs, out outStr);
if (status == GFTimeout)
{
FwkException("SetupJavaServers() Timed out while starting " +
"locator. Please check the logs in {0}", locatorDir);
}
else if (status != GFNoError)
{
FwkException("SetupJavaServers() Error while starting " +
"locator. Please check the logs in {0}", locatorDir);
}
FwkInfo(outStr);
}
if (isSslEnable)
{
Util.RegisterTestCompleteDelegate(TestCompleteWithSSL);
}
else
{
Util.RegisterTestCompleteDelegate(TestCompleteWithoutSSL);
}
m_locatorHost = locatorHost;
m_locatorType = locatorType;
FwkInfo("SetupJavaServers() started locator on host {0}.",
locatorHost);
//}
}
//}
}
FwkInfo("SetupJavaServers() endpoints: {0}", endpoints);
// Write the endpoints for both the tag and the cumulative one
string globalEndPoints;
try
{
globalEndPoints = Util.BBGet(string.Empty,
FwkTest<TKey, TVal>.EndPointTag) as string;
}
catch (Apache.Geode.DUnitFramework.KeyNotFoundException)
{
globalEndPoints = null;
}
if (globalEndPoints != null && globalEndPoints.Length > 0 &&
endpoints != null && endpoints.Length > 0)
{
globalEndPoints += ',' + endpoints;
}
else
{
globalEndPoints = endpoints;
}
Util.BBSet(JavaServerBB, FwkTest<TKey, TVal>.EndPointTag, globalEndPoints);
Util.BBSet(JavaServerBB, FwkTest<TKey, TVal>.EndPointTag + hostGroup, endpoints);
lock (((IDictionary)m_javaServerHostMap).SyncRoot)
{
Util.BBSet(JavaServerBB, JavaServerMapKey, m_javaServerHostMap);
}
FwkInfo("SetupJavaServers() completed.");
}
private void StartJavaServers(string argStr)
{
int numServers = -1;
int argIndx;
string extraServerArgs;
string[] args = ParseJavaServerArgs(argStr, ref numServers,
out argIndx, out extraServerArgs);
string gfeDir = Util.GetEnvironmentVariable("GFE_DIR");
string endpoints = string.Empty;
string locatorAddress = GetJavaLocator();
FwkAssert(gfeDir != null && gfeDir.Length != 0,
"StartJavaServers() GFE_DIR is not set.");
FwkAssert(locatorAddress != null && locatorAddress.Length > 0,
"StartJavaServers() LOCATOR_ADDRESS is not set.");
string hostGroup = GetHostGroup();
Match mt = Regex.Match(gfeDir, "^[^:]+:[0-9]+(,[^:]+:[0-9]+)*$");
if (mt == null || mt.Length == 0)
{
int startServer = 1;
int endServer;
if (args.Length == (argIndx + 1))
{
startServer = int.Parse(args[argIndx]);
endServer = (numServers == -1 ? startServer :
(startServer + numServers - 1));
}
else
{
endServer = (numServers == -1 ? m_numServers : numServers);
}
for (int serverNum = startServer; serverNum <= endServer; serverNum++)
{
if (m_exiting)
{
break;
}
string serverId = hostGroup + '_' + serverNum;
HostInfo hostInfo = GetHostInfo(serverId);
string targetHost = hostInfo.HostName;
string hostType = hostInfo.HostType;
string startDir = GetJavaStartDir(serverId, hostType);
extraServerArgs = hostInfo.ExtraServerArgs + ' ' + extraServerArgs;
string sslArg = GetSslProperty(hostType, true, startDir);
FwkInfo("ssl arguments for server: {0} ",sslArg);
string javaServerOtherArgs = GetServerSecurityArgs(hostType) + ' ' + sslArg;
if (javaServerOtherArgs != null && javaServerOtherArgs.Length > 0)
{
FwkInfo("StartJavaServers() Using security server args: {0}",
javaServerOtherArgs);
}
javaServerOtherArgs = JavaServerOtherArgs + ' ' + javaServerOtherArgs;
if (targetHost == null || targetHost.Length == 0 ||
Util.IsHostMyself(targetHost))
{
string cacheXml = startDir + PathSep + "cache.xml";
string javaServerArgs = "start" + JavaServerJavaArgs + " -dir=" +
startDir + " cache-xml-file=" + cacheXml + " locators=" +
locatorAddress + extraServerArgs + javaServerOtherArgs ;
// Assume the GFE_DIR is for starting a local server
FwkInfo("StartJavaServers() starting {0} with GFE_DIR {1} " +
"and arguments: {2}", JavaServerName, gfeDir, javaServerArgs);
string outStr;
int status = StartLocalGFExe(JavaServerName, gfeDir,
javaServerArgs, out outStr);
if (status == GFTimeout)
{
FwkException("StartJavaServers() Timed out waiting for Java " +
"cacheserver to start. Please check the server log in {0}.",
startDir);
}
else if (status != GFNoError)
{
FwkSevere("StartJavaServers() Error in starting Java " +
"cacheserver. Please check the server log in {0}.", startDir);
Thread.Sleep(60000);
}
FwkInfo("StartJavaServers() output from start script: {0}",
outStr);
}
else if (hostType != Util.SystemType)
{
FwkInfo("StartJavaServers() starting '{0}' on remote host " +
"'{1}' of type {2}", serverId, targetHost, hostType);
string javaCSArgs = "start" +
JavaServerJavaArgsUnix + " -dir=" + startDir +
" cache-xml-file=cache.xml locators=" + locatorAddress +
extraServerArgs + javaServerOtherArgs;
FwkInfo(StartRemoteGFExe(targetHost, hostType,
"cacheserver", javaCSArgs));
}
else
{
string taskSpec = CreateWorkerTaskSpecification(
"startJavaServers", serverNum.ToString(), null);
FwkInfo("StartJavaServers() starting '{0}' on host '{1}'",
serverId, targetHost);
Util.BBSet(Util.ClientId + '.' + GetWorkerId(
serverNum.ToString()), FwkReadData.HostGroupKey,
hostGroup);
if (!Util.RunClientWinTask(Util.ClientId, targetHost, taskSpec))
{
FwkException("StartJavaServers() failed to start '{0}' on host '{1}'",
serverId, targetHost);
}
}
lock (((IDictionary)m_javaServerHostMap).SyncRoot)
{
hostInfo.Started = true;
m_javaServerHostMap[serverId] = hostInfo;
}
Util.ServerLog("StartJavaServers() started '{0}' on host '{1}'",
serverId, targetHost);
}
}
ResetKey("sslEnable");
bool isSslEnabled = GetBoolValue("sslEnable");
if (isSslEnabled)
{
Util.RegisterTestCompleteDelegate(TestCompleteWithSSL);
}
else
{
Util.RegisterTestCompleteDelegate(TestCompleteWithoutSSL);
}
FwkInfo("StartJavaServers() completed.");
}
private void StopJavaServers(string argStr)
{
string gfeDir = Util.GetEnvironmentVariable("GFE_DIR");
FwkAssert(gfeDir != null && gfeDir.Length != 0,
"StopJavaServers() GFE_DIR is not set.");
Match mt = Regex.Match(gfeDir, "^[^:]+:[0-9]+(,[^:]+:[0-9]+)*$");
if (mt == null || mt.Length == 0)
{
int numServers = -1;
int argIndx;
string extraServerArgs;
string[] args = ParseJavaServerArgs(argStr, ref numServers,
out argIndx, out extraServerArgs);
string hostGroup = GetHostGroup();
string javaServerPath = gfeDir + PathSep + "bin" +
PathSep + JavaServerName;
// Assume the GFE_DIR is for stopping a local server
int startServer = 1;
int endServer;
if (args.Length == (argIndx + 1))
{
startServer = int.Parse(args[argIndx]);
endServer = (numServers == -1 ? startServer :
(startServer + numServers - 1));
}
else
{
endServer = (numServers == -1 ? m_numServers : numServers);
}
for (int serverNum = startServer; serverNum <= endServer; serverNum++)
{
if (m_exiting)
{
break;
}
string serverId = hostGroup + '_' + serverNum;
HostInfo hostInfo = GetHostInfo(serverId);
string targetHost = hostInfo.HostName;
string hostType = hostInfo.HostType;
string startDir = GetJavaStartDir(serverId, hostType);
string javaServerArgs = "stop -dir=" + startDir;
if (targetHost == null || targetHost.Length == 0 ||
Util.IsHostMyself(targetHost))
{
FwkInfo("StopJavaServers() stopping {0} with GFE_DIR {1} " +
"and arguments: {2}", JavaServerName, gfeDir, javaServerArgs);
string outStr;
int status = StartLocalGFExe(JavaServerName, gfeDir,
javaServerArgs, out outStr);
if (status != GFNoError)
{
if (status == GFTimeout)
{
FwkSevere("StopJavaServers() Timed out waiting for Java " +
"cacheserver to stop. Please check the server log in {0}.",
startDir);
}
else
{
Thread.Sleep(20000);
}
KillLocalJavaServer(serverId, "-9");
}
}
else if (hostType != Util.SystemType)
{
FwkInfo("StopJavaServers() stopping '{0}' on remote host " +
"'{1}' of type {2}", serverId, targetHost, hostType);
FwkInfo(StartRemoteGFExe(targetHost, hostType,
"cacheserver", javaServerArgs));
}
else
{
string taskSpec = CreateWorkerTaskSpecification(
"stopJavaServers", serverNum.ToString(), null);
FwkInfo("StopJavaServers() stopping '{0}' on host '{1}'",
serverId, targetHost);
if (!Util.RunClientWinTask(Util.ClientId, targetHost, taskSpec))
{
FwkSevere("StopJavaServers() failed to stop '{0}' on host '{1}'",
serverId, targetHost);
}
FwkInfo("StopJavaServers() stopped '{0}' on host '{1}'",
serverId, targetHost);
}
lock (((ICollection)m_javaServerHostMap).SyncRoot)
{
hostInfo.Started = false;
m_javaServerHostMap[serverId] = hostInfo;
}
Util.ServerLog("StopJavaServers() stopped '{0}' on host '{1}'",
serverId, targetHost);
}
}
FwkInfo("StopJavaServers() completed.");
}
private void KillJavaServers(string argStr)
{
string gfeDir = Util.GetEnvironmentVariable("GFE_DIR");
FwkAssert(gfeDir != null && gfeDir.Length != 0,
"KillJavaServers() GFE_DIR is not set.");
Match mt = Regex.Match(gfeDir, "^[^:]+:[0-9]+(,[^:]+:[0-9]+)*$");
if (mt == null || mt.Length == 0)
{
int numServers = -1;
int argIndx;
string extraServerArgs;
string[] args = ParseJavaServerArgs(argStr, ref numServers,
out argIndx, out extraServerArgs);
string hostGroup = GetHostGroup();
string javaServerPath = gfeDir + PathSep + "bin" +
PathSep + JavaServerName;
// Assume the GFE_DIR is for stopping a local server
int startServer = 1;
int endServer;
string signal = "15";
if (args.Length >= (argIndx + 1))
{
startServer = int.Parse(args[argIndx++]);
endServer = (numServers == -1 ? startServer :
(startServer + numServers - 1));
if (args.Length >= (argIndx + 1))
{
signal = args[argIndx];
}
}
else
{
endServer = (numServers == -1 ? m_numServers : numServers);
}
for (int serverNum = startServer; serverNum <= endServer; serverNum++)
{
if (m_exiting)
{
break;
}
string serverId = hostGroup + '_' + serverNum;
HostInfo hostInfo = GetHostInfo(serverId);
string targetHost = hostInfo.HostName;
string hostType = hostInfo.HostType;
if (targetHost == null || targetHost.Length == 0 ||
Util.IsHostMyself(targetHost))
{
FwkInfo("KillJavaServers() killing '{0}' on localhost", serverId);
KillLocalJavaServer(serverId, '-' + signal);
}
else if (hostType != Util.SystemType)
{
FwkInfo("KillJavaServers() killing '{0}' on remote host " +
"'{1}' of type {2}", serverId, targetHost, hostType);
string startDir = GetJavaStartDir(serverId, hostType);
string killCmd = '"' + Util.GetFwkLogDir(hostType) +
"/data/killJavaServer.sh\" " + signal + " \"" + startDir + '"';
FwkInfo(Util.RunClientShellTask(Util.ClientId, targetHost,
killCmd, null));
}
else
{
string taskSpec = CreateWorkerTaskSpecification(
"killJavaServers", serverNum.ToString(), signal);
FwkInfo("KillJavaServers() killing '{0}' on host '{1}'",
serverId, targetHost);
if (!Util.RunClientWinTask(Util.ClientId, targetHost, taskSpec))
{
FwkSevere("KillJavaServers() failed to kill '{0}' on host '{1}'",
serverId, targetHost);
}
}
lock (((ICollection)m_javaServerHostMap).SyncRoot)
{
hostInfo.Started = false;
m_javaServerHostMap[serverId] = hostInfo;
}
Util.ServerLog("KillJavaServers() killed '{0}' on host '{1}'",
serverId, targetHost);
}
}
FwkInfo("KillJavaServers() completed.");
}
private static string GetGFJavaPID(string javaLog)
{
string javaPID = null;
bool islocator = javaLog.Contains("locator.log");
using (FileStream fs = new FileStream(javaLog, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite))
{
StreamReader sr = new StreamReader(fs);
Regex pidRE = new Regex(@"Process ID: [\s]*(?<PID>[^\s]*)",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
while (!sr.EndOfStream)
{
Match mt = pidRE.Match(sr.ReadLine());
if (mt != null && mt.Length > 0)
{
javaPID = mt.Groups["PID"].Value;
if(!islocator)
break;
}
}
sr.Close();
fs.Close();
}
return javaPID;
}
private static string GetJavaServerPID(string serverId)
{
string startDir = GetJavaStartDir(serverId, Util.SystemType);
string javaLog = startDir + "/cacheserver.log";
return GetGFJavaPID(javaLog);
}
private static bool KillLocalGFJava(string javaPID, string signal)
{
try
{
Process.GetProcessById(int.Parse(javaPID)).Kill();
return true;
}
catch (Exception excp)
{
LogException("KillLocalGFJava: {0}: {1}", excp.GetType().Name, excp.Message);
return false;
}
}
private static bool KillLocalGFJava_disabled(string javaPID, string signal)
{
bool success = false;
if (javaPID != null)
{
Process javaProc;
if (!Util.StartProcess("/bin/kill", "-f " + signal + ' ' + javaPID,
false, TempDir, false, false, false, out javaProc))
{
LogException("KillLocalGFJava(): unable to run 'kill'");
}
// Wait for java process to stop
bool stopped = javaProc.WaitForExit(MaxWaitMillis);
if (!stopped)
{
try
{
javaProc.Kill();
}
catch
{
}
LogSevere("KillLocalGFJava() Could not execute " +
"kill successfully.");
}
int numTries = 30;
while (numTries-- > 0)
{
if (!Util.StartProcess("/bin/kill", "-f -0 " + javaPID,
false, TempDir, false, false, false, out javaProc))
{
LogException("KillLocalGFJava(): unable to run 'kill'");
}
stopped = javaProc.WaitForExit(MaxWaitMillis);
if (stopped && javaProc.ExitCode == 0)
{
success = true;
break;
}
Thread.Sleep(10000);
}
}
return success;
}
private static void KillLocalJavaServer(string serverId, string signal)
{
string javaPID = GetJavaServerPID(serverId);
LogInfo("KillLocalJavaServer() killing '{0}' with PID '{1}' using " +
"signal '{2}'", serverId, javaPID, signal);
if (KillLocalGFJava(javaPID, signal))
{
string startDir = GetJavaStartDir(serverId, Util.SystemType);
File.Delete(startDir + "/.cacheserver.ser");
}
else
{
LogException("KillLocalJavaServer() Timed out waiting for " +
"Java cacheserver to stop.");
}
}
#endregion
#region Public methods loaded by XMLs
/// <summary>
/// Will run a process using Cygwin bash
/// </summary>
public void DoRunProcess()
{
string progName = GetStringValue("program");
//bool driverUsingpsexec = false;
bool hostIsWindows = false;
try
{
//driverUsingpsexec = (bool)Util.BBGet(string.Empty, "UsePsexec");
hostIsWindows = (bool)Util.BBGet(string.Empty, Util.HostName + ".IsWindows");
}
catch
{
}
if (progName == null)
{
FwkException("DoRunProcess(): program not specified for task {0}.",
TaskName);
}
string args = GetStringValue("arguments");
if (progName == "cp") // for smpke perf xml
{
if (hostIsWindows )//&& driverUsingpsexec)
progName = "copy";
string[] argStr = args.Split(' ');
int i = argStr[0].IndexOf("/framework/xml/");
string gfBaseDir = Util.GetEnvironmentVariable("GFBASE");
string sharePath = Util.NormalizePath(gfBaseDir);
string specName = argStr[0].Substring(i);
string perfStatictic = sharePath + specName;
args = perfStatictic + ' ' + (string)Util.BBGet(string.Empty,"XMLLOGDIR") + '/' + argStr[1];
}
string fullProg = progName + ' ' + args;
fullProg = fullProg.Trim();
// Special treatment for java server scripts since they are C++ specific
// (e.g. the environment variables they require, the FwkBBClient program,
// the auto-ssh ...)
string[] progs = fullProg.Split(';');
for (int index = 0; index < progs.Length; index++)
{
if (m_exiting)
{
break;
}
string prog = progs[index].Trim();
int javaIndx;
if ((javaIndx = prog.IndexOf(SetupJSName)) >= 0)
{
args = prog.Substring(javaIndx + SetupJSName.Length).Trim();
SetupJavaServers(args);
}
else if ((javaIndx = prog.IndexOf(StartJSName)) >= 0)
{
args = prog.Substring(javaIndx + StartJSName.Length).Trim();
StartJavaServers(args);
}
else if ((javaIndx = prog.IndexOf(StopJSName)) >= 0)
{
args = prog.Substring(javaIndx + StopJSName.Length).Trim();
StopJavaServers(args);
}
else if ((javaIndx = prog.IndexOf(KillJSName)) >= 0)
{
args = prog.Substring(javaIndx + KillJSName.Length).Trim();
KillJavaServers(args);
}
else
{
FwkInfo("DoRunProcess() starting '{0}' using bash", prog);
Process runProc = new Process();
ProcessStartInfo startInfo;
if (hostIsWindows)// && driverUsingpsexec)
{
prog = prog.Replace('/', '\\');
startInfo = new ProcessStartInfo("cmd",
string.Format("/C \"{0}\"", prog));
}
else
startInfo = new ProcessStartInfo("bash",
string.Format("-c \"{0}\"", prog));
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
runProc.StartInfo = startInfo;
if (!runProc.Start())
{
FwkException("DoRunProcess() unable to run '{0}' using bash", prog);
}
StreamReader outSr = runProc.StandardOutput;
StreamReader errSr = runProc.StandardError;
string outStr = outSr.ReadToEnd();
string errStr = errSr.ReadToEnd();
runProc.WaitForExit();
errSr.Close();
outSr.Close();
if (outStr != null && outStr.Length > 0)
{
FwkInfo("DoRunProcess() Output from executing '{0}':" +
"{1}{2}{3}{4}", prog, Environment.NewLine, outStr,
Environment.NewLine, Util.MarkerString);
}
if (errStr != null && errStr.Length > 0)
{
FwkSevere("DoRunProcess() Error output from executing '{0}':" +
"{1}{2}{3}{4}", prog, Environment.NewLine, errStr,
Environment.NewLine, Util.MarkerString);
}
FwkInfo("DoRunProcess() completed '{0}'.", prog);
}
}
}
public void DoSleep()
{
int secs = GetUIntValue(SleepTime);
if (secs < 1)
{
secs = 30;
}
FwkInfo("DoSleep() called for task: '{0}', sleeping for {1} seconds.",
TaskName, secs);
Thread.Sleep(secs * 1000);
}
public void DoRunProcessAndSleep()
{
DoRunProcess();
if (!m_exiting)
{
int secs = GetUIntValue(SleepTime);
if (secs > 0)
{
Thread.Sleep(secs * 1000);
}
}
}
public void DoStopStartServer()
{
if (m_firstRun)
{
m_firstRun = false;
Util.BBIncrement(JavaServerBB, JavaServerCountKey);
}
string op = GetStringValue("operation");
if (op == null || op.Length == 0)
{
FwkException("DoStopStartServer(): operation not specified.");
}
string serverId = GetStringValue("ServerId");
if (serverId == null || serverId.Length == 0)
{
FwkException("DoStopStartServer(): server id not specified.");
}
FwkInfo("DoStopStartServer(): stopping and starting server {0}.",
serverId);
UnitFnMethod<string> stopDeleg = null;
string stopArg = null;
if (op == "stop")
{
stopDeleg = StopJavaServers;
stopArg = serverId;
}
else if (op == "term")
{
stopDeleg = KillJavaServers;
stopArg = serverId;
}
else if (op == "kill")
{
stopDeleg = KillJavaServers;
stopArg = serverId + " 9";
}
else
{
FwkException("DoStopStartServer(): unknown operation {0}.", op);
}
int secs = GetUIntValue(SleepTime);
int minServers = GetUIntValue(MinServers);
minServers = (minServers <= 0) ? 1 : minServers;
FwkInfo("DoStopStartServer(): using minServers: {0}", minServers);
bool done = false;
while (!done)
{
int numServers = Util.BBDecrement(JavaServerBB, JavaServerCountKey);
if (numServers >= minServers)
{
stopDeleg(stopArg);
Thread.Sleep(60000);
StartJavaServers(serverId);
Thread.Sleep(60000);
Util.BBIncrement(JavaServerBB, JavaServerCountKey);
done = true;
}
else
{
Util.BBIncrement(JavaServerBB, JavaServerCountKey);
Thread.Sleep(1000);
}
}
if (secs > 0)
{
Thread.Sleep(secs * 1000);
}
}
#endregion
public static void TestCompleteWithSSL()
{
TestComplete(true);
}
public static void TestCompleteWithoutSSL()
{
TestComplete(false);
}
public static void TestComplete(bool ssl)
{
m_exiting = true;
lock (((ICollection)m_javaServerHostMap).SyncRoot)
{
if (m_javaServerHostMap.Count == 0)
{
try
{
m_javaServerHostMap = Util.BBGet(JavaServerBB, JavaServerMapKey)
as Dictionary<string, HostInfo>;
}
catch
{
}
}
if (m_javaServerHostMap.Count > 0)
{
// Stop all the remaining java servers here.
string gfeDir = Util.GetEnvironmentVariable("GFE_DIR");
LogAssert(gfeDir != null, "ClientExit() GFE_DIR is not set.");
LogAssert(gfeDir.Length != 0, "ClientExit() GFE_DIR is not set.");
Match mt = Regex.Match(gfeDir, "^[^:]+:[0-9]+(,[^:]+:[0-9]+)*$");
if (mt == null || mt.Length == 0)
{
foreach (KeyValuePair<string, HostInfo> serverHostPair
in m_javaServerHostMap)
{
string serverId = serverHostPair.Key;
string targetHost = serverHostPair.Value.HostName;
string hostType = serverHostPair.Value.HostType;
string startDir = GetJavaStartDir(serverId, hostType);
string javaServerArgs = "stop -dir=" + startDir;
if (serverHostPair.Value.Started)
{
if (targetHost == null || targetHost.Length == 0 ||
Util.IsHostMyself(targetHost))
{
LogInfo("ClientExit() stopping {0} with GFE_DIR {1} and " +
"arguments: {2}", JavaServerName, gfeDir, javaServerArgs);
string outStr;
int status = StartLocalGFExe(JavaServerName, gfeDir,
javaServerArgs, out outStr);
if (status != GFNoError)
{
if (status == GFTimeout)
{
LogSevere("ClientExit() Timed out waiting for Java " +
"cacheserver to stop. Please check the server log " +
"in {0}.", startDir);
}
KillLocalJavaServer(serverId, "-9");
}
}
else if (hostType != Util.SystemType)
{
// Stop the remote host
LogInfo("ClientExit() stopping '{0}' on remote host " +
"'{1}' of type {2}", serverId, targetHost, hostType);
LogInfo(StartRemoteGFExe(targetHost, hostType,
"cacheserver", javaServerArgs));
}
}
}
}
m_javaServerHostMap.Clear();
}
// Stop the locator here.
if (m_locatorHost != null && m_locatorType != null)
{
LogInfo("ClientExit() stopping locator on host {0}", m_locatorHost);
for (int i = 0; i < locCount; i++)
{
string locatorDir = GetLocatorStartDir((i + 1).ToString(), Util.SystemType);
/* if (ssl)
{
locatorDir = locatorDir + "/..";
}
*/
string locatorPID = GetGFJavaPID(locatorDir +
PathSep + "locator.log");
if (locatorPID != null && locatorPID.Length > 0)
{
if (m_locatorType != Util.SystemType)
{
string killCmd = "kill -15 " + locatorPID;
LogInfo(Util.RunClientShellTask(Util.ClientId, m_locatorHost,
killCmd, null));
Thread.Sleep(3000);
killCmd = "kill -9 " + locatorPID;
LogInfo(Util.RunClientShellTask(Util.ClientId, m_locatorHost,
killCmd, null));
LogInfo("ClientExit() successfully stopped locator PID {0} on host {1}",
locatorPID, m_locatorHost);
}
else
{
if (!KillLocalGFJava(locatorPID, "-15") &&
!KillLocalGFJava(locatorPID, "-9"))
{
LogSevere("ClientExit() Error while stopping " +
"locator. Please check the logs in {0}", locatorDir);
}
else
{
LogInfo("ClientExit() successfully stopped locator on host {0}",
m_locatorHost);
}
}
}
}
}
}
locCount = 0;
m_locatorHost = null;
m_locatorType = null;
Util.BBRemove(string.Empty, "LOCATOR_ADDRESS");
Util.BBRemove(string.Empty, "LOCATOR_ADDRESS_POOL");
m_exiting = false;
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
using XenAdmin.Alerts;
using XenAdmin.Core;
using XenAdmin.Network;
using XenAdminTests.UnitTests.UnitTestHelper;
using XenAPI;
namespace XenAdminTests.UnitTests.AlertTests
{
[TestFixture, Category(TestCategories.Unit)]
public class XenServerUpdateAlertTests
{
private Mock<IXenConnection> connA;
private Mock<IXenConnection> connB;
private Mock<Host> hostA;
private Mock<Host> hostB;
protected Cache cacheA;
protected Cache cacheB;
[Test]
public void TestAlertWithConnectionAndHosts()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123");
var alert = new XenServerVersionAlert(ver);
alert.IncludeConnection(connA.Object);
alert.IncludeConnection(connB.Object);
alert.IncludeHosts(new List<Host>() { hostA.Object, hostB.Object });
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = "HostAName, HostBName, ConnAName, ConnBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Once);
VerifyHostsExpectations(Times.Once);
}
[Test]
public void TestAlertWithHostsAndNoConnection()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123");
var alert = new XenServerVersionAlert(ver);
alert.IncludeHosts(new List<Host> { hostA.Object, hostB.Object });
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = "HostAName, HostBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Never);
VerifyHostsExpectations(Times.Once);
}
[Test]
public void TestAlertWithConnectionAndNoHosts()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123");
var alert = new XenServerVersionAlert(ver);
alert.IncludeConnection(connA.Object);
alert.IncludeConnection(connB.Object);
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = "ConnAName, ConnBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Once);
VerifyHostsExpectations(Times.Never);
}
[Test]
public void TestAlertWithNoConnectionAndNoHosts()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123");
var alert = new XenServerVersionAlert(ver);
IUnitTestVerifier validator = new VerifyGetters(alert);
validator.Verify(new AlertClassUnitTestData
{
AppliesTo = string.Empty,
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsTrue(alert.CanIgnore);
VerifyConnExpectations(Times.Never);
VerifyHostsExpectations(Times.Never);
}
[Test, ExpectedException(typeof(NullReferenceException))]
public void TestAlertWithNullVersion()
{
var alert = new XenServerVersionAlert(null);
}
private void VerifyConnExpectations(Func<Times> times)
{
connA.VerifyGet(n => n.Name, times());
connB.VerifyGet(n => n.Name, times());
}
private void VerifyHostsExpectations(Func<Times> times)
{
hostA.VerifyGet(n => n.Name, times());
hostB.VerifyGet(n => n.Name, times());
}
[SetUp]
public void TestSetUp()
{
connA = new Mock<IXenConnection>(MockBehavior.Strict);
connA.Setup(n => n.Name).Returns("ConnAName");
cacheA = new Cache();
connA.Setup(x => x.Cache).Returns(cacheA);
connB = new Mock<IXenConnection>(MockBehavior.Strict);
connB.Setup(n => n.Name).Returns("ConnBName");
cacheB = new Cache();
connB.Setup(x => x.Cache).Returns(cacheB);
hostA = new Mock<Host>(MockBehavior.Strict);
hostA.Setup(n => n.Name).Returns("HostAName");
hostA.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostA.Object));
hostB = new Mock<Host>(MockBehavior.Strict);
hostB.Setup(n => n.Name).Returns("HostBName");
hostB.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostB.Object));
}
[TearDown]
public void TestTearDown()
{
cacheA = null;
cacheB = null;
connA = null;
connB = null;
hostA = null;
hostB = null;
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpatialAnalysis.CellularEnvironment;
using SpatialAnalysis.Data;
using SpatialAnalysis.IsovistUtility;
using SpatialAnalysis.Geometry;
using SpatialAnalysis.Agents;
using System.Threading.Tasks;
using System.Windows.Threading;
using System.Threading;
using SpatialAnalysis.Interoperability;
namespace SpatialAnalysis.Events
{
/// <summary>
/// Class VisibilityEvaluationEvent.
/// </summary>
public class VisibilityTarget //VisibilityTarget
{
/// <summary>
/// Gets or sets all visible cells.
/// </summary>
/// <value>All visible cells.</value>
public HashSet<int> AllVisibleCells { get; set; }
/// <summary>
/// Gets or sets the referenced vantage cells.
/// </summary>
/// <value>The referenced vantage cells.</value>
public Dictionary<int, List<int>> ReferencedVantageCells{ get; set; }
/// <summary>
/// Gets or sets the vantage cells.
/// </summary>
/// <value>The vantage cells.</value>
public ICollection<int> VantageCells { get; set; }
//public Isovist[] VisibilityTargetIsovists { get; set; }
/// <summary>
/// Gets or sets the visual targets.
/// </summary>
/// <value>The visual targets.</value>
public SpatialAnalysis.Geometry.BarrierPolygon[] VisualTargets { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="VisibilityEvaluationEvent"/> class.
/// </summary>
/// <param name="allVisibleCells">All visible cells.</param>
/// <param name="visibilityTargetIsovists">The visibility target isovists.</param>
/// <param name="visualTargets">The visual targets.</param>
public VisibilityTarget(HashSet<int> allVisibleCells, ICollection<Isovist> visibilityTargetIsovists, ICollection<SpatialAnalysis.Geometry.BarrierPolygon> visualTargets)
{
this.AllVisibleCells = allVisibleCells;
//this.VisibilityTargetIsovists = visibilityTargetIsovists;
this.VisualTargets = visualTargets.ToArray();
this.ReferencedVantageCells = new Dictionary<int, List<int>>();
var vantageCells = new List<int>(visibilityTargetIsovists.Count);
foreach (var item in this.AllVisibleCells)
{
this.ReferencedVantageCells.Add(item, new List<int>());
}
foreach (var isovist in visibilityTargetIsovists)
{
vantageCells.Add(isovist.VantageCell.ID);
foreach (var cellID in isovist.VisibleCells)
{
this.ReferencedVantageCells[cellID].Add(isovist.VantageCell.ID);
}
}
this.VantageCells = vantageCells;
}
/// <summary>
/// Initializes a new instance of the <see cref="VisibilityEvaluationEvent"/> class.
/// </summary>
/// <param name="visualTargets">The visual targets.</param>
/// <param name="cellularFloor">The cellular floor.</param>
/// <param name="tolerance">The tolerance by default set to the main document's absolute tolerance value.</param>
/// <exception cref="System.ArgumentException">Cannot generate 'Occupancy Visual Event' with no visibility target cells!</exception>
public VisibilityTarget(ICollection<SpatialAnalysis.Geometry.BarrierPolygon> visualTargets, CellularFloor cellularFloor, double tolerance = OSMDocument.AbsoluteTolerance)
{
this.VisualTargets = visualTargets.ToArray();
HashSet<Index> allIndices = new HashSet<Index>();
foreach (SpatialAnalysis.Geometry.BarrierPolygon item in this.VisualTargets)
{
allIndices.UnionWith(cellularFloor.GetIndicesInsideBarrier(item, tolerance));
}
var visibleCells = new HashSet<int>();
foreach (Index item in allIndices)
{
if (cellularFloor.ContainsCell(item) &&
cellularFloor.Cells[item.I, item.J].VisualOverlapState == OverlapState.Outside)
{
visibleCells.Add(cellularFloor.Cells[item.I, item.J].ID);
}
}
allIndices.Clear();
allIndices = null;
if (visibleCells.Count == 0)
{
throw new ArgumentException("Cannot generate 'Occupancy Visual Event' with no visibility target cells!");
}
var cellsOnEdge = CellUtility.GetEdgeOfField(cellularFloor, visibleCells);
List<Isovist> isovists = new List<Isovist>(cellsOnEdge.Count);
double depth = cellularFloor.Origin.DistanceTo(cellularFloor.TopRight) + 1;
foreach (int item in cellsOnEdge)
{
isovists.Add(new Isovist(cellularFloor.FindCell(item)));
}
Parallel.ForEach(isovists, (a) =>
{
a.Compute(depth, BarrierType.Visual, cellularFloor, 0.0000001);
});
HashSet<int> visibleArea = new HashSet<int>();
foreach (Isovist item in isovists)
{
visibleArea.UnionWith(item.VisibleCells);
}
this.AllVisibleCells = visibleArea;
this.ReferencedVantageCells = new Dictionary<int, List<int>>();
var vantageCells = new List<int>(isovists.Count);
foreach (var item in this.AllVisibleCells)
{
this.ReferencedVantageCells.Add(item, new List<int>());
}
foreach (var isovist in isovists)
{
vantageCells.Add(isovist.VantageCell.ID);
foreach (var cellID in isovist.VisibleCells)
{
this.ReferencedVantageCells[cellID].Add(isovist.VantageCell.ID);
}
}
this.VantageCells = vantageCells;
}
/// <summary>
/// Saves the instance of the visual event as string.
/// </summary>
/// <returns>System.String.</returns>
public string SaveAsString()
{
StringBuilder sb = new StringBuilder();
foreach (SpatialAnalysis.Geometry.BarrierPolygon item in VisualTargets)
{
sb.AppendLine(item.ToString());
}
string text = sb.ToString();
sb.Clear();
sb = null;
return text;
}
/// <summary>
/// Creates an instance of the event from its string representation .
/// </summary>
/// <param name="lines">The lines.</param>
/// <param name="start">The start.</param>
/// <param name="cellularFloor">The cellular floor.</param>
/// <param name="tolerance">The tolerance.</param>
/// <returns>VisibilityEvaluationEvent.</returns>
public static VisibilityTarget FromString(List<String> lines, int start, Length_Unit_Types unitType, CellularFloor cellularFloor, double tolerance = 0.0000001d)
{
List<SpatialAnalysis.Geometry.BarrierPolygon> barriers = new List<Geometry.BarrierPolygon>();
for (int i = start; i < lines.Count; i++)
{
var barrier = SpatialAnalysis.Geometry.BarrierPolygon.FromStringRepresentation(lines[i]);
UnitConversion.Transform(barrier.BoundaryPoints, unitType, cellularFloor.UnitType);
barriers.Add(barrier);
}
return new VisibilityTarget(barriers, cellularFloor, tolerance);
}
/// <summary>
/// Targets the visibility test.
/// </summary>
/// <param name="currentState">The current state of the agent.</param>
/// <param name="visibilityCosineFactor">The visibility cosine factor.</param>
/// <param name="cellularFloor">The cellular floor.</param>
/// <returns>UV.</returns>
public UV TargetVisibilityTest(StateBase currentState, double visibilityCosineFactor, CellularFloorBaseGeometry cellularFloor)
{
var vantageCell = cellularFloor.FindCell(currentState.Location);
if (!this.AllVisibleCells.Contains(vantageCell.ID))
{
return null;
}
UV target = null;
foreach (var cellID in this.ReferencedVantageCells[vantageCell.ID])
{
UV targetCell = cellularFloor.FindCell(cellID);
UV direction = targetCell - currentState.Location;
direction.Unitize();
if (direction.DotProduct(currentState.Direction) >= visibilityCosineFactor)
{
target = targetCell;
break;
}
}
return target;
}
/// <summary>
/// Determines whether a visual the event is raised.
/// </summary>
/// <param name="currentState">The current state of the agent.</param>
/// <param name="visibilityCosineFactor">The visibility cosine factor.</param>
/// <param name="cellularFloor">The cellular floor.</param>
/// <returns><c>true</c> if visual the event is raised, <c>false</c> otherwise.</returns>
public bool VisualEventRaised(StateBase currentState, double visibilityCosineFactor, CellularFloorBaseGeometry cellularFloor)
{
var vantageCell = cellularFloor.FindCell(currentState.Location);
if (!this.AllVisibleCells.Contains(vantageCell.ID))
{
return false;
}
bool raised = false;
foreach (var cellID in this.ReferencedVantageCells[vantageCell.ID])
{
UV targetCell = cellularFloor.FindCell(cellID);
UV direction = targetCell - currentState.Location;
direction.Unitize();
if (direction.DotProduct(currentState.Direction) >= visibilityCosineFactor)
{
raised = true;
break;
}
}
return raised;
}
public static bool operator ==(VisibilityTarget a, VisibilityTarget b)
{
if ((object)a == null && (object)b == null)
{
return true;
}
if ((object)a == null || (object)b == null)
{
return false;
}
if (a.AllVisibleCells.Count == b.AllVisibleCells.Count)
{
foreach (var item in a.AllVisibleCells)
{
if (!b.AllVisibleCells.Contains(item))
{
return false;
}
}
return true;
}
else
{
return false;
}
}
public static bool operator !=(VisibilityTarget a, VisibilityTarget b)
{
return !(a == b);
}
}
}
| |
//******************************************
// Copyright (C) 2014-2015 Charles Nurse *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Collections.Generic;
using FamilyTreeProject.Common;
using FamilyTreeProject.GEDCOM.Common;
using FamilyTreeProject.GEDCOM.Records;
namespace FamilyTreeProject.GEDCOM.Structures
{
///<summary>
/// The GEDCOMEventStructure Class models Genealogical Fact Records and
/// Attribute Records.
///</summary>
///<remarks>
/// <h2>GEDCOM 5.5 Fact Structure</h2>
/// n [ BIRT | CHR ] [Y|<NULL>] {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
/// +1 FAMC @<XREF:FAM>@ {0:1}
///
/// n [ DEAT | BURI | CREM ] [Y|<NULL>] {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n ADOP [Y|<NULL>] {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
/// +1 FAMC @<XREF:FAM>@ {0:1}
/// +2 ADOP <ADOPTED_BY_WHICH_PARENT> {0:1}
///
/// n [ BAPM | BARM | BASM | BLES ] [Y|<NULL>] {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n [ CHRA | CONF | FCOM | ORDN ] [Y|<NULL>] {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n [ NATU | EMIG | IMMI ] [Y|<NULL>] {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n [ CENS | PROB | WILL] [Y|<NULL>] {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n [ GRAD | RETI ] [Y|<NULL>] {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n [ ANUL | CENS | DIV | DIVF ] [Y|<NULL>] {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n [ ENGA | MARR | MARB | MARC ] [Y|<NULL>] {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n [ MARL | MARS ] [Y|<NULL>] {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n EVEN {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// <h2>GEDCOM 5.5 Attribute Structure</h2>
/// n CAST <CASTE_NAME> {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n DSCR <PHYSICAL_DESCRIPTION> {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n EDUC <SCHOLASTIC_ACHIEVEMENT> {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n IDNO <NATIONAL_ID_NUMBER> {1:1}*<br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n NATI <NATIONAL_OR_TRIBAL_ORIGIN> {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n NCHI <COUNT_OF_CHILDREN> {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n NMR <COUNT_OF_MARRIAGES> {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n OCCU <OCCUPATION> {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n PROP <POSSESSIONS> {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n RELI <RELIGIOUS_AFFILIATION> {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n RESI {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n SSN <SOCIAL_SECURITY_NUMBER> {0:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// n TITL <NOBILITY_TYPE_TITLE> {1:1} <br />
/// +1 <<EVENT_DETAIL>> {0:1} <i>see Below</i><br />
///
/// <h3>GEDCOM 5.5 Fact Detail</h3>
/// n TYPE <EVENT_DESCRIPTOR> {0:1} - TypeDetail<br />
/// n DATE <DATE_VALUE> {0:1} - Date<br />
/// n <<PLACE_STRUCTURE>> {0:1} - Place<br />
/// n <<ADDRESS_STRUCTURE>> {0:1} - Address/Phones<br />
/// n AGE <AGE_AT_EVENT> {0:1} - Age<br />
/// n AGNC <RESPONSIBLE_AGENCY> {0:1} - Agency<br />
/// n CAUS <CAUSE_OF_EVENT> {0:1} - Cause<br />
/// n <<SOURCE_CITATION>> {0:M} - <i>see GEDCOMStructure - SourceCitations</i><br />
/// n <<MULTIMEDIA_LINK>> {0:M} - <i>see GEDCOMStructure - Multimedia</i><br />
/// n <<NOTE_STRUCTURE>> {0:M} - <i>see GEDCOMStructure - Notes</i><br />
///</remarks>
public class GEDCOMEventStructure : GEDCOMStructure
{
private readonly EventClass _eventClass = EventClass.Unknown;
/// <summary>
/// Constructs a GEDCOMEventStructure from a GEDCOMRecord
/// </summary>
/// <param name = "record">a GEDCOMRecord</param>
public GEDCOMEventStructure(GEDCOMRecord record) : base(record)
{
}
/// <summary>
/// Constructs a GEDCOMEventStructure from a GEDCOMRecord
/// </summary>
/// <param name = "record">a GEDCOMRecord</param>
/// <param name = "eventClass"></param>
public GEDCOMEventStructure(GEDCOMRecord record, EventClass eventClass) : base(record)
{
_eventClass = eventClass;
}
public GEDCOMEventStructure(int level, string tag, string date, string place) : base(new GEDCOMRecord(level, "", "", tag, ""))
{
var dateRecord = new GEDCOMRecord(level + 1, "", "", "DATE", date);
ChildRecords.Add(dateRecord);
var placeRecord = new GEDCOMPlaceStructure(level + 1, place);
ChildRecords.Add(placeRecord);
}
/// <summary>
/// Gets the Address connected to this event
/// </summary>
public GEDCOMAddressStructure Address
{
get { return ChildRecords.GetLineByTag<GEDCOMAddressStructure>(GEDCOMTag.ADDR); }
}
/// <summary>
/// Gets the Age of the Individual at the time of this event
/// </summary>
public string Age
{
get { return ChildRecords.GetRecordData(GEDCOMTag.AGE); }
}
/// <summary>
/// Gets the Responsible Agency for the event
/// </summary>
public string Agency
{
get { return ChildRecords.GetRecordData(GEDCOMTag.AGNC); }
}
/// <summary>
/// Gets the Age of the Husband at the time of this event
/// </summary>
public string AgeOfHusband
{
get
{
string age = String.Empty;
GEDCOMRecord husband = ChildRecords.GetLineByTag(GEDCOMTag.HUSB);
if (husband != null)
{
age = husband.ChildRecords.GetRecordData(GEDCOMTag.AGE);
}
return age;
}
}
/// <summary>
/// Gets the Age of the Wife at the time of this event
/// </summary>
public string AgeOfWife
{
get
{
string age = String.Empty;
GEDCOMRecord wife = ChildRecords.GetLineByTag(GEDCOMTag.WIFE);
if (wife != null)
{
age = wife.ChildRecords.GetRecordData(GEDCOMTag.AGE);
}
return age;
}
}
/// <summary>
/// Gets the Cuase of the event
/// </summary>
public string Cause
{
get { return ChildRecords.GetRecordData(GEDCOMTag.CAUS); }
}
/// <summary>
/// Gets the Date of the event
/// </summary>
public string Date
{
get { return ChildRecords.GetRecordData(GEDCOMTag.DATE); }
}
/// <summary>
/// Gets the Class of the event
/// </summary>
public EventClass EventClass
{
get { return _eventClass; }
}
/// <summary>
/// Gets the Type of the event
/// </summary>
public FactType FamilyEventType
{
get
{
if (EventClass == EventClass.Family)
{
switch (TagName)
{
case GEDCOMTag.ANUL:
return FactType.Annulment;
case GEDCOMTag.DIV:
return FactType.Divorce;
case GEDCOMTag.DIVF:
return FactType.DivorceFiled;
case GEDCOMTag.ENGA:
return FactType.Engagement;
case GEDCOMTag.MARR:
return FactType.Marriage;
case GEDCOMTag.MARB:
return FactType.MarriageBann;
case GEDCOMTag.MARC:
return FactType.MarriageContract;
case GEDCOMTag.MARL:
return FactType.MarriageLicense;
case GEDCOMTag.MARS:
return FactType.MarriageSettlement;
case GEDCOMTag.EVEN:
return FactType.Other;
default:
return FactType.Unknown;
}
}
else
{
return FactType.Unknown;
}
}
}
/// <summary>
/// Gets the Type of the event
/// </summary>
public FactType IndividualAttributeType
{
get
{
if (EventClass == EventClass.Attribute)
{
switch (TagName)
{
case GEDCOMTag.CAST:
return FactType.Caste;
case GEDCOMTag.DSCR:
return FactType.Description;
case GEDCOMTag.EDUC:
return FactType.Education;
case GEDCOMTag.IDNO:
return FactType.IdNumber;
case GEDCOMTag.NATI:
return FactType.NationalOrTribalOrigin;
case GEDCOMTag.NCHI:
return FactType.NoOfChildren;
case GEDCOMTag.NMR:
return FactType.NoOfMarriages;
case GEDCOMTag.OCCU:
return FactType.Occupation;
case GEDCOMTag.PROP:
return FactType.Property;
case GEDCOMTag.RELI:
return FactType.Religion;
case GEDCOMTag.RESI:
return FactType.Residence;
case GEDCOMTag.SSN:
return FactType.SocialSecurityNumber;
case GEDCOMTag.TITL:
return FactType.Title;
default:
return FactType.Unknown;
}
}
else
{
return FactType.Unknown;
}
}
}
/// <summary>
/// Gets the Type of the event
/// </summary>
public FactType IndividualEventType
{
get
{
if (EventClass == EventClass.Individual)
{
switch (TagName)
{
case GEDCOMTag.ADOP:
return FactType.Adoption;
case GEDCOMTag.BAPM:
return FactType.Baptism;
case GEDCOMTag.BARM:
return FactType.BarMitzvah;
case GEDCOMTag.BASM:
return FactType.BasMitzvah;
case GEDCOMTag.BIRT:
return FactType.Birth;
case GEDCOMTag.BLES:
return FactType.Blessing;
case GEDCOMTag.BURI:
return FactType.Burial;
case GEDCOMTag.CENS:
return FactType.Census;
case GEDCOMTag.CHR:
return FactType.Christening;
case GEDCOMTag.CHRA:
return FactType.AdultChristening;
case GEDCOMTag.CONF:
return FactType.Confirmation;
case GEDCOMTag.CREM:
return FactType.Cremation;
case GEDCOMTag.DEAT:
return FactType.Death;
case GEDCOMTag.EMIG:
return FactType.Emigration;
case GEDCOMTag.FCOM:
return FactType.FirstCommunion;
case GEDCOMTag.GRAD:
return FactType.Graduation;
case GEDCOMTag.IMMI:
return FactType.Immigration;
case GEDCOMTag.NATU:
return FactType.Naturalisation;
case GEDCOMTag.ORDN:
return FactType.Ordination;
case GEDCOMTag.PROB:
return FactType.Probate;
case GEDCOMTag.RETI:
return FactType.Retirement;
case GEDCOMTag.WILL:
return FactType.Will;
case GEDCOMTag.EVEN:
return FactType.Other;
default:
return FactType.Unknown;
}
}
else
{
return FactType.Unknown;
}
}
}
/// <summary>
/// Gets a List of PhoneNumbers
/// </summary>
public List<string> PhoneNumbers
{
get
{
List<GEDCOMRecord> phoneRecords = ChildRecords.GetLinesByTag<GEDCOMRecord>(GEDCOMTag.PHON);
List<string> phoneNumbers = new List<string>();
foreach (GEDCOMRecord phoneRecord in phoneRecords)
{
if (!String.IsNullOrEmpty(phoneRecord.Data))
{
phoneNumbers.Add(phoneRecord.Data);
}
}
return phoneNumbers;
}
}
/// <summary>
/// Gets the Place of the event
/// </summary>
public GEDCOMPlaceStructure Place
{
get { return ChildRecords.GetLineByTag<GEDCOMPlaceStructure>(GEDCOMTag.PLAC); }
}
/// <summary>
/// Gets the Type Detail of the event (if just defined as an EVEN)
/// </summary>
public string TypeDetail
{
get { return ChildRecords.GetRecordData(GEDCOMTag.TYPE); }
}
}
}
| |
// <copyright file="IluptElementSorterTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex;
using MathNet.Numerics.LinearAlgebra.Complex.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Solvers.Preconditioners
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Test for element sort algorithm of Ilupt class.
/// </summary>
[TestFixture, Category("LASolver")]
public sealed class IluptElementSorterTest
{
/// <summary>
/// Heap sort with increasing integer array.
/// </summary>
[Test]
public void HeapSortWithIncreasingIntegerArray()
{
var sortedIndices = new[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with decreasing integer array.
/// </summary>
[Test]
public void HeapSortWithDecreasingIntegerArray()
{
var sortedIndices = new[] {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with random integer array.
/// </summary>
[Test]
public void HeapSortWithRandomIntegerArray()
{
var sortedIndices = new[] {5, 2, 8, 6, 0, 4, 1, 7, 3, 9};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with duplicate entries.
/// </summary>
[Test]
public void HeapSortWithDuplicateEntries()
{
var sortedIndices = new[] {1, 1, 1, 1, 2, 2, 2, 2, 3, 4};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(4, sortedIndices[i], "#01-" + i);
}
else
{
if (i == 1)
{
Assert.AreEqual(3, sortedIndices[i], "#01-" + i);
}
else
{
if (i < 6)
{
if (sortedIndices[i] != 2)
{
Assert.Fail("#01-" + i);
}
}
else
{
if (sortedIndices[i] != 1)
{
Assert.Fail("#01-" + i);
}
}
}
}
}
}
/// <summary>
/// Heap sort with special constructed integer array.
/// </summary>
[Test]
public void HeapSortWithSpecialConstructedIntegerArray()
{
var sortedIndices = new[] {0, 0, 0, 0, 0, 1, 0, 0, 0, 0};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(1, sortedIndices[i], "#01-" + i);
break;
}
}
sortedIndices = new[] {1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(1, sortedIndices[i], "#02-" + i);
break;
}
}
sortedIndices = new[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(1, sortedIndices[i], "#03-" + i);
break;
}
}
sortedIndices = new[] {1, 1, 1, 0, 1, 1, 1, 1, 1, 1};
ILUTPElementSorter.SortIntegersDecreasing(sortedIndices);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 9)
{
Assert.AreEqual(0, sortedIndices[i], "#04-" + i);
break;
}
}
}
/// <summary>
/// Heap sort with increasing double array.
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArray()
{
var sortedIndices = new int[10];
Vector<Complex> values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with decreasing doubleArray
/// </summary>
[Test]
public void HeapSortWithDecreasingDoubleArray()
{
var sortedIndices = new int[10];
Vector<Complex> values = new DenseVector(10);
values[0] = 9;
values[1] = 8;
values[2] = 7;
values[3] = 6;
values[4] = 5;
values[5] = 4;
values[6] = 3;
values[7] = 2;
values[8] = 1;
values[9] = 0;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
Assert.AreEqual(i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with random double array.
/// </summary>
[Test]
public void HeapSortWithRandomDoubleArray()
{
var sortedIndices = new int[10];
Vector<Complex> values = new DenseVector(10);
values[0] = 5;
values[1] = 2;
values[2] = 8;
values[3] = 6;
values[4] = 0;
values[5] = 4;
values[6] = 1;
values[7] = 7;
values[8] = 3;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
switch (i)
{
case 0:
Assert.AreEqual(9, sortedIndices[i], "#01-" + i);
break;
case 1:
Assert.AreEqual(2, sortedIndices[i], "#01-" + i);
break;
case 2:
Assert.AreEqual(7, sortedIndices[i], "#01-" + i);
break;
case 3:
Assert.AreEqual(3, sortedIndices[i], "#01-" + i);
break;
case 4:
Assert.AreEqual(0, sortedIndices[i], "#01-" + i);
break;
case 5:
Assert.AreEqual(5, sortedIndices[i], "#01-" + i);
break;
case 6:
Assert.AreEqual(8, sortedIndices[i], "#01-" + i);
break;
case 7:
Assert.AreEqual(1, sortedIndices[i], "#01-" + i);
break;
case 8:
Assert.AreEqual(6, sortedIndices[i], "#01-" + i);
break;
case 9:
Assert.AreEqual(4, sortedIndices[i], "#01-" + i);
break;
}
}
}
/// <summary>
/// Heap sort with duplicate double entries.
/// </summary>
[Test]
public void HeapSortWithDuplicateDoubleEntries()
{
var sortedIndices = new int[10];
Vector<Complex> values = new DenseVector(10);
values[0] = 1;
values[1] = 1;
values[2] = 1;
values[3] = 1;
values[4] = 2;
values[5] = 2;
values[6] = 2;
values[7] = 2;
values[8] = 3;
values[9] = 4;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(9, sortedIndices[i], "#01-" + i);
}
else
{
if (i == 1)
{
Assert.AreEqual(8, sortedIndices[i], "#01-" + i);
}
else
{
if (i < 6)
{
if ((sortedIndices[i] != 4) &&
(sortedIndices[i] != 5) &&
(sortedIndices[i] != 6) &&
(sortedIndices[i] != 7))
{
Assert.Fail("#01-" + i);
}
}
else
{
if ((sortedIndices[i] != 0) &&
(sortedIndices[i] != 1) &&
(sortedIndices[i] != 2) &&
(sortedIndices[i] != 3))
{
Assert.Fail("#01-" + i);
}
}
}
}
}
}
/// <summary>
/// Heap sort with special constructed double array.
/// </summary>
[Test]
public void HeapSortWithSpecialConstructedDoubleArray()
{
var sortedIndices = new int[10];
Vector<Complex> values = new DenseVector(10);
values[0] = 0;
values[1] = 0;
values[2] = 0;
values[3] = 0;
values[4] = 0;
values[5] = 1;
values[6] = 0;
values[7] = 0;
values[8] = 0;
values[9] = 0;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(5, sortedIndices[i], "#01-" + i);
break;
}
}
values[0] = 1;
values[1] = 0;
values[2] = 0;
values[3] = 0;
values[4] = 0;
values[5] = 0;
values[6] = 0;
values[7] = 0;
values[8] = 0;
values[9] = 0;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(0, sortedIndices[i], "#02-" + i);
break;
}
}
values[0] = 0;
values[1] = 0;
values[2] = 0;
values[3] = 0;
values[4] = 0;
values[5] = 0;
values[6] = 0;
values[7] = 0;
values[8] = 0;
values[9] = 1;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 0)
{
Assert.AreEqual(9, sortedIndices[i], "#03-" + i);
break;
}
}
values[0] = 1;
values[1] = 1;
values[2] = 1;
values[3] = 0;
values[4] = 1;
values[5] = 1;
values[6] = 1;
values[7] = 1;
values[8] = 1;
values[9] = 1;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length; i++)
{
if (i == 9)
{
Assert.AreEqual(3, sortedIndices[i], "#04-" + i);
break;
}
}
}
/// <summary>
/// Heap sort with increasing double array with lower bound
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArrayWithLowerBound()
{
var sortedIndices = new int[10];
Vector<Complex> values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(4, sortedIndices.Length - 1, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length - 4; i++)
{
Assert.AreEqual(sortedIndices.Length - 1 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with increasing double array with upper bound.
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArrayWithUpperBound()
{
var sortedIndices = new int[10];
Vector<Complex> values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 5, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length - 5; i++)
{
Assert.AreEqual(sortedIndices.Length - 5 - i, sortedIndices[i], "#01-" + i);
}
}
/// <summary>
/// Heap sort with increasing double array with lower and upper bound.
/// </summary>
[Test]
public void HeapSortWithIncreasingDoubleArrayWithLowerAndUpperBound()
{
var sortedIndices = new int[10];
Vector<Complex> values = new DenseVector(10);
values[0] = 0;
values[1] = 1;
values[2] = 2;
values[3] = 3;
values[4] = 4;
values[5] = 5;
values[6] = 6;
values[7] = 7;
values[8] = 8;
values[9] = 9;
for (var i = 0; i < sortedIndices.Length; i++)
{
sortedIndices[i] = i;
}
ILUTPElementSorter.SortDoubleIndicesDecreasing(2, sortedIndices.Length - 3, sortedIndices, values);
for (var i = 0; i < sortedIndices.Length - 4; i++)
{
Assert.AreEqual(sortedIndices.Length - 3 - i, sortedIndices[i], "#01-" + i);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using Orleans.CodeGeneration;
using Orleans.Runtime;
namespace Orleans.Serialization
{
/// <summary>
/// Writer for Orleans binary token streams
/// </summary>
public class BinaryTokenStreamWriter
{
private readonly ByteArrayBuilder ab;
private static readonly Dictionary<RuntimeTypeHandle, SerializationTokenType> typeTokens;
private static readonly Dictionary<RuntimeTypeHandle, Action<BinaryTokenStreamWriter, object>> writers;
static BinaryTokenStreamWriter()
{
typeTokens = new Dictionary<RuntimeTypeHandle, SerializationTokenType>();
typeTokens[typeof(bool).TypeHandle] = SerializationTokenType.Boolean;
typeTokens[typeof(int).TypeHandle] = SerializationTokenType.Int;
typeTokens[typeof(uint).TypeHandle] = SerializationTokenType.Uint;
typeTokens[typeof(short).TypeHandle] = SerializationTokenType.Short;
typeTokens[typeof(ushort).TypeHandle] = SerializationTokenType.Ushort;
typeTokens[typeof(long).TypeHandle] = SerializationTokenType.Long;
typeTokens[typeof(ulong).TypeHandle] = SerializationTokenType.Ulong;
typeTokens[typeof(byte).TypeHandle] = SerializationTokenType.Byte;
typeTokens[typeof(sbyte).TypeHandle] = SerializationTokenType.Sbyte;
typeTokens[typeof(float).TypeHandle] = SerializationTokenType.Float;
typeTokens[typeof(double).TypeHandle] = SerializationTokenType.Double;
typeTokens[typeof(decimal).TypeHandle] = SerializationTokenType.Decimal;
typeTokens[typeof(string).TypeHandle] = SerializationTokenType.String;
typeTokens[typeof(char).TypeHandle] = SerializationTokenType.Character;
typeTokens[typeof(Guid).TypeHandle] = SerializationTokenType.Guid;
typeTokens[typeof(DateTime).TypeHandle] = SerializationTokenType.Date;
typeTokens[typeof(TimeSpan).TypeHandle] = SerializationTokenType.TimeSpan;
typeTokens[typeof(GrainId).TypeHandle] = SerializationTokenType.GrainId;
typeTokens[typeof(ActivationId).TypeHandle] = SerializationTokenType.ActivationId;
typeTokens[typeof(SiloAddress).TypeHandle] = SerializationTokenType.SiloAddress;
typeTokens[typeof(ActivationAddress).TypeHandle] = SerializationTokenType.ActivationAddress;
typeTokens[typeof(IPAddress).TypeHandle] = SerializationTokenType.IpAddress;
typeTokens[typeof(IPEndPoint).TypeHandle] = SerializationTokenType.IpEndPoint;
typeTokens[typeof(CorrelationId).TypeHandle] = SerializationTokenType.CorrelationId;
typeTokens[typeof(InvokeMethodRequest).TypeHandle] = SerializationTokenType.Request;
typeTokens[typeof(Response).TypeHandle] = SerializationTokenType.Response;
typeTokens[typeof(Dictionary<string, object>).TypeHandle] = SerializationTokenType.StringObjDict;
typeTokens[typeof(Object).TypeHandle] = SerializationTokenType.Object;
typeTokens[typeof(List<>).TypeHandle] = SerializationTokenType.List;
typeTokens[typeof(SortedList<,>).TypeHandle] = SerializationTokenType.SortedList;
typeTokens[typeof(Dictionary<,>).TypeHandle] = SerializationTokenType.Dictionary;
typeTokens[typeof(HashSet<>).TypeHandle] = SerializationTokenType.Set;
typeTokens[typeof(SortedSet<>).TypeHandle] = SerializationTokenType.SortedSet;
typeTokens[typeof(KeyValuePair<,>).TypeHandle] = SerializationTokenType.KeyValuePair;
typeTokens[typeof(LinkedList<>).TypeHandle] = SerializationTokenType.LinkedList;
typeTokens[typeof(Stack<>).TypeHandle] = SerializationTokenType.Stack;
typeTokens[typeof(Queue<>).TypeHandle] = SerializationTokenType.Queue;
typeTokens[typeof(Tuple<>).TypeHandle] = SerializationTokenType.Tuple + 1;
typeTokens[typeof(Tuple<,>).TypeHandle] = SerializationTokenType.Tuple + 2;
typeTokens[typeof(Tuple<,,>).TypeHandle] = SerializationTokenType.Tuple + 3;
typeTokens[typeof(Tuple<,,,>).TypeHandle] = SerializationTokenType.Tuple + 4;
typeTokens[typeof(Tuple<,,,,>).TypeHandle] = SerializationTokenType.Tuple + 5;
typeTokens[typeof(Tuple<,,,,,>).TypeHandle] = SerializationTokenType.Tuple + 6;
typeTokens[typeof(Tuple<,,,,,,>).TypeHandle] = SerializationTokenType.Tuple + 7;
writers = new Dictionary<RuntimeTypeHandle, Action<BinaryTokenStreamWriter, object>>();
writers[typeof(bool).TypeHandle] = (stream, obj) => stream.Write((bool) obj);
writers[typeof(int).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Int); stream.Write((int) obj); };
writers[typeof(uint).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Uint); stream.Write((uint) obj); };
writers[typeof(short).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Short); stream.Write((short) obj); };
writers[typeof(ushort).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Ushort); stream.Write((ushort) obj); };
writers[typeof(long).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Long); stream.Write((long) obj); };
writers[typeof(ulong).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Ulong); stream.Write((ulong) obj); };
writers[typeof(byte).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Byte); stream.Write((byte) obj); };
writers[typeof(sbyte).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Sbyte); stream.Write((sbyte) obj); };
writers[typeof(float).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Float); stream.Write((float) obj); };
writers[typeof(double).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Double); stream.Write((double) obj); };
writers[typeof(decimal).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Decimal); stream.Write((decimal)obj); };
writers[typeof(string).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.String); stream.Write((string)obj); };
writers[typeof(char).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Character); stream.Write((char) obj); };
writers[typeof(Guid).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Guid); stream.Write((Guid) obj); };
writers[typeof(DateTime).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Date); stream.Write((DateTime) obj); };
writers[typeof(TimeSpan).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.TimeSpan); stream.Write((TimeSpan) obj); };
writers[typeof(GrainId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.GrainId); stream.Write((GrainId) obj); };
writers[typeof(ActivationId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.ActivationId); stream.Write((ActivationId) obj); };
writers[typeof(SiloAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.SiloAddress); stream.Write((SiloAddress) obj); };
writers[typeof(ActivationAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.ActivationAddress); stream.Write((ActivationAddress) obj); };
writers[typeof(IPAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.IpAddress); stream.Write((IPAddress) obj); };
writers[typeof(IPEndPoint).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.IpEndPoint); stream.Write((IPEndPoint) obj); };
writers[typeof(CorrelationId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.CorrelationId); stream.Write((CorrelationId) obj); };
}
/// <summary> Default constructor. </summary>
public BinaryTokenStreamWriter()
{
ab = new ByteArrayBuilder();
Trace("Starting new binary token stream");
}
/// <summary> Return the output stream as a set of <c>ArraySegment</c>. </summary>
/// <returns>Data from this stream, converted to output type.</returns>
public IList<ArraySegment<byte>> ToBytes()
{
return ab.ToBytes();
}
/// <summary> Return the output stream as a <c>byte[]</c>. </summary>
/// <returns>Data from this stream, converted to output type.</returns>
public byte[] ToByteArray()
{
return ab.ToByteArray();
}
/// <summary> Release any serialization buffers being used by this stream. </summary>
public void ReleaseBuffers()
{
ab.ReleaseBuffers();
}
/// <summary> Current write position in the stream. </summary>
public int CurrentOffset { get { return ab.Length; } }
// Numbers
/// <summary> Write an <c>Int32</c> value to the stream. </summary>
public void Write(int i)
{
Trace("--Wrote integer {0}", i);
ab.Append(i);
}
/// <summary> Write an <c>Int16</c> value to the stream. </summary>
public void Write(short s)
{
Trace("--Wrote short {0}", s);
ab.Append(s);
}
/// <summary> Write an <c>Int64</c> value to the stream. </summary>
public void Write(long l)
{
Trace("--Wrote long {0}", l);
ab.Append(l);
}
/// <summary> Write a <c>sbyte</c> value to the stream. </summary>
public void Write(sbyte b)
{
Trace("--Wrote sbyte {0}", b);
ab.Append(b);
}
/// <summary> Write a <c>UInt32</c> value to the stream. </summary>
public void Write(uint u)
{
Trace("--Wrote uint {0}", u);
ab.Append(u);
}
/// <summary> Write a <c>UInt16</c> value to the stream. </summary>
public void Write(ushort u)
{
Trace("--Wrote ushort {0}", u);
ab.Append(u);
}
/// <summary> Write a <c>UInt64</c> value to the stream. </summary>
public void Write(ulong u)
{
Trace("--Wrote ulong {0}", u);
ab.Append(u);
}
/// <summary> Write a <c>byte</c> value to the stream. </summary>
public void Write(byte b)
{
Trace("--Wrote byte {0}", b);
ab.Append(b);
}
/// <summary> Write a <c>float</c> value to the stream. </summary>
public void Write(float f)
{
Trace("--Wrote float {0}", f);
ab.Append(f);
}
/// <summary> Write a <c>double</c> value to the stream. </summary>
public void Write(double d)
{
Trace("--Wrote double {0}", d);
ab.Append(d);
}
/// <summary> Write a <c>decimal</c> value to the stream. </summary>
public void Write(decimal d)
{
Trace("--Wrote decimal {0}", d);
ab.Append(Decimal.GetBits(d));
}
// Text
/// <summary> Write a <c>string</c> value to the stream. </summary>
public void Write(string s)
{
Trace("--Wrote string '{0}'", s);
if (null == s)
{
ab.Append(-1);
}
else
{
var bytes = Encoding.UTF8.GetBytes(s);
ab.Append(bytes.Length);
ab.Append(bytes);
}
}
/// <summary> Write a <c>char</c> value to the stream. </summary>
public void Write(char c)
{
Trace("--Wrote char {0}", c);
ab.Append(Convert.ToInt16(c));
}
// Other primitives
/// <summary> Write a <c>bool</c> value to the stream. </summary>
public void Write(bool b)
{
Trace("--Wrote Boolean {0}", b);
ab.Append((byte)(b ? SerializationTokenType.True : SerializationTokenType.False));
}
/// <summary> Write a <c>null</c> value to the stream. </summary>
public void WriteNull()
{
Trace("--Wrote null");
ab.Append((byte)SerializationTokenType.Null);
}
internal void Write(SerializationTokenType t)
{
Trace("--Wrote token {0}", t);
ab.Append((byte)t);
}
// Types
/// <summary> Write a type header for the specified Type to the stream. </summary>
/// <param name="t">Type to write header for.</param>
/// <param name="expected">Currently expected Type for this stream.</param>
public void WriteTypeHeader(Type t, Type expected = null)
{
Trace("-Writing type header for type {0}, expected {1}", t, expected);
if (t == expected)
{
ab.Append((byte)SerializationTokenType.ExpectedType);
return;
}
ab.Append((byte) SerializationTokenType.SpecifiedType);
if (t.IsArray)
{
ab.Append((byte)(SerializationTokenType.Array + (byte)t.GetArrayRank()));
WriteTypeHeader(t.GetElementType());
return;
}
SerializationTokenType token;
if (typeTokens.TryGetValue(t.TypeHandle, out token))
{
ab.Append((byte) token);
return;
}
if (t.GetTypeInfo().IsGenericType)
{
if (typeTokens.TryGetValue(t.GetGenericTypeDefinition().TypeHandle, out token))
{
ab.Append((byte)token);
foreach (var tp in t.GetGenericArguments())
{
WriteTypeHeader(tp);
}
return;
}
}
ab.Append((byte)SerializationTokenType.NamedType);
var typeKey = t.OrleansTypeKey();
ab.Append(typeKey.Length);
ab.Append(typeKey);
}
// Primitive arrays
/// <summary> Write a <c>byte[]</c> value to the stream. </summary>
public void Write(byte[] b)
{
Trace("--Wrote byte array of length {0}", b.Length);
ab.Append(b);
}
/// <summary> Write the specified number of bytes to the stream, starting at the specified offset in the input <c>byte[]</c>. </summary>
/// <param name="b">The input data to be written.</param>
/// <param name="offset">The offset into the inout byte[] to start writing bytes from.</param>
/// <param name="count">The number of bytes to be written.</param>
public void Write(byte[] b, int offset, int count)
{
if (count <= 0)
{
return;
}
Trace("--Wrote byte array of length {0}", count);
if ((offset == 0) && (count == b.Length))
{
Write(b);
}
else
{
var temp = new byte[count];
Buffer.BlockCopy(b, offset, temp, 0, count);
Write(temp);
}
}
/// <summary> Write a <c>Int16[]</c> value to the stream. </summary>
public void Write(short[] i)
{
Trace("--Wrote short array of length {0}", i.Length);
ab.Append(i);
}
/// <summary> Write a <c>Int32[]</c> value to the stream. </summary>
public void Write(int[] i)
{
Trace("--Wrote short array of length {0}", i.Length);
ab.Append(i);
}
/// <summary> Write a <c>Int64[]</c> value to the stream. </summary>
public void Write(long[] l)
{
Trace("--Wrote long array of length {0}", l.Length);
ab.Append(l);
}
/// <summary> Write a <c>UInt16[]</c> value to the stream. </summary>
public void Write(ushort[] i)
{
Trace("--Wrote ushort array of length {0}", i.Length);
ab.Append(i);
}
/// <summary> Write a <c>UInt32[]</c> value to the stream. </summary>
public void Write(uint[] i)
{
Trace("--Wrote uint array of length {0}", i.Length);
ab.Append(i);
}
/// <summary> Write a <c>UInt64[]</c> value to the stream. </summary>
public void Write(ulong[] l)
{
Trace("--Wrote ulong array of length {0}", l.Length);
ab.Append(l);
}
/// <summary> Write a <c>sbyte[]</c> value to the stream. </summary>
public void Write(sbyte[] l)
{
Trace("--Wrote sbyte array of length {0}", l.Length);
ab.Append(l);
}
/// <summary> Write a <c>char[]</c> value to the stream. </summary>
public void Write(char[] l)
{
Trace("--Wrote char array of length {0}", l.Length);
ab.Append(l);
}
/// <summary> Write a <c>bool[]</c> value to the stream. </summary>
public void Write(bool[] l)
{
Trace("--Wrote bool array of length {0}", l.Length);
ab.Append(l);
}
/// <summary> Write a <c>double[]</c> value to the stream. </summary>
public void Write(double[] d)
{
Trace("--Wrote double array of length {0}", d.Length);
ab.Append(d);
}
/// <summary> Write a <c>float[]</c> value to the stream. </summary>
public void Write(float[] f)
{
Trace("--Wrote float array of length {0}", f.Length);
ab.Append(f);
}
// Other simple types
/// <summary> Write a <c>CorrelationId</c> value to the stream. </summary>
internal void Write(CorrelationId id)
{
Write(id.ToByteArray());
}
/// <summary> Write a <c>IPEndPoint</c> value to the stream. </summary>
public void Write(IPEndPoint ep)
{
Write(ep.Address);
Write(ep.Port);
}
/// <summary> Write a <c>IPAddress</c> value to the stream. </summary>
public void Write(IPAddress ip)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
for (var i = 0; i < 12; i++)
{
Write((byte)0);
}
Write(ip.GetAddressBytes()); // IPv4 -- 4 bytes
}
else
{
Write(ip.GetAddressBytes()); // IPv6 -- 16 bytes
}
}
/// <summary> Write a <c>ActivationAddress</c> value to the stream. </summary>
internal void Write(ActivationAddress addr)
{
Write(addr.Silo ?? SiloAddress.Zero);
// GrainId must not be null
Write(addr.Grain);
Write(addr.Activation ?? ActivationId.Zero);
}
/// <summary> Write a <c>SiloAddress</c> value to the stream. </summary>
public void Write(SiloAddress addr)
{
Write(addr.Endpoint);
Write(addr.Generation);
}
internal void Write(UniqueKey key)
{
Write(key.N0);
Write(key.N1);
Write(key.TypeCodeData);
Write(key.KeyExt);
}
/// <summary> Write a <c>ActivationId</c> value to the stream. </summary>
internal void Write(ActivationId id)
{
Write(id.Key);
}
/// <summary> Write a <c>GrainId</c> value to the stream. </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
internal void Write(GrainId id)
{
Write(id.Key);
}
/// <summary> Write a <c>TimeSpan</c> value to the stream. </summary>
public void Write(TimeSpan ts)
{
Write(ts.Ticks);
}
/// <summary> Write a <c>DataTime</c> value to the stream. </summary>
public void Write(DateTime dt)
{
Write(dt.ToBinary());
}
/// <summary> Write a <c>Guid</c> value to the stream. </summary>
public void Write(Guid id)
{
Write(id.ToByteArray());
}
/// <summary>
/// Try to write a simple type (non-array) value to the stream.
/// </summary>
/// <param name="obj">Input object to be written to the output stream.</param>
/// <returns>Returns <c>true</c> if the value was successfully written to the output stream.</returns>
public bool TryWriteSimpleObject(object obj)
{
if (obj == null)
{
WriteNull();
return true;
}
Action<BinaryTokenStreamWriter, object> writer;
if (writers.TryGetValue(obj.GetType().TypeHandle, out writer))
{
writer(this, obj);
return true;
}
return false;
}
// General containers
/// <summary>
/// Write header for an <c>Array</c> to the output stream.
/// </summary>
/// <param name="a">Data object for which header should be written.</param>
/// <param name="expected">The most recent Expected Type currently active for this stream.</param>
internal void WriteArrayHeader(Array a, Type expected = null)
{
WriteTypeHeader(a.GetType(), expected);
for (var i = 0; i < a.Rank; i++)
{
ab.Append(a.GetLength(i));
}
}
// Back-references
internal void WriteReference(int offset)
{
Trace("Writing a reference to the object at offset {0}", offset);
ab.Append((byte) SerializationTokenType.Reference);
ab.Append(offset);
}
private StreamWriter trace;
[Conditional("TRACE_SERIALIZATION")]
private void Trace(string format, params object[] args)
{
if (trace == null)
{
var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks);
Console.WriteLine("Opening trace file at '{0}'", path);
trace = File.CreateText(path);
}
trace.Write(format, args);
trace.WriteLine(" at offset {0}", CurrentOffset);
trace.Flush();
}
}
}
| |
using System;
using Csla;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// InvoiceLineItem (editable child object).<br/>
/// This is a generated <see cref="InvoiceLineItem"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="InvoiceLineCollection"/> collection.
/// </remarks>
[Serializable]
public partial class InvoiceLineItem : BusinessBase<InvoiceLineItem>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="InvoiceLineId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<Guid> InvoiceLineIdProperty = RegisterProperty<Guid>(p => p.InvoiceLineId, "Invoice Line Id");
/// <summary>
/// Gets or sets the Invoice Line Id.
/// </summary>
/// <value>The Invoice Line Id.</value>
public Guid InvoiceLineId
{
get { return GetProperty(InvoiceLineIdProperty); }
set { SetProperty(InvoiceLineIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="ProductId"/> property.
/// </summary>
public static readonly PropertyInfo<Guid> ProductIdProperty = RegisterProperty<Guid>(p => p.ProductId, "Product Id");
/// <summary>
/// Gets or sets the Product Id.
/// </summary>
/// <value>The Product Id.</value>
public Guid ProductId
{
get { return GetProperty(ProductIdProperty); }
set { SetProperty(ProductIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Cost"/> property.
/// </summary>
public static readonly PropertyInfo<decimal> CostProperty = RegisterProperty<decimal>(p => p.Cost, "Cost");
/// <summary>
/// Gets or sets the Cost.
/// </summary>
/// <value>The Cost.</value>
public decimal Cost
{
get { return GetProperty(CostProperty); }
set { SetProperty(CostProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="PercentDiscount"/> property.
/// </summary>
public static readonly PropertyInfo<byte> PercentDiscountProperty = RegisterProperty<byte>(p => p.PercentDiscount, "Percent Discount");
/// <summary>
/// Gets or sets the Percent Discount.
/// </summary>
/// <value>The Percent Discount.</value>
public byte PercentDiscount
{
get { return GetProperty(PercentDiscountProperty); }
set { SetProperty(PercentDiscountProperty, value); }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="InvoiceLineItem"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public InvoiceLineItem()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="InvoiceLineItem"/> object properties.
/// </summary>
[RunLocal]
protected override void Child_Create()
{
LoadProperty(InvoiceLineIdProperty, Guid.NewGuid());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="InvoiceLineItem"/> object from the given <see cref="InvoiceLineItemDto"/>.
/// </summary>
/// <param name="data">The InvoiceLineItemDto to use.</param>
private void Child_Fetch(InvoiceLineItemDto data)
{
// Value properties
LoadProperty(InvoiceLineIdProperty, data.InvoiceLineId);
LoadProperty(ProductIdProperty, data.ProductId);
LoadProperty(CostProperty, data.Cost);
LoadProperty(PercentDiscountProperty, data.PercentDiscount);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Inserts a new <see cref="InvoiceLineItem"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(InvoiceEdit parent)
{
var dto = new InvoiceLineItemDto();
dto.Parent_InvoiceId = parent.InvoiceId;
dto.InvoiceLineId = InvoiceLineId;
dto.ProductId = ProductId;
dto.Cost = Cost;
dto.PercentDiscount = PercentDiscount;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IInvoiceLineItemDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="InvoiceLineItem"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new InvoiceLineItemDto();
dto.InvoiceLineId = InvoiceLineId;
dto.ProductId = ProductId;
dto.Cost = Cost;
dto.PercentDiscount = PercentDiscount;
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IInvoiceLineItemDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="InvoiceLineItem"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IInvoiceLineItemDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(InvoiceLineIdProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <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.Linq;
using System.Reflection;
using FluentAssertions.Common;
using FluentAssertions.Primitives;
using FluentAssertions.Types;
#if !OLD_MSTEST
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
#endif
namespace FluentAssertions.Specs
{
[TestClass]
public class TypeAssertionSpecs
{
#region Be
[TestMethod]
public void When_type_is_equal_to_the_same_type_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type sameType = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be(sameType);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_equal_to_another_type_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type differentType = typeof (ClassWithoutAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be(differentType);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_type_is_equal_to_another_type_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type differentType = typeof (ClassWithoutAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be(differentType, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>().WithMessage(
"Expected type to be FluentAssertions.Specs.ClassWithoutAttribute" +
" because we want to test the error message, but found FluentAssertions.Specs.ClassWithAttribute.");
}
[TestMethod]
public void When_asserting_equality_of_a_type_but_the_type_is_null_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type nullType = null;
Type someType = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
nullType.Should().Be(someType, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>().WithMessage(
"Expected type to be FluentAssertions.Specs.ClassWithAttribute" +
" because we want to test the error message, but found <null>.");
}
[TestMethod]
public void When_asserting_equality_of_a_type_with_null_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type someType = typeof (ClassWithAttribute);
Type nullType = null;
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
someType.Should().Be(nullType, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>().WithMessage(
"Expected type to be <null>" +
" because we want to test the error message, but found FluentAssertions.Specs.ClassWithAttribute.");
}
[TestMethod]
public void When_type_is_equal_to_same_type_from_different_assembly_it_fails_with_assembly_qualified_name
()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
#pragma warning disable 436 // disable the warning on conflicting types, as this is the intention for the spec
Type typeFromThisAssembly = typeof (ObjectAssertions);
#if !WINRT && !WINDOWS_PHONE_APP && !CORE_CLR
Type typeFromOtherAssembly =
typeof (TypeAssertions).Assembly.GetType("FluentAssertions.Primitives.ObjectAssertions");
#else
Type typeFromOtherAssembly =
Type.GetType("FluentAssertions.Primitives.ObjectAssertions,FluentAssertions.Core");
#endif
#pragma warning restore 436
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeFromThisAssembly.Should().Be(typeFromOtherAssembly, "because we want to test the error {0}",
"message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
const string expectedMessage =
"Expected type to be [FluentAssertions.Primitives.ObjectAssertions, FluentAssertions*]" +
" because we want to test the error message, but found " +
"[FluentAssertions.Primitives.ObjectAssertions, FluentAssertions*].";
act.ShouldThrow<AssertFailedException>().WithMessage(expectedMessage);
}
[TestMethod]
public void When_type_is_equal_to_the_same_type_using_generics_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be<ClassWithAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_equal_to_another_type_using_generics_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be<ClassWithoutAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_type_is_equal_to_another_type_using_generics_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Be<ClassWithoutAttribute>("because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected type to be FluentAssertions.Specs.ClassWithoutAttribute because we want to test " +
"the error message, but found FluentAssertions.Specs.ClassWithAttribute.");
}
#endregion
#region NotBe
[TestMethod]
public void When_type_is_not_equal_to_the_another_type_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type otherType = typeof (ClassWithoutAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe(otherType);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_not_equal_to_the_same_type_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type sameType = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe(sameType);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_type_is_not_equal_to_the_same_type_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
Type sameType = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe(sameType, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type not to be [FluentAssertions.Specs.ClassWithAttribute*]" +
" because we want to test the error message, but it is.");
}
[TestMethod]
public void When_type_is_not_equal_to_another_type_using_generics_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe<ClassWithoutAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_not_equal_to_the_same_type_using_generics_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe<ClassWithAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_type_is_not_equal_to_the_same_type_using_generics_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotBe<ClassWithAttribute>("because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected type not to be [FluentAssertions.Specs.ClassWithAttribute*] because we want to test " +
"the error message, but it is.");
}
#endregion
#region BeAssignableTo
[TestMethod]
public void When_asserting_an_object_is_assignable_its_own_type_it_succeeds()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange / Act / Assert
//-----------------------------------------------------------------------------------------------------------
typeof (DummyImplementingClass).Should().BeAssignableTo<DummyImplementingClass>();
}
[TestMethod]
public void When_asserting_an_object_is_assignable_to_its_base_type_it_succeeds()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange / Act / Assert
//-----------------------------------------------------------------------------------------------------------
typeof (DummyImplementingClass).Should().BeAssignableTo<DummyBaseClass>();
}
[TestMethod]
public void When_asserting_an_object_is_assignable_to_an_implemented_interface_type_it_succeeds()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange / Act / Assert
//-----------------------------------------------------------------------------------------------------------
typeof (DummyImplementingClass).Should().BeAssignableTo<IDisposable>();
}
[TestMethod]
public void When_asserting_an_object_is_assignable_to_an_unrelated_type_it_fails_with_a_a_useful_message()
{
//-----------------------------------------------------------------------------------------------------------
// Arrange
//-----------------------------------------------------------------------------------------------------------
Type someType = typeof (DummyImplementingClass);
//-----------------------------------------------------------------------------------------------------------
// Act / Assert
//-----------------------------------------------------------------------------------------------------------
someType.Invoking(
x => x.Should().BeAssignableTo<DateTime>("because we want to test the failure {0}", "message"))
.ShouldThrow<AssertFailedException>()
.WithMessage(string.Format(
"Expected type {0} to be assignable to {1} because we want to test the failure message, but it is not",
typeof (DummyImplementingClass), typeof (DateTime)));
}
#endregion
#region BeDerivedFrom
[TestMethod]
public void When_asserting_a_type_is_derived_from_its_base_class_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(DummyImplementingClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().BeDerivedFrom(typeof(DummyBaseClass));
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_is_derived_from_an_unrelated_class_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(DummyBaseClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().BeDerivedFrom(typeof(ClassWithMembers), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.DummyBaseClass to be derived from " +
"FluentAssertions.Specs.ClassWithMembers because we want to test the error message, but it is not.");
}
[TestMethod]
public void When_asserting_a_type_is_derived_from_an_interface_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatImplementsInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().BeDerivedFrom(typeof(IDummyInterface), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<ArgumentException>()
.WithMessage("Must not be an interface Type.\r\nParameter name: baseType");
}
#endregion
#region BeDerivedFromOfT
[TestMethod]
public void When_asserting_a_type_is_DerivedFromOfT_its_base_class_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(DummyImplementingClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().BeDerivedFrom<DummyBaseClass>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region BeDecoratedWith
[TestMethod]
public void When_type_is_decorated_with_expected_attribute_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type typeWithAttribute = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeWithAttribute.Should().BeDecoratedWith<DummyClassAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_not_decorated_with_expected_attribute_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type typeWithoutAttribute = typeof (ClassWithoutAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeWithoutAttribute.Should().BeDecoratedWith<DummyClassAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>();
}
[TestMethod]
public void When_type_is_not_decorated_with_expected_attribute_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type typeWithoutAttribute = typeof (ClassWithoutAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeWithoutAttribute.Should().BeDecoratedWith<DummyClassAttribute>(
"because we want to test the error {0}",
"message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassWithoutAttribute to be decorated with " +
"FluentAssertions.Specs.DummyClassAttribute because we want to test the error message, but the attribute " +
"was not found.");
}
[TestMethod]
public void When_type_is_decorated_with_expected_attribute_with_the_expected_properties_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type typeWithAttribute = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeWithAttribute.Should()
.BeDecoratedWith<DummyClassAttribute>(a => ((a.Name == "Expected") && a.IsEnabled));
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_type_is_decorated_with_expected_attribute_that_has_an_unexpected_property_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type typeWithAttribute = typeof (ClassWithAttribute);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
typeWithAttribute.Should()
.BeDecoratedWith<DummyClassAttribute>(a => ((a.Name == "Unexpected") && a.IsEnabled));
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassWithAttribute to be decorated with " +
"FluentAssertions.Specs.DummyClassAttribute that matches ((a.Name == \"Unexpected\")*a.IsEnabled), " +
"but no matching attribute was found.");
}
[TestMethod]
public void When_asserting_a_selection_of_decorated_types_is_decorated_with_an_attribute_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var types = new TypeSelector(new[]
{
typeof (ClassWithAttribute)
});
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
types.Should().BeDecoratedWith<DummyClassAttribute>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_selection_of_non_decorated_types_is_decorated_with_an_attribute_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var types = new TypeSelector(new[]
{
typeof (ClassWithAttribute),
typeof (ClassWithoutAttribute),
typeof (OtherClassWithoutAttribute)
});
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
types.Should().BeDecoratedWith<DummyClassAttribute>("because we do");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected all types to be decorated with FluentAssertions.Specs.DummyClassAttribute" +
" because we do, but the attribute was not found on the following types:\r\n" +
"FluentAssertions.Specs.ClassWithoutAttribute\r\n" +
"FluentAssertions.Specs.OtherClassWithoutAttribute");
}
[TestMethod]
public void When_asserting_a_selection_of_types_with_unexpected_attribute_property_it_fails()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var types = new TypeSelector(new[]
{
typeof (ClassWithAttribute),
typeof (ClassWithoutAttribute),
typeof (OtherClassWithoutAttribute)
});
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
types.Should()
.BeDecoratedWith<DummyClassAttribute>(a => ((a.Name == "Expected") && a.IsEnabled), "because we do");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected all types to be decorated with FluentAssertions.Specs.DummyClassAttribute" +
" that matches ((a.Name == \"Expected\")*a.IsEnabled) because we do," +
" but no matching attribute was found on the following types:\r\n" +
"FluentAssertions.Specs.ClassWithoutAttribute\r\n" +
"FluentAssertions.Specs.OtherClassWithoutAttribute");
}
#endregion
#region Implement
[TestMethod]
public void When_asserting_a_type_implements_an_interface_which_it_does_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof (ClassThatImplementsInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Implement(typeof (IDummyInterface));
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_implement_an_interface_which_it_does_then_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof (ClassThatDoesNotImplementInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Implement(typeof (IDummyInterface), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassThatDoesNotImplementInterface to implement " +
"interface FluentAssertions.Specs.IDummyInterface because we want to test the error message, " +
"but it does not.");
}
[TestMethod]
public void When_asserting_a_type_implements_a_NonInterface_type_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatDoesNotImplementInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Implement(typeof(DateTime), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<ArgumentException>()
.WithMessage("Must be an interface Type.\r\nParameter name: interfaceType");
}
#endregion
#region ImplementOfT
[TestMethod]
public void When_asserting_a_type_implementsOfT_an_interface_which_it_does_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatImplementsInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().Implement<IDummyInterface>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region NotImplement
[TestMethod]
public void When_asserting_a_type_does_not_implement_an_interface_which_it_does_not_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatDoesNotImplementInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotImplement(typeof(IDummyInterface));
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_implements_an_interface_which_it_does_not_then_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatImplementsInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotImplement(typeof(IDummyInterface), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassThatImplementsInterface to not implement interface " +
"FluentAssertions.Specs.IDummyInterface because we want to test the error message, but it does.");
}
[TestMethod]
public void When_asserting_a_type_does_not_implement_a_NonInterface_type_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatDoesNotImplementInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotImplement(typeof(DateTime), "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<ArgumentException>()
.WithMessage("Must be an interface Type.\r\nParameter name: interfaceType");
}
#endregion
#region NotImplementOfT
[TestMethod]
public void When_asserting_a_type_does_not_implementOfT_an_interface_which_it_does_not_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassThatDoesNotImplementInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotImplement<IDummyInterface>();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region HaveProperty
[TestMethod]
public void When_asserting_a_type_has_a_property_which_it_does_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveProperty(typeof(string), "PrivateWriteProtectedReadProperty")
.Which.Should()
.BeWritable(CSharpAccessModifier.Private)
.And.BeReadable(CSharpAccessModifier.Protected);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_has_a_property_which_it_does_not_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithNoMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveProperty(typeof(string), "PublicProperty", "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected String FluentAssertions.Specs.ClassWithNoMembers.PublicProperty to exist because we want to " +
"test the error message, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_has_a_property_which_it_has_with_a_different_type_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveProperty(typeof(int), "PrivateWriteProtectedReadProperty", "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected String FluentAssertions.Specs.ClassWithMembers.PrivateWriteProtectedReadProperty to be of type System.Int32 because we want to test the error message, but it is not.");
}
#endregion
#region HavePropertyOfT
[TestMethod]
public void When_asserting_a_type_has_a_propertyOfT_which_it_does_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveProperty<string>("PrivateWriteProtectedReadProperty")
.Which.Should()
.BeWritable(CSharpAccessModifier.Private)
.And.BeReadable(CSharpAccessModifier.Protected);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region NotHaveProperty
[TestMethod]
public void When_asserting_a_type_does_not_have_a_property_which_it_does_not_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof (ClassWithoutMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveProperty("Property");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_have_a_property_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof (ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveProperty("PrivateWriteProtectedReadProperty", "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected String FluentAssertions.Specs.ClassWithMembers.PrivateWriteProtectedReadProperty to not exist because we want to " +
"test the error message, but it does.");
}
#endregion
#region HaveExplicitProperty
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_property_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof (IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty(interfaceType, "ExplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_property_which_it_implements_implicitly_and_explicitly_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty(interfaceType, "ExplicitImplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_property_which_it_implements_implicitly_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty(interfaceType, "ImplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ImplicitStringProperty, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_property_which_it_does_not_implement_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty(interfaceType, "NonExistantProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.NonExistantProperty, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_property_from_an_unimplemented_interface_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IDummyInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty(interfaceType, "NonExistantProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " +
"FluentAssertions.Specs.IDummyInterface, but it does not.");
}
#endregion
#region HaveExplicitPropertyOfT
[TestMethod]
public void When_asserting_a_type_explicitlyOfT_implements_a_property_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitProperty<IExplicitInterface>("ExplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region NotHaveExplicitProperty
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty(interfaceType, "ExplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitStringProperty, but it does.");
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_implements_implicitly_and_explicitly_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty(interfaceType, "ExplicitImplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitImplicitStringProperty, but it does.");
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_implements_implicitly_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty(interfaceType, "ImplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_property_which_it_does_not_implement_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty(interfaceType, "NonExistantProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_property_from_an_unimplemented_interface_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IDummyInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty(interfaceType, "NonExistantProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " +
"FluentAssertions.Specs.IDummyInterface, but it does not.");
}
#endregion
#region NotHaveExplicitPropertyOfT
[TestMethod]
public void When_asserting_a_type_does_not_explicitlyOfT_implement_a_property_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitProperty<IExplicitInterface>("ExplicitStringProperty");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitStringProperty, but it does.");
}
#endregion
#region HaveExplicitMethod
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_method_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod(interfaceType, "ExplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_method_which_it_implements_implicitly_and_explicitly_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod(interfaceType, "ExplicitImplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_method_which_it_implements_implicitly_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod(interfaceType, "ImplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ImplicitMethod, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_method_which_it_does_not_implement_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod(interfaceType, "NonExistantMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.NonExistantMethod, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_explicitly_implements_a_method_from_an_unimplemented_interface_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IDummyInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod(interfaceType, "NonExistantProperty", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " +
"FluentAssertions.Specs.IDummyInterface, but it does not.");
}
#endregion
#region HaveExplicitMethodOfT
[TestMethod]
public void When_asserting_a_type_explicitly_implementsOfT_a_method_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveExplicitMethod<IExplicitInterface>("ExplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region NotHaveExplicitMethod
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod(interfaceType, "ExplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitMethod, but it does.");
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_implements_implicitly_and_explicitly_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod(interfaceType, "ExplicitImplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitImplicitMethod, but it does.");
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_implements_implicitly_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod(interfaceType, "ImplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_method_which_it_does_not_implement_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IExplicitInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod(interfaceType, "NonExistantMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implement_a_method_from_an_unimplemented_interface_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
var interfaceType = typeof(IDummyInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod(interfaceType, "NonExistantMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type FluentAssertions.Specs.ClassExplicitlyImplementingInterface to implement interface " +
"FluentAssertions.Specs.IDummyInterface, but it does not.");
}
#endregion
#region NotHaveExplicitMethodOfT
[TestMethod]
public void When_asserting_a_type_does_not_explicitly_implementOfT_a_method_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassExplicitlyImplementingInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.NotHaveExplicitMethod< IExplicitInterface>("ExplicitMethod", Enumerable.Empty<Type>());
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected FluentAssertions.Specs.ClassExplicitlyImplementingInterface to not explicitly implement " +
"FluentAssertions.Specs.IExplicitInterface.ExplicitMethod, but it does.");
}
#endregion
#region HaveIndexer
[TestMethod]
public void When_asserting_a_type_has_an_indexer_which_it_does_then_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveIndexer(typeof(string), new[] { typeof(string) })
.Which.Should()
.BeWritable(CSharpAccessModifier.Internal)
.And.BeReadable(CSharpAccessModifier.Private);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_has_an_indexer_which_it_does_not_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithNoMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveIndexer(typeof(string), new [] {typeof(int), typeof(Type)}, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected String FluentAssertions.Specs.ClassWithNoMembers[System.Int32, System.Type] to exist because we want to test the error" +
" message, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_has_an_indexer_with_different_parameters_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveIndexer(typeof(string), new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected String FluentAssertions.Specs.ClassWithMembers[System.Int32, System.Type] to exist because we want to test the error" +
" message, but it does not.");
}
#endregion
#region NotHaveIndexer
[TestMethod]
public void When_asserting_a_type_does_not_have_an_indexer_which_it_does_not_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithoutMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveIndexer(new [] {typeof(string)});
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_have_an_indexer_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveIndexer(new [] {typeof(string)}, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected indexer FluentAssertions.Specs.ClassWithMembers[System.String] to not exist because we want to " +
"test the error message, but it does.");
}
#endregion
#region HaveConstructor
[TestMethod]
public void When_asserting_a_type_has_a_constructor_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveConstructor(new Type[] { typeof(string) })
.Which.Should()
.HaveAccessModifier(CSharpAccessModifier.Private);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_has_a_constructor_which_it_does_not_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithNoMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveConstructor(new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected constructor FluentAssertions.Specs.ClassWithNoMembers(System.Int32, System.Type) to exist because " +
"we want to test the error message, but it does not.");
}
#endregion
#region HaveDefaultConstructor
[TestMethod]
public void When_asserting_a_type_has_a_default_constructor_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveDefaultConstructor()
.Which.Should()
.HaveAccessModifier(CSharpAccessModifier.ProtectedInternal);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_has_a_default_constructor_which_it_does_not_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithNoMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveDefaultConstructor("because the compiler generates one even if not explicitly defined.")
.Which.Should()
.HaveAccessModifier(CSharpAccessModifier.Public);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
#endregion
#region HaveMethod
[TestMethod]
public void When_asserting_a_type_has_a_method_which_it_does_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should()
.HaveMethod("VoidMethod", new Type[] { })
.Which.Should()
.HaveAccessModifier(CSharpAccessModifier.Private)
.And.ReturnVoid();
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_has_a_method_which_it_does_not_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithNoMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveMethod("NonExistantMethod", new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected method FluentAssertions.Specs.ClassWithNoMembers.NonExistantMethod(System.Int32, System.Type) to exist " +
"because we want to test the error message, but it does not.");
}
[TestMethod]
public void When_asserting_a_type_has_a_method_with_different_parameter_types_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveMethod("VoidMethod", new[] { typeof(int), typeof(Type) }, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected method FluentAssertions.Specs.ClassWithMembers.VoidMethod(System.Int32, System.Type) to exist " +
"because we want to test the error message, but it does not.");
}
#endregion
#region NotHaveMethod
[TestMethod]
public void When_asserting_a_type_does_not_have_a_method_which_it_does_not_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithoutMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveMethod("NonExistantMethod", new Type[] {});
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_have_a_method_which_it_has_with_different_parameter_types_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveMethod("VoidMethod", new [] { typeof(int) });
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_type_does_not_have_that_method_which_it_does_it_fails_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
var type = typeof(ClassWithMembers);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().NotHaveMethod("VoidMethod", new Type[] {}, "because we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage(
"Expected method Void FluentAssertions.Specs.ClassWithMembers.VoidMethod() to not exist because we want to " +
"test the error message, but it does.");
}
#endregion
#region HaveAccessModifier
[TestMethod]
public void When_asserting_a_public_type_is_public_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(IPublicInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Public);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_public_member_is_not_public_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(IPublicInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type
.Should()
.HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type IPublicInterface to be Internal because we want to test the error message, but it " +
"is Public.");
}
[TestMethod]
public void When_asserting_an_internal_type_is_internal_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(InternalClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Internal);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_an_internal_type_is_not_internal_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(InternalClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal, "because we want to test the" +
" error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type InternalClass to be ProtectedInternal because we want to test the error message, " +
"but it is Internal.");
}
[TestMethod]
public void When_asserting_a_nested_private_type_is_private_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
#if !WINRT && !WINDOWS_PHONE_APP
Type type = typeof(Nested).GetNestedType("PrivateClass", BindingFlags.NonPublic | BindingFlags.Instance);
#else
Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "PrivateClass").AsType();
#endif
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Private);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_nested_private_type_is_not_private_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
#if !WINRT && !WINDOWS_PHONE_APP
Type type = typeof(Nested).GetNestedType("PrivateClass", BindingFlags.NonPublic | BindingFlags.Instance);
#else
Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "PrivateClass").AsType();
#endif
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Protected, "we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type PrivateClass to be Protected because we want to test the error message, but it " +
"is Private.");
}
[TestMethod]
public void When_asserting_a_nested_protected_type_is_protected_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
#if !WINRT && !WINDOWS_PHONE_APP
Type type = typeof(Nested).GetNestedType("ProtectedEnum", BindingFlags.NonPublic | BindingFlags.Instance);
#else
Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "ProtectedEnum").AsType();
#endif
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Protected);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_nested_protected_type_is_not_protected_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
#if !WINRT && !WINDOWS_PHONE_APP
Type type = typeof(Nested).GetNestedType("ProtectedEnum", BindingFlags.NonPublic | BindingFlags.Instance);
#else
Type type = typeof(Nested).GetTypeInfo().DeclaredNestedTypes.First(t => t.Name == "ProtectedEnum").AsType();
#endif
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Public);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type ProtectedEnum to be Public, but it is Protected.");
}
[TestMethod]
public void When_asserting_a_nested_public_type_is_public_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.IPublicInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Public);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_nested_public_member_is_not_public_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.IPublicInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type
.Should()
.HaveAccessModifier(CSharpAccessModifier.Internal, "we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type IPublicInterface to be Internal because we want to test the error message, " +
"but it is Public.");
}
[TestMethod]
public void When_asserting_a_nested_internal_type_is_internal_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.InternalClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Internal);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_nested_internal_type_is_not_internal_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.InternalClass);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal, "because we want to test the" +
" error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type InternalClass to be ProtectedInternal because we want to test the error message, " +
"but it is Internal.");
}
[TestMethod]
public void When_asserting_a_nested_protected_internal_member_is_protected_internal_it_succeeds()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.IProtectedInternalInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.ProtectedInternal);
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldNotThrow();
}
[TestMethod]
public void When_asserting_a_nested_protected_internal_member_is_not_protected_internal_it_throws_with_a_useful_message()
{
//-------------------------------------------------------------------------------------------------------------------
// Arrange
//-------------------------------------------------------------------------------------------------------------------
Type type = typeof(Nested.IProtectedInternalInterface);
//-------------------------------------------------------------------------------------------------------------------
// Act
//-------------------------------------------------------------------------------------------------------------------
Action act = () =>
type.Should().HaveAccessModifier(CSharpAccessModifier.Private, "we want to test the error {0}", "message");
//-------------------------------------------------------------------------------------------------------------------
// Assert
//-------------------------------------------------------------------------------------------------------------------
act.ShouldThrow<AssertFailedException>()
.WithMessage("Expected type IProtectedInternalInterface to be Private because we want to test the error " +
"message, but it is ProtectedInternal.");
}
#endregion
}
#region Internal classes used in unit tests
[DummyClass("Expected", true)]
public class ClassWithAttribute
{
}
public class ClassWithoutAttribute
{
}
public class OtherClassWithoutAttribute
{
}
[AttributeUsage(AttributeTargets.Class)]
public class DummyClassAttribute : Attribute
{
public string Name { get; set; }
public bool IsEnabled { get; set; }
public DummyClassAttribute(string name, bool isEnabled)
{
Name = name;
IsEnabled = isEnabled;
}
}
public interface IDummyInterface
{
}
public class ClassThatImplementsInterface : IDummyInterface
{
}
public class ClassThatDoesNotImplementInterface
{
}
public class ClassWithMembers
{
protected internal ClassWithMembers() { }
private ClassWithMembers(String overload) { }
protected string PrivateWriteProtectedReadProperty { get { return null; } private set { } }
internal string this[string str] { private get { return str; } set { } }
protected internal string this[int i] { get { return i.ToString(); } private set { } }
private void VoidMethod() { }
private void VoidMethod(string overload) { }
}
public class ClassExplicitlyImplementingInterface : IExplicitInterface
{
public string ImplicitStringProperty { get { return null; } private set { } }
string IExplicitInterface.ExplicitStringProperty { set { } }
public string ExplicitImplicitStringProperty { get; set; }
string IExplicitInterface.ExplicitImplicitStringProperty { get; set; }
public void ImplicitMethod() { }
public void ImplicitMethod(string overload) { }
void IExplicitInterface.ExplicitMethod() { }
void IExplicitInterface.ExplicitMethod(string overload) { }
public void ExplicitImplicitMethod() { }
public void ExplicitImplicitMethod(string overload) { }
void IExplicitInterface.ExplicitImplicitMethod() { }
void IExplicitInterface.ExplicitImplicitMethod(string overload) { }
}
public interface IExplicitInterface
{
string ImplicitStringProperty { get; }
string ExplicitStringProperty { set; }
string ExplicitImplicitStringProperty { get; set; }
void ImplicitMethod();
void ImplicitMethod(string overload);
void ExplicitMethod();
void ExplicitMethod(string overload);
void ExplicitImplicitMethod();
void ExplicitImplicitMethod(string overload);
}
public class ClassWithoutMembers { }
public interface IPublicInterface { }
internal class InternalClass { }
class Nested
{
class PrivateClass { }
protected enum ProtectedEnum { }
public interface IPublicInterface { }
internal class InternalClass { }
protected internal interface IProtectedInternalInterface { }
}
#endregion
}
namespace FluentAssertions.Primitives
{
#pragma warning disable 436 // disable the warning on conflicting types, as this is the intention for the spec
/// <summary>
/// A class that intentionally has the exact same name and namespace as the ObjectAssertions from the FluentAssertions
/// assembly. This class is used to test the behavior of comparisons on such types.
/// </summary>
internal class ObjectAssertions
{
}
#pragma warning restore 436
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio.Shell;
using MSBuild = Microsoft.Build.Evaluation;
namespace Microsoft.PythonTools.Interpreter {
/// <summary>
/// MSBuild factory provider.
///
/// The MSBuild factory provider consuems the relevant IProjectContextProvider to find locations
/// for MSBuild projects. The IProjectContextProvider can provide either MSBuild.Project items
/// or strings which are paths to MSBuild project files.
///
/// The MSBuild interpreter factory provider ID is "MSBuild". The interpreter IDs are in the
/// format: id_in_project_file;path_to_project_file
///
///
/// </summary>
[InterpreterFactoryId(MSBuildProviderName)]
[Export(typeof(IPythonInterpreterFactoryProvider))]
[PartCreationPolicy(CreationPolicy.Shared)]
sealed class MSBuildProjectInterpreterFactoryProvider : IPythonInterpreterFactoryProvider, IDisposable {
private readonly IServiceProvider _site;
private readonly Dictionary<string, ProjectInfo> _projects = new Dictionary<string, ProjectInfo>();
private readonly Lazy<IInterpreterLog>[] _loggers;
private readonly Lazy<IProjectContextProvider>[] _contextProviders;
private readonly Lazy<IPythonInterpreterFactoryProvider, Dictionary<string, object>>[] _factoryProviders;
public const string MSBuildProviderName = "MSBuild";
private const string InterpreterFactoryIdMetadata = "InterpreterFactoryId";
private bool _initialized;
private bool _skipMSBuild;
private static readonly Regex InterpreterIdRegex = new Regex(
@"MSBuild\|(?<id>.+?)\|(?<moniker>.+)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant
);
[ImportingConstructor]
public MSBuildProjectInterpreterFactoryProvider(
[ImportMany]Lazy<IProjectContextProvider>[] contextProviders,
[ImportMany]Lazy<IPythonInterpreterFactoryProvider, Dictionary<string, object>>[] factoryProviders,
[ImportMany]Lazy<IInterpreterLog>[] loggers,
[Import(typeof(SVsServiceProvider), AllowDefault = true)] IServiceProvider site = null) {
_site = site;
_factoryProviders = factoryProviders;
_loggers = loggers;
_contextProviders = contextProviders;
}
private void EnsureInitialized() {
if (!_initialized) {
_initialized = true;
foreach (var provider in _contextProviders) {
IProjectContextProvider providerValue;
try {
providerValue = provider.Value;
} catch (CompositionException ce) {
Log("Failed to get IProjectContextProvider {0}", ce);
continue;
}
providerValue.ProjectsChanaged += Provider_ProjectContextsChanged;
providerValue.ProjectChanged += Provider_ProjectChanged;
Provider_ProjectContextsChanged(providerValue, EventArgs.Empty);
}
}
}
private void Provider_ProjectChanged(object sender, ProjectChangedEventArgs e) {
string filename = e.Project as string;
if (filename == null) {
var proj = e.Project as MSBuild.Project;
if (proj != null) {
filename = proj.FullPath;
}
}
ProjectInfo projInfo;
if (filename != null && _projects.TryGetValue(filename, out projInfo)) {
if (DiscoverInterpreters(projInfo)) {
OnInterpreterFactoriesChanged();
}
}
}
public event EventHandler InterpreterFactoriesChanged;
public IEnumerable<InterpreterConfiguration> GetInterpreterConfigurations() {
EnsureInitialized();
foreach (var project in _projects) {
if (project.Value.Factories != null) {
foreach (var fact in project.Value.Factories) {
yield return fact.Value.Config;
}
}
}
}
public IPythonInterpreterFactory GetInterpreterFactory(string id) {
EnsureInitialized();
var m = InterpreterIdRegex.Match(id);
if (!m.Success) {
return null;
}
// see if the project is loaded
ProjectInfo project;
FactoryInfo factInfo;
if (_projects.TryGetValue(m.Groups["moniker"].Value, out project) &&
project.Factories != null &&
project.Factories.TryGetValue(id, out factInfo)) {
return factInfo.Factory;
}
return null;
}
public object GetProperty(string id, string propName) {
Match m;
string moniker;
switch (propName) {
case "ProjectMoniker":
m = InterpreterIdRegex.Match(id);
if (m.Success && PathUtils.IsValidPath(moniker = m.Groups["moniker"].Value)) {
return moniker;
}
break;
case PythonRegistrySearch.CompanyPropertyKey:
m = InterpreterIdRegex.Match(id);
if (m.Success && PathUtils.IsValidPath(moniker = m.Groups["moniker"].Value)) {
try {
return Path.GetFileNameWithoutExtension(moniker);
} catch (ArgumentException) {
return PathUtils.GetFileOrDirectoryName(moniker);
}
}
break;
}
return null;
}
public static string GetInterpreterId(string file, string id) {
return String.Join("|", MSBuildProviderName, id, file);
}
public static string GetProjectRelativeId(string file, string id) {
var m = InterpreterIdRegex.Match(id);
if (m.Success && (m.Groups["moniker"].Value?.Equals(file, StringComparison.OrdinalIgnoreCase) ?? false)) {
return m.Groups["id"].Value;
}
return null;
}
private void HandleMSBuildProject(
object context,
IProjectContextProvider contextProvider,
HashSet<ProjectInfo> added,
HashSet<string> seen
) {
var projContext = context as MSBuild.Project;
if (projContext == null) {
var projectFile = context as string;
if (projectFile != null && projectFile.EndsWithOrdinal(".pyproj", ignoreCase: true)) {
projContext = new MSBuild.Project(projectFile);
}
}
if (projContext != null) {
if (!_projects.ContainsKey(projContext.FullPath)) {
var projInfo = new MSBuildProjectInfo(projContext, projContext.FullPath, contextProvider);
_projects[projContext.FullPath] = projInfo;
added.Add(projInfo);
}
seen.Add(projContext.FullPath);
}
}
private void Provider_ProjectContextsChanged(object sender, EventArgs e) {
var contextProvider = (IProjectContextProvider)sender;
bool discovered = false;
if (contextProvider != null) {
// Run through and and get the new interpreters to add...
HashSet<string> seen = new HashSet<string>();
HashSet<ProjectInfo> added = new HashSet<ProjectInfo>();
HashSet<ProjectInfo> removed = new HashSet<ProjectInfo>();
var contexts = contextProvider.Projects;
lock (_projects) {
foreach (var context in contextProvider.Projects) {
if (!_skipMSBuild) {
try {
HandleMSBuildProject(context, contextProvider, added, seen);
} catch (FileNotFoundException) {
_skipMSBuild = true;
}
}
var inMemory = context as InMemoryProject;
if (inMemory != null) {
if (!_projects.ContainsKey(inMemory.FullPath)) {
var projInfo = new InMemoryProjectInfo(inMemory, inMemory.FullPath, contextProvider);
_projects[inMemory.FullPath] = projInfo;
added.Add(projInfo);
}
seen.Add(inMemory.FullPath);
}
}
// Then remove any existing projects that are no longer there
var toRemove = _projects
.Where(x => x.Value.ContextProvider == contextProvider && !seen.Contains(x.Key))
.Select(x => x.Key)
.ToArray();
foreach (var projInfo in toRemove) {
var value = _projects[projInfo];
_projects.Remove(projInfo);
removed.Add(value);
value.Dispose();
}
}
// apply what we discovered without the projects lock...
foreach (var projInfo in added) {
discovered |= DiscoverInterpreters(projInfo);
}
foreach (var projInfo in removed) {
projInfo.Dispose();
if (projInfo.Factories.Count > 0) {
discovered = true;
}
}
}
if (discovered) {
OnInterpreterFactoriesChanged();
}
}
private void OnInterpreterFactoriesChanged() {
var evt = InterpreterFactoriesChanged;
if (evt != null) {
evt(this, EventArgs.Empty);
}
}
private void Log(string format, params object[] args) {
Log(String.Format(format, args));
}
private void Log(string msg) {
foreach (var logger in _loggers) {
IInterpreterLog loggerValue;
try {
loggerValue = logger.Value;
} catch (CompositionException) {
continue;
}
loggerValue.Log(msg);
}
}
/// <summary>
/// Call to find interpreters in the associated project. Separated from
/// the constructor to allow exceptions to be handled without causing
/// the project node to be invalid.
/// </summary>
private bool DiscoverInterpreters(ProjectInfo projectInfo) {
// <Interpreter Include="InterpreterDirectory">
// <Id>factoryProviderId;interpreterFactoryId</Id>
// <Version>...</Version>
// <InterpreterPath>...</InterpreterPath>
// <WindowsInterpreterPath>...</WindowsInterpreterPath>
// <PathEnvironmentVariable>...</PathEnvironmentVariable>
// <Description>...</Description>
// </Interpreter>
var projectHome = PathUtils.GetAbsoluteDirectoryPath(
Path.GetDirectoryName(projectInfo.FullPath),
projectInfo.GetPropertyValue("ProjectHome")
);
var factories = new Dictionary<string, FactoryInfo>();
foreach (var item in projectInfo.GetInterpreters()) {
// Errors in these options are fatal, so we set anyError and
// continue with the next entry.
var dir = GetValue(item, "EvaluatedInclude");
if (!PathUtils.IsValidPath(dir)) {
Log("Interpreter has invalid path: {0}", dir ?? "(null)");
continue;
}
dir = PathUtils.GetAbsoluteDirectoryPath(projectHome, dir);
var id = GetValue(item, MSBuildConstants.IdKey);
if (string.IsNullOrEmpty(id)) {
Log("Interpreter {0} has invalid value for '{1}': {2}", dir, MSBuildConstants.IdKey, id);
continue;
}
if (factories.ContainsKey(id)) {
Log("Interpreter {0} has a non-unique id: {1}", dir, id);
continue;
}
var verStr = GetValue(item, MSBuildConstants.VersionKey);
Version ver;
if (string.IsNullOrEmpty(verStr) || !Version.TryParse(verStr, out ver)) {
Log("Interpreter {0} has invalid value for '{1}': {2}", dir, MSBuildConstants.VersionKey, verStr);
continue;
}
// The rest of the options are non-fatal. We create an instance
// of NotFoundError with an amended description, which will
// allow the user to remove the entry from the project file
// later.
bool hasError = false;
var description = GetValue(item, MSBuildConstants.DescriptionKey);
if (string.IsNullOrEmpty(description)) {
description = PathUtils.CreateFriendlyDirectoryPath(projectHome, dir);
}
var path = GetValue(item, MSBuildConstants.InterpreterPathKey);
if (!PathUtils.IsValidPath(path)) {
Log("Interpreter {0} has invalid value for '{1}': {2}", dir, MSBuildConstants.InterpreterPathKey, path);
hasError = true;
} else if (!hasError) {
path = PathUtils.GetAbsoluteFilePath(dir, path);
}
var winPath = GetValue(item, MSBuildConstants.WindowsPathKey);
if (!PathUtils.IsValidPath(winPath)) {
Log("Interpreter {0} has invalid value for '{1}': {2}", dir, MSBuildConstants.WindowsPathKey, winPath);
hasError = true;
} else if (!hasError) {
winPath = PathUtils.GetAbsoluteFilePath(dir, winPath);
}
var pathVar = GetValue(item, MSBuildConstants.PathEnvVarKey);
if (string.IsNullOrEmpty(pathVar)) {
pathVar = "PYTHONPATH";
}
var arch = InterpreterArchitecture.TryParse(GetValue(item, MSBuildConstants.ArchitectureKey));
string fullId = GetInterpreterId(projectInfo.FullPath, id);
FactoryInfo info;
if (hasError) {
info = new ErrorFactoryInfo(fullId, ver, description, dir);
} else {
info = new ConfiguredFactoryInfo(this, new VisualStudioInterpreterConfiguration(
fullId,
description,
dir,
path,
winPath,
pathVar,
arch,
ver,
InterpreterUIMode.CannotBeDefault | InterpreterUIMode.CannotBeConfigured
));
}
MergeFactory(projectInfo, factories, info);
}
HashSet<FactoryInfo> previousFactories = new HashSet<FactoryInfo>();
if (projectInfo.Factories != null) {
previousFactories.UnionWith(projectInfo.Factories.Values);
}
HashSet<FactoryInfo> newFactories = new HashSet<FactoryInfo>(factories.Values);
bool anyChange = !newFactories.SetEquals(previousFactories);
if (anyChange || projectInfo.Factories == null) {
// Lock here mainly to ensure that any searches complete before
// we trigger the changed event.
lock (projectInfo) {
projectInfo.Factories = factories;
}
foreach (var removed in previousFactories.Except(newFactories)) {
projectInfo.ContextProvider.InterpreterUnloaded(
projectInfo.Context,
removed.Config
);
IDisposable disp = removed as IDisposable;
if (disp != null) {
disp.Dispose();
}
}
foreach (var added in newFactories.Except(previousFactories)) {
foreach (var factory in factories) {
projectInfo.ContextProvider.InterpreterLoaded(
projectInfo.Context,
factory.Value.Config
);
}
}
}
return anyChange;
}
private static void MergeFactory(ProjectInfo projectInfo, Dictionary<string, FactoryInfo> factories, FactoryInfo info) {
FactoryInfo existing;
if (projectInfo.Factories != null &&
projectInfo.Factories.TryGetValue(info.Config.Id, out existing) &&
existing.Equals(info)) {
// keep the existing factory, we may have already created it's IPythonInterpreterFactory instance
factories[info.Config.Id] = existing;
} else {
factories[info.Config.Id] = info;
}
}
private static string GetValue(Dictionary<string, string> from, string name) {
string res;
if (!from.TryGetValue(name, out res)) {
return String.Empty;
}
return res;
}
class FactoryInfo {
public readonly InterpreterConfiguration Config;
protected IPythonInterpreterFactory _factory;
public FactoryInfo(InterpreterConfiguration configuration) {
Config = configuration;
}
protected virtual void CreateFactory() {
}
public IPythonInterpreterFactory Factory {
get {
if (_factory == null) {
CreateFactory();
}
return _factory;
}
}
}
sealed class ConfiguredFactoryInfo : FactoryInfo, IDisposable {
private readonly MSBuildProjectInterpreterFactoryProvider _factoryProvider;
public ConfiguredFactoryInfo(MSBuildProjectInterpreterFactoryProvider factoryProvider, InterpreterConfiguration config) : base(config) {
_factoryProvider = factoryProvider;
}
protected override void CreateFactory() {
_factory = InterpreterFactoryCreator.CreateInterpreterFactory(
Config,
new InterpreterFactoryCreationOptions {
WatchFileSystem = true,
}
);
}
public override bool Equals(object obj) {
ConfiguredFactoryInfo other = obj as ConfiguredFactoryInfo;
if (other != null) {
return other.Config == Config;
}
return false;
}
public override int GetHashCode() {
return Config.GetHashCode();
}
public void Dispose() {
IDisposable fact = _factory as IDisposable;
if (fact != null) {
fact.Dispose();
}
}
}
sealed class ErrorFactoryInfo : FactoryInfo {
private string _dir;
public ErrorFactoryInfo(string id, Version ver, string description, string dir) :
base(new VisualStudioInterpreterConfiguration(id, "{0} (unavailable)".FormatInvariant(description), version: ver)) {
_dir = dir;
}
protected override void CreateFactory() {
_factory = new NotFoundInterpreterFactory(
Config.Id,
Config.Version,
Config.Description,
Directory.Exists(_dir) ? _dir : null
);
}
public override bool Equals(object obj) {
ErrorFactoryInfo other = obj as ErrorFactoryInfo;
if (other != null) {
return other.Config == Config &&
other._dir == _dir;
}
return false;
}
public override int GetHashCode() {
return Config.GetHashCode() ^ _dir?.GetHashCode() ?? 0;
}
}
/// <summary>
/// Represents an MSBuild project file. The file could have either been read from
/// disk or it could be a project file running inside of the IDE which is being
/// used for a Python project node.
/// </summary>
sealed class MSBuildProjectInfo : ProjectInfo {
public readonly MSBuild.Project Project;
public MSBuildProjectInfo(MSBuild.Project project, string filename, IProjectContextProvider context) : base(filename, context) {
Project = project;
}
public override object Context {
get {
return Project;
}
}
public override string GetPropertyValue(string name) {
return Project.GetPropertyValue(name);
}
internal override IEnumerable<Dictionary<string, string>> GetInterpreters() {
return Project.GetItems(MSBuildConstants.InterpreterItem).Select(
interp => new Dictionary<string, string>() {
{ "EvaluatedInclude", interp.EvaluatedInclude },
{ MSBuildConstants.IdKey, interp.GetMetadataValue(MSBuildConstants.IdKey) },
{ MSBuildConstants.VersionKey, interp.GetMetadataValue(MSBuildConstants.VersionKey) },
{ MSBuildConstants.DescriptionKey, interp.GetMetadataValue(MSBuildConstants.DescriptionKey) },
{ MSBuildConstants.InterpreterPathKey, interp.GetMetadataValue(MSBuildConstants.InterpreterPathKey) },
{ MSBuildConstants.WindowsPathKey, interp.GetMetadataValue(MSBuildConstants.WindowsPathKey) },
{ MSBuildConstants.PathEnvVarKey, interp.GetMetadataValue(MSBuildConstants.PathEnvVarKey) },
{ MSBuildConstants.ArchitectureKey, interp.GetMetadataValue(MSBuildConstants.ArchitectureKey) }
}
);
}
}
/// <summary>
/// Gets information about an "in-memory" project. Supports reading interpreters from
/// a project when we're out of proc that haven't yet been committed to disk.
/// </summary>
sealed class InMemoryProjectInfo : ProjectInfo {
public readonly InMemoryProject Project;
public InMemoryProjectInfo(InMemoryProject project, string filename, IProjectContextProvider context) : base(filename, context) {
Project = project;
}
public override object Context {
get {
return Project;
}
}
public override string GetPropertyValue(string name) {
object res;
if (Project.Properties.TryGetValue(name, out res) && res is string) {
return (string)res;
}
return String.Empty;
}
internal override IEnumerable<Dictionary<string, string>> GetInterpreters() {
object interps;
if (Project.Properties.TryGetValue("Interpreters", out interps) &&
interps is IEnumerable<Dictionary<string, string>>) {
return (IEnumerable<Dictionary<string, string>>)interps;
}
return Array.Empty<Dictionary<string, string>>();
}
}
/// <summary>
/// Tracks data about a project. Specific subclasses deal with how the underlying project
/// is being stored.
/// </summary>
abstract class ProjectInfo : IDisposable {
public readonly IProjectContextProvider ContextProvider;
public readonly string FullPath;
public Dictionary<string, FactoryInfo> Factories;
public readonly Dictionary<string, string> RootPaths = new Dictionary<string, string>();
public ProjectInfo(string filename, IProjectContextProvider context) {
FullPath = filename;
ContextProvider = context;
}
public void Dispose() {
if (Factories != null) {
foreach (var keyValue in Factories) {
IDisposable disp = keyValue.Value as IDisposable;
if (disp != null) {
disp.Dispose();
}
}
}
}
public abstract object Context {
get;
}
public abstract string GetPropertyValue(string name);
internal abstract IEnumerable<Dictionary<string, string>> GetInterpreters();
}
public void Dispose() {
if (_projects != null) {
foreach (var project in _projects) {
project.Value.Dispose();
}
}
}
/* We can't use IInterpreterRegistryService here because we need to do
this during initilization, and we don't have access to it until after
our ctor has run. So we do our own interpreter discovery */
private IPythonInterpreterFactory FindInterpreter(string id) {
return GetFactoryProvider(id)?.GetInterpreterFactory(id);
}
private InterpreterConfiguration FindConfiguration(string id) {
var factoryProvider = GetFactoryProvider(id);
if (factoryProvider != null) {
return factoryProvider
.GetInterpreterConfigurations()
.Where(x => x.Id == id)
.FirstOrDefault();
}
return null;
}
private IPythonInterpreterFactoryProvider GetFactoryProvider(string id) {
if (string.IsNullOrEmpty(id)) {
return null;
}
var interpAndId = id.Split(new[] { '|' }, 2);
if (interpAndId.Length == 2) {
foreach (var provider in GetProvidersAndMetadata()) {
object value;
if (provider.Value.TryGetValue(InterpreterFactoryIdMetadata, out value) &&
value is string &&
(string)value == interpAndId[0]) {
return provider.Key;
}
}
}
return null;
}
private IEnumerable<KeyValuePair<IPythonInterpreterFactoryProvider, Dictionary<string, object>>> GetProvidersAndMetadata() {
for (int i = 0; i < _factoryProviders.Length; i++) {
IPythonInterpreterFactoryProvider value = null;
try {
var provider = _factoryProviders[i];
if (provider != null) {
value = provider.Value;
}
} catch (CompositionException ce) {
Log("Failed to get interpreter factory value: {0}", ce);
_factoryProviders[i] = null;
}
if (value != null) {
yield return new KeyValuePair<IPythonInterpreterFactoryProvider, Dictionary<string, object>>(value, _factoryProviders[i].Metadata);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SpicyPixel.Threading
{
public partial class Fiber
{
/// <summary>
/// Returns a fiber that waits on all fibers to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all fibers complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all fibers to complete.</returns>
/// <param name="fibers">Fibers to wait for completion.</param>
public static Fiber WhenAll (params Fiber [] fibers)
{
return WhenAll (fibers, Timeout.Infinite, CancellationToken.None);
}
/// <summary>
/// Returns a fiber that waits on all fibers to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all fibers complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all fibers to complete.</returns>
/// <param name="fibers">Fibers to wait for completion.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public static Fiber WhenAll (Fiber [] fibers, CancellationToken cancellationToken)
{
return WhenAll (fibers, Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Returns a fiber that waits on all fibers to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all fibers complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all fibers to complete.</returns>
/// <param name="fibers">Fibers to wait for completion.</param>
/// <param name="timeout">Timeout.</param>
public static Fiber WhenAll (Fiber [] fibers, TimeSpan timeout)
{
return WhenAll (fibers, CheckTimeout (timeout), CancellationToken.None);
}
/// <summary>
/// Returns a fiber that waits on all fibers to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all fibers complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all fibers to complete.</returns>
/// <param name="fibers">Fibers to wait for completion.</param>
/// <param name="millisecondsTimeout">Milliseconds timeout.</param>
public static Fiber WhenAll (Fiber [] fibers, int millisecondsTimeout)
{
return WhenAll (fibers, millisecondsTimeout, CancellationToken.None);
}
/// <summary>
/// Returns a fiber that waits on all fibers to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all fibers complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all fibers to complete.</returns>
/// <param name="fibers">Fibers to wait for completion.</param>
/// <param name="millisecondsTimeout">Milliseconds timeout.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public static Fiber WhenAll (Fiber [] fibers, int millisecondsTimeout, CancellationToken cancellationToken)
{
return WhenAll (fibers, millisecondsTimeout, cancellationToken, FiberScheduler.Current);
}
/// <summary>
/// Returns a fiber that waits on all fibers to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all fibers complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all fibers to complete.</returns>
/// <param name="fibers">Fibers to wait for completion.</param>
/// <param name="millisecondsTimeout">Milliseconds timeout.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="scheduler">Scheduler.</param>
public static Fiber WhenAll (Fiber [] fibers, int millisecondsTimeout, CancellationToken cancellationToken, FiberScheduler scheduler)
{
if (fibers == null)
throw new ArgumentNullException ("fibers");
foreach (var fiber in fibers) {
if (fiber == null)
throw new ArgumentException ("fibers", "the fibers argument contains a null element");
}
return Fiber.Factory.StartNew (WhenAllFibersCoroutine (fibers, millisecondsTimeout, cancellationToken), cancellationToken, scheduler);
}
/// <summary>
/// Returns a fiber that waits on all fibers to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all fibers complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all fibers to complete.</returns>
/// <param name="fibers">Fibers to wait for completion.</param>
/// <param name="millisecondsTimeout">Milliseconds timeout.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="scheduler">Scheduler.</param>
public static Fiber WhenAll (IEnumerable<Fiber> fibers, int millisecondsTimeout, CancellationToken cancellationToken, FiberScheduler scheduler)
{
return WhenAll (fibers.ToArray (), millisecondsTimeout, cancellationToken, scheduler);
}
static IEnumerator WhenAllFibersCoroutine (IEnumerable<Fiber> fibers, int millisecondsTimeout, CancellationToken cancellationToken)
{
var startWait = DateTime.Now;
while (true) {
if ((millisecondsTimeout != Timeout.Infinite
&& (DateTime.Now - startWait).TotalMilliseconds >= millisecondsTimeout)) {
throw new TimeoutException ();
}
cancellationToken.ThrowIfCancellationRequested ();
if (fibers.All (f => f.IsCompleted)) {
if (fibers.Any (f => f.IsCanceled)) {
throw new System.Threading.OperationCanceledException ();
}
if (fibers.Any (f => f.IsFaulted)) {
throw new AggregateException (
fibers.Where (f => f.IsFaulted).Select (f => f.Exception));
}
yield break;
}
yield return FiberInstruction.YieldToAnyFiber;
}
}
/// <summary>
/// Returns a fiber that waits on all tasks to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all tasks complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all tasks to complete.</returns>
/// <param name="tasks">Tasks to wait for completion.</param>
public static Fiber WhenAll (params Task [] tasks)
{
return WhenAll (tasks, Timeout.Infinite, CancellationToken.None);
}
/// <summary>
/// Returns a fiber that waits on all tasks to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all tasks complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all tasks to complete.</returns>
/// <param name="tasks">Tasks to wait for completion.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public static Fiber WhenAll (Task [] tasks, CancellationToken cancellationToken)
{
return WhenAll (tasks, Timeout.Infinite, cancellationToken);
}
/// <summary>
/// Returns a fiber that waits on all tasks to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all tasks complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all tasks to complete.</returns>
/// <param name="tasks">Tasks to wait for completion.</param>
/// <param name="timeout">Timeout.</param>
public static Fiber WhenAll (Task [] tasks, TimeSpan timeout)
{
return WhenAll (tasks, CheckTimeout (timeout), CancellationToken.None);
}
/// <summary>
/// Returns a fiber that waits on all tasks to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all tasks complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all tasks to complete.</returns>
/// <param name="tasks">Tasks to wait for completion.</param>
/// <param name="millisecondsTimeout">Milliseconds timeout.</param>
public static Fiber WhenAll (Task [] tasks, int millisecondsTimeout)
{
return WhenAll (tasks, millisecondsTimeout, CancellationToken.None);
}
/// <summary>
/// Returns a fiber that waits on all tasks to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all tasks complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all tasks to complete.</returns>
/// <param name="tasks">Tasks to wait for completion.</param>
/// <param name="millisecondsTimeout">Milliseconds timeout.</param>
/// <param name="cancellationToken">Cancellation token.</param>
public static Fiber WhenAll (Task [] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
{
return WhenAll (tasks, millisecondsTimeout, cancellationToken, FiberScheduler.Current);
}
/// <summary>
/// Returns a fiber that waits on all tasks to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all tasks complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all tasks to complete.</returns>
/// <param name="tasks">Tasks to wait for completion.</param>
/// <param name="millisecondsTimeout">Milliseconds timeout.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="scheduler">Scheduler.</param>
public static Fiber WhenAll (Task [] tasks, int millisecondsTimeout, CancellationToken cancellationToken, FiberScheduler scheduler)
{
if (tasks == null)
throw new ArgumentNullException ("tasks");
foreach (var fiber in tasks) {
if (fiber == null)
throw new ArgumentException ("tasks", "the tasks argument contains a null element");
}
return Fiber.Factory.StartNew (WhenAllTasksCoroutine (tasks, millisecondsTimeout, cancellationToken), cancellationToken, scheduler);
}
/// <summary>
/// Returns a fiber that waits on all tasks to complete.
/// </summary>
/// <remarks>
/// `Fiber.ResultAsObject` will be `true` if all tasks complete
/// successfully or `false` if cancelled or timeout.
/// </remarks>
/// <returns>A fiber that waits on all tasks to complete.</returns>
/// <param name="tasks">Tasks to wait for completion.</param>
/// <param name="millisecondsTimeout">Milliseconds timeout.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <param name="scheduler">Scheduler.</param>
public static Fiber WhenAll (IEnumerable<Task> tasks, int millisecondsTimeout, CancellationToken cancellationToken, FiberScheduler scheduler)
{
return WhenAll (tasks.ToArray (), millisecondsTimeout, cancellationToken, scheduler);
}
static IEnumerator WhenAllTasksCoroutine (IEnumerable<Task> tasks, int millisecondsTimeout, CancellationToken cancellationToken)
{
var startWait = DateTime.Now;
while (true) {
if ((millisecondsTimeout != Timeout.Infinite
&& (DateTime.Now - startWait).TotalMilliseconds >= millisecondsTimeout)) {
throw new TimeoutException ();
}
cancellationToken.ThrowIfCancellationRequested ();
if (tasks.All (t => t.IsCompleted)) {
if (tasks.Any (t => t.IsCanceled)) {
throw new System.Threading.OperationCanceledException ();
}
if (tasks.Any (t => t.IsFaulted)) {
throw new AggregateException (
tasks.Where (t => t.IsFaulted).SelectMany (t => t.Exception.InnerExceptions));
}
yield break;
}
yield return FiberInstruction.YieldToAnyFiber;
}
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class Constructor : Method
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Constructor CloneNode()
{
return (Constructor)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public Constructor CleanClone()
{
return (Constructor)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.Constructor; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnConstructor(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( Constructor)node;
if (_modifiers != other._modifiers) return NoMatch("Constructor._modifiers");
if (_name != other._name) return NoMatch("Constructor._name");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("Constructor._attributes");
if (!Node.AllMatch(_parameters, other._parameters)) return NoMatch("Constructor._parameters");
if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("Constructor._genericParameters");
if (!Node.Matches(_returnType, other._returnType)) return NoMatch("Constructor._returnType");
if (!Node.AllMatch(_returnTypeAttributes, other._returnTypeAttributes)) return NoMatch("Constructor._returnTypeAttributes");
if (!Node.Matches(_body, other._body)) return NoMatch("Constructor._body");
if (!Node.AllMatch(_locals, other._locals)) return NoMatch("Constructor._locals");
if (_implementationFlags != other._implementationFlags) return NoMatch("Constructor._implementationFlags");
if (!Node.Matches(_explicitInfo, other._explicitInfo)) return NoMatch("Constructor._explicitInfo");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
if (_parameters != null)
{
ParameterDeclaration item = existing as ParameterDeclaration;
if (null != item)
{
ParameterDeclaration newItem = (ParameterDeclaration)newNode;
if (_parameters.Replace(item, newItem))
{
return true;
}
}
}
if (_genericParameters != null)
{
GenericParameterDeclaration item = existing as GenericParameterDeclaration;
if (null != item)
{
GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode;
if (_genericParameters.Replace(item, newItem))
{
return true;
}
}
}
if (_returnType == existing)
{
this.ReturnType = (TypeReference)newNode;
return true;
}
if (_returnTypeAttributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_returnTypeAttributes.Replace(item, newItem))
{
return true;
}
}
}
if (_body == existing)
{
this.Body = (Block)newNode;
return true;
}
if (_locals != null)
{
Local item = existing as Local;
if (null != item)
{
Local newItem = (Local)newNode;
if (_locals.Replace(item, newItem))
{
return true;
}
}
}
if (_explicitInfo == existing)
{
this.ExplicitInfo = (ExplicitMemberInfo)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
Constructor clone = (Constructor)FormatterServices.GetUninitializedObject(typeof(Constructor));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._modifiers = _modifiers;
clone._name = _name;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
if (null != _parameters)
{
clone._parameters = _parameters.Clone() as ParameterDeclarationCollection;
clone._parameters.InitializeParent(clone);
}
if (null != _genericParameters)
{
clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection;
clone._genericParameters.InitializeParent(clone);
}
if (null != _returnType)
{
clone._returnType = _returnType.Clone() as TypeReference;
clone._returnType.InitializeParent(clone);
}
if (null != _returnTypeAttributes)
{
clone._returnTypeAttributes = _returnTypeAttributes.Clone() as AttributeCollection;
clone._returnTypeAttributes.InitializeParent(clone);
}
if (null != _body)
{
clone._body = _body.Clone() as Block;
clone._body.InitializeParent(clone);
}
if (null != _locals)
{
clone._locals = _locals.Clone() as LocalCollection;
clone._locals.InitializeParent(clone);
}
clone._implementationFlags = _implementationFlags;
if (null != _explicitInfo)
{
clone._explicitInfo = _explicitInfo.Clone() as ExplicitMemberInfo;
clone._explicitInfo.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
if (null != _parameters)
{
_parameters.ClearTypeSystemBindings();
}
if (null != _genericParameters)
{
_genericParameters.ClearTypeSystemBindings();
}
if (null != _returnType)
{
_returnType.ClearTypeSystemBindings();
}
if (null != _returnTypeAttributes)
{
_returnTypeAttributes.ClearTypeSystemBindings();
}
if (null != _body)
{
_body.ClearTypeSystemBindings();
}
if (null != _locals)
{
_locals.ClearTypeSystemBindings();
}
if (null != _explicitInfo)
{
_explicitInfo.ClearTypeSystemBindings();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.