context stringlengths 2.52k 185k | gt stringclasses 1 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;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Threading;
using System.Xml;
using System.Runtime.Versioning;
using System.Diagnostics.CodeAnalysis;
// This class is the process wide dependency dispatcher. It contains all connection listeners for the entire process and
// receives notifications on those connections to dispatch to the corresponding AppDomain dispatcher to notify the
// appropriate dependencies.
internal class SqlDependencyProcessDispatcher : MarshalByRefObject
{
// Class to contain/store all relevant information about a connection that waits on the SSB queue.
private class SqlConnectionContainer
{
private SqlConnection _con;
private SqlCommand _com;
private SqlParameter _conversationGuidParam;
private SqlParameter _timeoutParam;
private SqlConnectionContainerHashHelper _hashHelper;
private string _queue;
private string _receiveQuery;
private string _beginConversationQuery;
private string _endConversationQuery;
private string _concatQuery;
private readonly int _defaultWaitforTimeout = 60000; // Waitfor(Receive) timeout (milleseconds)
private string _escapedQueueName;
private string _sprocName;
private string _dialogHandle;
private string _cachedServer;
private string _cachedDatabase;
private volatile bool _errorState = false;
private volatile bool _stop = false; // Can probably simplify this slightly - one bool instead of two.
private volatile bool _stopped = false;
private volatile bool _serviceQueueCreated = false;
private int _startCount = 0; // Each container class is called once per Start() - we refCount
// to track when we can dispose.
private Timer _retryTimer = null;
private Dictionary<string, int> _appDomainKeyHash = null; // AppDomainKey->Open RefCount
// Constructor
internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults)
{
bool setupCompleted = false;
try
{
_hashHelper = hashHelper;
string guid = null;
// If default, queue name is not present on hashHelper at this point - so we need to
// generate one and complete initialization.
if (useDefaults)
{
guid = Guid.NewGuid().ToString();
_queue = SQL.SqlNotificationServiceDefault + "-" + guid;
_hashHelper.ConnectionStringBuilder.ApplicationName = _queue; // Used by cleanup sproc.
}
else
{
_queue = _hashHelper.Queue;
}
// Always use ConnectionStringBuilder since in default case it is different from the
// connection string used in the hashHelper.
_con = new SqlConnection(_hashHelper.ConnectionStringBuilder.ConnectionString); // Create connection and open.
// Assert permission for this particular connection string since it differs from the user passed string
// which we have already demanded upon.
SqlConnectionString connStringObj = (SqlConnectionString)_con.ConnectionOptions;
_con.Open();
_cachedServer = _con.DataSource;
_escapedQueueName = SqlConnection.FixupDatabaseTransactionName(_queue); // Properly escape to prevent SQL Injection.
_appDomainKeyHash = new Dictionary<string, int>(); // Dictionary stores the Start/Stop refcount per AppDomain for this container.
_com = new SqlCommand()
{
Connection = _con,
// Determine if broker is enabled on current database.
CommandText = "select is_broker_enabled from sys.databases where database_id=db_id()"
};
if (!(bool)_com.ExecuteScalar())
{
throw SQL.SqlDependencyDatabaseBrokerDisabled();
}
_conversationGuidParam = new SqlParameter("@p1", SqlDbType.UniqueIdentifier);
_timeoutParam = new SqlParameter("@p2", SqlDbType.Int)
{
Value = 0 // Timeout set to 0 for initial sync query.
};
_com.Parameters.Add(_timeoutParam);
setupCompleted = true;
// connection with the server has been setup - from this point use TearDownAndDispose() in case of error
// Create standard query.
_receiveQuery = "WAITFOR(RECEIVE TOP (1) message_type_name, conversation_handle, cast(message_body AS XML) as message_body from " + _escapedQueueName + "), TIMEOUT @p2;";
// Create queue, service, sync query, and async query on user thread to ensure proper
// init prior to return.
if (useDefaults)
{ // Only create if user did not specify service & database.
_sprocName = SqlConnection.FixupDatabaseTransactionName(SQL.SqlNotificationStoredProcedureDefault + "-" + guid);
CreateQueueAndService(false); // Fail if we cannot create service, queue, etc.
}
else
{
// Continue query setup.
_com.CommandText = _receiveQuery;
_endConversationQuery = "END CONVERSATION @p1; ";
_concatQuery = _endConversationQuery + _receiveQuery;
}
IncrementStartCount(appDomainKey, out bool ignored);
// Query synchronously once to ensure everything is working correctly.
// We want the exception to occur on start to immediately inform caller.
SynchronouslyQueryServiceBrokerQueue();
_timeoutParam.Value = _defaultWaitforTimeout; // Sync successful, extend timeout to 60 seconds.
AsynchronouslyQueryServiceBrokerQueue();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
if (setupCompleted)
{
// Be sure to drop service & queue. This may fail if create service & queue failed.
// This method will not drop unless we created or service & queue ref-count is 0.
TearDownAndDispose();
}
else
{
// connection has not been fully setup yet - cannot use TearDownAndDispose();
// we have to dispose the command and the connection to avoid connection leaks (until GC collects them).
if (_com != null)
{
_com.Dispose();
_com = null;
}
if (_con != null)
{
_con.Dispose();
_con = null;
}
}
throw;
}
}
// Properties
internal string Database
{
get
{
if (_cachedDatabase == null)
{
_cachedDatabase = _con.Database;
}
return _cachedDatabase;
}
}
internal SqlConnectionContainerHashHelper HashHelper => _hashHelper;
internal bool InErrorState => _errorState;
internal string Queue => _queue;
internal string Server => _cachedServer;
// Methods
// This function is called by a ThreadPool thread as a result of an AppDomain calling
// SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload.
internal bool AppDomainUnload(string appDomainKey)
{
Debug.Assert(!string.IsNullOrEmpty(appDomainKey), "Unexpected empty appDomainKey!");
// Dictionary used to track how many times start has been called per app domain.
// For each decrement, subtract from count, and delete if we reach 0.
lock (_appDomainKeyHash)
{
if (_appDomainKeyHash.ContainsKey(appDomainKey))
{ // Do nothing if AppDomain did not call Start!
int value = _appDomainKeyHash[appDomainKey];
Debug.Assert(value > 0, "Why is value 0 or less?");
bool ignored = false;
while (value > 0)
{
Debug.Assert(!_stopped, "We should not yet be stopped!");
Stop(appDomainKey, out ignored); // Stop will decrement value and remove if necessary from _appDomainKeyHash.
value--;
}
// Stop will remove key when decremented to 0 for this AppDomain, which should now be the case.
Debug.Assert(0 == value, "We did not reach 0 at end of loop in AppDomainUnload!");
Debug.Assert(!_appDomainKeyHash.ContainsKey(appDomainKey), "Key not removed after AppDomainUnload!");
}
}
return _stopped;
}
private void AsynchronouslyQueryServiceBrokerQueue()
{
AsyncCallback callback = new AsyncCallback(AsyncResultCallback);
_com.BeginExecuteReader(CommandBehavior.Default, callback, null); // NO LOCK NEEDED
}
private void AsyncResultCallback(IAsyncResult asyncResult)
{
try
{
using (SqlDataReader reader = _com.EndExecuteReader(asyncResult))
{
ProcessNotificationResults(reader);
}
// Successfull completion of query - no errors.
if (!_stop)
{
AsynchronouslyQueryServiceBrokerQueue(); // Requeue...
}
else
{
TearDownAndDispose();
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
// Let the waiting thread detect the error and exit (otherwise, the Stop call loops forever)
_errorState = true;
throw;
}
if (!_stop)
{ // Only assert if not in cancel path.
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
}
// Failure - likely due to cancelled command. Check _stop state.
if (_stop)
{
TearDownAndDispose();
}
else
{
_errorState = true;
Restart(null); // Error code path. Will Invalidate based on server if 1st retry fails.
}
}
}
private void CreateQueueAndService(bool restart)
{
SqlCommand com = new SqlCommand()
{
Connection = _con
};
SqlTransaction trans = null;
try
{
trans = _con.BeginTransaction(); // Since we cannot batch proc creation, start transaction.
com.Transaction = trans;
string nameLiteral = SqlServerEscapeHelper.MakeStringLiteral(_queue);
com.CommandText =
"CREATE PROCEDURE " + _sprocName + " AS"
+ " BEGIN"
+ " BEGIN TRANSACTION;"
+ " RECEIVE TOP(0) conversation_handle FROM " + _escapedQueueName + ";"
+ " IF (SELECT COUNT(*) FROM " + _escapedQueueName + " WHERE message_type_name = 'http://schemas.microsoft.com/SQL/ServiceBroker/DialogTimer') > 0"
+ " BEGIN"
+ " if ((SELECT COUNT(*) FROM sys.services WHERE name = " + nameLiteral + ") > 0)"
+ " DROP SERVICE " + _escapedQueueName + ";"
+ " if (OBJECT_ID(" + nameLiteral + ", 'SQ') IS NOT NULL)"
+ " DROP QUEUE " + _escapedQueueName + ";"
+ " DROP PROCEDURE " + _sprocName + ";" // Don't need conditional because this is self
+ " END"
+ " COMMIT TRANSACTION;"
+ " END";
if (!restart)
{
com.ExecuteNonQuery();
}
else
{ // Upon restart, be resilient to the user dropping queue, service, or procedure.
try
{
com.ExecuteNonQuery(); // Cannot add 'IF OBJECT_ID' to create procedure query - wrap and discard failure.
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
try
{ // Since the failure will result in a rollback, rollback our object.
if (null != trans)
{
trans.Rollback();
trans = null;
}
}
catch (Exception f)
{
if (!ADP.IsCatchableExceptionType(f))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(f); // Discard failure, but trace for now.
}
}
if (null == trans)
{ // Create a new transaction for next operations.
trans = _con.BeginTransaction();
com.Transaction = trans;
}
}
com.CommandText =
"IF OBJECT_ID(" + nameLiteral + ", 'SQ') IS NULL"
+ " BEGIN"
+ " CREATE QUEUE " + _escapedQueueName + " WITH ACTIVATION (PROCEDURE_NAME=" + _sprocName + ", MAX_QUEUE_READERS=1, EXECUTE AS OWNER);"
+ " END;"
+ " IF (SELECT COUNT(*) FROM sys.services WHERE NAME=" + nameLiteral + ") = 0"
+ " BEGIN"
+ " CREATE SERVICE " + _escapedQueueName + " ON QUEUE " + _escapedQueueName + " ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);"
+ " IF (SELECT COUNT(*) FROM sys.database_principals WHERE name='sql_dependency_subscriber' AND type='R') <> 0"
+ " BEGIN"
+ " GRANT SEND ON SERVICE::" + _escapedQueueName + " TO sql_dependency_subscriber;"
+ " END; "
+ " END;"
+ " BEGIN DIALOG @dialog_handle FROM SERVICE " + _escapedQueueName + " TO SERVICE " + nameLiteral;
SqlParameter param = new SqlParameter()
{
ParameterName = "@dialog_handle",
DbType = DbType.Guid,
Direction = ParameterDirection.Output
};
com.Parameters.Add(param);
com.ExecuteNonQuery();
// Finish setting up queries and state. For re-start, we need to ensure we begin a new dialog above and reset
// our queries to use the new dialogHandle.
_dialogHandle = ((Guid)param.Value).ToString();
_beginConversationQuery = "BEGIN CONVERSATION TIMER ('" + _dialogHandle + "') TIMEOUT = 120; " + _receiveQuery;
_com.CommandText = _beginConversationQuery;
_endConversationQuery = "END CONVERSATION @p1; ";
_concatQuery = _endConversationQuery + _com.CommandText;
trans.Commit();
trans = null;
_serviceQueueCreated = true;
}
finally
{
if (null != trans)
{
try
{
trans.Rollback();
trans = null;
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
}
}
}
}
internal void IncrementStartCount(string appDomainKey, out bool appDomainStart)
{
appDomainStart = false; // Reset out param.
int result = Interlocked.Increment(ref _startCount); // Add to refCount.
// Dictionary used to track how many times start has been called per app domain.
// For each increment, add to count, and create entry if not present.
lock (_appDomainKeyHash)
{
if (_appDomainKeyHash.ContainsKey(appDomainKey))
{
_appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1;
}
else
{
_appDomainKeyHash[appDomainKey] = 1;
appDomainStart = true;
}
}
}
private void ProcessNotificationResults(SqlDataReader reader)
{
Guid handle = Guid.Empty; // Conversation_handle. Always close this!
try
{
if (!_stop)
{
while (reader.Read())
{
string msgType = reader.GetString(0);
handle = reader.GetGuid(1);
// Only process QueryNotification messages.
if (0 == string.Compare(msgType, "http://schemas.microsoft.com/SQL/Notifications/QueryNotification", StringComparison.OrdinalIgnoreCase))
{
SqlXml payload = reader.GetSqlXml(2);
if (null != payload)
{
SqlNotification notification = SqlNotificationParser.ProcessMessage(payload);
if (null != notification)
{
string key = notification.Key;
int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash"
if (index >= 0)
{ // Ensure ';' present.
string appDomainKey = key.Substring(0, index);
SqlDependencyPerAppDomainDispatcher dispatcher;
lock (s_staticInstance._sqlDependencyPerAppDomainDispatchers)
{
dispatcher = s_staticInstance._sqlDependencyPerAppDomainDispatchers[appDomainKey];
}
if (null != dispatcher)
{
try
{
dispatcher.InvalidateCommandID(notification); // CROSS APP-DOMAIN CALL!
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure. User event could throw exception.
}
}
else
{
Debug.Fail("Received notification but do not have an associated PerAppDomainDispatcher!");
}
}
else
{
Debug.Fail("Unexpected ID format received!");
}
}
else
{
Debug.Fail("Null notification returned from ProcessMessage!");
}
}
else
{
Debug.Fail("Null payload for QN notification type!");
}
}
else
{
handle = Guid.Empty;
}
}
}
}
finally
{
// Since we do not want to make a separate round trip just for the end conversation call, we need to
// batch it with the next command.
if (handle == Guid.Empty)
{ // This should only happen if failure occurred, or if non-QN format received.
_com.CommandText = _beginConversationQuery ?? _receiveQuery; // If we're doing the initial query, we won't have a conversation Guid to begin yet.
if (_com.Parameters.Count > 1)
{ // Remove conversation param since next execute is only query.
_com.Parameters.Remove(_conversationGuidParam);
}
Debug.Assert(_com.Parameters.Count == 1, "Unexpected number of parameters!");
}
else
{
_com.CommandText = _concatQuery; // END query + WAITFOR RECEIVE query.
_conversationGuidParam.Value = handle; // Set value for conversation handle.
if (_com.Parameters.Count == 1)
{ // Add parameter if previous execute was only query.
_com.Parameters.Add(_conversationGuidParam);
}
Debug.Assert(_com.Parameters.Count == 2, "Unexpected number of parameters!");
}
}
}
// SxS: this method uses WindowsIdentity.Impersonate to impersonate the current thread with the
// credentials used to create this SqlConnectionContainer.
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
private void Restart(object unused)
{ // Unused arg required by TimerCallback.
try
{
lock (this)
{
if (!_stop)
{ // Only execute if we are still in running state.
try
{
_con.Close();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard close failure, if it occurs. Only trace it.
}
}
}
// Rather than one long lock - take lock 3 times for shorter periods.
lock (this)
{
if (!_stop)
{
_con.Open();
}
}
lock (this)
{
if (!_stop)
{
if (_serviceQueueCreated)
{
bool failure = false;
try
{
CreateQueueAndService(true); // Ensure service, queue, etc is present, if we created it.
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
failure = true;
}
if (failure)
{
// If we failed to re-created queue, service, sproc - invalidate!
s_staticInstance.Invalidate(Server,
new SqlNotification(SqlNotificationInfo.Error,
SqlNotificationSource.Client,
SqlNotificationType.Change,
null));
}
}
}
}
lock (this)
{
if (!_stop)
{
_timeoutParam.Value = 0; // Reset timeout to zero - we do not want to block.
SynchronouslyQueryServiceBrokerQueue();
// If the above succeeds, we are back in success case - requeue for async call.
_timeoutParam.Value = _defaultWaitforTimeout; // If success, reset to default for re-queue.
AsynchronouslyQueryServiceBrokerQueue();
_errorState = false;
Timer retryTimer = _retryTimer;
if (retryTimer != null)
{
_retryTimer = null;
retryTimer.Dispose();
}
}
}
if (_stop)
{
TearDownAndDispose(); // Function will lock(this).
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
try
{
// If unexpected query or connection failure, invalidate all dependencies against this server.
// We may over-notify if only some of the connections to a particular database were affected,
// but this should not be frequent enough to be a concern.
// NOTE - we invalidate after failure first occurs and then retry fails. We will then continue
// to invalidate every time the retry fails.
s_staticInstance.Invalidate(Server,
new SqlNotification(SqlNotificationInfo.Error,
SqlNotificationSource.Client,
SqlNotificationType.Change,
null));
}
catch (Exception f)
{
if (!ADP.IsCatchableExceptionType(f))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(f); // Discard exception from Invalidate. User events can throw.
}
try
{
_con.Close();
}
catch (Exception f)
{
if (!ADP.IsCatchableExceptionType(f))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(f); // Discard close failure, if it occurs. Only trace it.
}
if (!_stop)
{
// Create a timer to callback in one minute, retrying the call to Restart().
_retryTimer = new Timer(new TimerCallback(Restart), null, _defaultWaitforTimeout, Timeout.Infinite);
// We will retry this indefinitely, until success - or Stop();
}
}
}
internal bool Stop(string appDomainKey, out bool appDomainStop)
{
appDomainStop = false;
// Dictionary used to track how many times start has been called per app domain.
// For each decrement, subtract from count, and delete if we reach 0.
if (null != appDomainKey)
{
// If null, then this was called from SqlDependencyProcessDispatcher, we ignore appDomainKeyHash.
lock (_appDomainKeyHash)
{
if (_appDomainKeyHash.ContainsKey(appDomainKey))
{ // Do nothing if AppDomain did not call Start!
int value = _appDomainKeyHash[appDomainKey];
Debug.Assert(value > 0, "Unexpected count for appDomainKey");
if (value > 0)
{
_appDomainKeyHash[appDomainKey] = value - 1;
}
else
{
Debug.Fail("Unexpected AppDomainKey count in Stop()");
}
if (1 == value)
{ // Remove from dictionary if pre-decrement count was one.
_appDomainKeyHash.Remove(appDomainKey);
appDomainStop = true;
}
}
else
{
Debug.Fail("Unexpected state on Stop() - no AppDomainKey entry in hashtable!");
}
}
}
Debug.Assert(_startCount > 0, "About to decrement _startCount less than 0!");
int result = Interlocked.Decrement(ref _startCount);
if (0 == result)
{ // If we've reached refCount 0, destroy.
// Lock to ensure Cancel() complete prior to other thread calling TearDown.
lock (this)
{
try
{
// Race condition with executing thread - will throw if connection is closed due to failure.
// Rather than fighting the race condition, just call it and discard any potential failure.
_com.Cancel(); // Cancel the pending command. No-op if connection closed.
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
_stop = true;
}
// Wait until stopped and service & queue are dropped.
Stopwatch retryStopwatch = Stopwatch.StartNew();
while (true)
{
lock (this)
{
if (_stopped)
{
break;
}
// If we are in error state (_errorState is true), force a tear down.
// Likewise, if we have exceeded the maximum retry period (30 seconds) waiting for cleanup, force a tear down.
// In rare cases during app domain unload, the async cleanup performed by AsyncResultCallback
// may fail to execute TearDownAndDispose, leaving this method in an infinite loop.
// To avoid the infinite loop, we force the cleanup here after 30 seconds. Since we have reached
// refcount of 0, either this method call or the thread running AsyncResultCallback is responsible for calling
// TearDownAndDispose when transitioning to the _stopped state. Failing to call TearDownAndDispose means we leak
// the service broker objects created by this SqlDependency instance, so we make a best effort here to call
// TearDownAndDispose in the maximum retry period case as well as in the _errorState case.
if (_errorState || retryStopwatch.Elapsed.Seconds >= 30)
{
Timer retryTimer = _retryTimer;
_retryTimer = null;
if (retryTimer != null)
{
retryTimer.Dispose(); // Dispose timer - stop retry loop!
}
TearDownAndDispose(); // Will not hit server unless connection open!
break;
}
}
// Yield the thread since the stop has not yet completed.
// To avoid CPU spikes while waiting, yield and wait for at least one millisecond
Thread.Sleep(1);
}
}
Debug.Assert(0 <= _startCount, "Invalid start count state");
return _stopped;
}
private void SynchronouslyQueryServiceBrokerQueue()
{
using (SqlDataReader reader = _com.ExecuteReader())
{
ProcessNotificationResults(reader);
}
}
[SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")]
private void TearDownAndDispose()
{
lock (this)
{ // Lock to ensure Stop() (with Cancel()) complete prior to TearDown.
try
{
// Only execute if connection is still up and open.
if (ConnectionState.Closed != _con.State && ConnectionState.Broken != _con.State)
{
if (_com.Parameters.Count > 1)
{ // Need to close dialog before completing.
// In the normal case, the "End Conversation" query is executed before a
// receive query and upon return we will clear the state. However, unless
// a non notification query result is returned, we will not clear it. That
// means a query is generally always executing with an "end conversation" on
// the wire. Rather than synchronize for success of the other "end conversation",
// simply re-execute.
try
{
_com.CommandText = _endConversationQuery;
_com.Parameters.Remove(_timeoutParam);
_com.ExecuteNonQuery();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure.
}
}
if (_serviceQueueCreated && !_errorState)
{
/*
BEGIN TRANSACTION;
DROP SERVICE "+_escapedQueueName+";
DROP QUEUE "+_escapedQueueName+";
DROP PROCEDURE "+_sprocName+";
COMMIT TRANSACTION;
*/
_com.CommandText = "BEGIN TRANSACTION; DROP SERVICE " + _escapedQueueName + "; DROP QUEUE " + _escapedQueueName + "; DROP PROCEDURE " + _sprocName + "; COMMIT TRANSACTION;";
try
{
_com.ExecuteNonQuery();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure.
}
}
}
}
finally
{
_stopped = true;
_con.Dispose(); // Close and dispose connection.
}
}
}
}
// Private class encapsulating the notification payload parsing logic.
private class SqlNotificationParser
{
[Flags]
private enum MessageAttributes
{
None = 0,
Type = 1,
Source = 2,
Info = 4,
All = Type + Source + Info,
}
// node names in the payload
private const string RootNode = "QueryNotification";
private const string MessageNode = "Message";
// attribute names (on the QueryNotification element)
private const string InfoAttribute = "info";
private const string SourceAttribute = "source";
private const string TypeAttribute = "type";
internal static SqlNotification ProcessMessage(SqlXml xmlMessage)
{
using (XmlReader xmlReader = xmlMessage.CreateReader())
{
string keyvalue = string.Empty;
MessageAttributes messageAttributes = MessageAttributes.None;
SqlNotificationType type = SqlNotificationType.Unknown;
SqlNotificationInfo info = SqlNotificationInfo.Unknown;
SqlNotificationSource source = SqlNotificationSource.Unknown;
string key = string.Empty;
// Move to main node, expecting "QueryNotification".
xmlReader.Read();
if ((XmlNodeType.Element == xmlReader.NodeType) &&
(RootNode == xmlReader.LocalName) &&
(3 <= xmlReader.AttributeCount))
{
// Loop until we've processed all the attributes.
while ((MessageAttributes.All != messageAttributes) && (xmlReader.MoveToNextAttribute()))
{
try
{
switch (xmlReader.LocalName)
{
case TypeAttribute:
try
{
SqlNotificationType temp = (SqlNotificationType)Enum.Parse(typeof(SqlNotificationType), xmlReader.Value, true);
if (Enum.IsDefined(typeof(SqlNotificationType), temp))
{
type = temp;
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
messageAttributes |= MessageAttributes.Type;
break;
case SourceAttribute:
try
{
SqlNotificationSource temp = (SqlNotificationSource)Enum.Parse(typeof(SqlNotificationSource), xmlReader.Value, true);
if (Enum.IsDefined(typeof(SqlNotificationSource), temp))
{
source = temp;
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
messageAttributes |= MessageAttributes.Source;
break;
case InfoAttribute:
try
{
string value = xmlReader.Value;
// 3 of the server info values do not match client values - map.
switch (value)
{
case "set options":
info = SqlNotificationInfo.Options;
break;
case "previous invalid":
info = SqlNotificationInfo.PreviousFire;
break;
case "query template limit":
info = SqlNotificationInfo.TemplateLimit;
break;
default:
SqlNotificationInfo temp = (SqlNotificationInfo)Enum.Parse(typeof(SqlNotificationInfo), value, true);
if (Enum.IsDefined(typeof(SqlNotificationInfo), temp))
{
info = temp;
}
break;
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
messageAttributes |= MessageAttributes.Info;
break;
default:
break;
}
}
catch (ArgumentException e)
{
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace.
return null;
}
}
if (MessageAttributes.All != messageAttributes)
{
return null;
}
// Proceed to the "Message" node.
if (!xmlReader.Read())
{
return null;
}
// Verify state after Read().
if ((XmlNodeType.Element != xmlReader.NodeType) || (0 != string.Compare(xmlReader.LocalName, MessageNode, StringComparison.OrdinalIgnoreCase)))
{
return null;
}
// Proceed to the Text Node.
if (!xmlReader.Read())
{
return null;
}
// Verify state after Read().
if (xmlReader.NodeType != XmlNodeType.Text)
{
return null;
}
// Create a new XmlTextReader on the Message node value.
using (XmlTextReader xmlMessageReader = new XmlTextReader(xmlReader.Value, XmlNodeType.Element, null))
{
// Proceed to the Text Node.
if (!xmlMessageReader.Read())
{
return null;
}
if (xmlMessageReader.NodeType == XmlNodeType.Text)
{
key = xmlMessageReader.Value;
xmlMessageReader.Close();
}
else
{
return null;
}
}
return new SqlNotification(info, source, type, key);
}
else
{
return null; // failure
}
}
}
}
// Private class encapsulating the SqlConnectionContainer hash logic.
private class SqlConnectionContainerHashHelper
{
// For default, queue is computed in SqlConnectionContainer constructor, so queue will be empty and
// connection string will not include app name based on queue. As a result, the connection string
// builder will always contain up to date info, but _connectionString and _queue will not.
// As a result, we will not use _connectionStringBuilder as part of Equals or GetHashCode.
private DbConnectionPoolIdentity _identity;
private string _connectionString;
private string _queue;
private SqlConnectionStringBuilder _connectionStringBuilder; // Not to be used for comparison!
internal SqlConnectionContainerHashHelper(DbConnectionPoolIdentity identity, string connectionString,
string queue, SqlConnectionStringBuilder connectionStringBuilder)
{
_identity = identity;
_connectionString = connectionString;
_queue = queue;
_connectionStringBuilder = connectionStringBuilder;
}
// Not to be used for comparison!
internal SqlConnectionStringBuilder ConnectionStringBuilder => _connectionStringBuilder;
internal DbConnectionPoolIdentity Identity => _identity;
internal string Queue => _queue;
public override bool Equals(object value)
{
SqlConnectionContainerHashHelper temp = (SqlConnectionContainerHashHelper)value;
bool result = false;
// Ignore SqlConnectionStringBuilder, since it is present largely for debug purposes.
if (null == temp)
{ // If passed value null - false.
result = false;
}
else if (this == temp)
{ // If instances equal - true.
result = true;
}
else
{
if ((_identity != null && temp._identity == null) || // If XOR of null identities false - false.
(_identity == null && temp._identity != null))
{
result = false;
}
else if (_identity == null && temp._identity == null)
{
if (temp._connectionString == _connectionString &&
string.Equals(temp._queue, _queue, StringComparison.OrdinalIgnoreCase))
{
result = true;
}
else
{
result = false;
}
}
else
{
if (temp._identity.Equals(_identity) &&
temp._connectionString == _connectionString &&
string.Equals(temp._queue, _queue, StringComparison.OrdinalIgnoreCase))
{
result = true;
}
else
{
result = false;
}
}
}
return result;
}
public override int GetHashCode()
{
int hashValue = 0;
if (null != _identity)
{
hashValue = _identity.GetHashCode();
}
if (null != _queue)
{
hashValue = unchecked(_connectionString.GetHashCode() + _queue.GetHashCode() + hashValue);
}
else
{
hashValue = unchecked(_connectionString.GetHashCode() + hashValue);
}
return hashValue;
}
}
// SqlDependencyProcessDispatcher static members
private static SqlDependencyProcessDispatcher s_staticInstance = new SqlDependencyProcessDispatcher(null);
// Dictionaries used as maps.
private Dictionary<SqlConnectionContainerHashHelper, SqlConnectionContainer> _connectionContainers; // NT_ID+ConStr+Service->Container
private Dictionary<string, SqlDependencyPerAppDomainDispatcher> _sqlDependencyPerAppDomainDispatchers; // AppDomainKey->Callback
// Constructors
// Private constructor - only called by public constructor for static initialization.
private SqlDependencyProcessDispatcher(object dummyVariable)
{
Debug.Assert(null == s_staticInstance, "Real constructor called with static instance already created!");
_connectionContainers = new Dictionary<SqlConnectionContainerHashHelper, SqlConnectionContainer>();
_sqlDependencyPerAppDomainDispatchers = new Dictionary<string, SqlDependencyPerAppDomainDispatcher>();
}
// Constructor is only called by remoting.
// Required to be public, even on internal class, for Remoting infrastructure.
public SqlDependencyProcessDispatcher()
{
// Empty constructor and object - dummy to obtain singleton.
}
// Properties
internal static SqlDependencyProcessDispatcher SingletonProcessDispatcher => s_staticInstance;
// Various private methods
private static SqlConnectionContainerHashHelper GetHashHelper(
string connectionString,
out SqlConnectionStringBuilder connectionStringBuilder,
out DbConnectionPoolIdentity identity,
out string user,
string queue)
{
// Force certain connection string properties to be used by SqlDependencyProcessDispatcher.
// This logic is done here to enable us to have the complete connection string now to be used
// for tracing as we flow through the logic.
connectionStringBuilder = new SqlConnectionStringBuilder(connectionString)
{
Pooling = false,
Enlist = false,
ConnectRetryCount = 0
};
if (null != queue)
{ // User provided!
connectionStringBuilder.ApplicationName = queue; // ApplicationName will be set to queue name.
}
if (connectionStringBuilder.IntegratedSecurity)
{
// Use existing identity infrastructure for error cases and proper hash value.
identity = DbConnectionPoolIdentity.GetCurrent();
user = null;
}
else
{
identity = null;
user = connectionStringBuilder.UserID;
}
return new SqlConnectionContainerHashHelper(identity, connectionStringBuilder.ConnectionString,
queue, connectionStringBuilder);
}
// Needed for remoting to prevent lifetime issues and default GC cleanup.
public override object InitializeLifetimeService()
{
return null;
}
private void Invalidate(string server, SqlNotification sqlNotification)
{
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
lock (_sqlDependencyPerAppDomainDispatchers)
{
foreach (KeyValuePair<string, SqlDependencyPerAppDomainDispatcher> entry in _sqlDependencyPerAppDomainDispatchers)
{
SqlDependencyPerAppDomainDispatcher perAppDomainDispatcher = entry.Value;
try
{
perAppDomainDispatcher.InvalidateServer(server, sqlNotification);
}
catch (Exception f)
{
// Since we are looping over dependency dispatchers, do not allow one Invalidate
// that results in a throw prevent us from invalidating all dependencies
// related to this server.
// NOTE - SqlDependencyPerAppDomainDispatcher already wraps individual dependency invalidates
// with try/catch, but we should be careful and do the same here.
if (!ADP.IsCatchableExceptionType(f))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(f); // Discard failure, but trace.
}
}
}
}
// Clean-up method initiated by other AppDomain.Unloads
// Individual AppDomains upon AppDomain.UnloadEvent will call this method.
internal void QueueAppDomainUnloading(string appDomainKey)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(AppDomainUnloading), appDomainKey);
}
// This method is only called by queued work-items from the method above.
private void AppDomainUnloading(object state)
{
string appDomainKey = (string)state;
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
lock (_connectionContainers)
{
List<SqlConnectionContainerHashHelper> containersToRemove = new List<SqlConnectionContainerHashHelper>();
foreach (KeyValuePair<SqlConnectionContainerHashHelper, SqlConnectionContainer> entry in _connectionContainers)
{
SqlConnectionContainer container = entry.Value;
if (container.AppDomainUnload(appDomainKey))
{ // Perhaps wrap in try catch.
containersToRemove.Add(container.HashHelper);
}
}
foreach (SqlConnectionContainerHashHelper hashHelper in containersToRemove)
{
_connectionContainers.Remove(hashHelper);
}
}
lock (_sqlDependencyPerAppDomainDispatchers)
{ // Remove from global Dictionary.
_sqlDependencyPerAppDomainDispatchers.Remove(appDomainKey);
}
}
// -------------
// Start methods
// -------------
internal bool StartWithDefault(
string connectionString,
out string server,
out DbConnectionPoolIdentity identity,
out string user,
out string database,
ref string service,
string appDomainKey,
SqlDependencyPerAppDomainDispatcher dispatcher,
out bool errorOccurred,
out bool appDomainStart)
{
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
return Start(
connectionString,
out server,
out identity,
out user,
out database,
ref service,
appDomainKey,
dispatcher,
out errorOccurred,
out appDomainStart,
true);
}
internal bool Start(
string connectionString,
string queue,
string appDomainKey,
SqlDependencyPerAppDomainDispatcher dispatcher)
{
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
return Start(
connectionString,
out string dummyValue1,
out DbConnectionPoolIdentity dummyValue3,
out dummyValue1,
out dummyValue1,
ref queue,
appDomainKey,
dispatcher,
out bool dummyValue2,
out dummyValue2,
false);
}
private bool Start(
string connectionString,
out string server,
out DbConnectionPoolIdentity identity,
out string user,
out string database,
ref string queueService,
string appDomainKey,
SqlDependencyPerAppDomainDispatcher dispatcher,
out bool errorOccurred,
out bool appDomainStart,
bool useDefaults)
{
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
server = null; // Reset out params.
identity = null;
user = null;
database = null;
errorOccurred = false;
appDomainStart = false;
lock (_sqlDependencyPerAppDomainDispatchers)
{
if (!_sqlDependencyPerAppDomainDispatchers.ContainsKey(appDomainKey))
{
_sqlDependencyPerAppDomainDispatchers[appDomainKey] = dispatcher;
}
}
SqlConnectionContainerHashHelper hashHelper = GetHashHelper(connectionString,
out SqlConnectionStringBuilder connectionStringBuilder,
out identity,
out user,
queueService);
bool started = false;
SqlConnectionContainer container = null;
lock (_connectionContainers)
{
if (!_connectionContainers.ContainsKey(hashHelper))
{
container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults);
_connectionContainers.Add(hashHelper, container);
started = true;
appDomainStart = true;
}
else
{
container = _connectionContainers[hashHelper];
if (container.InErrorState)
{
errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start().
}
else
{
container.IncrementStartCount(appDomainKey, out appDomainStart);
}
}
}
if (useDefaults && !errorOccurred)
{ // Return server, database, and queue for use by SqlDependency.
server = container.Server;
database = container.Database;
queueService = container.Queue;
}
return started;
}
// Stop methods
internal bool Stop(
string connectionString,
out string server,
out DbConnectionPoolIdentity identity,
out string user,
out string database,
ref string queueService,
string appDomainKey,
out bool appDomainStop)
{
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
server = null; // Reset out param.
identity = null;
user = null;
database = null;
appDomainStop = false;
SqlConnectionContainerHashHelper hashHelper = GetHashHelper(connectionString,
out SqlConnectionStringBuilder connectionStringBuilder,
out identity,
out user,
queueService);
bool stopped = false;
lock (_connectionContainers)
{
if (_connectionContainers.ContainsKey(hashHelper))
{
SqlConnectionContainer container = _connectionContainers[hashHelper];
server = container.Server; // Return server, database, and queue info for use by calling SqlDependency.
database = container.Database;
queueService = container.Queue;
if (container.Stop(appDomainKey, out appDomainStop))
{ // Stop can be blocking if refCount == 0 on container.
stopped = true;
_connectionContainers.Remove(hashHelper); // Remove from collection.
}
}
}
return stopped;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Security.Principal
{
//
// Identifier authorities
//
internal enum IdentifierAuthority : long
{
NullAuthority = 0,
WorldAuthority = 1,
LocalAuthority = 2,
CreatorAuthority = 3,
NonUniqueAuthority = 4,
NTAuthority = 5,
SiteServerAuthority = 6,
InternetSiteAuthority = 7,
ExchangeAuthority = 8,
ResourceManagerAuthority = 9,
}
//
// SID name usage
//
internal enum SidNameUse
{
User = 1,
Group = 2,
Domain = 3,
Alias = 4,
WellKnownGroup = 5,
DeletedAccount = 6,
Invalid = 7,
Unknown = 8,
Computer = 9,
}
//
// Well-known SID types
//
public enum WellKnownSidType
{
/// <summary>Indicates a null SID.</summary>
NullSid = 0,
/// <summary>Indicates a SID that matches everyone.</summary>
WorldSid = 1,
/// <summary>Indicates a local SID.</summary>
LocalSid = 2,
/// <summary>Indicates a SID that matches the owner or creator of an object.</summary>
CreatorOwnerSid = 3,
/// <summary>Indicates a SID that matches the creator group of an object.</summary>
CreatorGroupSid = 4,
/// <summary>Indicates a creator owner server SID.</summary>
CreatorOwnerServerSid = 5,
/// <summary>Indicates a creator group server SID.</summary>
CreatorGroupServerSid = 6,
/// <summary>Indicates a SID for the Windows NT authority account.</summary>
NTAuthoritySid = 7,
/// <summary>Indicates a SID for a dial-up account.</summary>
DialupSid = 8,
/// <summary>Indicates a SID for a network account. This SID is added to the process of a token when it logs on across a network.</summary>
NetworkSid = 9,
/// <summary>Indicates a SID for a batch process. This SID is added to the process of a token when it logs on as a batch job.</summary>
BatchSid = 10,
/// <summary>Indicates a SID for an interactive account. This SID is added to the process of a token when it logs on interactively.</summary>
InteractiveSid = 11,
/// <summary>Indicates a SID for a service. This SID is added to the process of a token when it logs on as a service.</summary>
ServiceSid = 12,
/// <summary>Indicates a SID for the anonymous account.</summary>
AnonymousSid = 13,
/// <summary>Indicates a proxy SID.</summary>
ProxySid = 14,
/// <summary>Indicates a SID for an enterprise controller.</summary>
EnterpriseControllersSid = 15,
/// <summary>Indicates a SID for self.</summary>
SelfSid = 16,
/// <summary>Indicates a SID that matches any authenticated user.</summary>
AuthenticatedUserSid = 17,
/// <summary>Indicates a SID for restricted code.</summary>
RestrictedCodeSid = 18,
/// <summary>Indicates a SID that matches a terminal server account.</summary>
TerminalServerSid = 19,
/// <summary>Indicates a SID that matches remote logons.</summary>
RemoteLogonIdSid = 20,
/// <summary>Indicates a SID that matches logon IDs.</summary>
LogonIdsSid = 21,
/// <summary>Indicates a SID that matches the local system.</summary>
LocalSystemSid = 22,
/// <summary>Indicates a SID that matches a local service.</summary>
LocalServiceSid = 23,
/// <summary>Indicates a SID that matches a network service.</summary>
NetworkServiceSid = 24,
/// <summary>Indicates a SID that matches the domain account.</summary>
BuiltinDomainSid = 25,
/// <summary>Indicates a SID that matches the administrator group.</summary>
BuiltinAdministratorsSid = 26,
/// <summary>Indicates a SID that matches built-in user accounts.</summary>
BuiltinUsersSid = 27,
/// <summary>Indicates a SID that matches the guest account.</summary>
BuiltinGuestsSid = 28,
/// <summary>Indicates a SID that matches the power users group.</summary>
BuiltinPowerUsersSid = 29,
/// <summary>Indicates a SID that matches the account operators account.</summary>
BuiltinAccountOperatorsSid = 30,
/// <summary>Indicates a SID that matches the system operators group.</summary>
BuiltinSystemOperatorsSid = 31,
/// <summary>Indicates a SID that matches the print operators group.</summary>
BuiltinPrintOperatorsSid = 32,
/// <summary>Indicates a SID that matches the backup operators group.</summary>
BuiltinBackupOperatorsSid = 33,
/// <summary>Indicates a SID that matches the replicator account.</summary>
BuiltinReplicatorSid = 34,
/// <summary>Indicates a SID that matches pre-Windows 2000 compatible accounts.</summary>
BuiltinPreWindows2000CompatibleAccessSid = 35,
/// <summary>Indicates a SID that matches remote desktop users.</summary>
BuiltinRemoteDesktopUsersSid = 36,
/// <summary>Indicates a SID that matches the network operators group.</summary>
BuiltinNetworkConfigurationOperatorsSid = 37,
/// <summary>Indicates a SID that matches the account administrator's account.</summary>
AccountAdministratorSid = 38,
/// <summary>Indicates a SID that matches the account guest group.</summary>
AccountGuestSid = 39,
/// <summary>Indicates a SID that matches account Kerberos target group.</summary>
AccountKrbtgtSid = 40,
/// <summary>Indicates a SID that matches the account domain administrator group.</summary>
AccountDomainAdminsSid = 41,
/// <summary>Indicates a SID that matches the account domain users group.</summary>
AccountDomainUsersSid = 42,
/// <summary>Indicates a SID that matches the account domain guests group.</summary>
AccountDomainGuestsSid = 43,
/// <summary>Indicates a SID that matches the account computer group.</summary>
AccountComputersSid = 44,
/// <summary>Indicates a SID that matches the account controller group.</summary>
AccountControllersSid = 45,
/// <summary>Indicates a SID that matches the certificate administrators group.</summary>
AccountCertAdminsSid = 46,
/// <summary>Indicates a SID that matches the schema administrators group.</summary>
AccountSchemaAdminsSid = 47,
/// <summary>Indicates a SID that matches the enterprise administrators group.</summary>
AccountEnterpriseAdminsSid = 48,
/// <summary>Indicates a SID that matches the policy administrators group.</summary>
AccountPolicyAdminsSid = 49,
/// <summary>Indicates a SID that matches the RAS and IAS server account.</summary>
AccountRasAndIasServersSid = 50,
/// <summary>Indicates a SID present when the Microsoft NTLM authentication package authenticated the client.</summary>
NtlmAuthenticationSid = 51,
/// <summary>Indicates a SID present when the Microsoft Digest authentication package authenticated the client.</summary>
DigestAuthenticationSid = 52,
/// <summary>Indicates a SID present when the Secure Channel (SSL/TLS) authentication package authenticated the client.</summary>
SChannelAuthenticationSid = 53,
/// <summary>Indicates a SID present when the user authenticated from within the forest or across a trust that does not have the selective authentication option enabled. If this SID is present, then <see cref="OtherOrganizationSid"/> cannot be present.</summary>
ThisOrganizationSid = 54,
/// <summary>Indicates a SID present when the user authenticated across a forest with the selective authentication option enabled. If this SID is present, then <see cref="ThisOrganizationSid"/> cannot be present.</summary>
OtherOrganizationSid = 55,
/// <summary>Indicates a SID that allows a user to create incoming forest trusts. It is added to the token of users who are a member of the Incoming Forest Trust Builders built-in group in the root domain of the forest.</summary>
BuiltinIncomingForestTrustBuildersSid = 56,
/// <summary>Indicates a SID that matches the performance monitor user group.</summary>
BuiltinPerformanceMonitoringUsersSid = 57,
/// <summary>Indicates a SID that matches the performance log user group.</summary>
BuiltinPerformanceLoggingUsersSid = 58,
/// <summary>Indicates a SID that matches the Windows Authorization Access group.</summary>
BuiltinAuthorizationAccessSid = 59,
/// <summary>Indicates a SID is present in a server that can issue terminal server licenses.</summary>
WinBuiltinTerminalServerLicenseServersSid = 60,
[Obsolete("This member has been depcreated and is only maintained for backwards compatability. WellKnownSidType values greater than MaxDefined may be defined in future releases.")]
[EditorBrowsable(EditorBrowsableState.Never)]
MaxDefined = WinBuiltinTerminalServerLicenseServersSid,
/// <summary>Indicates a SID that matches the distributed COM user group.</summary>
WinBuiltinDCOMUsersSid = 61,
/// <summary>Indicates a SID that matches the Internet built-in user group.</summary>
WinBuiltinIUsersSid = 62,
/// <summary>Indicates a SID that matches the Internet user group.</summary>
WinIUserSid = 63,
/// <summary>Indicates a SID that allows a user to use cryptographic operations. It is added to the token of users who are a member of the CryptoOperators built-in group. </summary>
WinBuiltinCryptoOperatorsSid = 64,
/// <summary>Indicates a SID that matches an untrusted label.</summary>
WinUntrustedLabelSid = 65,
/// <summary>Indicates a SID that matches an low level of trust label.</summary>
WinLowLabelSid = 66,
/// <summary>Indicates a SID that matches an medium level of trust label.</summary>
WinMediumLabelSid = 67,
/// <summary>Indicates a SID that matches a high level of trust label.</summary>
WinHighLabelSid = 68,
/// <summary>Indicates a SID that matches a system label.</summary>
WinSystemLabelSid = 69,
/// <summary>Indicates a SID that matches a write restricted code group.</summary>
WinWriteRestrictedCodeSid = 70,
/// <summary>Indicates a SID that matches a creator and owner rights group.</summary>
WinCreatorOwnerRightsSid = 71,
/// <summary>Indicates a SID that matches a cacheable principals group.</summary>
WinCacheablePrincipalsGroupSid = 72,
/// <summary>Indicates a SID that matches a non-cacheable principals group.</summary>
WinNonCacheablePrincipalsGroupSid = 73,
/// <summary>Indicates a SID that matches an enterprise wide read-only controllers group.</summary>
WinEnterpriseReadonlyControllersSid = 74,
/// <summary>Indicates a SID that matches an account read-only controllers group.</summary>
WinAccountReadonlyControllersSid = 75,
/// <summary>Indicates a SID that matches an event log readers group.</summary>
WinBuiltinEventLogReadersGroup = 76,
/// <summary>Indicates a SID that matches a read-only enterprise domain controller.</summary>
WinNewEnterpriseReadonlyControllersSid = 77,
/// <summary>Indicates a SID that matches the built-in DCOM certification services access group.</summary>
WinBuiltinCertSvcDComAccessGroup = 78,
/// <summary>Indicates a SID that matches the medium plus integrity label.</summary>
WinMediumPlusLabelSid = 79,
/// <summary>Indicates a SID that matches a local logon group.</summary>
WinLocalLogonSid = 80,
/// <summary>Indicates a SID that matches a console logon group.</summary>
WinConsoleLogonSid = 81,
/// <summary>Indicates a SID that matches a certificate for the given organization.</summary>
WinThisOrganizationCertificateSid = 82,
/// <summary>Indicates a SID that matches the application package authority.</summary>
WinApplicationPackageAuthoritySid = 83,
/// <summary>Indicates a SID that applies to all app containers.</summary>
WinBuiltinAnyPackageSid = 84,
/// <summary>Indicates a SID of Internet client capability for app containers.</summary>
WinCapabilityInternetClientSid = 85,
/// <summary>Indicates a SID of Internet client and server capability for app containers.</summary>
WinCapabilityInternetClientServerSid = 86,
/// <summary>Indicates a SID of private network client and server capability for app containers.</summary>
WinCapabilityPrivateNetworkClientServerSid = 87,
/// <summary>Indicates a SID for pictures library capability for app containers.</summary>
WinCapabilityPicturesLibrarySid = 88,
/// <summary>Indicates a SID for videos library capability for app containers.</summary>
WinCapabilityVideosLibrarySid = 89,
/// <summary>Indicates a SID for music library capability for app containers.</summary>
WinCapabilityMusicLibrarySid = 90,
/// <summary>Indicates a SID for documents library capability for app containers.</summary>
WinCapabilityDocumentsLibrarySid = 91,
/// <summary>Indicates a SID for shared user certificates capability for app containers.</summary>
WinCapabilitySharedUserCertificatesSid = 92,
/// <summary>Indicates a SID for Windows credentials capability for app containers.</summary>
WinCapabilityEnterpriseAuthenticationSid = 93,
/// <summary>Indicates a SID for removable storage capability for app containers.</summary>
WinCapabilityRemovableStorageSid = 94
// Note: Adding additional values require changes everywhere where the value above is used as the maximum defined WellKnownSidType value.
// E.g. System.Security.Principal.SecurityIdentifier constructor
}
//
// This class implements revision 1 SIDs
// NOTE: The SecurityIdentifier class is immutable and must remain this way
//
public sealed class SecurityIdentifier : IdentityReference, IComparable<SecurityIdentifier>
{
#region Public Constants
//
// Identifier authority must be at most six bytes long
//
internal static readonly long MaxIdentifierAuthority = 0xFFFFFFFFFFFF;
//
// Maximum number of subauthorities in a SID
//
internal static readonly byte MaxSubAuthorities = 15;
//
// Minimum length of a binary representation of a SID
//
public static readonly int MinBinaryLength = 1 + 1 + 6; // Revision (1) + subauth count (1) + identifier authority (6)
//
// Maximum length of a binary representation of a SID
//
public static readonly int MaxBinaryLength = 1 + 1 + 6 + MaxSubAuthorities * 4; // 4 bytes for each subauth
#endregion
#region Private Members
//
// Immutable properties of a SID
//
private IdentifierAuthority _identifierAuthority;
private int[] _subAuthorities;
private byte[] _binaryForm;
private SecurityIdentifier _accountDomainSid;
private bool _accountDomainSidInitialized = false;
//
// Computed attributes of a SID
//
private string _sddlForm = null;
#endregion
#region Constructors
//
// Shared constructor logic
// NOTE: subauthorities are really unsigned integers, but due to CLS
// lack of support for unsigned integers the caller must perform
// the typecast
//
private void CreateFromParts(IdentifierAuthority identifierAuthority, int[] subAuthorities)
{
if (subAuthorities == null)
{
throw new ArgumentNullException(nameof(subAuthorities));
}
//
// Check the number of subauthorities passed in
//
if (subAuthorities.Length > MaxSubAuthorities)
{
throw new ArgumentOutOfRangeException(
"subAuthorities.Length",
subAuthorities.Length,
SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities));
}
//
// Identifier authority is at most 6 bytes long
//
if (identifierAuthority < 0 ||
(long)identifierAuthority > MaxIdentifierAuthority)
{
throw new ArgumentOutOfRangeException(
nameof(identifierAuthority),
identifierAuthority,
SR.IdentityReference_IdentifierAuthorityTooLarge);
}
//
// Create a local copy of the data passed in
//
_identifierAuthority = identifierAuthority;
_subAuthorities = new int[subAuthorities.Length];
subAuthorities.CopyTo(_subAuthorities, 0);
//
// Compute and store the binary form
//
// typedef struct _SID {
// UCHAR Revision;
// UCHAR SubAuthorityCount;
// SID_IDENTIFIER_AUTHORITY IdentifierAuthority;
// ULONG SubAuthority[ANYSIZE_ARRAY]
// } SID, *PISID;
//
byte i;
_binaryForm = new byte[1 + 1 + 6 + 4 * this.SubAuthorityCount];
//
// First two bytes contain revision and subauthority count
//
_binaryForm[0] = Revision;
_binaryForm[1] = (byte)this.SubAuthorityCount;
//
// Identifier authority takes up 6 bytes
//
for (i = 0; i < 6; i++)
{
_binaryForm[2 + i] = (byte)((((ulong)_identifierAuthority) >> ((5 - i) * 8)) & 0xFF);
}
//
// Subauthorities go last, preserving big-endian representation
//
for (i = 0; i < this.SubAuthorityCount; i++)
{
byte shift;
for (shift = 0; shift < 4; shift += 1)
{
_binaryForm[8 + 4 * i + shift] = unchecked((byte)(((ulong)_subAuthorities[i]) >> (shift * 8)));
}
}
}
private void CreateFromBinaryForm(byte[] binaryForm, int offset)
{
//
// Give us something to work with
//
if (binaryForm == null)
{
throw new ArgumentNullException(nameof(binaryForm));
}
//
// Negative offsets are not allowed
//
if (offset < 0)
{
throw new ArgumentOutOfRangeException(
nameof(offset),
offset,
SR.ArgumentOutOfRange_NeedNonNegNum);
}
//
// At least a minimum-size SID should fit in the buffer
//
if (binaryForm.Length - offset < SecurityIdentifier.MinBinaryLength)
{
throw new ArgumentOutOfRangeException(
nameof(binaryForm),
SR.ArgumentOutOfRange_ArrayTooSmall);
}
IdentifierAuthority Authority;
int[] SubAuthorities;
//
// Extract the elements of a SID
//
if (binaryForm[offset] != Revision)
{
//
// Revision is incorrect
//
throw new ArgumentException(
SR.IdentityReference_InvalidSidRevision,
nameof(binaryForm));
}
//
// Insist on the correct number of subauthorities
//
if (binaryForm[offset + 1] > MaxSubAuthorities)
{
throw new ArgumentException(
SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, MaxSubAuthorities),
nameof(binaryForm));
}
//
// Make sure the buffer is big enough
//
int Length = 1 + 1 + 6 + 4 * binaryForm[offset + 1];
if (binaryForm.Length - offset < Length)
{
throw new ArgumentException(
SR.ArgumentOutOfRange_ArrayTooSmall,
nameof(binaryForm));
}
Authority =
(IdentifierAuthority)(
(((long)binaryForm[offset + 2]) << 40) +
(((long)binaryForm[offset + 3]) << 32) +
(((long)binaryForm[offset + 4]) << 24) +
(((long)binaryForm[offset + 5]) << 16) +
(((long)binaryForm[offset + 6]) << 8) +
(((long)binaryForm[offset + 7])));
SubAuthorities = new int[binaryForm[offset + 1]];
//
// Subauthorities are represented in big-endian format
//
for (byte i = 0; i < binaryForm[offset + 1]; i++)
{
unchecked
{
SubAuthorities[i] =
(int)(
(((uint)binaryForm[offset + 8 + 4 * i + 0]) << 0) +
(((uint)binaryForm[offset + 8 + 4 * i + 1]) << 8) +
(((uint)binaryForm[offset + 8 + 4 * i + 2]) << 16) +
(((uint)binaryForm[offset + 8 + 4 * i + 3]) << 24));
}
}
CreateFromParts(Authority, SubAuthorities);
return;
}
//
// Constructs a SecurityIdentifier object from its string representation
// Returns 'null' if string passed in is not a valid SID
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier(string sddlForm)
{
byte[] resultSid;
//
// Give us something to work with
//
if (sddlForm == null)
{
throw new ArgumentNullException(nameof(sddlForm));
}
//
// Call into the underlying O/S conversion routine
//
int Error = Win32.CreateSidFromString(sddlForm, out resultSid);
if (Error == Interop.Errors.ERROR_INVALID_SID)
{
throw new ArgumentException(SR.Argument_InvalidValue, nameof(sddlForm));
}
else if (Error == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY)
{
throw new OutOfMemoryException();
}
else if (Error != Interop.Errors.ERROR_SUCCESS)
{
Debug.Fail($"Win32.CreateSidFromString returned unrecognized error {Error}");
throw new Win32Exception(Error);
}
CreateFromBinaryForm(resultSid, 0);
}
//
// Constructs a SecurityIdentifier object from its binary representation
//
public SecurityIdentifier(byte[] binaryForm, int offset)
{
CreateFromBinaryForm(binaryForm, offset);
}
//
// Constructs a SecurityIdentifier object from an IntPtr
//
public SecurityIdentifier(IntPtr binaryForm)
: this(binaryForm, true)
{
}
internal SecurityIdentifier(IntPtr binaryForm, bool noDemand)
: this(Win32.ConvertIntPtrSidToByteArraySid(binaryForm), 0)
{
}
//
// Constructs a well-known SID
// The 'domainSid' parameter is optional and only used
// by the well-known types that require it
// NOTE: although there is a P/Invoke call involved in the implementation of this constructor,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid)
{
//
// sidType must not be equal to LogonIdsSid
//
if (sidType == WellKnownSidType.LogonIdsSid)
{
throw new ArgumentException(SR.IdentityReference_CannotCreateLogonIdsSid, nameof(sidType));
}
byte[] resultSid;
int Error;
//
// sidType should not exceed the max defined value
//
if ((sidType < WellKnownSidType.NullSid) || (sidType > WellKnownSidType.WinCapabilityRemovableStorageSid))
{
throw new ArgumentException(SR.Argument_InvalidValue, nameof(sidType));
}
//
// for sidType between 38 to 50, the domainSid parameter must be specified
//
if ((sidType >= WellKnownSidType.AccountAdministratorSid) && (sidType <= WellKnownSidType.AccountRasAndIasServersSid))
{
if (domainSid == null)
{
throw new ArgumentNullException(nameof(domainSid), SR.Format(SR.IdentityReference_DomainSidRequired, sidType));
}
//
// verify that the domain sid is a valid windows domain sid
// to do that we call GetAccountDomainSid and the return value should be the same as the domainSid
//
SecurityIdentifier resultDomainSid;
int ErrorCode;
ErrorCode = Win32.GetWindowsAccountDomainSid(domainSid, out resultDomainSid);
if (ErrorCode == Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
{
throw new OutOfMemoryException();
}
else if (ErrorCode == Interop.Errors.ERROR_NON_ACCOUNT_SID)
{
// this means that the domain sid is not valid
throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid));
}
else if (ErrorCode != Interop.Errors.ERROR_SUCCESS)
{
Debug.Fail($"Win32.GetWindowsAccountDomainSid returned unrecognized error {ErrorCode}");
throw new Win32Exception(ErrorCode);
}
//
// if domainSid is passed in as S-1-5-21-3-4-5-6, the above api will return S-1-5-21-3-4-5 as the domainSid
// Since these do not match S-1-5-21-3-4-5-6 is not a valid domainSid (wrong number of subauthorities)
//
if (resultDomainSid != domainSid)
{
throw new ArgumentException(SR.IdentityReference_NotAWindowsDomain, nameof(domainSid));
}
}
Error = Win32.CreateWellKnownSid(sidType, domainSid, out resultSid);
if (Error == Interop.Errors.ERROR_INVALID_PARAMETER)
{
throw new ArgumentException(new Win32Exception(Error).Message, "sidType/domainSid");
}
else if (Error != Interop.Errors.ERROR_SUCCESS)
{
Debug.Fail($"Win32.CreateWellKnownSid returned unrecognized error {Error}");
throw new Win32Exception(Error);
}
CreateFromBinaryForm(resultSid, 0);
}
internal SecurityIdentifier(IdentifierAuthority identifierAuthority, int[] subAuthorities)
{
CreateFromParts(identifierAuthority, subAuthorities);
}
#endregion
#region Static Properties
//
// Revision is always '1'
//
internal static byte Revision
{
get
{
return 1;
}
}
#endregion
#region Non-static Properties
//
// This is for internal consumption only, hence it is marked 'internal'
// Making this call public would require a deep copy of the data to
// prevent the caller from messing with the internal representation.
//
internal byte[] BinaryForm
{
get
{
return _binaryForm;
}
}
internal IdentifierAuthority IdentifierAuthority
{
get
{
return _identifierAuthority;
}
}
internal int SubAuthorityCount
{
get
{
return _subAuthorities.Length;
}
}
public int BinaryLength
{
get
{
return _binaryForm.Length;
}
}
//
// Returns the domain portion of a SID or null if the specified
// SID is not an account SID
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public SecurityIdentifier AccountDomainSid
{
get
{
if (!_accountDomainSidInitialized)
{
_accountDomainSid = GetAccountDomainSid();
_accountDomainSidInitialized = true;
}
return _accountDomainSid;
}
}
#endregion
#region Inherited properties and methods
public override bool Equals(object o)
{
return (this == o as SecurityIdentifier); // invokes operator==
}
public bool Equals(SecurityIdentifier sid)
{
return (this == sid); // invokes operator==
}
public override int GetHashCode()
{
int hashCode = ((long)this.IdentifierAuthority).GetHashCode();
for (int i = 0; i < SubAuthorityCount; i++)
{
hashCode ^= this.GetSubAuthority(i);
}
return hashCode;
}
public override string ToString()
{
if (_sddlForm == null)
{
//
// Typecasting of _IdentifierAuthority to a ulong below is important, since
// otherwise you would see this: "S-1-NTAuthority-32-544"
//
#if netcoreapp20
StringBuilder result = new StringBuilder();
result.Append("S-1-").Append((ulong)_identifierAuthority);
for (int i = 0; i < SubAuthorityCount; i++)
{
result.Append('-').Append((uint)(_subAuthorities[i]));
}
_sddlForm = result.ToString();
#else
// length of buffer calculation
// prefix = "S-1-".Length: 4;
// authority: ulong.MaxValue.ToString("D") : 20;
// subauth = MaxSubAuthorities * ( uint.MaxValue.ToString("D").Length + '-'.Length ): 15 * (10+1): 165;
// max possible length = 4 + 20 + 165: 189
Span<char> result = stackalloc char[189];
result[0] = 'S';
result[1] = '-';
result[2] = '1';
result[3] = '-';
int written;
int length = 4;
((ulong)_identifierAuthority).TryFormat(result.Slice(length), out written);
length += written;
int[] values = _subAuthorities;
for (int index = 0; index < values.Length; index++)
{
result[length] = '-';
length += 1;
((uint)values[index]).TryFormat(result.Slice(length), out written);
length += written;
}
_sddlForm = result.Slice(0, length).ToString();
#endif
}
return _sddlForm;
}
public override string Value
{
get
{
return ToString().ToUpperInvariant();
}
}
internal static bool IsValidTargetTypeStatic(Type targetType)
{
if (targetType == typeof(NTAccount))
{
return true;
}
else if (targetType == typeof(SecurityIdentifier))
{
return true;
}
else
{
return false;
}
}
public override bool IsValidTargetType(Type targetType)
{
return IsValidTargetTypeStatic(targetType);
}
internal SecurityIdentifier GetAccountDomainSid()
{
SecurityIdentifier ResultSid;
int Error;
Error = Win32.GetWindowsAccountDomainSid(this, out ResultSid);
if (Error == Interop.Errors.ERROR_INSUFFICIENT_BUFFER)
{
throw new OutOfMemoryException();
}
else if (Error == Interop.Errors.ERROR_NON_ACCOUNT_SID)
{
ResultSid = null;
}
else if (Error != Interop.Errors.ERROR_SUCCESS)
{
Debug.Fail($"Win32.GetWindowsAccountDomainSid returned unrecognized error {Error}");
throw new Win32Exception(Error);
}
return ResultSid;
}
public bool IsAccountSid()
{
if (!_accountDomainSidInitialized)
{
_accountDomainSid = GetAccountDomainSid();
_accountDomainSidInitialized = true;
}
if (_accountDomainSid == null)
{
return false;
}
return true;
}
public override IdentityReference Translate(Type targetType)
{
if (targetType == null)
{
throw new ArgumentNullException(nameof(targetType));
}
if (targetType == typeof(SecurityIdentifier))
{
return this; // assumes SecurityIdentifier objects are immutable
}
else if (targetType == typeof(NTAccount))
{
IdentityReferenceCollection irSource = new IdentityReferenceCollection(1);
irSource.Add(this);
IdentityReferenceCollection irTarget;
irTarget = SecurityIdentifier.Translate(irSource, targetType, true);
return irTarget[0];
}
else
{
throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType));
}
}
#endregion
#region Operators
public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right)
{
object l = left;
object r = right;
if (l == r)
{
return true;
}
else if (l == null || r == null)
{
return false;
}
else
{
return (left.CompareTo(right) == 0);
}
}
public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right)
{
return !(left == right);
}
#endregion
#region IComparable implementation
public int CompareTo(SecurityIdentifier sid)
{
if (sid == null)
{
throw new ArgumentNullException(nameof(sid));
}
if (this.IdentifierAuthority < sid.IdentifierAuthority)
{
return -1;
}
if (this.IdentifierAuthority > sid.IdentifierAuthority)
{
return 1;
}
if (this.SubAuthorityCount < sid.SubAuthorityCount)
{
return -1;
}
if (this.SubAuthorityCount > sid.SubAuthorityCount)
{
return 1;
}
for (int i = 0; i < this.SubAuthorityCount; i++)
{
int diff = this.GetSubAuthority(i) - sid.GetSubAuthority(i);
if (diff != 0)
{
return diff;
}
}
return 0;
}
#endregion
#region Public Methods
internal int GetSubAuthority(int index)
{
return _subAuthorities[index];
}
//
// Determines whether this SID is a well-known SID of the specified type
//
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public bool IsWellKnown(WellKnownSidType type)
{
return Win32.IsWellKnownSid(this, type);
}
public void GetBinaryForm(byte[] binaryForm, int offset)
{
_binaryForm.CopyTo(binaryForm, offset);
}
//
// NOTE: although there is a P/Invoke call involved in the implementation of this method,
// there is no security risk involved, so no security demand is being made.
//
public bool IsEqualDomainSid(SecurityIdentifier sid)
{
return Win32.IsEqualDomainSid(this, sid);
}
private static IdentityReferenceCollection TranslateToNTAccounts(IdentityReferenceCollection sourceSids, out bool someFailed)
{
if (sourceSids == null)
{
throw new ArgumentNullException(nameof(sourceSids));
}
if (sourceSids.Count == 0)
{
throw new ArgumentException(SR.Arg_EmptyCollection, nameof(sourceSids));
}
IntPtr[] SidArrayPtr = new IntPtr[sourceSids.Count];
GCHandle[] HandleArray = new GCHandle[sourceSids.Count];
SafeLsaPolicyHandle LsaHandle = null;
SafeLsaMemoryHandle ReferencedDomainsPtr = null;
SafeLsaMemoryHandle NamesPtr = null;
try
{
//
// Pin all elements in the array of SIDs
//
int currentSid = 0;
foreach (IdentityReference id in sourceSids)
{
SecurityIdentifier sid = id as SecurityIdentifier;
if (sid == null)
{
throw new ArgumentException(SR.Argument_ImproperType, nameof(sourceSids));
}
HandleArray[currentSid] = GCHandle.Alloc(sid.BinaryForm, GCHandleType.Pinned);
SidArrayPtr[currentSid] = HandleArray[currentSid].AddrOfPinnedObject();
currentSid++;
}
//
// Open LSA policy (for lookup requires it)
//
LsaHandle = Win32.LsaOpenPolicy(null, PolicyRights.POLICY_LOOKUP_NAMES);
//
// Perform the actual lookup
//
someFailed = false;
uint ReturnCode;
ReturnCode = Interop.Advapi32.LsaLookupSids(LsaHandle, sourceSids.Count, SidArrayPtr, out ReferencedDomainsPtr, out NamesPtr);
//
// Make a decision regarding whether it makes sense to proceed
// based on the return code and the value of the forceSuccess argument
//
if (ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY ||
ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES)
{
throw new OutOfMemoryException();
}
else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (ReturnCode == Interop.StatusOptions.STATUS_NONE_MAPPED ||
ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
{
someFailed = true;
}
else if (ReturnCode != 0)
{
uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError(ReturnCode);
Debug.Fail($"Interop.LsaLookupSids returned {win32ErrorCode}");
throw new Win32Exception(unchecked((int)win32ErrorCode));
}
NamesPtr.Initialize((uint)sourceSids.Count, (uint)Marshal.SizeOf<Interop.LSA_TRANSLATED_NAME>());
Win32.InitializeReferencedDomainsPointer(ReferencedDomainsPtr);
//
// Interpret the results and generate NTAccount objects
//
IdentityReferenceCollection Result = new IdentityReferenceCollection(sourceSids.Count);
if (ReturnCode == 0 || ReturnCode == Interop.StatusOptions.STATUS_SOME_NOT_MAPPED)
{
//
// Interpret the results and generate NT Account objects
//
Interop.LSA_REFERENCED_DOMAIN_LIST rdl = ReferencedDomainsPtr.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0);
string[] ReferencedDomains = new string[rdl.Entries];
for (int i = 0; i < rdl.Entries; i++)
{
Interop.LSA_TRUST_INFORMATION ti = (Interop.LSA_TRUST_INFORMATION)Marshal.PtrToStructure<Interop.LSA_TRUST_INFORMATION>(new IntPtr((long)rdl.Domains + i * Marshal.SizeOf<Interop.LSA_TRUST_INFORMATION>()));
ReferencedDomains[i] = Marshal.PtrToStringUni(ti.Name.Buffer, ti.Name.Length / sizeof(char));
}
Interop.LSA_TRANSLATED_NAME[] translatedNames = new Interop.LSA_TRANSLATED_NAME[sourceSids.Count];
NamesPtr.ReadArray(0, translatedNames, 0, translatedNames.Length);
for (int i = 0; i < sourceSids.Count; i++)
{
Interop.LSA_TRANSLATED_NAME Ltn = translatedNames[i];
switch ((SidNameUse)Ltn.Use)
{
case SidNameUse.User:
case SidNameUse.Group:
case SidNameUse.Alias:
case SidNameUse.Computer:
case SidNameUse.WellKnownGroup:
string account = Marshal.PtrToStringUni(Ltn.Name.Buffer, Ltn.Name.Length / sizeof(char)); ;
string domain = ReferencedDomains[Ltn.DomainIndex];
Result.Add(new NTAccount(domain, account));
break;
default:
someFailed = true;
Result.Add(sourceSids[i]);
break;
}
}
}
else
{
for (int i = 0; i < sourceSids.Count; i++)
{
Result.Add(sourceSids[i]);
}
}
return Result;
}
finally
{
for (int i = 0; i < sourceSids.Count; i++)
{
if (HandleArray[i].IsAllocated)
{
HandleArray[i].Free();
}
}
LsaHandle?.Dispose();
ReferencedDomainsPtr?.Dispose();
NamesPtr?.Dispose();
}
}
internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, bool forceSuccess)
{
bool SomeFailed = false;
IdentityReferenceCollection Result;
Result = Translate(sourceSids, targetType, out SomeFailed);
if (forceSuccess && SomeFailed)
{
IdentityReferenceCollection UnmappedIdentities = new IdentityReferenceCollection();
foreach (IdentityReference id in Result)
{
if (id.GetType() != targetType)
{
UnmappedIdentities.Add(id);
}
}
throw new IdentityNotMappedException(SR.IdentityReference_IdentityNotMapped, UnmappedIdentities);
}
return Result;
}
internal static IdentityReferenceCollection Translate(IdentityReferenceCollection sourceSids, Type targetType, out bool someFailed)
{
if (sourceSids == null)
{
throw new ArgumentNullException(nameof(sourceSids));
}
if (targetType == typeof(NTAccount))
{
return TranslateToNTAccounts(sourceSids, out someFailed);
}
throw new ArgumentException(SR.IdentityReference_MustBeIdentityReference, nameof(targetType));
}
#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.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
namespace System.Globalization
{
//
// List of calendar data
// Note the we cache overrides.
// Note that localized names (resource names) aren't available from here.
//
// NOTE: Calendars depend on the locale name that creates it. Only a few
// properties are available without locales using CalendarData.GetCalendar(CalendarData)
internal partial class CalendarData
{
// Max calendars
internal const int MAX_CALENDARS = 23;
// Identity
internal String sNativeName; // Calendar Name for the locale
// Formats
internal String[] saShortDates; // Short Data format, default first
internal String[] saYearMonths; // Year/Month Data format, default first
internal String[] saLongDates; // Long Data format, default first
internal String sMonthDay; // Month/Day format
// Calendar Parts Names
internal String[] saEraNames; // Names of Eras
internal String[] saAbbrevEraNames; // Abbreviated Era Names
internal String[] saAbbrevEnglishEraNames; // Abbreviated Era Names in English
internal String[] saDayNames; // Day Names, null to use locale data, starts on Sunday
internal String[] saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
internal String[] saSuperShortDayNames; // Super short Day of week names
internal String[] saMonthNames; // Month Names (13)
internal String[] saAbbrevMonthNames; // Abbrev Month Names (13)
internal String[] saMonthGenitiveNames; // Genitive Month Names (13)
internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13)
internal String[] saLeapYearMonthNames; // Multiple strings for the month names in a leap year.
// Integers at end to make marshaller happier
internal int iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
internal int iCurrentEra = 0; // current era # (usually 1)
// Use overrides?
internal bool bUseUserOverrides; // True if we want user overrides.
// Static invariant for the invariant locale
internal static CalendarData Invariant;
// Private constructor
private CalendarData() { }
// Invariant constructor
static CalendarData()
{
// Set our default/gregorian US calendar data
// Calendar IDs are 1-based, arrays are 0 based.
CalendarData invariant = new CalendarData();
// Set default data for calendar
// Note that we don't load resources since this IS NOT supposed to change (by definition)
invariant.sNativeName = "Gregorian Calendar"; // Calendar Name
// Year
invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
invariant.iCurrentEra = 1; // Current era #
// Formats
invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format
invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy" }; // long date format
invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format
invariant.sMonthDay = "MMMM dd"; // Month day pattern
// Calendar Parts Names
invariant.saEraNames = new String[] { "A.D." }; // Era names
invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names
invariant.saAbbrevEnglishEraNames = new String[] { "AD" }; // Abbreviated era names in English
invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names
invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names
invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names
invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December", String.Empty}; // month names
invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", String.Empty}; // abbreviated month names
invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant)
invariant.saAbbrevMonthGenitiveNames = invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant)
invariant.bUseUserOverrides = false;
// Calendar was built, go ahead and assign it...
Invariant = invariant;
}
//
// Get a bunch of data for a calendar
//
internal CalendarData(String localeName, CalendarId calendarId, bool bUseUserOverrides)
{
this.bUseUserOverrides = bUseUserOverrides;
if (!LoadCalendarDataFromSystem(localeName, calendarId))
{
Contract.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName);
// Something failed, try invariant for missing parts
// This is really not good, but we don't want the callers to crash.
if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale.
// Formats
if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first
if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first
if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates; // Long Data format, default first
if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay; // Month/Day format
// Calendar Parts Names
if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames; // Names of Eras
if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames; // Abbreviated Era Names
if (this.saAbbrevEnglishEraNames == null) this.saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English
if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday
if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames; // Super short Day of week names
if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames; // Month Names (13)
if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames; // Abbrev Month Names (13)
// Genitive and Leap names can follow the fallback below
}
if (calendarId == CalendarId.TAIWAN)
{
if (SystemSupportsTaiwaneseCalendar())
{
// We got the month/day names from the OS (same as gregorian), but the native name is wrong
this.sNativeName = "\x4e2d\x83ef\x6c11\x570b\x66c6";
}
else
{
this.sNativeName = String.Empty;
}
}
// Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc)
if (this.saMonthGenitiveNames == null || this.saMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saMonthGenitiveNames[0]))
this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant)
if (this.saAbbrevMonthGenitiveNames == null || this.saAbbrevMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0]))
this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
if (this.saLeapYearMonthNames == null || this.saLeapYearMonthNames.Length == 0 || String.IsNullOrEmpty(this.saLeapYearMonthNames[0]))
this.saLeapYearMonthNames = this.saMonthNames;
InitializeEraNames(localeName, calendarId);
InitializeAbbreviatedEraNames(localeName, calendarId);
// Abbreviated English Era Names are only used for the Japanese calendar.
if (calendarId == CalendarId.JAPAN)
{
this.saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames();
}
else
{
// For all others just use the an empty string (doesn't matter we'll never ask for it for other calendars)
this.saAbbrevEnglishEraNames = new String[] { "" };
}
// Japanese is the only thing with > 1 era. Its current era # is how many ever
// eras are in the array. (And the others all have 1 string in the array)
this.iCurrentEra = this.saEraNames.Length;
}
private void InitializeEraNames(string localeName, CalendarId calendarId)
{
// Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows
switch (calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0]))
{
this.saEraNames = new String[] { "A.D." };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saEraNames = new String[] { "A.D." };
break;
case CalendarId.HEBREW:
this.saEraNames = new String[] { "C.E." };
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saEraNames = new String[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" };
}
else
{
this.saEraNames = new String[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" };
}
break;
case CalendarId.GREGORIAN_ARABIC:
case CalendarId.GREGORIAN_XLIT_ENGLISH:
case CalendarId.GREGORIAN_XLIT_FRENCH:
// These are all the same:
this.saEraNames = new String[] { "\x0645" };
break;
case CalendarId.GREGORIAN_ME_FRENCH:
this.saEraNames = new String[] { "ap. J.-C." };
break;
case CalendarId.TAIWAN:
if (SystemSupportsTaiwaneseCalendar())
{
this.saEraNames = new String[] { "\x4e2d\x83ef\x6c11\x570b" };
}
else
{
this.saEraNames = new String[] { String.Empty };
}
break;
case CalendarId.KOREA:
this.saEraNames = new String[] { "\xb2e8\xae30" };
break;
case CalendarId.THAI:
this.saEraNames = new String[] { "\x0e1e\x002e\x0e28\x002e" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saEraNames = JapaneseCalendar.EraNames();
break;
default:
// Most calendars are just "A.D."
this.saEraNames = Invariant.saEraNames;
break;
}
}
private void InitializeAbbreviatedEraNames(string localeName, CalendarId calendarId)
{
// Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows
switch (calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
{
this.saAbbrevEraNames = new String[] { "AD" };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saAbbrevEraNames = new String[] { "AD" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames();
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saAbbrevEraNames = new String[] { "\x0780\x002e" };
}
else
{
this.saAbbrevEraNames = new String[] { "\x0647\x0640" };
}
break;
case CalendarId.TAIWAN:
// Get era name and abbreviate it
this.saAbbrevEraNames = new String[1];
if (this.saEraNames[0].Length == 4)
{
this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2, 2);
}
else
{
this.saAbbrevEraNames[0] = this.saEraNames[0];
}
break;
default:
// Most calendars just use the full name
this.saAbbrevEraNames = this.saEraNames;
break;
}
}
internal static CalendarData GetCalendarData(CalendarId calendarId)
{
//
// Get a calendar.
// Unfortunately we depend on the locale in the OS, so we need a locale
// no matter what. So just get the appropriate calendar from the
// appropriate locale here
//
// Get a culture name
// TODO: NLS Arrowhead Arrowhead - note that this doesn't handle the new calendars (lunisolar, etc)
String culture = CalendarIdToCultureName(calendarId);
// Return our calendar
return CultureInfo.GetCultureInfo(culture).m_cultureData.GetCalendar(calendarId);
}
private static String CalendarIdToCultureName(CalendarId calendarId)
{
switch (calendarId)
{
case CalendarId.GREGORIAN_US:
return "fa-IR"; // "fa-IR" Iran
case CalendarId.JAPAN:
return "ja-JP"; // "ja-JP" Japan
case CalendarId.TAIWAN:
return "zh-TW"; // zh-TW Taiwan
case CalendarId.KOREA:
return "ko-KR"; // "ko-KR" Korea
case CalendarId.HIJRI:
case CalendarId.GREGORIAN_ARABIC:
case CalendarId.UMALQURA:
return "ar-SA"; // "ar-SA" Saudi Arabia
case CalendarId.THAI:
return "th-TH"; // "th-TH" Thailand
case CalendarId.HEBREW:
return "he-IL"; // "he-IL" Israel
case CalendarId.GREGORIAN_ME_FRENCH:
return "ar-DZ"; // "ar-DZ" Algeria
case CalendarId.GREGORIAN_XLIT_ENGLISH:
case CalendarId.GREGORIAN_XLIT_FRENCH:
return "ar-IQ"; // "ar-IQ"; Iraq
default:
// Default to gregorian en-US
break;
}
return "en-US";
}
}
}
| |
// Posted by Jeff Brown here:
// http://www.codeproject.com/Articles/15633/Manipulating-NTFS-Junction-Points-in-NET
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace Monitor.Core.Utilities
{
/// <summary>
/// Provides access to NTFS junction points in .Net.
/// </summary>
public static class JunctionPoint
{
/// <summary>
/// The file or directory is not a reparse point.
/// </summary>
private const int ERROR_NOT_A_REPARSE_POINT = 4390;
/// <summary>
/// The reparse point attribute cannot be set because it conflicts with an existing attribute.
/// </summary>
private const int ERROR_REPARSE_ATTRIBUTE_CONFLICT = 4391;
/// <summary>
/// The data present in the reparse point buffer is invalid.
/// </summary>
private const int ERROR_INVALID_REPARSE_DATA = 4392;
/// <summary>
/// The tag present in the reparse point buffer is invalid.
/// </summary>
private const int ERROR_REPARSE_TAG_INVALID = 4393;
/// <summary>
/// There is a mismatch between the tag specified in the request and the tag present in the reparse point.
/// </summary>
private const int ERROR_REPARSE_TAG_MISMATCH = 4394;
/// <summary>
/// Command to set the reparse point data block.
/// </summary>
private const int FSCTL_SET_REPARSE_POINT = 0x000900A4;
/// <summary>
/// Command to get the reparse point data block.
/// </summary>
private const int FSCTL_GET_REPARSE_POINT = 0x000900A8;
/// <summary>
/// Command to delete the reparse point data base.
/// </summary>
private const int FSCTL_DELETE_REPARSE_POINT = 0x000900AC;
/// <summary>
/// Reparse point tag used to identify mount points and junction points.
/// </summary>
private const uint IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003;
/// <summary>
/// This prefix indicates to NTFS that the path is to be treated as a non-interpreted
/// path in the virtual file system.
/// </summary>
private const string NonInterpretedPathPrefix = @"\??\";
[Flags]
private enum EFileAccess : uint
{
GenericRead = 0x80000000,
GenericWrite = 0x40000000,
GenericExecute = 0x20000000,
GenericAll = 0x10000000,
}
[Flags]
private enum EFileShare : uint
{
None = 0x00000000,
Read = 0x00000001,
Write = 0x00000002,
Delete = 0x00000004,
}
private enum ECreationDisposition : uint
{
New = 1,
CreateAlways = 2,
OpenExisting = 3,
OpenAlways = 4,
TruncateExisting = 5,
}
[Flags]
private enum EFileAttributes : uint
{
Readonly = 0x00000001,
Hidden = 0x00000002,
System = 0x00000004,
Directory = 0x00000010,
Archive = 0x00000020,
Device = 0x00000040,
Normal = 0x00000080,
Temporary = 0x00000100,
SparseFile = 0x00000200,
ReparsePoint = 0x00000400,
Compressed = 0x00000800,
Offline = 0x00001000,
NotContentIndexed = 0x00002000,
Encrypted = 0x00004000,
Write_Through = 0x80000000,
Overlapped = 0x40000000,
NoBuffering = 0x20000000,
RandomAccess = 0x10000000,
SequentialScan = 0x08000000,
DeleteOnClose = 0x04000000,
BackupSemantics = 0x02000000,
PosixSemantics = 0x01000000,
OpenReparsePoint = 0x00200000,
OpenNoRecall = 0x00100000,
FirstPipeInstance = 0x00080000
}
[StructLayout(LayoutKind.Sequential)]
private struct REPARSE_DATA_BUFFER
{
/// <summary>
/// Reparse point tag. Must be a Microsoft reparse point tag.
/// </summary>
public uint ReparseTag;
/// <summary>
/// Size, in bytes, of the data after the Reserved member. This can be calculated by:
/// (4 * sizeof(ushort)) + SubstituteNameLength + PrintNameLength +
/// (namesAreNullTerminated ? 2 * sizeof(char) : 0);
/// </summary>
public ushort ReparseDataLength;
/// <summary>
/// Reserved; do not use.
/// </summary>
public ushort Reserved;
/// <summary>
/// Offset, in bytes, of the substitute name string in the PathBuffer array.
/// </summary>
public ushort SubstituteNameOffset;
/// <summary>
/// Length, in bytes, of the substitute name string. If this string is null-terminated,
/// SubstituteNameLength does not include space for the null character.
/// </summary>
public ushort SubstituteNameLength;
/// <summary>
/// Offset, in bytes, of the print name string in the PathBuffer array.
/// </summary>
public ushort PrintNameOffset;
/// <summary>
/// Length, in bytes, of the print name string. If this string is null-terminated,
/// PrintNameLength does not include space for the null character.
/// </summary>
public ushort PrintNameLength;
/// <summary>
/// A buffer containing the unicode-encoded path string. The path string contains
/// the substitute name string and print name string.
/// </summary>
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3FF0)]
public byte[] PathBuffer;
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode,
IntPtr InBuffer, int nInBufferSize,
IntPtr OutBuffer, int nOutBufferSize,
out int pBytesReturned, IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr CreateFile(
string lpFileName,
EFileAccess dwDesiredAccess,
EFileShare dwShareMode,
IntPtr lpSecurityAttributes,
ECreationDisposition dwCreationDisposition,
EFileAttributes dwFlagsAndAttributes,
IntPtr hTemplateFile);
/// <summary>
/// Creates a junction point from the specified directory to the specified target directory.
/// </summary>
/// <remarks>
/// Only works on NTFS.
/// </remarks>
/// <param name="junctionPoint">The junction point path</param>
/// <param name="targetDir">The target directory</param>
/// <param name="overwrite">If true overwrites an existing reparse point or empty directory</param>
/// <exception cref="IOException">Thrown when the junction point could not be created or when
/// an existing directory was found and <paramref name="overwrite" /> if false</exception>
public static void Create(string junctionPoint, string targetDir, bool overwrite)
{
targetDir = Path.GetFullPath(targetDir);
if (!Directory.Exists(targetDir))
throw new IOException("Target path does not exist or is not a directory.");
if (Directory.Exists(junctionPoint))
{
if (!overwrite)
throw new IOException("Directory already exists and overwrite parameter is false.");
}
else
{
Directory.CreateDirectory(junctionPoint);
}
using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite))
{
byte[] targetDirBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(targetDir));
REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER();
reparseDataBuffer.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
reparseDataBuffer.ReparseDataLength = (ushort)(targetDirBytes.Length + 12);
reparseDataBuffer.SubstituteNameOffset = 0;
reparseDataBuffer.SubstituteNameLength = (ushort)targetDirBytes.Length;
reparseDataBuffer.PrintNameOffset = (ushort)(targetDirBytes.Length + 2);
reparseDataBuffer.PrintNameLength = 0;
reparseDataBuffer.PathBuffer = new byte[0x3ff0];
Array.Copy(targetDirBytes, reparseDataBuffer.PathBuffer, targetDirBytes.Length);
int inBufferSize = Marshal.SizeOf(reparseDataBuffer);
IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize);
try
{
Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);
int bytesReturned;
bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT,
inBuffer, targetDirBytes.Length + 20, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);
if (!result)
ThrowLastWin32Error("Unable to create junction point.");
}
finally
{
Marshal.FreeHGlobal(inBuffer);
}
}
}
/// <summary>
/// Deletes a junction point at the specified source directory along with the directory itself.
/// Does nothing if the junction point does not exist.
/// </summary>
/// <remarks>
/// Only works on NTFS.
/// </remarks>
/// <param name="junctionPoint">The junction point path</param>
public static void Delete(string junctionPoint)
{
if (!Directory.Exists(junctionPoint))
{
if (File.Exists(junctionPoint))
throw new IOException("Path is not a junction point.");
return;
}
using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite))
{
REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER();
reparseDataBuffer.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
reparseDataBuffer.ReparseDataLength = 0;
reparseDataBuffer.PathBuffer = new byte[0x3ff0];
int inBufferSize = Marshal.SizeOf(reparseDataBuffer);
IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize);
try
{
Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);
int bytesReturned;
bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_DELETE_REPARSE_POINT,
inBuffer, 8, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);
if (!result)
ThrowLastWin32Error("Unable to delete junction point.");
}
finally
{
Marshal.FreeHGlobal(inBuffer);
}
try
{
Directory.Delete(junctionPoint);
}
catch (IOException ex)
{
throw new IOException("Unable to delete junction point.", ex);
}
}
}
/// <summary>
/// Determines whether the specified path exists and refers to a junction point.
/// </summary>
/// <param name="path">The junction point path</param>
/// <returns>True if the specified path represents a junction point</returns>
/// <exception cref="IOException">Thrown if the specified path is invalid
/// or some other error occurs</exception>
public static bool Exists(string path)
{
if (! Directory.Exists(path))
return false;
using (SafeFileHandle handle = OpenReparsePoint(path, EFileAccess.GenericRead))
{
string target = InternalGetTarget(handle);
return target != null;
}
}
/// <summary>
/// Gets the target of the specified junction point.
/// </summary>
/// <remarks>
/// Only works on NTFS.
/// </remarks>
/// <param name="junctionPoint">The junction point path</param>
/// <returns>The target of the junction point</returns>
/// <exception cref="IOException">Thrown when the specified path does not
/// exist, is invalid, is not a junction point, or some other error occurs</exception>
public static string GetTarget(string junctionPoint)
{
using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericRead))
{
string target = InternalGetTarget(handle);
if (target == null)
throw new IOException("Path is not a junction point.");
return target;
}
}
private static string InternalGetTarget(SafeFileHandle handle)
{
int outBufferSize = Marshal.SizeOf(typeof(REPARSE_DATA_BUFFER));
IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize);
try
{
int bytesReturned;
bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_GET_REPARSE_POINT,
IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero);
if (!result)
{
int error = Marshal.GetLastWin32Error();
if (error == ERROR_NOT_A_REPARSE_POINT)
return null;
ThrowLastWin32Error("Unable to get information about junction point.");
}
REPARSE_DATA_BUFFER reparseDataBuffer = (REPARSE_DATA_BUFFER)
Marshal.PtrToStructure(outBuffer, typeof(REPARSE_DATA_BUFFER));
if (reparseDataBuffer.ReparseTag != IO_REPARSE_TAG_MOUNT_POINT)
return null;
string targetDir = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer,
reparseDataBuffer.SubstituteNameOffset, reparseDataBuffer.SubstituteNameLength);
if (targetDir.StartsWith(NonInterpretedPathPrefix))
targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length);
return targetDir;
}
finally
{
Marshal.FreeHGlobal(outBuffer);
}
}
private static SafeFileHandle OpenReparsePoint(string reparsePoint, EFileAccess accessMode)
{
SafeFileHandle reparsePointHandle = new SafeFileHandle(CreateFile(reparsePoint, accessMode,
EFileShare.Read | EFileShare.Write | EFileShare.Delete,
IntPtr.Zero, ECreationDisposition.OpenExisting,
EFileAttributes.BackupSemantics | EFileAttributes.OpenReparsePoint, IntPtr.Zero), true);
if (Marshal.GetLastWin32Error() != 0)
ThrowLastWin32Error("Unable to open reparse point.");
return reparsePointHandle;
}
private static void ThrowLastWin32Error(string message)
{
throw new IOException(message, Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
}
}
}
| |
// 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.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
//
// Note: F# compiler depends on the exact tuple hashing algorithm. Do not ever change it.
//
namespace System
{
/// <summary>
/// Helper so we can call some tuple methods recursively without knowing the underlying types.
/// </summary>
internal interface ITupleInternal : ITuple
{
string ToString(StringBuilder sb);
int GetHashCode(IEqualityComparer comparer);
}
public static class Tuple
{
public static Tuple<T1> Create<T1>(T1 item1)
{
return new Tuple<T1>(item1);
}
public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
{
return new Tuple<T1, T2>(item1, item2);
}
public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3)
{
return new Tuple<T1, T2, T3>(item1, item2, item3);
}
public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4)
{
return new Tuple<T1, T2, T3, T4>(item1, item2, item3, item4);
}
public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
{
return new Tuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
}
public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
{
return new Tuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6);
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
{
return new Tuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7);
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8)
{
return new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>(item1, item2, item3, item4, item5, item6, item7, new Tuple<T8>(item8));
}
// From System.Web.Util.HashCodeCombiner
internal static int CombineHashCodes(int h1, int h2)
{
return (((h1 << 5) + h1) ^ h2);
}
internal static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4)
{
return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5)
{
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5);
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6)
{
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7)
{
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7));
}
internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8)
{
return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8));
}
}
[Serializable]
public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1;
public T1 Item1 { get { return m_Item1; } }
public Tuple(T1 item1)
{
m_Item1 = item1;
}
public override Boolean Equals(Object obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default);
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
{
if (other == null) return false;
Tuple<T1> objTuple = other as Tuple<T1>;
if (objTuple == null)
{
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1);
}
Int32 IComparable.CompareTo(Object obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
{
if (other == null) return 1;
Tuple<T1> objTuple = other as Tuple<T1>;
if (objTuple == null)
{
throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
return comparer.Compare(m_Item1, objTuple.m_Item1);
}
public override int GetHashCode()
{
return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return comparer.GetHashCode(m_Item1);
}
Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.ToString(StringBuilder sb)
{
sb.Append(m_Item1);
sb.Append(")");
return sb.ToString();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 1;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
if (index != 0)
{
throw new IndexOutOfRangeException();
}
return Item1;
}
}
}
[Serializable]
public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1;
private readonly T2 m_Item2;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public Tuple(T1 item1, T2 item2)
{
m_Item1 = item1;
m_Item2 = item2;
}
public override Boolean Equals(Object obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
{
if (other == null) return false;
Tuple<T1, T2> objTuple = other as Tuple<T1, T2>;
if (objTuple == null)
{
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2);
}
Int32 IComparable.CompareTo(Object obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
{
if (other == null) return 1;
Tuple<T1, T2> objTuple = other as Tuple<T1, T2>;
if (objTuple == null)
{
throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
return comparer.Compare(m_Item2, objTuple.m_Item2);
}
public override int GetHashCode()
{
return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2));
}
Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.ToString(StringBuilder sb)
{
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(")");
return sb.ToString();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 2;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
default:
throw new IndexOutOfRangeException();
}
}
}
}
[Serializable]
public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public Tuple(T1 item1, T2 item2, T3 item3)
{
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
}
public override Boolean Equals(Object obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
{
if (other == null) return false;
Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>;
if (objTuple == null)
{
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3);
}
Int32 IComparable.CompareTo(Object obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
{
if (other == null) return 1;
Tuple<T1, T2, T3> objTuple = other as Tuple<T1, T2, T3>;
if (objTuple == null)
{
throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
return comparer.Compare(m_Item3, objTuple.m_Item3);
}
public override int GetHashCode()
{
return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3));
}
Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.ToString(StringBuilder sb)
{
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(")");
return sb.ToString();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 3;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
default:
throw new IndexOutOfRangeException();
}
}
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
private readonly T4 m_Item4;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public T4 Item4 { get { return m_Item4; } }
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4)
{
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
m_Item4 = item4;
}
public override Boolean Equals(Object obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
{
if (other == null) return false;
Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>;
if (objTuple == null)
{
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4);
}
Int32 IComparable.CompareTo(Object obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
{
if (other == null) return 1;
Tuple<T1, T2, T3, T4> objTuple = other as Tuple<T1, T2, T3, T4>;
if (objTuple == null)
{
throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
c = comparer.Compare(m_Item3, objTuple.m_Item3);
if (c != 0) return c;
return comparer.Compare(m_Item4, objTuple.m_Item4);
}
public override int GetHashCode()
{
return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4));
}
Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.ToString(StringBuilder sb)
{
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(", ");
sb.Append(m_Item4);
sb.Append(")");
return sb.ToString();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 4;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
default:
throw new IndexOutOfRangeException();
}
}
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
private readonly T4 m_Item4;
private readonly T5 m_Item5;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public T4 Item4 { get { return m_Item4; } }
public T5 Item5 { get { return m_Item5; } }
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
{
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
m_Item4 = item4;
m_Item5 = item5;
}
public override Boolean Equals(Object obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
{
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>;
if (objTuple == null)
{
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5);
}
Int32 IComparable.CompareTo(Object obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
{
if (other == null) return 1;
Tuple<T1, T2, T3, T4, T5> objTuple = other as Tuple<T1, T2, T3, T4, T5>;
if (objTuple == null)
{
throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
c = comparer.Compare(m_Item3, objTuple.m_Item3);
if (c != 0) return c;
c = comparer.Compare(m_Item4, objTuple.m_Item4);
if (c != 0) return c;
return comparer.Compare(m_Item5, objTuple.m_Item5);
}
public override int GetHashCode()
{
return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5));
}
Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.ToString(StringBuilder sb)
{
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(", ");
sb.Append(m_Item4);
sb.Append(", ");
sb.Append(m_Item5);
sb.Append(")");
return sb.ToString();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 5;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
default:
throw new IndexOutOfRangeException();
}
}
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
private readonly T4 m_Item4;
private readonly T5 m_Item5;
private readonly T6 m_Item6;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public T4 Item4 { get { return m_Item4; } }
public T5 Item5 { get { return m_Item5; } }
public T6 Item6 { get { return m_Item6; } }
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
{
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
m_Item4 = item4;
m_Item5 = item5;
m_Item6 = item6;
}
public override Boolean Equals(Object obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
{
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>;
if (objTuple == null)
{
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6);
}
Int32 IComparable.CompareTo(Object obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
{
if (other == null) return 1;
Tuple<T1, T2, T3, T4, T5, T6> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6>;
if (objTuple == null)
{
throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
c = comparer.Compare(m_Item3, objTuple.m_Item3);
if (c != 0) return c;
c = comparer.Compare(m_Item4, objTuple.m_Item4);
if (c != 0) return c;
c = comparer.Compare(m_Item5, objTuple.m_Item5);
if (c != 0) return c;
return comparer.Compare(m_Item6, objTuple.m_Item6);
}
public override int GetHashCode()
{
return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6));
}
Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.ToString(StringBuilder sb)
{
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(", ");
sb.Append(m_Item4);
sb.Append(", ");
sb.Append(m_Item5);
sb.Append(", ");
sb.Append(m_Item6);
sb.Append(")");
return sb.ToString();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 6;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
default:
throw new IndexOutOfRangeException();
}
}
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
private readonly T4 m_Item4;
private readonly T5 m_Item5;
private readonly T6 m_Item6;
private readonly T7 m_Item7;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public T4 Item4 { get { return m_Item4; } }
public T5 Item5 { get { return m_Item5; } }
public T6 Item6 { get { return m_Item6; } }
public T7 Item7 { get { return m_Item7; } }
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
{
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
m_Item4 = item4;
m_Item5 = item5;
m_Item6 = item6;
m_Item7 = item7;
}
public override Boolean Equals(Object obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
{
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>;
if (objTuple == null)
{
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7);
}
Int32 IComparable.CompareTo(Object obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
{
if (other == null) return 1;
Tuple<T1, T2, T3, T4, T5, T6, T7> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7>;
if (objTuple == null)
{
throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
c = comparer.Compare(m_Item3, objTuple.m_Item3);
if (c != 0) return c;
c = comparer.Compare(m_Item4, objTuple.m_Item4);
if (c != 0) return c;
c = comparer.Compare(m_Item5, objTuple.m_Item5);
if (c != 0) return c;
c = comparer.Compare(m_Item6, objTuple.m_Item6);
if (c != 0) return c;
return comparer.Compare(m_Item7, objTuple.m_Item7);
}
public override int GetHashCode()
{
return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7));
}
Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.ToString(StringBuilder sb)
{
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(", ");
sb.Append(m_Item4);
sb.Append(", ");
sb.Append(m_Item5);
sb.Append(", ");
sb.Append(m_Item6);
sb.Append(", ");
sb.Append(m_Item7);
sb.Append(")");
return sb.ToString();
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length => 7;
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
case 6:
return Item7;
default:
throw new IndexOutOfRangeException();
}
}
}
}
[Serializable]
public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
private readonly T4 m_Item4;
private readonly T5 m_Item5;
private readonly T6 m_Item6;
private readonly T7 m_Item7;
private readonly TRest m_Rest;
public T1 Item1 { get { return m_Item1; } }
public T2 Item2 { get { return m_Item2; } }
public T3 Item3 { get { return m_Item3; } }
public T4 Item4 { get { return m_Item4; } }
public T5 Item5 { get { return m_Item5; } }
public T6 Item6 { get { return m_Item6; } }
public T7 Item7 { get { return m_Item7; } }
public TRest Rest { get { return m_Rest; } }
public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
{
if (!(rest is ITupleInternal))
{
throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleLastArgumentNotATuple"));
}
m_Item1 = item1;
m_Item2 = item2;
m_Item3 = item3;
m_Item4 = item4;
m_Item5 = item5;
m_Item6 = item6;
m_Item7 = item7;
m_Rest = rest;
}
public override Boolean Equals(Object obj)
{
return ((IStructuralEquatable)this).Equals(obj, EqualityComparer<Object>.Default); ;
}
Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
{
if (other == null) return false;
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>;
if (objTuple == null)
{
return false;
}
return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7) && comparer.Equals(m_Rest, objTuple.m_Rest);
}
Int32 IComparable.CompareTo(Object obj)
{
return ((IStructuralComparable)this).CompareTo(obj, Comparer<Object>.Default);
}
Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
{
if (other == null) return 1;
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> objTuple = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>;
if (objTuple == null)
{
throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
}
int c = 0;
c = comparer.Compare(m_Item1, objTuple.m_Item1);
if (c != 0) return c;
c = comparer.Compare(m_Item2, objTuple.m_Item2);
if (c != 0) return c;
c = comparer.Compare(m_Item3, objTuple.m_Item3);
if (c != 0) return c;
c = comparer.Compare(m_Item4, objTuple.m_Item4);
if (c != 0) return c;
c = comparer.Compare(m_Item5, objTuple.m_Item5);
if (c != 0) return c;
c = comparer.Compare(m_Item6, objTuple.m_Item6);
if (c != 0) return c;
c = comparer.Compare(m_Item7, objTuple.m_Item7);
if (c != 0) return c;
return comparer.Compare(m_Rest, objTuple.m_Rest);
}
public override int GetHashCode()
{
return ((IStructuralEquatable)this).GetHashCode(EqualityComparer<Object>.Default);
}
Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
{
// We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
ITupleInternal t = (ITupleInternal)m_Rest;
if (t.Length >= 8) { return t.GetHashCode(comparer); }
// In this case, the rest memeber has less than 8 elements so we need to combine some our elements with the elements in rest
int k = 8 - t.Length;
switch (k)
{
case 1:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 2:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 3:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 4:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 5:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 6:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
case 7:
return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), t.GetHashCode(comparer));
}
Debug.Assert(false, "Missed all cases for computing Tuple hash code");
return -1;
}
Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer)
{
return ((IStructuralEquatable)this).GetHashCode(comparer);
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
return ((ITupleInternal)this).ToString(sb);
}
string ITupleInternal.ToString(StringBuilder sb)
{
sb.Append(m_Item1);
sb.Append(", ");
sb.Append(m_Item2);
sb.Append(", ");
sb.Append(m_Item3);
sb.Append(", ");
sb.Append(m_Item4);
sb.Append(", ");
sb.Append(m_Item5);
sb.Append(", ");
sb.Append(m_Item6);
sb.Append(", ");
sb.Append(m_Item7);
sb.Append(", ");
return ((ITupleInternal)m_Rest).ToString(sb);
}
/// <summary>
/// The number of positions in this data structure.
/// </summary>
int ITuple.Length
{
get
{
return 7 + ((ITupleInternal)Rest).Length;
}
}
/// <summary>
/// Get the element at position <param name="index"/>.
/// </summary>
object ITuple.this[int index]
{
get
{
switch (index)
{
case 0:
return Item1;
case 1:
return Item2;
case 2:
return Item3;
case 3:
return Item4;
case 4:
return Item5;
case 5:
return Item6;
case 6:
return Item7;
}
return ((ITupleInternal)Rest)[index - 7];
}
}
}
}
| |
//
// Service.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright 2006-2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Hyena;
using Hyena.SExpEngine;
using Banshee.ServiceStack;
using Banshee.MediaProfiles;
namespace Banshee.GStreamer
{
public class Service : IExtensionService
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void BansheeLogHandler (LogEntryType type, IntPtr component, IntPtr message);
private BansheeLogHandler native_log_handler = null;
public Service ()
{
}
[DllImport (PlayerEngine.LibBansheeLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern void gstreamer_initialize (bool debugging, BansheeLogHandler log_handler);
void IExtensionService.Initialize ()
{
bool debugging = ApplicationContext.Debugging;
if (debugging) {
native_log_handler = new BansheeLogHandler (NativeLogHandler);
}
gstreamer_initialize (debugging, native_log_handler);
var profile_manager = ServiceManager.MediaProfileManager;
if (profile_manager != null) {
profile_manager.Initialized += OnMediaProfileManagerInitialized;
}
}
private void OnMediaProfileManagerInitialized (object o, EventArgs args)
{
MediaProfileManager profile_manager = ServiceManager.MediaProfileManager;
if (profile_manager != null) {
Pipeline.AddSExprFunction ("gst-element-is-available", SExprTestElement);
Pipeline.AddSExprFunction ("gst-construct-pipeline", SExprConstructPipeline);
Pipeline.AddSExprFunction ("gst-construct-caps", SExprConstructCaps);
Pipeline.AddSExprFunction ("gst-construct-element", SExprConstructElement);
profile_manager.TestProfile += OnTestMediaProfile;
profile_manager.TestAll ();
}
}
void IDisposable.Dispose ()
{
}
private void NativeLogHandler (LogEntryType type, IntPtr componentPtr, IntPtr messagePtr)
{
string component = componentPtr == IntPtr.Zero ? null : GLib.Marshaller.Utf8PtrToString (componentPtr);
string message = componentPtr == IntPtr.Zero ? null : GLib.Marshaller.Utf8PtrToString (messagePtr);
if (message == null) {
return;
} else if (component != null) {
message = String.Format ("(libbanshee:{0}) {1}", component, message);
}
Log.Commit (type, message, null, false);
}
private static void OnTestMediaProfile (object o, TestProfileArgs args)
{
bool no_test = ApplicationContext.EnvironmentIsSet ("BANSHEE_PROFILES_NO_TEST");
bool available = false;
foreach (Pipeline.Process process in args.Profile.Pipeline.GetPendingProcessesById ("gstreamer")) {
string pipeline = args.Profile.Pipeline.CompileProcess (process);
if (no_test || TestPipeline (pipeline)) {
args.Profile.Pipeline.AddProcess (process);
available = true;
break;
} else if (!no_test) {
Hyena.Log.DebugFormat ("GStreamer pipeline does not run: {0}", pipeline);
}
}
args.ProfileAvailable = available;
}
[DllImport (PlayerEngine.LibBansheeLibrary, CallingConvention = CallingConvention.Cdecl)]
private static extern bool gstreamer_test_pipeline (IntPtr pipeline);
internal static bool TestPipeline (string pipeline)
{
if (String.IsNullOrEmpty (pipeline)) {
return false;
}
IntPtr pipeline_ptr = GLib.Marshaller.StringToPtrGStrdup (pipeline);
if (pipeline_ptr == IntPtr.Zero) {
return false;
}
try {
return gstreamer_test_pipeline (pipeline_ptr);
} finally {
GLib.Marshaller.Free (pipeline_ptr);
}
}
private TreeNode SExprTestElement (EvaluatorBase evaluator, TreeNode [] args)
{
if (args.Length != 1) {
throw new ArgumentException ("gst-test-element accepts one argument");
}
TreeNode arg = evaluator.Evaluate (args[0]);
if (!(arg is StringLiteral)) {
throw new ArgumentException ("gst-test-element requires a string argument");
}
StringLiteral element_node = (StringLiteral)arg;
return new BooleanLiteral (TestPipeline (element_node.Value));
}
private TreeNode SExprConstructPipeline (EvaluatorBase evaluator, TreeNode [] args)
{
StringBuilder builder = new StringBuilder ();
List<string> elements = new List<string> ();
for (int i = 0; i < args.Length; i++) {
TreeNode node = evaluator.Evaluate (args[i]);
if (!(node is LiteralNodeBase)) {
throw new ArgumentException ("node must evaluate to a literal");
}
string value = node.ToString ().Trim ();
if (value.Length == 0) {
continue;
}
elements.Add (value);
}
for (int i = 0; i < elements.Count; i++) {
builder.Append (elements[i]);
if (i < elements.Count - 1) {
builder.Append (" ! ");
}
}
return new StringLiteral (builder.ToString ());
}
private TreeNode SExprConstructElement (EvaluatorBase evaluator, TreeNode [] args)
{
return SExprConstructPipelinePart (evaluator, args, true);
}
private TreeNode SExprConstructCaps (EvaluatorBase evaluator, TreeNode [] args)
{
return SExprConstructPipelinePart (evaluator, args, false);
}
private TreeNode SExprConstructPipelinePart (EvaluatorBase evaluator, TreeNode [] args, bool element)
{
StringBuilder builder = new StringBuilder ();
TreeNode list = new TreeNode ();
foreach (TreeNode arg in args) {
list.AddChild (evaluator.Evaluate (arg));
}
list = list.Flatten ();
for (int i = 0; i < list.ChildCount; i++) {
TreeNode node = list.Children[i];
string value = node.ToString ().Trim ();
builder.Append (value);
if (i == 0) {
if (list.ChildCount > 1) {
builder.Append (element ? ' ' : ',');
}
continue;
} else if (i % 2 == 1) {
builder.Append ('=');
} else if (i < list.ChildCount - 1) {
builder.Append (element ? ' ' : ',');
}
}
return new StringLiteral (builder.ToString ());
}
string IService.ServiceName {
get { return "GStreamerCoreService"; }
}
}
}
| |
#region license
// Copyright (c) 2004, 2005, 2006, 2007 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
using System;
using System.Collections.Generic;
using Boo.Lang.Compiler.Ast;
using System.IO;
namespace Boo.Lang.Compiler.TypeSystem
{
class GenericParameterInferrer
{
CompilerContext _context;
IMethod _genericMethod;
ExpressionCollection _arguments;
Dictionary<IGenericParameter, InferredType> _inferredTypes = new Dictionary<IGenericParameter, InferredType>();
public GenericParameterInferrer(CompilerContext context, IMethod genericMethod, ExpressionCollection arguments)
{
_context = context;
_genericMethod = genericMethod;
_arguments = arguments;
InitializeInferredTypes(GenericMethod.GenericInfo.GenericParameters);
InitializeDependencies(
GenericMethod.GenericInfo.GenericParameters,
GenericMethod.CallableType.GetSignature());
}
public IMethod GenericMethod
{
get { return _genericMethod; }
}
public ExpressionCollection Arguments
{
get { return _arguments; }
}
public bool Run()
{
InferenceStart();
if (Arguments.Count != GenericMethod.GetParameters().Length)
{
return InferenceComplete(false);
}
InferExplicits();
while (HasUnfixedTypes())
{
bool wasFixed = FixAll(HasNoDependencies) || FixAll(HasDependantsAndBounds);
if (!wasFixed)
{
return InferenceComplete(false);
}
InferCallables();
};
return InferenceComplete(true);
}
/// <summary>
/// Performs inference on explicitly typed arguments.
/// </summary>
/// <remarks>
/// Corresponds to the first phase in generic parameter inference according to the C# 3.0 spec.
/// </remarks>
private void InferExplicits()
{
CallableSignature definitionSignature = GenericMethod.CallableType.GetSignature();
for (int i = 0; i < Arguments.Count; i++)
{
Infer(
definitionSignature.Parameters[i].Type,
Arguments[i].ExpressionType,
Inference.AllowCovariance);
}
}
/// <summary>
/// Performs inference on implicitly typed callables whose input types have already been inferred.
/// </summary>
/// <remarks>
/// Corresponds to the second phase in generic parameter inference according to the C# 3.0 spec.
/// </remarks>
private void InferCallables()
{
// TODO
}
/// <summary>
/// Attempts to infer the type of generic parameters that occur in a formal parameter type
/// according to its actual argument type.
/// </summary>
/// <returns>False if inference failed; otherwise, true. </returns>
private bool Infer(IType formalType, IType actualType, Inference inference)
{
// Skip unspecified actual types
if (actualType == null) return true;
if (formalType is IGenericParameter)
{
return InferGenericParameter((IGenericParameter)formalType, actualType, inference);
}
if (formalType is ICallableType)
{
return InferCallableType((ICallableType)formalType, actualType, inference);
}
if (formalType.ConstructedInfo != null)
{
return InferConstructedType(formalType, actualType, inference);
}
if (formalType is IArrayType)
{
return InferArrayType((IArrayType)formalType, actualType, inference);
}
return InferSimpleType(formalType, actualType, inference);
}
private bool InferGenericParameter(IGenericParameter formalType, IType actualType, Inference inference)
{
if (_inferredTypes.ContainsKey(formalType))
{
InferredType inferredType = _inferredTypes[formalType];
if ((inference & Inference.AllowContravariance) != Inference.AllowContravariance)
{
inferredType.ApplyLowerBound(actualType);
}
if ((inference & Inference.AllowCovariance) != Inference.AllowCovariance)
{
inferredType.ApplyUpperBound(actualType);
}
}
return true;
}
private bool InferCallableType(ICallableType formalType, IType actualType, Inference inference)
{
ICallableType callableActualType = actualType as ICallableType;
if (callableActualType == null) return false;
CallableSignature formalSignature = formalType.GetSignature();
CallableSignature actualSignature = callableActualType.GetSignature();
// TODO: expand actual signature when it involves varargs?
if (formalSignature.Parameters.Length != actualSignature.Parameters.Length) return false;
// Infer return type, maintaining inference direction
if (!Infer(formalSignature.ReturnType, actualSignature.ReturnType, inference))
{
return false;
}
// Infer parameter types, inverting inference direction
for (int i = 0; i < formalSignature.Parameters.Length; ++i)
{
bool inferenceSuccessful = Infer(
formalSignature.Parameters[i].Type,
actualSignature.Parameters[i].Type,
Invert(inference));
if (!inferenceSuccessful) return false;
}
return true;
}
private bool InferConstructedType(IType formalType, IType actualType, Inference inference)
{
// look for a single occurance of the formal
// constructed type in the actual type's hierarchy
IType constructedActualType = GenericsServices.FindConstructedType(
actualType,
formalType.ConstructedInfo.GenericDefinition);
if (constructedActualType == null)
{
return false;
}
// Exact inference requires the constructed occurance to be
// the actual type itself
if (inference == Inference.Exact && actualType != constructedActualType)
{
return false;
}
for (int i = 0; i < formalType.ConstructedInfo.GenericArguments.Length; ++i)
{
bool inferenceSuccessful = Infer(
formalType.ConstructedInfo.GenericArguments[i],
constructedActualType.ConstructedInfo.GenericArguments[i],
Inference.Exact); // Generic arguments must match exactly, no variance allowed
if (!inferenceSuccessful) return false;
}
return true;
}
private bool InferArrayType(IArrayType formalType, IType actualType, Inference inference)
{
IArrayType actualArrayType = actualType as IArrayType;
return
(actualArrayType != null) &&
(actualArrayType.GetArrayRank() == formalType.GetArrayRank()) &&
(Infer(formalType.GetElementType(), actualType.GetElementType(), inference));
}
private bool InferSimpleType(IType formalType, IType actualType, Inference inference)
{
// Inference has no effect on formal parameter types that are not generic parameters
return true;
}
private bool FixAll(Predicate<InferredType> predicate)
{
bool wasFixed = false;
foreach (KeyValuePair<IGenericParameter, InferredType> kvp in _inferredTypes)
{
IGenericParameter gp = kvp.Key;
InferredType inferredType = kvp.Value;
if (!inferredType.Fixed && predicate(inferredType))
{
wasFixed |= Fix(gp, inferredType);
}
}
return wasFixed;
}
private bool Fix(IGenericParameter genericParameter, InferredType inferredType)
{
if (inferredType.Fix())
{
_context.TraceVerbose("Generic parameter {0} fixed to {1}.", genericParameter.Name, inferredType.ResultingType);
return true;
}
return false;
}
private bool HasUnfixedTypes()
{
foreach (InferredType inferredType in _inferredTypes.Values)
{
if (!inferredType.Fixed) return true;
}
return false;
}
private bool HasNoDependencies(InferredType inferredType)
{
return !inferredType.HasDependencies;
}
private bool HasDependantsAndBounds(InferredType inferredType)
{
return inferredType.HasDependants && inferredType.HasBounds;
}
private IType GetInferredType(IGenericParameter gp)
{
if (_inferredTypes.ContainsKey(gp))
{
return _inferredTypes[gp].ResultingType;
}
else
{
return null;
}
}
public IType[] GetInferredTypes()
{
return Array.ConvertAll<IGenericParameter, IType>(
GenericMethod.GenericInfo.GenericParameters,
GetInferredType);
}
private void InitializeInferredTypes(IEnumerable<IGenericParameter> parameters)
{
foreach (IGenericParameter gp in parameters)
{
_inferredTypes[gp] = new InferredType();
}
}
private void InitializeDependencies(IGenericParameter[] genericParameters, CallableSignature signature)
{
IType[] parameterTypes = GetParameterTypes(signature);
foreach (IType parameterType in parameterTypes)
{
ICallableType callableParameterType = parameterType as ICallableType;
if (callableParameterType == null) continue;
CalculateDependencies(callableParameterType.GetSignature());
}
}
private void CalculateDependencies(CallableSignature signature)
{
foreach (IType inputType in GetParameterTypes(signature))
{
CalculateDependencies(inputType, signature.ReturnType);
}
}
private void CalculateDependencies(IType inputType, IType outputType)
{
foreach (IGenericParameter dependant in FindGenericParameters(outputType))
{
foreach (IGenericParameter dependee in FindGenericParameters(inputType))
{
SetDependency(dependant, dependee);
}
}
}
private IEnumerable<IGenericParameter> FindGenericParameters(IType type)
{
IGenericParameter genericParameter = type as IGenericParameter;
if (genericParameter != null && _inferredTypes.ContainsKey(genericParameter))
{
yield return genericParameter;
}
if (type is IArrayType)
{
foreach (IGenericParameter gp in FindGenericParameters(type.GetElementType())) yield return gp;
yield break;
}
if (type.ConstructedInfo != null)
{
foreach (IType typeArgument in type.ConstructedInfo.GenericArguments)
{
foreach (IGenericParameter gp in FindGenericParameters(typeArgument)) yield return gp;
}
yield break;
}
ICallableType callableType = type as ICallableType;
if (callableType != null)
{
CallableSignature signature = callableType.GetSignature();
foreach (IGenericParameter gp in FindGenericParameters(signature.ReturnType)) yield return gp;
foreach (IParameter parameter in signature.Parameters)
{
foreach (IGenericParameter gp in FindGenericParameters(parameter.Type)) yield return gp;
}
yield break;
}
}
private void SetDependency(IGenericParameter dependant, IGenericParameter dependee)
{
_inferredTypes[dependant].SetDependencyOn(_inferredTypes[dependee]);
}
private IType[] GetParameterTypes(CallableSignature signature)
{
return Array.ConvertAll<IParameter, IType>(
signature.Parameters,
delegate(IParameter p) { return p.Type; });
}
private void InferenceStart()
{
string argumentsString = string.Join(
", ", Array.ConvertAll<Expression, string>(
_arguments.ToArray(),
delegate(Expression e) { return e.ToString(); }));
_context.TraceVerbose("Attempting to infer generic type arguments for {0} from argument list ({1}).", _genericMethod, argumentsString);
}
private bool InferenceComplete(bool successfully)
{
_context.TraceVerbose(
"Generic type inference for {0} {1}.",
_genericMethod,
successfully ? "succeeded" : "failed");
return successfully;
}
private Inference Invert(Inference inference)
{
switch (inference)
{
case Inference.AllowCovariance:
return Inference.AllowContravariance;
case Inference.AllowContravariance:
return Inference.AllowCovariance;
default:
return Inference.Exact;
}
}
enum Inference
{
/// <summary>
/// The type parameter must be set to the exact actual type.
/// </summary>
Exact = 0,
/// <summary>
/// The type parameter can be set to a supertype of the actual type.
/// </summary>
AllowCovariance = 1,
/// <summary>
/// The type parameter is allowed to be set to a type derived from the actual type.
/// </summary>
AllowContravariance = 2
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Microsoft.Research.ClousotRegression;
namespace BrianScenarios
{
public class Assembly
{
bool rof;
string name;
[Pure]
[ClousotRegressionTest]
public bool IsReflectionLoadOnly
{
get
{
Contract.Ensures(Contract.Result<bool>() == this.rof);
return this.rof;
}
}
// Ok: verifies the postcondition
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 27, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 38, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 7, MethodILOffset = 43)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 12, MethodILOffset = 43)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 20, MethodILOffset = 43)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 13, MethodILOffset = 43)]
private Assembly(int dummyParameter)
{
Contract.Ensures(IsReflectionLoadOnly == rof);
this.rof = true;
this.name = "foo";
}
// Not ok: rof is NOT the field there...
[ClousotRegressionTest, RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 22, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 33, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 7, MethodILOffset = 38)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 12, MethodILOffset = 38)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"ensures unproven: IsReflectionLoadOnly == rof", PrimaryILOffset = 15, MethodILOffset = 38)]
private Assembly(bool rof, int dummy)
{
Contract.Ensures(IsReflectionLoadOnly == rof);
this.rof = true;
this.name = "foo";
}
// Ok
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 22, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 33, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 7, MethodILOffset = 38)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 12, MethodILOffset = 38)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 15, MethodILOffset = 38)]
private Assembly(bool rof)
{
Contract.Ensures(IsReflectionLoadOnly == rof);
this.rof = rof;
this.name = "foo";
}
// Ok
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 5, MethodILOffset = 21)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 10, MethodILOffset = 21)]
public static Assembly ForReflectionLoadOnly()
{
Contract.Ensures(Contract.Result<Assembly>().IsReflectionLoadOnly);
return new Assembly(true);
}
// Ok
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 5, MethodILOffset = 24)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 13, MethodILOffset = 24)]
public static Assembly ForGeneralReflection()
{
Contract.Ensures(!Contract.Result<Assembly>().IsReflectionLoadOnly);
return new Assembly(false);
}
// OK
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 12, MethodILOffset = 11)]
public void DoSomething()
{
Contract.Requires(this.IsReflectionLoadOnly);
}
// ok
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 12, MethodILOffset = 14)]
public void DoSomethingElse()
{
Contract.Requires(!this.IsReflectionLoadOnly);
}
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.name != null);
}
}
namespace ContractsTest
{
class XorInPrecondition
{
public static void Foo(Object a, Object b)
{
Contract.Requires((a == null) ^ (b == null), "expected exactly one or the other to be null.");
}
public static void Foo1(Object a, Object b)
{
Contract.Requires((a == null) != (b == null), "expected exactly one or the other to be null.");
}
[ClousotRegressionTest("clousot1")]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=14,MethodILOffset=8)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=18,MethodILOffset=15)]
public static void Bar()
{
Object obj = new Object();
Foo(obj, null);
Foo1(obj, null);
}
}
class AndInPrecondition
{
public static void Foo(Object a, Object b)
{
Contract.Requires((a != null) & (b != null));
}
public static void Foo1(Object a, Object b)
{
Contract.Requires((a != null) && (b != null));
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"requires unproven: (a != null) & (b != null)",PrimaryILOffset=15,MethodILOffset=8)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=13,MethodILOffset=15)]
public static void Bar()
{
Object obj = new Object();
Foo(obj, obj);
Foo1(obj, obj);
}
}
class OrInPrecondition
{
public static void Foo(Object a, Object b)
{
Contract.Requires((a != null) | (b != null));
}
public static void Foo1(Object a, Object b)
{
Contract.Requires((a != null) || (b != null));
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"requires unproven: (a != null) | (b != null)",PrimaryILOffset=15,MethodILOffset=8)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"requires is valid",PrimaryILOffset=13,MethodILOffset=15)]
public static void Bar()
{
Object obj = new Object();
Foo(obj, obj);
Foo1(obj, obj);
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests
{
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Management.Automation;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Management.ServiceManagement.Model;
using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo;
using Microsoft.WindowsAzure.Management.ServiceManagement.Test.Properties;
using Microsoft.WindowsAzure.ServiceManagement;
[TestClass]
public class FunctionalTest : ServiceManagementTest
{
bool createOwnService = false;
private static string defaultService;
private static string defaultVm;
private const string vhdBlob = "vhdstore/os.vhd";
private string vhdName = "os.vhd";
private string serviceName;
private string vmName;
protected static string vhdBlobLocation;
[ClassInitialize]
public static void ClassInit(TestContext context)
{
if (string.IsNullOrEmpty(Resource.DefaultSubscriptionName))
{
Assert.Inconclusive("No Subscription is selected!");
}
do
{
defaultService = Utilities.GetUniqueShortName(serviceNamePrefix);
}
while (vmPowershellCmdlets.TestAzureServiceName(defaultService));
defaultVm = Utilities.GetUniqueShortName(vmNamePrefix);
Assert.IsNull(vmPowershellCmdlets.GetAzureVM(defaultVm, defaultService));
vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, defaultVm, defaultService, imageName, username, password, locationName);
Console.WriteLine("Service Name: {0} is created.", defaultService);
vhdBlobLocation = blobUrlRoot + vhdBlob;
try
{
vmPowershellCmdlets.AddAzureVhd(new FileInfo(localFile), vhdBlobLocation);
}
catch (Exception e)
{
if (e.ToString().Contains("already exists"))
{
// Use the already uploaded vhd.
Console.WriteLine("Using already uploaded blob..");
}
else
{
throw;
}
}
}
[TestInitialize]
public void Initialize()
{
pass = false;
testStartTime = DateTime.Now;
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureStorageAccount)")]
[Ignore]
public void ScriptTestSample()
{
var result = vmPowershellCmdlets.RunPSScript("Get-Help Save-AzureVhd -full");
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove)-AzureAffinityGroup)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\affinityGroupData.csv", "affinityGroupData#csv", DataAccessMethod.Sequential)]
public void AzureAffinityGroupTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string affinityName1 = Convert.ToString(TestContext.DataRow["affinityName1"]);
string affinityLabel1 = Convert.ToString(TestContext.DataRow["affinityLabel1"]);
string location1 = Convert.ToString(TestContext.DataRow["location1"]);
string description1 = Convert.ToString(TestContext.DataRow["description1"]);
string affinityName2 = Convert.ToString(TestContext.DataRow["affinityName2"]);
string affinityLabel2 = Convert.ToString(TestContext.DataRow["affinityLabel2"]);
string location2 = Convert.ToString(TestContext.DataRow["location2"]);
string description2 = Convert.ToString(TestContext.DataRow["description2"]);
try
{
ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper();
// Remove previously created affinity groups
foreach (var aff in vmPowershellCmdlets.GetAzureAffinityGroup(null))
{
if (aff.Name == affinityName1 || aff.Name == affinityName2)
{
vmPowershellCmdlets.RemoveAzureAffinityGroup(aff.Name);
}
}
// New-AzureAffinityGroup
vmPowershellCmdlets.NewAzureAffinityGroup(affinityName1, location1, affinityLabel1, description1);
vmPowershellCmdlets.NewAzureAffinityGroup(affinityName2, location2, affinityLabel2, description2);
Console.WriteLine("Affinity groups created: {0}, {1}", affinityName1, affinityName2);
// Get-AzureAffinityGroup
pass = AffinityGroupVerify(vmPowershellCmdlets.GetAzureAffinityGroup(affinityName1)[0], affinityName1, affinityLabel1, location1, description1);
pass &= AffinityGroupVerify(vmPowershellCmdlets.GetAzureAffinityGroup(affinityName2)[0], affinityName2, affinityLabel2, location2, description2);
// Set-AzureAffinityGroup
vmPowershellCmdlets.SetAzureAffinityGroup(affinityName2, affinityLabel1, description1);
Console.WriteLine("update affinity group: {0}", affinityName2);
pass &= AffinityGroupVerify(vmPowershellCmdlets.GetAzureAffinityGroup(affinityName2)[0], affinityName2, affinityLabel1, location2, description1);
// Remove-AzureAffinityGroup
vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityName2);
pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityName2);
vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityName1);
pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityName1);
}
catch (Exception e)
{
pass = false;
Assert.Fail(e.ToString());
}
}
private bool AffinityGroupVerify(AffinityGroupContext affContext, string name, string label, string location, string description)
{
bool result = true;
Console.WriteLine("AffinityGroup: Name - {0}, Location - {1}, Label - {2}, Description - {3}", affContext.Name, affContext.Location, affContext.Label, affContext.Description);
try
{
Assert.AreEqual(affContext.Name, name, "Error: Affinity Name is not equal!");
Assert.AreEqual(affContext.Label, label, "Error: Affinity Label is not equal!");
Assert.AreEqual(affContext.Location, location, "Error: Affinity Location is not equal!");
Assert.AreEqual(affContext.Description, description, "Error: Affinity Description is not equal!");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
result = false;
}
return result;
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Remove)-AzureCertificate)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\certificateData.csv", "certificateData#csv", DataAccessMethod.Sequential)]
public void AzureCertificateTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
// Certificate files to test
string cerFileName = Convert.ToString(TestContext.DataRow["cerFileName"]);
string pfxFileName = Convert.ToString(TestContext.DataRow["pfxFileName"]);
string password = Convert.ToString(TestContext.DataRow["password"]);
string thumbprintAlgorithm = Convert.ToString(TestContext.DataRow["algorithm"]);
// Install the .cer file to local machine.
StoreLocation certStoreLocation = StoreLocation.CurrentUser;
StoreName certStoreName = StoreName.My;
X509Certificate2 installedCert = InstallCert(cerFileName, certStoreLocation, certStoreName);
// Certificate1: get it from the installed certificate.
PSObject cert1 = vmPowershellCmdlets.RunPSScript(
String.Format("Get-Item cert:\\{0}\\{1}\\{2}", certStoreLocation.ToString(), certStoreName.ToString(), installedCert.Thumbprint))[0];
string cert1data = Convert.ToBase64String(((X509Certificate2)cert1.BaseObject).RawData);
// Certificate2: get it from .pfx file.
X509Certificate2Collection cert2 = new X509Certificate2Collection();
cert2.Import(pfxFileName, password, X509KeyStorageFlags.PersistKeySet);
string cert2data = Convert.ToBase64String(cert2[0].RawData);
// Certificate3: get it from .cer file.
X509Certificate2Collection cert3 = new X509Certificate2Collection();
cert3.Import(cerFileName);
string cert3data = Convert.ToBase64String(cert3[0].RawData);
try
{
RemoveAllExistingCerts(defaultService);
// Add a cert item
vmPowershellCmdlets.AddAzureCertificate(defaultService, cert1);
CertificateContext getCert1 = vmPowershellCmdlets.GetAzureCertificate(defaultService)[0];
Console.WriteLine("Cert is added: {0}", getCert1.Thumbprint);
Assert.AreEqual(getCert1.Data, cert1data, "Cert is different!!");
vmPowershellCmdlets.RemoveAzureCertificate(defaultService, getCert1.Thumbprint, thumbprintAlgorithm);
pass = Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, defaultService, getCert1.Thumbprint, thumbprintAlgorithm);
// Add .pfx file
vmPowershellCmdlets.AddAzureCertificate(defaultService, pfxFileName, password);
CertificateContext getCert2 = vmPowershellCmdlets.GetAzureCertificate(defaultService, cert2[0].Thumbprint, thumbprintAlgorithm)[0];
Console.WriteLine("Cert is added: {0}", cert2[0].Thumbprint);
Assert.AreEqual(getCert2.Data, cert2data, "Cert is different!!");
vmPowershellCmdlets.RemoveAzureCertificate(defaultService, cert2[0].Thumbprint, thumbprintAlgorithm);
pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, defaultService, cert2[0].Thumbprint, thumbprintAlgorithm);
// Add .cer file
vmPowershellCmdlets.AddAzureCertificate(defaultService, cerFileName);
CertificateContext getCert3 = vmPowershellCmdlets.GetAzureCertificate(defaultService, cert3[0].Thumbprint, thumbprintAlgorithm)[0];
Console.WriteLine("Cert is added: {0}", cert3[0].Thumbprint);
Assert.AreEqual(getCert3.Data, cert3data, "Cert is different!!");
vmPowershellCmdlets.RemoveAzureCertificate(defaultService, cert3[0].Thumbprint, thumbprintAlgorithm);
pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, defaultService, cert3[0].Thumbprint, thumbprintAlgorithm);
}
catch (Exception e)
{
pass = false;
Assert.Fail(e.ToString());
}
finally
{
UninstallCert(installedCert, certStoreLocation, certStoreName);
RemoveAllExistingCerts(defaultService);
}
}
private void RemoveAllExistingCerts(string serviceName)
{
vmPowershellCmdlets.RunPSScript(String.Format("{0} -ServiceName {1} | {2}", Utilities.GetAzureCertificateCmdletName, serviceName, Utilities.RemoveAzureCertificateCmdletName));
}
private X509Certificate2 InstallCert(string certFile, StoreLocation location, StoreName name)
{
X509Certificate2 cert = new X509Certificate2(certFile);
X509Store certStore = new X509Store(name, location);
certStore.Open(OpenFlags.ReadWrite);
certStore.Add(cert);
certStore.Close();
Console.WriteLine("Cert, {0}, is installed.", cert.Thumbprint);
return cert;
}
private void UninstallCert(X509Certificate2 cert, StoreLocation location, StoreName name)
{
try
{
X509Store certStore = new X509Store(name, location);
certStore.Open(OpenFlags.ReadWrite);
certStore.Remove(cert);
certStore.Close();
Console.WriteLine("Cert, {0}, is uninstalled.", cert.Thumbprint);
}
catch (Exception e)
{
Console.WriteLine("Error during uninstalling the cert: {0}", e.ToString());
throw;
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (New-AzureCertificateSetting)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\certificateData.csv", "certificateData#csv", DataAccessMethod.Sequential)]
public void AzureCertificateSettingTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
// Install the .cer file to local machine.
string cerFileName = Convert.ToString(TestContext.DataRow["cerFileName"]);
StoreLocation certStoreLocation = StoreLocation.CurrentUser;
StoreName certStoreName = StoreName.My;
X509Certificate2 installedCert = InstallCert(cerFileName, certStoreLocation, certStoreName);
PSObject certToUpload = vmPowershellCmdlets.RunPSScript(
String.Format("Get-Item cert:\\{0}\\{1}\\{2}", certStoreLocation.ToString(), certStoreName.ToString(), installedCert.Thumbprint))[0];
try
{
vmName = Utilities.GetUniqueShortName(vmNamePrefix);
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmPowershellCmdlets.NewAzureService(serviceName, locationName);
vmPowershellCmdlets.AddAzureCertificate(serviceName, certToUpload);
CertificateSettingList certList = new CertificateSettingList();
certList.Add(vmPowershellCmdlets.NewAzureCertificateSetting(certStoreName.ToString(), installedCert.Thumbprint));
AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, InstanceSize.Small, imageName);
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, certList, username, password);
PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null);
PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo);
vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm });
PersistentVMRoleContext result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName);
Console.WriteLine("{0} is created", result.Name);
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail(e.ToString());
}
finally
{
UninstallCert(installedCert, certStoreLocation, certStoreName);
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Set,Remove)-AzureDataDisk)")]
public void AzureDataDiskTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string diskLabel1 = "disk1";
int diskSize1 = 30;
int lunSlot1 = 0;
string diskLabel2 = "disk2";
int diskSize2 = 50;
int lunSlot2 = 2;
try
{
AddAzureDataDiskConfig dataDiskInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize1, diskLabel1, lunSlot1);
AddAzureDataDiskConfig dataDiskInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize2, diskLabel2, lunSlot2);
vmPowershellCmdlets.AddDataDisk(defaultVm, defaultService, new [] {dataDiskInfo1, dataDiskInfo2}); // Add-AzureEndpoint with Get-AzureVM and Update-AzureVm
Assert.IsTrue(CheckDataDisk(defaultVm, defaultService, dataDiskInfo1, HostCaching.None), "Data disk is not properly added");
Console.WriteLine("Data disk added correctly.");
Assert.IsTrue(CheckDataDisk(defaultVm, defaultService, dataDiskInfo2, HostCaching.None), "Data disk is not properly added");
Console.WriteLine("Data disk added correctly.");
vmPowershellCmdlets.SetDataDisk(defaultVm, defaultService, HostCaching.ReadOnly, lunSlot1);
Assert.IsTrue(CheckDataDisk(defaultVm, defaultService, dataDiskInfo1, HostCaching.ReadOnly), "Data disk is not properly changed");
Console.WriteLine("Data disk is changed correctly.");
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
// Remove DataDisks created
foreach (DataVirtualHardDisk disk in vmPowershellCmdlets.GetAzureDataDisk(defaultVm, defaultService))
{
vmPowershellCmdlets.RemoveDataDisk(defaultVm, defaultService, new[] { disk.Lun }); // Remove-AzureDataDisk
RemoveDisk(disk.DiskName, 10);
}
Assert.AreEqual(0, vmPowershellCmdlets.GetAzureDataDisk(defaultVm, defaultService).Count, "DataDisk is not removed.");
}
}
private void RemoveDisk(string diskName, int maxTry)
{
for (int i = 0; i < maxTry ; i++)
{
try
{
vmPowershellCmdlets.RemoveAzureDisk(diskName, true);
break;
}
catch (Exception e)
{
if (i == maxTry)
{
Console.WriteLine("Max try reached. Couldn't delete the Virtual disk");
}
if (e.ToString().Contains("currently in use"))
{
Thread.Sleep(5000);
continue;
}
}
}
}
private bool CheckDataDisk(string vmName, string serviceName, AddAzureDataDiskConfig dataDiskInfo, HostCaching hc)
{
bool found = false;
foreach (DataVirtualHardDisk disk in vmPowershellCmdlets.GetAzureDataDisk(vmName, serviceName))
{
Console.WriteLine("DataDisk - Name:{0}, Label:{1}, Size:{2}, LUN:{3}, HostCaching: {4}", disk.DiskName, disk.DiskLabel, disk.LogicalDiskSizeInGB, disk.Lun, disk.HostCaching);
if (disk.DiskLabel == dataDiskInfo.DiskLabel && disk.LogicalDiskSizeInGB == dataDiskInfo.DiskSizeGB && disk.Lun == dataDiskInfo.LunSlot)
{
if (disk.HostCaching == hc.ToString())
{
found = true;
Console.WriteLine("DataDisk found: {0}", disk.DiskLabel);
}
}
}
return found;
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Update,Remove)-AzureDisk)")]
public void AzureDiskTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string mediaLocation = String.Format("{0}vhdstore/{1}", blobUrlRoot, vhdName);
try
{
vmPowershellCmdlets.AddAzureDisk(vhdName, mediaLocation, vhdName, null);
bool found = false;
foreach (DiskContext disk in vmPowershellCmdlets.GetAzureDisk(vhdName))
{
Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", disk.DiskName, disk.Label, disk.DiskSizeInGB);
if (disk.DiskName == vhdName && disk.Label == vhdName)
{
found = true;
Console.WriteLine("{0} is found", disk.DiskName);
}
}
Assert.IsTrue(found, "Error: Disk is not added");
string newLabel = "NewLabel";
vmPowershellCmdlets.UpdateAzureDisk(vhdName, newLabel);
DiskContext disk2 = vmPowershellCmdlets.GetAzureDisk(vhdName)[0];
Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", disk2.DiskName, disk2.Label, disk2.DiskSizeInGB);
Assert.AreEqual(newLabel, disk2.Label);
Console.WriteLine("Disk Label is successfully updated");
vmPowershellCmdlets.RemoveAzureDisk(vhdName, false);
Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDisk, vhdName), "The disk was not removed");
}
catch (Exception e)
{
pass = false;
if (e.ToString().Contains("ResourceNotFound"))
{
Console.WriteLine("Please upload {0} file to \\vhdtest\\ blob directory before running this test", vhdName);
}
Assert.Fail("Exception occurs: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove,Move)-AzureDeployment)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)]
public void AzureDeploymentTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
// Choose the package and config files from local machine
string packageName = Convert.ToString(TestContext.DataRow["packageName"]);
string configName = Convert.ToString(TestContext.DataRow["configName"]);
string upgradePackageName = Convert.ToString(TestContext.DataRow["upgradePackage"]);
string upgradeConfigName = Convert.ToString(TestContext.DataRow["upgradeConfig"]);
string upgradeConfigName2 = Convert.ToString(TestContext.DataRow["upgradeConfig2"]);
var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName);
var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName);
var packagePath2 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + upgradePackageName);
var configPath2 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + upgradeConfigName);
var configPath3 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + upgradeConfigName2);
Assert.IsTrue(File.Exists(packagePath1.FullName), "file not exist={0}", packagePath1);
Assert.IsTrue(File.Exists(packagePath2.FullName), "file not exist={0}", packagePath2);
Assert.IsTrue(File.Exists(configPath1.FullName), "file not exist={0}", configPath1);
Assert.IsTrue(File.Exists(configPath2.FullName), "file not exist={0}", configPath2);
Assert.IsTrue(File.Exists(configPath3.FullName), "file not exist={0}", configPath3);
string deploymentName = "deployment1";
string deploymentLabel = "label1";
DeploymentInfoContext result;
try
{
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
Console.WriteLine("service, {0}, is created.", serviceName);
vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Staging, deploymentLabel, deploymentName, false, false);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Staging);
pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Staging, null, 1);
Console.WriteLine("successfully deployed the package");
// Move the deployment from 'Staging' to 'Production'
vmPowershellCmdlets.MoveAzureDeployment(serviceName);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 1);
Console.WriteLine("successfully moved");
// Set the deployment status to 'Suspended'
vmPowershellCmdlets.SetAzureDeploymentStatus(serviceName, DeploymentSlotType.Production, DeploymentStatus.Suspended);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, DeploymentStatus.Suspended, 1);
Console.WriteLine("successfully changed the status");
// Update the deployment
vmPowershellCmdlets.SetAzureDeploymentConfig(serviceName, DeploymentSlotType.Production, configPath2.FullName);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2);
Console.WriteLine("successfully updated the deployment");
// Upgrade the deployment
DateTime start = DateTime.Now;
vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Simultaneous, packagePath2.FullName, configPath3.FullName);
TimeSpan duration = DateTime.Now - start;
Console.WriteLine("Auto upgrade took {0}.", duration);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 4);
Console.WriteLine("successfully updated the deployment");
vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true);
pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production);
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
}
}
/// <summary>
///
/// </summary>
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get)-AzureDns)")]
public void AzureDnsTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string dnsName = "OpenDns1";
string ipAddress = "208.67.222.222";
try
{
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmPowershellCmdlets.NewAzureService(serviceName, locationName);
DnsServer dns = vmPowershellCmdlets.NewAzureDns(dnsName, ipAddress);
AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, InstanceSize.ExtraSmall, imageName);
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password);
PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null);
PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo);
vmPowershellCmdlets.NewAzureVM(serviceName, new []{vm}, null, new[]{dns}, null, null, null, null, null, null);
DnsServerList dnsList = vmPowershellCmdlets.GetAzureDns(vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production).DnsSettings);
foreach (DnsServer dnsServer in dnsList)
{
Console.WriteLine("DNS Server Name: {0}, DNS Server Address: {1}", dnsServer.Name, dnsServer.Address);
Assert.AreEqual(dnsServer.Name, dns.Name);
Assert.AreEqual(dnsServer.Address, dns.Address);
}
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Set,Remove)-AzureEndpoint)")]
public void AzureEndpointTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string ep1Name = "tcp1";
int ep1LocalPort = 60010;
int ep1PublicPort = 60011;
string ep1LBSetName = "lbset1";
int ep1ProbePort = 60012;
string ep1ProbePath = string.Empty;
int? ep1ProbeInterval = 7;
int? ep1ProbeTimeout = null;
string ep2Name = "tcp2";
int ep2LocalPort = 60020;
int ep2PublicPort = 60021;
int ep2LocalPortChanged = 60030;
int ep2PublicPortChanged = 60031;
string ep2LBSetName = "lbset2";
int ep2ProbePort = 60022;
string ep2ProbePath = string.Empty;
int? ep2ProbeInterval = null;
int? ep2ProbeTimeout = 32;
AzureEndPointConfigInfo ep1Info = new AzureEndPointConfigInfo(
ProtocolInfo.tcp,
ep1LocalPort,
ep1PublicPort,
ep1Name,
ep1LBSetName,
ep1ProbePort,
ProtocolInfo.tcp,
ep1ProbePath,
ep1ProbeInterval,
ep1ProbeTimeout);
AzureEndPointConfigInfo ep2Info = new AzureEndPointConfigInfo(
ProtocolInfo.tcp,
ep2LocalPort,
ep2PublicPort,
ep2Name,
ep2LBSetName,
ep2ProbePort,
ProtocolInfo.tcp,
ep2ProbePath,
ep2ProbeInterval,
ep2ProbeTimeout);
try
{
foreach (AzureEndPointConfigInfo.ParameterSet p in Enum.GetValues(typeof(AzureEndPointConfigInfo.ParameterSet)))
{
string pSetName = Enum.GetName(typeof(AzureEndPointConfigInfo.ParameterSet), p);
Console.WriteLine("--Begin Endpoint Test with '{0}' parameter set.", pSetName);
ep1Info.ParamSet = p;
ep2Info.ParamSet = p;
ep2Info.EndpointLocalPort = ep2LocalPort;
ep2Info.EndpointPublicPort = ep2PublicPort;
// Add two new endpoints
Console.WriteLine("-----Add 2 new endpoints.");
vmPowershellCmdlets.AddEndPoint(defaultVm, defaultService, new[] { ep1Info, ep2Info }); // Add-AzureEndpoint with Get-AzureVM and Update-AzureVm
CheckEndpoint(defaultVm, defaultService, new[] { ep1Info, ep2Info });
// Change the endpoint
Console.WriteLine("-----Change the second endpoint.");
ep2Info.EndpointLocalPort = ep2LocalPortChanged;
ep2Info.EndpointPublicPort = ep2PublicPortChanged;
vmPowershellCmdlets.SetEndPoint(defaultVm, defaultService, ep2Info); // Set-AzureEndpoint with Get-AzureVM and Update-AzureVm
CheckEndpoint(defaultVm, defaultService, new[] { ep2Info });
// Remove Endpoint
Console.WriteLine("-----Remove endpoints.");
vmPowershellCmdlets.RemoveEndPoint(defaultVm, defaultService, new[] { ep1Name, ep2Name }); // Remove-AzureEndpoint
CheckEndpointRemoved(defaultVm, defaultService, new[] { ep1Info, ep2Info });
Console.WriteLine("Endpoint Test passed with '{0}' parameter set.", pSetName);
}
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
private bool CheckEndpoint(string vmName, string serviceName, AzureEndPointConfigInfo [] epInfos)
{
var serverEndpoints = vmPowershellCmdlets.GetAzureEndPoint(vmPowershellCmdlets.GetAzureVM(vmName, serviceName));
// List the endpoints found for debugging.
Console.WriteLine("***** Checking for Endpoints **************************************************");
Console.WriteLine("***** Listing Returned Endpoints");
foreach (InputEndpointContext ep in serverEndpoints)
{
Console.WriteLine("Endpoint - Name:{0} Protocol:{1} Port:{2} LocalPort:{3} Vip:{4}", ep.Name, ep.Protocol, ep.Port, ep.LocalPort, ep.Vip);
if (!string.IsNullOrEmpty(ep.LBSetName))
{
Console.WriteLine("\t- LBSetName:{0}", ep.LBSetName);
Console.WriteLine("\t- Probe - Port:{0} Protocol:{1} Interval:{2} Timeout:{3}", ep.ProbePort, ep.ProbeProtocol, ep.ProbeIntervalInSeconds, ep.ProbeTimeoutInSeconds);
}
}
Console.WriteLine("*******************************************************************************");
// Check if the specified endpoints were found.
foreach (AzureEndPointConfigInfo epInfo in epInfos)
{
bool found = false;
foreach (InputEndpointContext ep in serverEndpoints)
{
if (epInfo.CheckInputEndpointContext(ep))
{
found = true;
Console.WriteLine("Endpoint found: {0}", epInfo.EndpointName);
}
}
Assert.IsTrue(found, string.Format("Error: Endpoint '{0}' was not found!", epInfo.EndpointName));
}
return true;
}
private bool CheckEndpointRemoved(string vmName, string serviceName, AzureEndPointConfigInfo[] epInfos)
{
var serverEndpoints = vmPowershellCmdlets.GetAzureEndPoint(vmPowershellCmdlets.GetAzureVM(vmName, serviceName));
// List the endpoints found for debugging.
Console.WriteLine("***** Checking for Removed Endpoints ******************************************");
Console.WriteLine("***** Listing Returned Endpoints");
foreach (InputEndpointContext ep in serverEndpoints)
{
Console.WriteLine("Endpoint - Name:{0} Protocol:{1} Port:{2} LocalPort:{3} Vip:{4}", ep.Name, ep.Protocol, ep.Port, ep.LocalPort, ep.Vip);
if (!string.IsNullOrEmpty(ep.LBSetName))
{
Console.WriteLine("\t- LBSetName:{0}", ep.LBSetName);
Console.WriteLine("\t- Probe - Port:{0} Protocol:{1} Interval:{2} Timeout:{3}", ep.ProbePort, ep.ProbeProtocol, ep.ProbeIntervalInSeconds, ep.ProbeTimeoutInSeconds);
}
}
Console.WriteLine("*******************************************************************************");
// Check if the specified endpoints were found.
foreach (AzureEndPointConfigInfo epInfo in epInfos)
{
bool found = false;
foreach (InputEndpointContext ep in serverEndpoints)
{
if (epInfo.CheckInputEndpointContext(ep))
{
found = true;
Console.WriteLine("Endpoint found: {0}", epInfo.EndpointName);
}
}
Assert.IsFalse(found, string.Format("Error: Endpoint '{0}' was found!", epInfo.EndpointName));
}
return true;
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet Set-AzureAvailabilitySet)")]
public void AzureAvailabilitySetTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string testAVSetName = "testAVSet1";
try
{
var vm = vmPowershellCmdlets.SetAzureAvailabilitySet(defaultVm, defaultService, testAVSetName);
vmPowershellCmdlets.UpdateAzureVM(defaultVm, defaultService, vm);
CheckAvailabilitySet(defaultVm, defaultService, testAVSetName);
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
private void CheckAvailabilitySet(string vmName, string serviceName, string availabilitySetName)
{
var vm = vmPowershellCmdlets.GetAzureVM(vmName, serviceName);
Assert.IsTrue(vm.AvailabilitySetName.Equals(availabilitySetName, StringComparison.InvariantCultureIgnoreCase));
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureLocation)")]
public void AzureLocationTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
foreach (LocationsContext loc in vmPowershellCmdlets.GetAzureLocation())
{
Console.WriteLine("Location: Name - {0}, DisplayName - {1}", loc.Name, loc.DisplayName);
}
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureOSDisk)")]
public void AzureOSDiskTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
PersistentVM vm = vmPowershellCmdlets.GetAzureVM(defaultVm, defaultService).VM;
OSVirtualHardDisk osdisk = vmPowershellCmdlets.GetAzureOSDisk(vm);
Console.WriteLine("OS Disk: Name - {0}, Label - {1}, HostCaching - {2}, OS - {3}", osdisk.DiskName, osdisk.DiskLabel, osdisk.HostCaching, osdisk.OS);
Assert.IsTrue(osdisk.Equals(vm.OSVirtualHardDisk), "OS disk returned is not the same!");
PersistentVM vm2 = vmPowershellCmdlets.SetAzureOSDisk(HostCaching.ReadOnly, vm);
osdisk = vmPowershellCmdlets.GetAzureOSDisk(vm2);
Console.WriteLine("OS Disk: Name - {0}, Label - {1}, HostCaching - {2}, OS - {3}", osdisk.DiskName, osdisk.DiskLabel, osdisk.HostCaching, osdisk.OS);
Assert.IsTrue(osdisk.Equals(vm2.OSVirtualHardDisk), "OS disk returned is not the same!");
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureOSVersion)")]
public void AzureOSVersionTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
foreach (OSVersionsContext osVersions in vmPowershellCmdlets.GetAzureOSVersion())
{
Console.WriteLine("OS Version: Family - {0}, FamilyLabel - {1}, Version - {2}", osVersions.Family, osVersions.FamilyLabel, osVersions.Version);
}
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureRole)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)]
public void AzureRoleTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
// Choose the package and config files from local machine
string packageName = Convert.ToString(TestContext.DataRow["packageName"]);
string configName = Convert.ToString(TestContext.DataRow["configName"]);
string upgradePackageName = Convert.ToString(TestContext.DataRow["upgradePackage"]);
string upgradeConfigName = Convert.ToString(TestContext.DataRow["upgradeConfig"]);
var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName);
var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName);
Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1);
Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1);
string deploymentName = "deployment1";
string deploymentLabel = "label1";
string slot = DeploymentSlotType.Production;
//DeploymentInfoContext result;
string roleName = "";
try
{
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, slot, deploymentLabel, deploymentName, false, false);
foreach (RoleContext role in vmPowershellCmdlets.GetAzureRole(serviceName, slot, null, false))
{
Console.WriteLine("Role: Name - {0}, ServiceName - {1}, DeploymenntID - {2}, InstanceCount - {3}", role.RoleName, role.ServiceName, role.DeploymentID, role.InstanceCount);
Assert.AreEqual(serviceName, role.ServiceName);
roleName = role.RoleName;
}
vmPowershellCmdlets.SetAzureRole(serviceName, slot, roleName, 2);
foreach (RoleContext role in vmPowershellCmdlets.GetAzureRole(serviceName, slot, null, false))
{
Console.WriteLine("Role: Name - {0}, ServiceName - {1}, DeploymenntID - {2}, InstanceCount - {3}", role.RoleName, role.ServiceName, role.DeploymentID, role.InstanceCount);
Assert.AreEqual(serviceName, role.ServiceName);
Assert.AreEqual(2, role.InstanceCount);
}
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureSubnet)")]
public void AzureSubnetTest()
{
createOwnService = true;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
PersistentVM vm = vmPowershellCmdlets.NewAzureVMConfig(new AzureVMConfigInfo(vmName, InstanceSize.Small, imageName));
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password);
azureProvisioningConfig.Vm = vm;
string [] subs = new [] {"subnet1", "subnet2", "subnet3"};
vm = vmPowershellCmdlets.SetAzureSubnet(vmPowershellCmdlets.AddAzureProvisioningConfig(azureProvisioningConfig), subs);
SubnetNamesCollection subnets = vmPowershellCmdlets.GetAzureSubnet(vm);
foreach (string subnet in subnets)
{
Console.WriteLine("Subnet: {0}", subnet);
}
CollectionAssert.AreEqual(subnets, subs);
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get)-AzureStorageKey)")]
public void AzureStorageKeyTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
try
{
StorageServiceKeyOperationContext key1 = vmPowershellCmdlets.GetAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccount); // Get-AzureStorageAccountKey
Console.WriteLine("Primary - {0}", key1.Primary);
Console.WriteLine("Secondary - {0}", key1.Secondary);
StorageServiceKeyOperationContext key2 = vmPowershellCmdlets.NewAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccount, KeyType.Secondary);
Console.WriteLine("Primary - {0}", key2.Primary);
Console.WriteLine("Secondary - {0}", key2.Secondary);
Assert.AreEqual(key1.Primary, key2.Primary);
Assert.AreNotEqual(key1.Secondary, key2.Secondary);
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove)-AzureStorageAccount)")]
public void AzureStorageAccountTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string storageAccountPrefix = "psteststorage";
string storageName1 = Utilities.GetUniqueShortName(storageAccountPrefix);
string locationName1 = "West US";
string storageName2 = Utilities.GetUniqueShortName(storageAccountPrefix);
string locationName2 = "West US";
try
{
vmPowershellCmdlets.NewAzureStorageAccount(storageName1, locationName1, null, null, null);
vmPowershellCmdlets.NewAzureStorageAccount(storageName2, locationName2, null, null, null);
Assert.IsNotNull(vmPowershellCmdlets.GetAzureStorageAccount(storageName1));
Console.WriteLine("{0} is created", storageName1);
Assert.IsNotNull(vmPowershellCmdlets.GetAzureStorageAccount(storageName2));
Console.WriteLine("{0} is created", storageName2);
vmPowershellCmdlets.SetAzureStorageAccount(storageName1, "newLabel", "newDescription", false);
StorageServicePropertiesOperationContext storage = vmPowershellCmdlets.GetAzureStorageAccount(storageName1)[0];
Console.WriteLine("Name: {0}, Label: {1}, Description: {2}, GeoReplication: {3}", storage.StorageAccountName, storage.Label, storage.StorageAccountDescription, storage.GeoReplicationEnabled.ToString());
Assert.IsTrue((storage.Label == "newLabel" && storage.StorageAccountDescription == "newDescription" && storage.GeoReplicationEnabled == false), "storage account is not changed correctly");
vmPowershellCmdlets.RemoveAzureStorageAccount(storageName1);
vmPowershellCmdlets.RemoveAzureStorageAccount(storageName2);
Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureStorageAccount, storageName1), "The storage account was not removed");
Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureStorageAccount, storageName2), "The storage account was not removed");
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Save,Update,Remove)-AzureVMImage)")]
public void AzureVMImageTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string newImageName = Utilities.GetUniqueShortName("vmimage");
string mediaLocation = string.Format("{0}vhdstore/{1}", blobUrlRoot, vhdName);
string oldLabel = "old label";
string newLabel = "new label";
try
{
OSImageContext result = vmPowershellCmdlets.AddAzureVMImage(newImageName, mediaLocation, OS.Windows, oldLabel);
OSImageContext resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0];
Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned));
result = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, newLabel);
resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0];
Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned));
vmPowershellCmdlets.RemoveAzureVMImage(newImageName);
pass = true;
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set,Remove)-AzureVNetConfig)")]
public void AzureVNetConfigTest()
{
createOwnService = false;
StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);
string affinityGroup = "WestUsAffinityGroup";
try
{
if (Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityGroup))
{
vmPowershellCmdlets.NewAzureAffinityGroup(affinityGroup, Resource.Location, null, null);
}
vmPowershellCmdlets.SetAzureVNetConfig(vnetConfigFilePath);
var result = vmPowershellCmdlets.GetAzureVNetConfig(vnetConfigFilePath);
vmPowershellCmdlets.SetAzureVNetConfig(vnetConfigFilePath);
Collection<VirtualNetworkSiteContext> vnetSites = vmPowershellCmdlets.GetAzureVNetSite(null);
foreach (var re in vnetSites)
{
Console.WriteLine("VNet: {0}", re.Name);
}
vmPowershellCmdlets.RemoveAzureVNetConfig();
Collection<VirtualNetworkSiteContext> vnetSitesAfter = vmPowershellCmdlets.GetAzureVNetSite(null);
Assert.AreNotEqual(vnetSites.Count, vnetSitesAfter.Count, "No Vnet is removed");
foreach (var re in vnetSitesAfter)
{
Console.WriteLine("VNet: {0}", re.Name);
}
pass = true;
}
catch (Exception e)
{
if (e.ToString().Contains("while in use"))
{
Console.WriteLine(e.InnerException.ToString());
}
else
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Set,Remove)-AzureEndpoint)")]
public void VMSizeTest()
{
string newImageName = Utilities.GetUniqueShortName("vmimage");
string mediaLocation = string.Format("{0}vhdstore/{1}", blobUrlRoot, vhdName);
try
{
Array instanceSizes = Enum.GetValues(typeof(InstanceSize));
int arrayLength = instanceSizes.GetLength(0);
for (int i = 1; i < arrayLength; i++)
{
// Add-AzureVMImage test for VM size
OSImageContext result2 = vmPowershellCmdlets.AddAzureVMImage(newImageName, mediaLocation, OS.Windows, (InstanceSize) instanceSizes.GetValue(i));
OSImageContext resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0];
Assert.IsTrue(CompareContext<OSImageContext>(result2, resultReturned));
Console.WriteLine(i);
// Update-AzureVMImage test for VM size
result2 = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, (InstanceSize) instanceSizes.GetValue(Math.Max((i + 1) % arrayLength, 1)));
resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0];
Assert.IsTrue(CompareContext<OSImageContext>(result2, resultReturned));
vmPowershellCmdlets.RemoveAzureVMImage(newImageName);
}
foreach (InstanceSize size in instanceSizes)
{
if (size.Equals(InstanceSize.A6) || size.Equals(InstanceSize.A7))
{ // We skip tests for regular VM sizes. Also, a VM created with regular size cannot be updated to Hi-MEM.
serviceName = Utilities.GetUniqueShortName(serviceNamePrefix);
vmName = Utilities.GetUniqueShortName(vmNamePrefix);
// New-AzureQuickVM test for VM size
PersistentVMRoleContext result = vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, serviceName, imageName, username, password, locationName, size);
Assert.AreEqual(size.ToString(), result.InstanceSize);
Console.WriteLine("VM size, {0}, is verified for New-AzureQuickVM", size.ToString());
vmPowershellCmdlets.RemoveAzureVM(vmName, serviceName);
// New-AzureVMConfig test for VM size
AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, size, imageName);
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password);
PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null);
PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo);
vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm });
result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName);
Assert.AreEqual(size.ToString(), result.InstanceSize);
Console.WriteLine("VM size, {0}, is verified for New-AzureVMConfig", size.ToString());
vmPowershellCmdlets.RemoveAzureVM(vmName, serviceName);
vmPowershellCmdlets.RemoveAzureService(serviceName);
// Set-AzureVMSize test for VM size.
SetAzureVMSizeConfig vmSizeConfig = new SetAzureVMSizeConfig(size);
vmPowershellCmdlets.SetVMSize(defaultVm, defaultService, vmSizeConfig);
result = vmPowershellCmdlets.GetAzureVM(defaultVm, defaultService);
Assert.AreEqual(size.ToString(), result.InstanceSize);
Console.WriteLine("VM size, {0}, is verified for Set-AzureVMSize", size.ToString());
}
}
}
catch (Exception e)
{
pass = false;
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
private bool CompareContext<T>(T obj1, T obj2)
{
bool result = true;
Type type = typeof(T);
foreach(PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
string typeName = property.PropertyType.FullName;
if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") || typeName.Contains("Nullable"))
{
var obj1Value = property.GetValue(obj1, null);
var obj2Value = property.GetValue(obj2, null);
if (obj1Value == null)
{
result &= (obj2Value == null);
}
else
{
result &= (obj1Value.Equals(obj2Value));
}
}
else
{
Console.WriteLine("This type is not compared: {0}", typeName);
}
}
return result;
}
[TestCleanup]
public virtual void CleanUp()
{
Console.WriteLine("Test {0}", pass ? "passed" : "failed");
// Cleanup
if ((createOwnService && cleanupIfPassed && pass) || (createOwnService && cleanupIfFailed && !pass))
{
Console.WriteLine("Starting to clean up created VM and service.");
try
{
vmPowershellCmdlets.RemoveAzureVM(vmName, serviceName);
Console.WriteLine("VM, {0}, is deleted", vmName);
}
catch (Exception e)
{
Console.WriteLine("Error during removing VM: {0}", e.ToString());
}
try
{
vmPowershellCmdlets.RemoveAzureService(serviceName);
Console.WriteLine("Service, {0}, is deleted", serviceName);
}
catch (Exception e)
{
Console.WriteLine("Error during removing VM: {0}", e.ToString());
}
}
}
[ClassCleanup]
public static void ClassCleanUp()
{
try
{
vmPowershellCmdlets.RemoveAzureVM(defaultVm, defaultService);
Console.WriteLine("VM, {0}, is deleted", defaultVm);
}
catch (Exception e)
{
Console.WriteLine("Error during removing VM: {0}", e.ToString());
}
try
{
vmPowershellCmdlets.RemoveAzureService(defaultService);
Console.WriteLine("Service, {0}, is deleted", defaultService);
}
catch (Exception e)
{
Console.WriteLine("Error during removing VM: {0}", e.ToString());
}
}
}
}
| |
/*
* Copyright 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using ZXing.Common;
namespace ZXing.OneD
{
/// <summary>
/// This object renders a CODE128 code as a <see cref="BitMatrix" />.
///
/// <author>erik.barbara@gmail.com (Erik Barbara)</author>
/// </summary>
internal sealed class Code128Writer : OneDimensionalCodeWriter
{
private const int CODE_START_B = 104;
private const int CODE_START_C = 105;
private const int CODE_CODE_B = 100;
private const int CODE_CODE_C = 99;
private const int CODE_STOP = 106;
// Dummy characters used to specify control characters in input
private const char ESCAPE_FNC_1 = '\u00f1';
private const char ESCAPE_FNC_2 = '\u00f2';
private const char ESCAPE_FNC_3 = '\u00f3';
private const char ESCAPE_FNC_4 = '\u00f4';
private const int CODE_FNC_1 = 102; // Code A, Code B, Code C
private const int CODE_FNC_2 = 97; // Code A, Code B
private const int CODE_FNC_3 = 96; // Code A, Code B
private const int CODE_FNC_4_B = 100; // Code B
private bool forceCodesetB;
public override BitMatrix encode(String contents,
BarcodeFormat format,
int width,
int height,
IDictionary<EncodeHintType, object> hints)
{
if (format != BarcodeFormat.CODE_128)
{
throw new ArgumentException("Can only encode CODE_128, but got " + format);
}
forceCodesetB = (hints != null &&
hints.ContainsKey(EncodeHintType.CODE128_FORCE_CODESET_B) &&
(bool) hints[EncodeHintType.CODE128_FORCE_CODESET_B]);
return base.encode(contents, format, width, height, hints);
}
override public bool[] encode(String contents)
{
int length = contents.Length;
// Check length
if (length < 1 || length > 80)
{
throw new ArgumentException(
"Contents length should be between 1 and 80 characters, but got " + length);
}
// Check content
for (int i = 0; i < length; i++)
{
char c = contents[i];
if (c < ' ' || c > '~')
{
switch (c)
{
case ESCAPE_FNC_1:
case ESCAPE_FNC_2:
case ESCAPE_FNC_3:
case ESCAPE_FNC_4:
break;
default:
throw new ArgumentException("Bad character in input: " + c);
}
}
}
var patterns = new List<int[]>(); // temporary storage for patterns
int checkSum = 0;
int checkWeight = 1;
int codeSet = 0; // selected code (CODE_CODE_B or CODE_CODE_C)
int position = 0; // position in contents
while (position < length)
{
//Select code to use
int requiredDigitCount = codeSet == CODE_CODE_C ? 2 : 4;
int newCodeSet;
if (isDigits(contents, position, requiredDigitCount))
{
newCodeSet = forceCodesetB ? CODE_CODE_B : CODE_CODE_C;
}
else
{
newCodeSet = CODE_CODE_B;
}
//Get the pattern index
int patternIndex;
if (newCodeSet == codeSet)
{
// Encode the current character
// First handle escapes
switch (contents[position])
{
case ESCAPE_FNC_1:
patternIndex = CODE_FNC_1;
break;
case ESCAPE_FNC_2:
patternIndex = CODE_FNC_2;
break;
case ESCAPE_FNC_3:
patternIndex = CODE_FNC_3;
break;
case ESCAPE_FNC_4:
patternIndex = CODE_FNC_4_B; // FIXME if this ever outputs Code A
break;
default:
// Then handle normal characters otherwise
if (codeSet == CODE_CODE_B)
{
patternIndex = contents[position] - ' ';
}
else
{ // CODE_CODE_C
patternIndex = Int32.Parse(contents.Substring(position, 2));
position++; // Also incremented below
}
break;
}
position++;
}
else
{
// Should we change the current code?
// Do we have a code set?
if (codeSet == 0)
{
// No, we don't have a code set
if (newCodeSet == CODE_CODE_B)
{
patternIndex = CODE_START_B;
}
else
{
// CODE_CODE_C
patternIndex = CODE_START_C;
}
}
else
{
// Yes, we have a code set
patternIndex = newCodeSet;
}
codeSet = newCodeSet;
}
// Get the pattern
patterns.Add(Code128Reader.CODE_PATTERNS[patternIndex]);
// Compute checksum
checkSum += patternIndex * checkWeight;
if (position != 0)
{
checkWeight++;
}
}
// Compute and append checksum
checkSum %= 103;
patterns.Add(Code128Reader.CODE_PATTERNS[checkSum]);
// Append stop code
patterns.Add(Code128Reader.CODE_PATTERNS[CODE_STOP]);
// Compute code width
int codeWidth = 0;
foreach (int[] pattern in patterns)
{
foreach (int width in pattern)
{
codeWidth += width;
}
}
// Compute result
var result = new bool[codeWidth];
int pos = 0;
foreach (int[] pattern in patterns)
{
pos += appendPattern(result, pos, pattern, true);
}
return result;
}
private static bool isDigits(String value, int start, int length)
{
int end = start + length;
int last = value.Length;
for (int i = start; i < end && i < last; i++)
{
char c = value[i];
if (c < '0' || c > '9')
{
if (c != ESCAPE_FNC_1)
{
return false;
}
end++; // ignore FNC_1
}
}
return end <= last; // end > last if we've run out of string
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData.Query
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using Microsoft.Data.Edm;
using Microsoft.Data.Edm.Library;
using Microsoft.Data.OData.Metadata;
using Microsoft.Data.OData.Query.Metadata;
#endregion Namespaces
/// <summary>
/// Binder which applies metadata to a lexical QueryToken tree and produces a bound semantic QueryNode tree.
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Keeping the visitor in one place makes sense.")]
#if INTERNAL_DROP
internal class MetadataBinder
#else
public class MetadataBinder
#endif
{
/// <summary>
/// The model used for binding.
/// </summary>
private readonly IEdmModel model;
/// <summary>
/// Collection of query option tokens associated with the currect query being processed.
/// If a given query option is bound it should be removed from this collection.
/// </summary>
private List<QueryOptionQueryToken> queryOptions;
/// <summary>
/// If the binder is binding an expression, like $filter or $orderby, this member holds
/// the reference to the parameter node for the expression.
/// </summary>
private ParameterQueryNode parameter;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="model">The model to use for binding.</param>
public MetadataBinder(IEdmModel model)
{
ExceptionUtils.CheckArgumentNotNull(model, "model");
this.model = model;
}
/// <summary>
/// Gets the EDM model.
/// </summary>
protected IEdmModel Model
{
get { return this.model; }
}
/// <summary>
/// Binds the specified <paramref name="queryDescriptorQueryToken"/> to the metadata and returns a bound query.
/// </summary>
/// <param name="queryDescriptorQueryToken">The lexical query descriptor for the query to process.</param>
/// <returns>Metadata bound semantic query descriptor for the query.</returns>
public QueryDescriptorQueryNode BindQuery(QueryDescriptorQueryToken queryDescriptorQueryToken)
{
ExceptionUtils.CheckArgumentNotNull(queryDescriptorQueryToken, "queryDescriptorQueryToken");
return this.BindQueryDescriptor(queryDescriptorQueryToken);
}
/// <summary>
/// Visits a <see cref="QueryToken"/> in the lexical tree and binds it to metadata producing a semantic <see cref="QueryNode"/>.
/// </summary>
/// <param name="token">The query token on the input.</param>
/// <returns>The bound query node output.</returns>
protected QueryNode Bind(QueryToken token)
{
ExceptionUtils.CheckArgumentNotNull(token, "token");
QueryNode result;
switch (token.Kind)
{
case QueryTokenKind.Extension:
result = this.BindExtension(token);
break;
case QueryTokenKind.Any:
result = this.BindAny((AnyQueryToken)token);
break;
case QueryTokenKind.All:
result = this.BindAll((AllQueryToken)token);
break;
case QueryTokenKind.Segment:
result = this.BindSegment((SegmentQueryToken)token);
break;
case QueryTokenKind.NonRootSegment:
result = this.BindNavigationProperty((NavigationPropertyToken)token);
break;
case QueryTokenKind.Literal:
result = this.BindLiteral((LiteralQueryToken)token);
break;
case QueryTokenKind.BinaryOperator:
result = this.BindBinaryOperator((BinaryOperatorQueryToken)token);
break;
case QueryTokenKind.UnaryOperator:
result = this.BindUnaryOperator((UnaryOperatorQueryToken)token);
break;
case QueryTokenKind.PropertyAccess:
result = this.BindPropertyAccess((PropertyAccessQueryToken)token);
break;
case QueryTokenKind.FunctionCall:
result = this.BindFunctionCall((FunctionCallQueryToken)token);
break;
case QueryTokenKind.QueryOption:
result = this.BindQueryOption((QueryOptionQueryToken)token);
break;
case QueryTokenKind.Cast:
result = this.BindCast((CastToken)token);
break;
case QueryTokenKind.Parameter:
result = this.BindParameter((ParameterQueryToken)token);
break;
default:
throw new ODataException(Strings.MetadataBinder_UnsupportedQueryTokenKind(token.Kind));
}
if (result == null)
{
throw new ODataException(Strings.MetadataBinder_BoundNodeCannotBeNull(token.Kind));
}
return result;
}
/// <summary>
/// Binds a parameter token.
/// </summary>
/// <param name="parameterQueryToken">The parameter token to bind.</param>
/// <returns>The bound query node.</returns>
protected virtual QueryNode BindParameter(ParameterQueryToken parameterQueryToken)
{
ExceptionUtils.CheckArgumentNotNull(parameterQueryToken, "extensionToken");
QueryNode source = this.Bind(parameterQueryToken.Parent);
IEdmType type = GetType(source);
return new ParameterQueryNode
{
ParameterType = type.ToTypeReference()
};
}
/// <summary>
/// Binds an extension token.
/// </summary>
/// <param name="extensionToken">The extension token to bind.</param>
/// <returns>The bound query node.</returns>
protected virtual QueryNode BindExtension(QueryToken extensionToken)
{
ExceptionUtils.CheckArgumentNotNull(extensionToken, "extensionToken");
throw new ODataException(Strings.MetadataBinder_UnsupportedExtensionToken);
}
/// <summary>
/// Need to revert this.
/// </summary>
/// <param name="segmentToken">Need to revert this.</param>
/// <returns>Need to revert this.</returns>
protected virtual QueryNode BindSegment(SegmentQueryToken segmentToken)
{
ExceptionUtils.CheckArgumentNotNull(segmentToken, "segmentToken");
ExceptionUtils.CheckArgumentNotNull(segmentToken.Name, "segmentToken.Name");
if (segmentToken.Parent == null)
{
return this.BindRootSegment(segmentToken);
}
else
{
return this.BindNonRootSegment(segmentToken);
// TODO: return this.BindNonRootSegment(segmentToken);
throw new NotImplementedException();
}
}
protected virtual QueryNode BindNonRootSegment(SegmentQueryToken segmentToken)
{
var parent = Bind(segmentToken.Parent);
if (parent is SingleValueQueryNode)
{
var parentType = (parent as SingleValueQueryNode).TypeReference.Definition;
if (parentType is IEdmEntityType)
{
var parentEntityType = parentType as IEdmEntityType;
var targetProperty = parentEntityType.Properties().FirstOrDefault(p => p.Name.Equals(segmentToken.Name));
if (targetProperty != null)
{
if (targetProperty is IEdmNavigationProperty)
{
var targetNavProperty = targetProperty as IEdmNavigationProperty;
return new NavigationPropertyNode
{
NavigationProperty = targetNavProperty,
Source = parent
};
}
if (targetProperty is IEdmStructuralProperty)
{
return new PropertyAccessQueryNode
{
Source = parent as SingleValueQueryNode,
Property = targetProperty
};
}
}
}
}
throw new NotImplementedException();
}
/// <summary>
/// Binds a <see cref="QueryDescriptorQueryToken"/>.
/// </summary>
/// <param name="queryDescriptorToken">The query descriptor token to bind.</param>
/// <returns>The bound query descriptor.</returns>
protected virtual QueryDescriptorQueryNode BindQueryDescriptor(QueryDescriptorQueryToken queryDescriptorToken)
{
ExceptionUtils.CheckArgumentNotNull(queryDescriptorToken, "queryDescriptorToken");
ExceptionUtils.CheckArgumentNotNull(queryDescriptorToken.Path, "queryDescriptorToken.Path");
// Make a copy of query options since we may consume some of them as we bind the query
this.queryOptions = new List<QueryOptionQueryToken>(queryDescriptorToken.QueryOptions);
//// TODO: check whether there is a $count segment at the top; if so strip it and first process everything else and
//// then add it to the bound query tree at the end
// First bind the path
QueryNode query = this.Bind(queryDescriptorToken.Path);
// Apply filter first, then order-by, skip, top, select and expand
query = this.ProcessFilter(query, queryDescriptorToken.Filter);
query = this.ProcessOrderBy(query, queryDescriptorToken.OrderByTokens);
query = ProcessSkip(query, queryDescriptorToken.Skip);
query = ProcessTop(query, queryDescriptorToken.Top);
//// TODO: if we found a $count segment process it now and add it to the query
QueryDescriptorQueryNode queryDescriptorNode = new QueryDescriptorQueryNode();
queryDescriptorNode.Query = query;
// Add the remaining query options to the query descriptor.
List<QueryNode> boundQueryOptions = this.ProcessQueryOptions();
queryDescriptorNode.CustomQueryOptions = new ReadOnlyCollection<QueryNode>(boundQueryOptions);
Debug.Assert(this.queryOptions == null, "this.queryOptions == null");
return queryDescriptorNode;
}
/// <summary>
/// Binds a literal token.
/// </summary>
/// <param name="literalToken">The literal token to bind.</param>
/// <returns>The bound literal token.</returns>
protected virtual QueryNode BindLiteral(LiteralQueryToken literalToken)
{
ExceptionUtils.CheckArgumentNotNull(literalToken, "literalToken");
return new ConstantQueryNode()
{
Value = literalToken.Value
};
}
/// <summary>
/// Binds a binary operator token.
/// </summary>
/// <param name="binaryOperatorToken">The binary operator token to bind.</param>
/// <returns>The bound binary operator token.</returns>
protected virtual QueryNode BindBinaryOperator(BinaryOperatorQueryToken binaryOperatorToken)
{
ExceptionUtils.CheckArgumentNotNull(binaryOperatorToken, "binaryOperatorToken");
SingleValueQueryNode left = this.Bind(binaryOperatorToken.Left) as SingleValueQueryNode;
if (left == null)
{
throw new ODataException(Strings.MetadataBinder_BinaryOperatorOperandNotSingleValue(binaryOperatorToken.OperatorKind.ToString()));
}
SingleValueQueryNode right = this.Bind(binaryOperatorToken.Right) as SingleValueQueryNode;
if (right == null)
{
throw new ODataException(Strings.MetadataBinder_BinaryOperatorOperandNotSingleValue(binaryOperatorToken.OperatorKind.ToString()));
}
IEdmTypeReference leftType = left.TypeReference;
IEdmTypeReference rightType = right.TypeReference;
if (!TypePromotionUtils.PromoteOperandTypes(binaryOperatorToken.OperatorKind, ref leftType, ref rightType))
{
string leftTypeName = left.TypeReference == null ? "<null>" : left.TypeReference.ODataFullName();
string rightTypeName = right.TypeReference == null ? "<null>" : right.TypeReference.ODataFullName();
throw new ODataException(Strings.MetadataBinder_IncompatibleOperandsError(leftTypeName, rightTypeName, binaryOperatorToken.OperatorKind));
}
if (leftType != null)
{
left = ConvertToType(left, leftType);
}
if (rightType != null)
{
right = ConvertToType(right, rightType);
}
return new BinaryOperatorQueryNode()
{
OperatorKind = binaryOperatorToken.OperatorKind,
Left = left,
Right = right
};
}
/// <summary>
/// Binds a unary operator token.
/// </summary>
/// <param name="unaryOperatorToken">The unary operator token to bind.</param>
/// <returns>The bound unary operator token.</returns>
protected virtual QueryNode BindUnaryOperator(UnaryOperatorQueryToken unaryOperatorToken)
{
ExceptionUtils.CheckArgumentNotNull(unaryOperatorToken, "unaryOperatorToken");
SingleValueQueryNode operand = this.Bind(unaryOperatorToken.Operand) as SingleValueQueryNode;
if (operand == null)
{
throw new ODataException(Strings.MetadataBinder_UnaryOperatorOperandNotSingleValue(unaryOperatorToken.OperatorKind.ToString()));
}
IEdmTypeReference typeReference = operand.TypeReference;
if (!TypePromotionUtils.PromoteOperandType(unaryOperatorToken.OperatorKind, ref typeReference))
{
string typeName = operand.TypeReference == null ? "<null>" : operand.TypeReference.ODataFullName();
throw new ODataException(Strings.MetadataBinder_IncompatibleOperandError(typeName, unaryOperatorToken.OperatorKind));
}
if (typeReference != null)
{
operand = ConvertToType(operand, typeReference);
}
return new UnaryOperatorQueryNode()
{
OperatorKind = unaryOperatorToken.OperatorKind,
Operand = operand
};
}
/// <summary>
/// Binds a type segment token.
/// </summary>
/// <param name="castToken">The type segment token to bind.</param>
/// <returns>The bound type segment token.</returns>
protected virtual QueryNode BindCast(CastToken castToken)
{
ExceptionUtils.CheckArgumentNotNull(castToken, "typeSegmentToken");
var childType = this.model.FindType(castToken.SegmentSpace + "." + castToken.SegmentName);
// Check whether childType is a derived type of the type of its parent node
QueryNode parent;
IEdmType parentType;
if (castToken.Source == null)
{
parent = null;
parentType = this.parameter.ParameterType.Definition;
}
else
{
parent = this.Bind(castToken.Source);
parentType = GetType(parent);
}
if (!childType.IsOrInheritsFrom(parentType))
{
throw new ODataException(Strings.MetadataBinder_HierarchyNotFollowed(childType.FullName(), parentType.ODataFullName()));
}
return new CastNode()
{
EdmType = childType,
Source = (SingleValueQueryNode)parent
};
}
/// <summary>
/// Binds Any token.
/// </summary>
/// <param name="anyQueryToken">The Any token to bind.</param>
/// <returns>The bound Any node.</returns>
protected virtual QueryNode BindAny(AnyQueryToken anyQueryToken)
{
ExceptionUtils.CheckArgumentNotNull(anyQueryToken, "anyQueryToken");
QueryNode property = this.Bind(anyQueryToken.Parent);
QueryNode expr = this.Bind(anyQueryToken.Expression);
return new AnyQueryNode()
{
Body = expr,
Source = property
};
}
/// <summary>
/// Binds All token.
/// </summary>
/// <param name="allQueryToken">The All token to bind.</param>
/// <returns>The bound All node.</returns>
protected virtual QueryNode BindAll(AllQueryToken allQueryToken)
{
ExceptionUtils.CheckArgumentNotNull(allQueryToken, "allQueryToken");
QueryNode property = this.Bind(allQueryToken.Parent);
QueryNode expr = this.Bind(allQueryToken.Expression);
return new AllQueryNode()
{
Body = expr,
Source = property
};
}
/// <summary>
/// Binds a property access token.
/// </summary>
/// <param name="propertyAccessToken">The property access token to bind.</param>
/// <returns>The bound property access token.</returns>
protected virtual QueryNode BindPropertyAccess(PropertyAccessQueryToken propertyAccessToken)
{
ExceptionUtils.CheckArgumentNotNull(propertyAccessToken, "propertyAccessToken");
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(propertyAccessToken.Name, "propertyAccessToken.Name");
SingleValueQueryNode parentNode;
SingleValueQueryNode navigationPath = null;
// Set the parentNode (get the parent type, so you can check whether the Name inside propertyAccessToken really is legit offshoot of the parent type)
QueryNode parent = null;
if (propertyAccessToken.Parent == null)
{
if (this.parameter == null)
{
throw new ODataException(Strings.MetadataBinder_PropertyAccessWithoutParentParameter);
}
parentNode = this.parameter;
parent = this.parameter;
}
else
{
parent = this.Bind(propertyAccessToken.Parent) as SingleValueQueryNode;
if (parent == null)
{
throw new ODataException(Strings.MetadataBinder_PropertyAccessSourceNotSingleValue(propertyAccessToken.Name));
}
NavigationPropertyNode parentNav = parent as NavigationPropertyNode;
CastNode parentCast = parent as CastNode;
PropertyAccessQueryNode parentProperty = parent as PropertyAccessQueryNode;
if (parentProperty != null)
{
navigationPath = parentProperty;
var propertyPath = (IEdmStructuralProperty)parentProperty.Property;
parentNode = new ParameterQueryNode()
{
ParameterType = propertyPath.Type
};
}
else if (parentCast != null)
{
IEdmType entityType = parentCast.EdmType;
parentNode = new ParameterQueryNode()
{
ParameterType = entityType.ToTypeReference()
};
}
else if (parentNav != null)
{
navigationPath = parentNav;
IEdmEntityType entityType = parentNav.NavigationProperty.ToEntityType();
parentNode = new ParameterQueryNode()
{
ParameterType = new EdmEntityTypeReference(entityType, true)
};
}
else
{
parentNode = this.Bind(propertyAccessToken.Parent) as SingleValueQueryNode;
}
}
// Now that we have the parent type, can find its corresponding EDM type
IEdmStructuredTypeReference structuredParentType =
parentNode.TypeReference == null ? null : parentNode.TypeReference.AsStructuredOrNull();
IEdmProperty property =
structuredParentType == null ? null : structuredParentType.FindProperty(propertyAccessToken.Name);
if (property != null)
{
// TODO: Check that we have entity set once we add the entity set propagation into the bound tree
// See RequestQueryParser.ExpressionParser.ParseMemberAccess
if (property.Type.IsNonEntityODataCollectionTypeKind())
{
throw new ODataException(Strings.MetadataBinder_MultiValuePropertyNotSupportedInExpression(property.Name));
}
if (property.PropertyKind == EdmPropertyKind.Navigation)
{
// TODO: Implement navigations
throw new NotImplementedException();
}
if (navigationPath != null)
{
parentNode = navigationPath;
}
return new PropertyAccessQueryNode()
{
Source = (SingleValueQueryNode)parent,
Property = property
};
}
else
{
if (parentNode.TypeReference != null && !parentNode.TypeReference.Definition.IsOpenType())
{
throw new ODataException(Strings.MetadataBinder_PropertyNotDeclared(parentNode.TypeReference.ODataFullName(), propertyAccessToken.Name));
}
// TODO: Implement open property support
throw new NotImplementedException();
}
}
/// <summary>
/// Binds a function call token.
/// </summary>
/// <param name="functionCallToken">The function call token to bind.</param>
/// <returns>The bound function call token.</returns>
protected virtual QueryNode BindFunctionCall(FunctionCallQueryToken functionCallToken)
{
ExceptionUtils.CheckArgumentNotNull(functionCallToken, "functionCallToken");
ExceptionUtils.CheckArgumentNotNull(functionCallToken.Name, "functionCallToken.Name");
// Bind all arguments
List<QueryNode> argumentNodes = new List<QueryNode>(functionCallToken.Arguments.Select(ar => this.Bind(ar)));
// Special case the operators which look like function calls
if (functionCallToken.Name == "cast")
{
// TODO: Implement cast operators
throw new NotImplementedException();
}
else if (functionCallToken.Name == "isof")
{
// TODO: Implement cast operators
throw new NotImplementedException();
}
else
{
// Try to find the function in our built-in functions
BuiltInFunctionSignature[] signatures;
if (!BuiltInFunctions.TryGetBuiltInFunction(functionCallToken.Name, out signatures))
{
throw new ODataException(Strings.MetadataBinder_UnknownFunction(functionCallToken.Name));
}
// Right now all functions take a single value for all arguments
IEdmTypeReference[] argumentTypes = new IEdmTypeReference[argumentNodes.Count];
for (int i = 0; i < argumentNodes.Count; i++)
{
SingleValueQueryNode argumentNode = argumentNodes[i] as SingleValueQueryNode;
if (argumentNode == null)
{
throw new ODataException(Strings.MetadataBinder_FunctionArgumentNotSingleValue(functionCallToken.Name));
}
argumentTypes[i] = argumentNode.TypeReference;
}
BuiltInFunctionSignature signature = (BuiltInFunctionSignature)
TypePromotionUtils.FindBestFunctionSignature(signatures, argumentTypes);
if (signature == null)
{
throw new ODataException(Strings.MetadataBinder_NoApplicableFunctionFound(
functionCallToken.Name,
BuiltInFunctions.BuildFunctionSignatureListDescription(functionCallToken.Name, signatures)));
}
// Convert all argument nodes to the best signature argument type
Debug.Assert(signature.ArgumentTypes.Length == argumentNodes.Count, "The best signature match doesn't have the same number of arguments.");
for (int i = 0; i < argumentNodes.Count; i++)
{
Debug.Assert(argumentNodes[i] is SingleValueQueryNode, "We should have already verified that all arguments are single values.");
SingleValueQueryNode argumentNode = (SingleValueQueryNode)argumentNodes[i];
IEdmTypeReference signatureArgumentType = signature.ArgumentTypes[i];
if (signatureArgumentType != argumentNode.TypeReference)
{
argumentNodes[i] = ConvertToType(argumentNode, signatureArgumentType);
}
}
return new SingleValueFunctionCallQueryNode
{
Name = functionCallToken.Name,
Arguments = new ReadOnlyCollection<QueryNode>(argumentNodes),
ReturnType = signature.ReturnType
};
}
}
/// <summary>
/// Binds a query option token.
/// </summary>
/// <param name="queryOptionToken">The query option token to bind.</param>
/// <returns>The bound query option token.</returns>
/// <remarks>The default implementation of this method will not allow any system query options
/// (query options starting with '$') that were not previously processed.</remarks>
protected virtual QueryNode BindQueryOption(QueryOptionQueryToken queryOptionToken)
{
ExceptionUtils.CheckArgumentNotNull(queryOptionToken, "queryOptionToken");
// If we find a system query option here we will throw
string name = queryOptionToken.Name;
if (!string.IsNullOrEmpty(name) && name[0] == '$')
{
throw new ODataException(Strings.MetadataBinder_UnsupportedSystemQueryOption(name));
}
return new CustomQueryOptionQueryNode
{
Name = name,
Value = queryOptionToken.Value
};
}
/// <summary>
/// Binds a string to its associated type.
/// </summary>
/// <param name="parentReference">The parent type to be used to find binding options.</param>
/// <param name="propertyName">The string designated the property name to be bound.</param>
/// <returns>The property associated with string and parent type.</returns>
private static IEdmProperty BindProperty(IEdmTypeReference parentReference, string propertyName)
{
IEdmStructuredTypeReference structuredParentType =
parentReference == null ? null : parentReference.AsStructuredOrNull();
return structuredParentType == null ? null : structuredParentType.FindProperty(propertyName);
}
/// <summary>
/// Retrieves type associated to a segment.
/// </summary>
/// <param name="segment">The segment to be bound.</param>
/// <returns>The bound node.</returns>
private static IEdmType GetType(QueryNode segment)
{
NavigationPropertyNode segmentNav = segment as NavigationPropertyNode;
CastNode segmentCast = segment as CastNode;
PropertyAccessQueryNode segmentProperty = segment as PropertyAccessQueryNode;
ParameterQueryNode segmentParam = segment as ParameterQueryNode;
if (segmentCast != null)
{
return segmentCast.EdmType;
}
else if (segmentNav != null)
{
return segmentNav.NavigationProperty.ToEntityType();
}
else if (segmentProperty != null)
{
return segmentProperty.TypeReference.Definition;
}
else if (segmentParam != null)
{
return segmentParam.TypeReference.Definition;
}
else
{
throw new ODataException(Strings.MetadataBinder_NoTypeSupported);
}
}
/// <summary>
/// Processes the skip operator (if any) and returns the combined query.
/// </summary>
/// <param name="query">The query tree constructed so far.</param>
/// <param name="skip">The skip amount or null if none was specified.</param>
/// <returns>
/// The unmodified <paramref name="query"/> if no skip is specified or the combined
/// query tree including the skip operator if it was specified.
/// </returns>
private static QueryNode ProcessSkip(QueryNode query, int? skip)
{
ExceptionUtils.CheckArgumentNotNull(query, "query");
if (skip.HasValue)
{
CollectionQueryNode entityCollection = query.AsEntityCollectionNode();
if (entityCollection == null)
{
throw new ODataException(Strings.MetadataBinder_SkipNotApplicable);
}
int skipValue = skip.Value;
if (skipValue < 0)
{
throw new ODataException(Strings.MetadataBinder_SkipRequiresNonNegativeInteger(skipValue.ToString(CultureInfo.CurrentCulture)));
}
query = new SkipQueryNode()
{
Collection = entityCollection,
Amount = new ConstantQueryNode { Value = skipValue }
};
}
return query;
}
/// <summary>
/// Processes the top operator (if any) and returns the combined query.
/// </summary>
/// <param name="query">The query tree constructed so far.</param>
/// <param name="top">The top amount or null if none was specified.</param>
/// <returns>
/// The unmodified <paramref name="query"/> if no top is specified or the combined
/// query tree including the top operator if it was specified.
/// </returns>
private static QueryNode ProcessTop(QueryNode query, int? top)
{
ExceptionUtils.CheckArgumentNotNull(query, "query");
if (top.HasValue)
{
CollectionQueryNode entityCollection = query.AsEntityCollectionNode();
if (entityCollection == null)
{
throw new ODataException(Strings.MetadataBinder_TopNotApplicable);
}
int topValue = top.Value;
if (topValue < 0)
{
throw new ODataException(Strings.MetadataBinder_TopRequiresNonNegativeInteger(topValue.ToString(CultureInfo.CurrentCulture)));
}
query = new TopQueryNode()
{
Collection = entityCollection,
Amount = new ConstantQueryNode { Value = topValue }
};
}
return query;
}
/// <summary>
/// Determines if a segment is a complex type.
/// </summary>
/// <param name="instance">Segment to be checked.</param>
/// <param name="parentType">The type of the parent segment.</param>
/// <returns>True if segment represents a complex type and false otherwise.</returns>
private static Boolean IsDerivedComplexType(NavigationPropertyToken instance, IEdmType parentType)
{
IEdmProperty property = BindProperty(parentType.ToTypeReference(), instance.Name);
return property.Type.IsODataComplexTypeKind();
}
/// <summary>
/// Checks if the source is of the specified type and if not tries to inject a convert.
/// </summary>
/// <param name="source">The source node to apply the convertion to.</param>
/// <param name="targetTypeReference">The target primitive type.</param>
/// <returns>The converted query node.</returns>
private static SingleValueQueryNode ConvertToType(SingleValueQueryNode source, IEdmTypeReference targetTypeReference)
{
Debug.Assert(source != null, "source != null");
Debug.Assert(targetTypeReference != null, "targetType != null");
Debug.Assert(targetTypeReference.IsODataPrimitiveTypeKind(), "Can only convert primitive types.");
if (source.TypeReference != null)
{
// TODO: Do we check this here or in the caller?
Debug.Assert(source.TypeReference.IsODataPrimitiveTypeKind(), "Can only work on primitive types.");
if (source.TypeReference.IsEquivalentTo(targetTypeReference))
{
return source;
}
else
{
if (!TypePromotionUtils.CanConvertTo(source.TypeReference, targetTypeReference))
{
throw new ODataException(Strings.MetadataBinder_CannotConvertToType(source.TypeReference.ODataFullName(), targetTypeReference.ODataFullName()));
}
}
}
// If the source doesn't have a type (possibly an open property), then it's possible to convert it
// cause we don't know for sure.
return new ConvertQueryNode()
{
Source = source,
TargetType = targetTypeReference
};
}
/// <summary>
/// Binds a <see cref="NavigationPropertyToken"/>.
/// </summary>
/// <param name="segmentToken">The segment token to bind.</param>
/// <returns>The bound node.</returns>
private SingleValueQueryNode BindNavigationProperty(NavigationPropertyToken segmentToken)
{
QueryNode source = null;
IEdmNavigationProperty property;
if (segmentToken.Parent != null)
{
source = this.Bind(segmentToken.Parent);
IEdmType entityType = null;
if (IsDerivedComplexType(segmentToken, GetType(source)))
{
IEdmProperty returnProperty = BindProperty(GetType(source).ToTypeReference(), segmentToken.Name);
return new PropertyAccessQueryNode()
{
Source = (SingleValueQueryNode)source,
Property = returnProperty
};
}
else
{
entityType = GetType(source);
}
ParameterQueryNode parentNode = new ParameterQueryNode
{ ParameterType = entityType.ToTypeReference() };
property = (IEdmNavigationProperty)BindProperty(parentNode.TypeReference, segmentToken.Name);
}
else
{
if (IsDerivedComplexType(segmentToken, this.parameter.TypeReference.Definition))
{
IEdmProperty returnProperty = BindProperty(new EdmEntityTypeReference((IEdmEntityType)this.parameter.TypeReference.Definition, true), segmentToken.Name);
return new PropertyAccessQueryNode
{
Source = this.parameter,
Property = returnProperty
};
}
property = (IEdmNavigationProperty)BindProperty(this.parameter.TypeReference, segmentToken.Name);
}
// Ensure that only collections head Any queries and nothing else
if (property.OwnMultiplicity() == EdmMultiplicity.Many && segmentToken.AnyAllParent == false)
{
throw new ODataException(Strings.MetadataBinder_PropertyAccessSourceNotSingleValue(segmentToken.Name));
}
else if (property.OwnMultiplicity() != EdmMultiplicity.Many && segmentToken.AnyAllParent == true)
{
throw new ODataException(Strings.MetadataBinder_InvalidAnyAllHead);
}
return new NavigationPropertyNode() { Source = source, NavigationProperty = property };
}
/// <summary>
/// Processes the filter of the query (if any).
/// </summary>
/// <param name="query">The query tree constructed so far.</param>
/// <param name="filter">The filter to bind.</param>
/// <returns>If no filter is specified, returns the <paramref name="query"/> unchanged. If a filter is specified it returns the combined query including the filter.</returns>
private QueryNode ProcessFilter(QueryNode query, QueryToken filter)
{
ExceptionUtils.CheckArgumentNotNull(query, "query");
if (filter != null)
{
CollectionQueryNode entityCollection = query.AsEntityCollectionNode();
if (entityCollection == null)
{
throw new ODataException(Strings.MetadataBinder_FilterNotApplicable);
}
this.parameter = new ParameterQueryNode() { ParameterType = entityCollection.ItemType };
QueryNode expressionNode = this.Bind(filter);
SingleValueQueryNode expressionResultNode = expressionNode as SingleValueQueryNode;
if (expressionResultNode == null ||
(expressionResultNode.TypeReference != null && !expressionResultNode.TypeReference.IsODataPrimitiveTypeKind()))
{
throw new ODataException(Strings.MetadataBinder_FilterExpressionNotSingleValue);
}
// The type may be null here if the query statically represents the null literal
// TODO: once we support open types/properties a 'null' type will mean 'we don't know the type'. Review.
IEdmTypeReference expressionResultType = expressionResultNode.TypeReference;
if (expressionResultType != null)
{
IEdmPrimitiveTypeReference primitiveExpressionResultType = expressionResultType.AsPrimitiveOrNull();
if (primitiveExpressionResultType == null || primitiveExpressionResultType.PrimitiveKind() != EdmPrimitiveTypeKind.Boolean)
{
throw new ODataException(Strings.MetadataBinder_FilterExpressionNotSingleValue);
}
}
query = new FilterQueryNode()
{
Collection = entityCollection,
Parameter = this.parameter,
Expression = expressionResultNode
};
this.parameter = null;
}
return query;
}
/// <summary>
/// Processes the order-by tokens of a query (if any).
/// </summary>
/// <param name="query">The query tree constructed so far.</param>
/// <param name="orderByTokens">The order-by tokens to bind.</param>
/// <returns>If no order-by tokens are specified, returns the <paramref name="query"/> unchanged. If order-by tokens are specified it returns the combined query including the ordering.</returns>
private QueryNode ProcessOrderBy(QueryNode query, IEnumerable<OrderByQueryToken> orderByTokens)
{
ExceptionUtils.CheckArgumentNotNull(query, "query");
foreach (OrderByQueryToken orderByToken in orderByTokens)
{
query = this.ProcessSingleOrderBy(query, orderByToken);
}
return query;
}
/// <summary>
/// Process the remaining query options (represent the set of custom query options after
/// service operation parameters and system query options have been removed).
/// </summary>
/// <returns>The list of <see cref="QueryNode"/> instances after binding.</returns>
private List<QueryNode> ProcessQueryOptions()
{
List<QueryNode> customQueryOptionNodes = new List<QueryNode>();
foreach (QueryOptionQueryToken queryToken in this.queryOptions)
{
QueryNode customQueryOptionNode = this.Bind(queryToken);
if (customQueryOptionNode != null)
{
customQueryOptionNodes.Add(customQueryOptionNode);
}
}
this.queryOptions = null;
return customQueryOptionNodes;
}
/// <summary>
/// Processes the specified order-by token.
/// </summary>
/// <param name="query">The query tree constructed so far.</param>
/// <param name="orderByToken">The order-by token to bind.</param>
/// <returns>Returns the combined query including the ordering.</returns>
private QueryNode ProcessSingleOrderBy(QueryNode query, OrderByQueryToken orderByToken)
{
Debug.Assert(query != null, "query != null");
ExceptionUtils.CheckArgumentNotNull(orderByToken, "orderByToken");
CollectionQueryNode entityCollection = query.AsEntityCollectionNode();
if (entityCollection == null)
{
throw new ODataException(Strings.MetadataBinder_OrderByNotApplicable);
}
this.parameter = new ParameterQueryNode() { ParameterType = entityCollection.ItemType };
QueryNode expressionNode = this.Bind(orderByToken.Expression);
// TODO: shall we really restrict order-by expressions to primitive types?
SingleValueQueryNode expressionResultNode = expressionNode as SingleValueQueryNode;
if (expressionResultNode == null ||
(expressionResultNode.TypeReference != null && !expressionResultNode.TypeReference.IsODataPrimitiveTypeKind()))
{
throw new ODataException(Strings.MetadataBinder_OrderByExpressionNotSingleValue);
}
query = new OrderByQueryNode()
{
Collection = entityCollection,
Direction = orderByToken.Direction,
Parameter = this.parameter,
Expression = expressionResultNode
};
this.parameter = null;
return query;
}
/// <summary>
/// Binds a root path segment.
/// </summary>
/// <param name="segmentToken">The segment to bind.</param>
/// <returns>The bound node.</returns>
private QueryNode BindRootSegment(SegmentQueryToken segmentToken)
{
Debug.Assert(segmentToken != null, "segmentToken != null");
Debug.Assert(segmentToken.Parent == null, "Only root segments should be allowed here.");
Debug.Assert(!string.IsNullOrEmpty(segmentToken.Name), "!string.IsNullOrEmpty(segmentToken.Name)");
//// This is a metadata-only version of the RequestUriProcessor.CreateFirstSegment.
if (segmentToken.Name == UriQueryConstants.MetadataSegment)
{
// TODO: $metadata segment parsing - no key values are allowed.
throw new NotImplementedException();
}
if (segmentToken.Name == UriQueryConstants.BatchSegment)
{
// TODO: $batch segment parsing - no key values are allowed.
throw new NotImplementedException();
}
// TODO: WCF DS checks for $count here first and fails. But not for the other $ segments.
// which means other $segments get to SO resolution. On the other hand the WCF DS would eventually fail if an SO started with $.
// Look for a service operation
IEdmFunctionImport serviceOperation = this.model.TryResolveServiceOperation(segmentToken.Name);
if (serviceOperation != null)
{
return this.BindServiceOperation(segmentToken, serviceOperation);
}
// TODO: Content-ID reference resolution. Do we actually do anything here or do we perform this through extending the metadata binder?
// Look for an entity set.
IEdmEntitySet entitySet = this.model.TryResolveEntitySet(segmentToken.Name);
if (entitySet == null)
{
throw new ODataException(Strings.MetadataBinder_RootSegmentResourceNotFound(segmentToken.Name));
}
EntitySetQueryNode entitySetQueryNode = new EntitySetQueryNode()
{
EntitySet = entitySet
};
if (segmentToken.NamedValues != null)
{
return this.BindKeyValues(entitySetQueryNode, segmentToken.NamedValues);
}
return entitySetQueryNode;
}
/// <summary>
/// Binds a service operation segment.
/// </summary>
/// <param name="segmentToken">The segment which represents a service operation.</param>
/// <param name="serviceOperation">The service operation to bind.</param>
/// <returns>The bound node.</returns>
private QueryNode BindServiceOperation(SegmentQueryToken segmentToken, IEdmFunctionImport serviceOperation)
{
Debug.Assert(segmentToken != null, "segmentToken != null");
Debug.Assert(serviceOperation != null, "serviceOperation != null");
Debug.Assert(segmentToken.Name == serviceOperation.Name, "The segment represents a different service operation.");
//// This is a metadata copy of the RequestUriProcessor.CreateSegmentForServiceOperation
//// The WCF DS checks the verb in this place, we can't do that here
// All service operations other than those returning IQueryable MUST NOT have () appended to the URI
// V1/V2 behavior: if it's IEnumerable<T>, we do not allow () either, because it's not further composable.
ODataServiceOperationResultKind? resultKind = serviceOperation.GetServiceOperationResultKind(this.model);
if (resultKind != ODataServiceOperationResultKind.QueryWithMultipleResults && segmentToken.NamedValues != null)
{
throw new ODataException(Strings.MetadataBinder_NonQueryableServiceOperationWithKeyLookup(segmentToken.Name));
}
if (!resultKind.HasValue)
{
throw new ODataException(Strings.MetadataBinder_ServiceOperationWithoutResultKind(serviceOperation.Name));
}
IEnumerable<QueryNode> serviceOperationParameters = this.BindServiceOperationParameters(serviceOperation);
switch (resultKind.Value)
{
case ODataServiceOperationResultKind.QueryWithMultipleResults:
if (serviceOperation.ReturnType.TypeKind() != EdmTypeKind.Entity)
{
throw new ODataException(Strings.MetadataBinder_QueryServiceOperationOfNonEntityType(serviceOperation.Name, resultKind.Value.ToString(), serviceOperation.ReturnType.ODataFullName()));
}
CollectionServiceOperationQueryNode collectionServiceOperationQueryNode = new CollectionServiceOperationQueryNode()
{
ServiceOperation = serviceOperation,
Parameters = serviceOperationParameters
};
if (segmentToken.NamedValues != null)
{
return this.BindKeyValues(collectionServiceOperationQueryNode, segmentToken.NamedValues);
}
else
{
return collectionServiceOperationQueryNode;
}
case ODataServiceOperationResultKind.QueryWithSingleResult:
if (!serviceOperation.ReturnType.IsODataEntityTypeKind())
{
throw new ODataException(Strings.MetadataBinder_QueryServiceOperationOfNonEntityType(serviceOperation.Name, resultKind.Value.ToString(), serviceOperation.ReturnType.ODataFullName()));
}
return new SingleValueServiceOperationQueryNode()
{
ServiceOperation = serviceOperation,
Parameters = serviceOperationParameters
};
case ODataServiceOperationResultKind.DirectValue:
if (serviceOperation.ReturnType.IsODataPrimitiveTypeKind())
{
// Direct primitive values are composable, $value is allowed on them.
return new SingleValueServiceOperationQueryNode()
{
ServiceOperation = serviceOperation,
Parameters = serviceOperationParameters
};
}
else
{
// Direct non-primitive values are not composable at all
return new UncomposableServiceOperationQueryNode()
{
ServiceOperation = serviceOperation,
Parameters = serviceOperationParameters
};
}
case ODataServiceOperationResultKind.Enumeration:
case ODataServiceOperationResultKind.Void:
// Enumeration and void service operations are not composable
return new UncomposableServiceOperationQueryNode()
{
ServiceOperation = serviceOperation,
Parameters = serviceOperationParameters
};
default:
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.MetadataBinder_BindServiceOperation));
}
}
/// <summary>
/// Binds the service operation parameters from query options.
/// </summary>
/// <param name="serviceOperation">The service operation to bind the parameters for.</param>
/// <returns>Enumeration of parameter values for the service operation.</returns>
private IEnumerable<QueryNode> BindServiceOperationParameters(IEdmFunctionImport serviceOperation)
{
Debug.Assert(serviceOperation != null, "serviceOperation != null");
//// This is a copy of RequestUriProcessor.ReadOperationParameters
List<QueryNode> parameters = new List<QueryNode>();
foreach (IEdmFunctionParameter serviceOperationParameter in serviceOperation.Parameters)
{
IEdmTypeReference parameterType = serviceOperationParameter.Type;
string parameterTextValue = this.ConsumeQueryOption(serviceOperationParameter.Name);
object parameterValue;
if (string.IsNullOrEmpty(parameterTextValue))
{
if (!parameterType.IsNullable)
{
// The target parameter type is non-nullable, but we found null value, this usually means that the parameter is missing
throw new ODataException(Strings.MetadataBinder_ServiceOperationParameterMissing(serviceOperation.Name, serviceOperationParameter.Name));
}
parameterValue = null;
}
else
{
// We choose to be a little more flexible than with keys and
// allow surrounding whitespace (which is never significant).
parameterTextValue = parameterTextValue.Trim();
if (!UriPrimitiveTypeParser.TryUriStringToPrimitive(parameterTextValue, parameterType, out parameterValue))
{
throw new ODataException(Strings.MetadataBinder_ServiceOperationParameterInvalidType(serviceOperationParameter.Name, parameterTextValue, serviceOperation.Name, serviceOperationParameter.Type.ODataFullName()));
}
}
parameters.Add(new ConstantQueryNode() { Value = parameterValue });
}
if (parameters.Count == 0)
{
return null;
}
return new ReadOnlyCollection<QueryNode>(parameters);
}
/// <summary>
/// Binds key values to a key lookup on a collection.
/// </summary>
/// <param name="collectionQueryNode">Already bound collection node.</param>
/// <param name="namedValues">The named value tokens to bind.</param>
/// <returns>The bound key lookup.</returns>
private QueryNode BindKeyValues(CollectionQueryNode collectionQueryNode, IEnumerable<NamedValue> namedValues)
{
Debug.Assert(namedValues != null, "namedValues != null");
Debug.Assert(collectionQueryNode != null, "collectionQueryNode != null");
Debug.Assert(collectionQueryNode.ItemType != null, "collectionQueryNode.ItemType != null");
IEdmTypeReference collectionItemType = collectionQueryNode.ItemType;
List<KeyPropertyValue> keyPropertyValues = new List<KeyPropertyValue>();
if (!collectionItemType.IsODataEntityTypeKind())
{
throw new ODataException(Strings.MetadataBinder_KeyValueApplicableOnlyToEntityType(collectionItemType.ODataFullName()));
}
IEdmEntityTypeReference collectionItemEntityTypeReference = collectionItemType.AsEntityOrNull();
Debug.Assert(collectionItemEntityTypeReference != null, "collectionItemEntityTypeReference != null");
IEdmEntityType collectionItemEntityType = collectionItemEntityTypeReference.EntityDefinition();
HashSet<string> keyPropertyNames = new HashSet<string>(StringComparer.Ordinal);
foreach (NamedValue namedValue in namedValues)
{
KeyPropertyValue keyPropertyValue = this.BindKeyPropertyValue(namedValue, collectionItemEntityType);
Debug.Assert(keyPropertyValue != null, "keyPropertyValue != null");
Debug.Assert(keyPropertyValue.KeyProperty != null, "keyPropertyValue.KeyProperty != null");
if (!keyPropertyNames.Add(keyPropertyValue.KeyProperty.Name))
{
throw new ODataException(Strings.MetadataBinder_DuplicitKeyPropertyInKeyValues(keyPropertyValue.KeyProperty.Name));
}
keyPropertyValues.Add(keyPropertyValue);
}
if (keyPropertyValues.Count == 0)
{
// No key values specified, for example '/Customers()', do not include the key lookup at all
return collectionQueryNode;
}
else if (keyPropertyValues.Count != collectionItemEntityType.Key().Count())
{
throw new ODataException(Strings.MetadataBinder_NotAllKeyPropertiesSpecifiedInKeyValues(collectionQueryNode.ItemType.ODataFullName()));
}
else
{
return new KeyLookupQueryNode()
{
Collection = collectionQueryNode,
KeyPropertyValues = new ReadOnlyCollection<KeyPropertyValue>(keyPropertyValues)
};
}
}
/// <summary>
/// Binds a key property value.
/// </summary>
/// <param name="namedValue">The named value to bind.</param>
/// <param name="collectionItemEntityType">The type of a single item in a collection to apply the key value to.</param>
/// <returns>The bound key property value node.</returns>
private KeyPropertyValue BindKeyPropertyValue(NamedValue namedValue, IEdmEntityType collectionItemEntityType)
{
// These are exception checks because the data comes directly from the potentially user specified tree.
ExceptionUtils.CheckArgumentNotNull(namedValue, "namedValue");
ExceptionUtils.CheckArgumentNotNull(namedValue.Value, "namedValue.Value");
Debug.Assert(collectionItemEntityType != null, "collectionItemType != null");
IEdmProperty keyProperty = null;
if (namedValue.Name == null)
{
foreach (IEdmProperty p in collectionItemEntityType.Key())
{
if (keyProperty == null)
{
keyProperty = p;
}
else
{
throw new ODataException(Strings.MetadataBinder_UnnamedKeyValueOnTypeWithMultipleKeyProperties(collectionItemEntityType.ODataFullName()));
}
}
}
else
{
keyProperty = collectionItemEntityType.Key().Where(k => string.CompareOrdinal(k.Name, namedValue.Name) == 0).SingleOrDefault();
if (keyProperty == null)
{
throw new ODataException(Strings.MetadataBinder_PropertyNotDeclaredOrNotKeyInKeyValue(namedValue.Name, collectionItemEntityType.ODataFullName()));
}
}
IEdmTypeReference keyPropertyType = keyProperty.Type;
SingleValueQueryNode value = (SingleValueQueryNode)this.Bind(namedValue.Value);
// TODO: Check that the value is of primitive type
value = ConvertToType(value, keyPropertyType);
Debug.Assert(keyProperty != null, "keyProperty != null");
return new KeyPropertyValue()
{
KeyProperty = keyProperty,
KeyValue = value
};
}
/// <summary>
/// Finds a query option by its name and consumes it (removes it from still available query options).
/// </summary>
/// <param name="queryOptionName">The query option name to get.</param>
/// <returns>The value of the query option or null if it was not found.</returns>
private string ConsumeQueryOption(string queryOptionName)
{
if (this.queryOptions != null)
{
return this.queryOptions.GetQueryOptionValueAndRemove(queryOptionName);
}
else
{
return null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Globalization;
using System.Reflection;
namespace System.ComponentModel
{
/// <summary>
/// TypeConverter to convert Nullable types to and from strings or the underlying simple type.
/// </summary>
public class NullableConverter : TypeConverter
{
private readonly Type _nullableType;
private readonly Type _simpleType;
private readonly TypeConverter _simpleTypeConverter;
/// <summary>
/// Nullable converter is initialized with the underlying simple type.
/// </summary>
public NullableConverter(Type type)
{
_nullableType = type;
_simpleType = Nullable.GetUnderlyingType(type);
if (_simpleType == null)
{
throw new ArgumentException(SR.NullableConverterBadCtorArg, nameof(type));
}
_simpleTypeConverter = TypeDescriptor.GetConverter(_simpleType);
}
/// <summary>
/// <para>Gets a value indicating whether this converter can convert an object in the
/// given source type to the underlying simple type or a null.</para>
/// </summary>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == _simpleType)
{
return true;
}
else if (_simpleTypeConverter != null)
{
return _simpleTypeConverter.CanConvertFrom(context, sourceType);
}
else
{
return base.CanConvertFrom(context, sourceType);
}
}
/// <summary>
/// Converts the given value to the converter's underlying simple type or a null.
/// </summary>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value == null || value.GetType() == _simpleType)
{
return value;
}
else if (value is string && string.IsNullOrEmpty(value as string))
{
return null;
}
else if (_simpleTypeConverter != null)
{
return _simpleTypeConverter.ConvertFrom(context, culture, value);
}
else
{
return base.ConvertFrom(context, culture, value);
}
}
/// <summary>
/// Gets a value indicating whether this converter can convert a value object to the destination type.
/// </summary>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == _simpleType)
{
return true;
}
else if (_simpleTypeConverter != null)
{
return _simpleTypeConverter.CanConvertTo(context, destinationType);
}
else
{
return base.CanConvertTo(context, destinationType);
}
}
/// <summary>
/// Converts the given value object to the destination type.
/// </summary>
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException(nameof(destinationType));
}
if (destinationType == _simpleType && value != null && _nullableType.GetTypeInfo().IsAssignableFrom(value.GetType().GetTypeInfo()))
{
return value;
}
else if (value == null)
{
// Handle our own nulls here
if (destinationType == typeof(string))
{
return string.Empty;
}
}
else if (_simpleTypeConverter != null)
{
return _simpleTypeConverter.ConvertTo(context, culture, value, destinationType);
}
return base.ConvertTo(context, culture, value, destinationType);
}
/// <include file='doc\NullableConverter.uex' path='docs/doc[@for="NullableConverter.CreateInstance"]/*' />
/// <summary>
/// </summary>
public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
{
if (_simpleTypeConverter != null)
{
object instance = _simpleTypeConverter.CreateInstance(context, propertyValues);
return instance;
}
return base.CreateInstance(context, propertyValues);
}
/// <summary>
/// <para>
/// Gets a value indicating whether changing a value on this object requires a call to
/// <see cref='System.ComponentModel.TypeConverter.CreateInstance'/> to create a new value,
/// using the specified context.
/// </para>
/// </summary>
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
{
if (_simpleTypeConverter != null)
{
return _simpleTypeConverter.GetCreateInstanceSupported(context);
}
return base.GetCreateInstanceSupported(context);
}
#if !NETSTANDARD10
/// <summary>
/// <para>
/// Gets a collection of properties for the type of array specified by the value
/// parameter using the specified context and attributes.
/// </para>
/// </summary>
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
if (_simpleTypeConverter != null)
{
object unwrappedValue = value;
return _simpleTypeConverter.GetProperties(context, unwrappedValue, attributes);
}
return base.GetProperties(context, value, attributes);
}
#endif // !NETSTANDARD10
/// <summary>
/// <para>Gets a value indicating whether this object supports properties using the specified context.</para>
/// </summary>
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
if (_simpleTypeConverter != null)
{
return _simpleTypeConverter.GetPropertiesSupported(context);
}
return base.GetPropertiesSupported(context);
}
/// <summary>
/// <para>Gets a collection of standard values for the data type this type converter is designed for.</para>
/// </summary>
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
if (_simpleTypeConverter != null)
{
StandardValuesCollection values = _simpleTypeConverter.GetStandardValues(context);
if (GetStandardValuesSupported(context) && values != null)
{
// Create a set of standard values around nullable instances.
object[] wrappedValues = new object[values.Count + 1];
int idx = 0;
wrappedValues[idx++] = null;
foreach (object value in values)
{
wrappedValues[idx++] = value;
}
return new StandardValuesCollection(wrappedValues);
}
}
return base.GetStandardValues(context);
}
/// <summary>
/// <para>
/// Gets a value indicating whether the collection of standard values returned from
/// <see cref='System.ComponentModel.TypeConverter.GetStandardValues'/> is an exclusive
/// list of possible values, using the specified context.
/// </para>
/// </summary>
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
if (_simpleTypeConverter != null)
{
return _simpleTypeConverter.GetStandardValuesExclusive(context);
}
return base.GetStandardValuesExclusive(context);
}
/// <summary>
/// <para>
/// Gets a value indicating whether this object supports a standard set of values that can
/// be picked from a list using the specified context.
/// </para>
/// </summary>
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
if (_simpleTypeConverter != null)
{
return _simpleTypeConverter.GetStandardValuesSupported(context);
}
return base.GetStandardValuesSupported(context);
}
/// <summary>
/// <para>Gets a value indicating whether the given value object is valid for this type.</para>
/// </summary>
public override bool IsValid(ITypeDescriptorContext context, object value)
{
if (_simpleTypeConverter != null)
{
object unwrappedValue = value;
if (unwrappedValue == null)
{
return true; // null is valid for nullable.
}
else
{
return _simpleTypeConverter.IsValid(context, unwrappedValue);
}
}
return base.IsValid(context, value);
}
/// <summary>
/// The type this converter was initialized with.
/// </summary>
public Type NullableType
{
get
{
return _nullableType;
}
}
/// <summary>
/// The simple type that is represented as a nullable.
/// </summary>
public Type UnderlyingType
{
get
{
return _simpleType;
}
}
/// <summary>
/// Converter associated with the underlying simple type.
/// </summary>
public TypeConverter UnderlyingTypeConverter
{
get
{
return _simpleTypeConverter;
}
}
}
}
| |
// 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.Immutable;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using System.Threading;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching
{
/// <summary>
/// Looks for code of the form:
///
/// var x = o as Type;
/// if (x != null) ...
///
/// and converts it to:
///
/// if (o is Type x) ...
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpAsAndNullCheckDiagnosticAnalyzer : AbstractCodeStyleDiagnosticAnalyzer
{
public override bool OpenFileOnly(Workspace workspace) => false;
public CSharpAsAndNullCheckDiagnosticAnalyzer()
: base(IDEDiagnosticIds.InlineAsTypeCheckId,
new LocalizableResourceString(
nameof(FeaturesResources.Use_pattern_matching), FeaturesResources.ResourceManager, typeof(FeaturesResources)))
{
}
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSyntaxNodeAction(SyntaxNodeAction, SyntaxKind.IfStatement);
private void SyntaxNodeAction(SyntaxNodeAnalysisContext syntaxContext)
{
var options = syntaxContext.Options;
var syntaxTree = syntaxContext.Node.SyntaxTree;
var cancellationToken = syntaxContext.CancellationToken;
var optionSet = options.GetDocumentOptionSetAsync(syntaxTree, cancellationToken).GetAwaiter().GetResult();
if (optionSet == null)
{
return;
}
var styleOption = optionSet.GetOption(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck);
if (!styleOption.Value)
{
// Bail immediately if the user has disabled this feature.
return;
}
var severity = styleOption.Notification.Value;
// look for the form "if (a != null)" or "if (null != a)"
var ifStatement = (IfStatementSyntax)syntaxContext.Node;
// "x is Type y" is only available in C# 7.0 and above. Don't offer this refactoring
// in projects targetting a lesser version.
if (((CSharpParseOptions)ifStatement.SyntaxTree.Options).LanguageVersion < LanguageVersion.CSharp7)
{
return;
}
// If has to be in a block so we can at least look for a preceding local variable declaration.
if (!ifStatement.Parent.IsKind(SyntaxKind.Block))
{
return;
}
// We need to find the leftmost expression in the if-condition. If this is a
// "x != null" expression, then we can replace it with "o is Type x".
var condition = GetLeftmostCondition(ifStatement.Condition);
if (!condition.IsKind(SyntaxKind.NotEqualsExpression))
{
return;
}
// look for the form "x != null" or "null != x".
if (!IsNullCheckExpression(condition.Left, condition.Right) &&
!IsNullCheckExpression(condition.Right, condition.Left))
{
return;
}
var conditionName = condition.Left is IdentifierNameSyntax
? (IdentifierNameSyntax)condition.Left
: (IdentifierNameSyntax)condition.Right;
// Now make sure the previous statement is "var a = ..."
var parentBlock = (BlockSyntax)ifStatement.Parent;
var ifIndex = parentBlock.Statements.IndexOf(ifStatement);
if (ifIndex == 0)
{
return;
}
var previousStatement = parentBlock.Statements[ifIndex - 1];
if (!previousStatement.IsKind(SyntaxKind.LocalDeclarationStatement))
{
return;
}
var localDeclarationStatement = (LocalDeclarationStatementSyntax)previousStatement;
var variableDeclaration = localDeclarationStatement.Declaration;
if (variableDeclaration.Variables.Count != 1)
{
return;
}
var declarator = variableDeclaration.Variables[0];
if (declarator.Initializer == null)
{
return;
}
if (!Equals(declarator.Identifier.ValueText, conditionName.Identifier.ValueText))
{
return;
}
// Make sure the initializer has the form "... = expr as Type;
var initializerValue = declarator.Initializer.Value;
if (!initializerValue.IsKind(SyntaxKind.AsExpression))
{
return;
}
// If we convert this to 'if (o is Type x)' then 'x' will not be definitely assigned
// in the Else branch of the IfStatement, or after the IfStatement. Make sure
// that doesn't cause definite assignment issues.
if (IsAccessedBeforeAssignment(syntaxContext, declarator, ifStatement, cancellationToken))
{
return;
}
// Looks good!
var additionalLocations = ImmutableArray.Create(
localDeclarationStatement.GetLocation(),
ifStatement.GetLocation(),
condition.GetLocation(),
initializerValue.GetLocation());
// Put a diagnostic with the appropriate severity on the declaration-statement itself.
syntaxContext.ReportDiagnostic(Diagnostic.Create(
GetDescriptorWithSeverity(severity),
localDeclarationStatement.GetLocation(),
additionalLocations));
}
private bool IsAccessedBeforeAssignment(
SyntaxNodeAnalysisContext syntaxContext,
VariableDeclaratorSyntax declarator,
IfStatementSyntax ifStatement,
CancellationToken cancellationToken)
{
var semanticModel = syntaxContext.SemanticModel;
var localVariable = semanticModel.GetDeclaredSymbol(declarator);
var isAssigned = false;
var isAccessedBeforeAssignment = false;
CheckDefiniteAssignment(
semanticModel, localVariable, ifStatement.Else,
out isAssigned, out isAccessedBeforeAssignment,
cancellationToken);
if (isAccessedBeforeAssignment)
{
return true;
}
var parentBlock = (BlockSyntax)ifStatement.Parent;
var ifIndex = parentBlock.Statements.IndexOf(ifStatement);
for (int i = ifIndex + 1, n = parentBlock.Statements.Count; i < n; i++)
{
if (!isAssigned)
{
CheckDefiniteAssignment(
semanticModel, localVariable, parentBlock.Statements[i],
out isAssigned, out isAccessedBeforeAssignment,
cancellationToken);
if (isAccessedBeforeAssignment)
{
return true;
}
}
}
return false;
}
private void CheckDefiniteAssignment(
SemanticModel semanticModel, ISymbol localVariable, SyntaxNode node,
out bool isAssigned, out bool isAccessedBeforeAssignment,
CancellationToken cancellationToken)
{
if (node != null)
{
foreach (var id in node.DescendantNodes().OfType<IdentifierNameSyntax>())
{
var symbol = semanticModel.GetSymbolInfo(id, cancellationToken).GetAnySymbol();
if (localVariable.Equals(symbol))
{
isAssigned = id.IsOnlyWrittenTo();
isAccessedBeforeAssignment = !isAssigned;
return;
}
}
}
isAssigned = false;
isAccessedBeforeAssignment = false;
}
private BinaryExpressionSyntax GetLeftmostCondition(ExpressionSyntax condition)
{
switch (condition.Kind())
{
case SyntaxKind.ParenthesizedExpression:
return GetLeftmostCondition(((ParenthesizedExpressionSyntax)condition).Expression);
case SyntaxKind.ConditionalExpression:
return GetLeftmostCondition(((ConditionalExpressionSyntax)condition).Condition);
case SyntaxKind.LogicalAndExpression:
case SyntaxKind.LogicalOrExpression:
return GetLeftmostCondition(((BinaryExpressionSyntax)condition).Left);
}
return condition as BinaryExpressionSyntax;
}
private bool IsNullCheckExpression(ExpressionSyntax left, ExpressionSyntax right) =>
left.IsKind(SyntaxKind.IdentifierName) && right.IsKind(SyntaxKind.NullLiteralExpression);
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticDocumentAnalysis;
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Net;
using System.Text;
using System.Collections;
namespace OpenSource.UPnP
{
/// <summary>
/// A generic HTTP/UPnP Packet
/// </summary>
[Serializable()]
public sealed class HTTPMessage : ICloneable
{
internal bool DontShowContentLength = false;
public bool OverrideContentLength = false;
/// <summary>
/// Contructs an Empty Packet
/// </summary>
public HTTPMessage():this("1.1")
{
}
public HTTPMessage(string version)
{
OpenSource.Utilities.InstanceTracker.Add(this);
TheHeaders = new Hashtable();
ResponseCode = -1;
ResponseData = "";
Method = "";
MethodData = "";
DataBuffer = new byte[0];
Version = version;
}
public object Clone()
{
object obj = this.MemberwiseClone();
OpenSource.Utilities.InstanceTracker.Add(obj);
return(obj);
}
/// <summary>
/// Get/Set the body as a Byte Array
/// </summary>
public byte[] BodyBuffer
{
get
{
return(DataBuffer);
}
set
{
DataBuffer = value;
}
}
/// <summary>
/// Returns the Character encoding of the body, if it was defined
/// </summary>
public string CharSet
{
get
{
string ct = ContentType;
DText p = new DText();
p.ATTRMARK = ";";
p.MULTMARK = "=";
p[0] = ct;
string V = "";
if (p.DCOUNT()>1)
{
for(int i=1;i<=p.DCOUNT();++i)
{
if (p[i,1].Trim().ToUpper()=="CHARSET")
{
V = p[i,2].Trim().ToUpper();
if (V.StartsWith("\"")==true)
{
V = V.Substring(1);
}
if (V.EndsWith("\"")==true)
{
V = V.Substring(0,V.Length-1);
}
break;
}
}
return(V);
}
else
{
return("");
}
}
}
/// <summary>
/// Gets/Sets the Content-type field
/// </summary>
public string ContentType
{
get
{
return(GetTag("Content-Type"));
}
set
{
AddTag("Content-Type",value);
}
}
/// <summary>
/// Gets the Body (encoded as CharSet) as a String, Sets the body as a UTF-8 encoded string
/// </summary>
public String StringBuffer
{
get
{
if (CharSet=="UTF-16")
{
UnicodeEncoding UTF16 = new UnicodeEncoding();
return(UTF16.GetString(DataBuffer));
}
else
{
UTF8Encoding UTF8 = new UTF8Encoding();
return(UTF8.GetString(DataBuffer));
}
}
set
{
UTF8Encoding UTF8 = new UTF8Encoding();
DataBuffer = UTF8.GetBytes(value);
}
}
/// <summary>
/// Removes a header
/// </summary>
/// <param name="TagName"></param>
public void RemoveTag(String TagName)
{
try
{
TheHeaders.Remove(TagName.ToUpper());
}
catch(Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
}
}
public IDictionaryEnumerator GetHeaderEnumerator()
{
return(TheHeaders.GetEnumerator());
}
/// <summary>
/// Add/Change a Header
/// </summary>
/// <param name="TagName">Header Tag</param>
/// <param name="TagData">Header Value</param>
public void AddTag(String TagName, String TagData)
{
TheHeaders[TagName.ToUpper()] = TagData;
//TheHeaders[TagName] = TagData;
}
public void AppendTag(string TagName, string TagData)
{
if (TheHeaders.ContainsKey(TagName.ToUpper())==false)
{
TheHeaders[TagName.ToUpper()] = TagData;
}
else
{
if (TheHeaders[TagName.ToUpper()].GetType()==typeof(string))
{
ArrayList n = new ArrayList();
n.Add(TheHeaders[TagName.ToUpper()]);
TheHeaders[TagName.ToUpper()] = n;
}
((ArrayList)TheHeaders[TagName.ToUpper()]).Add(TagData);
}
}
public bool HasTag(string TagName)
{
return(TheHeaders.ContainsKey(TagName.ToUpper()));
}
/// <summary>
/// Returns the value for this tag
/// </summary>
/// <param name="TagName">Header Tag</param>
/// <returns>Header Value</returns>
public String GetTag(String TagName)
{
Object x = TheHeaders[TagName.ToUpper()];
if (x==null)
{
return("");
}
else
{
if (x.GetType()==typeof(string))
{
return(((String)x).Trim());
}
else
{
string RetVal = "";
foreach(string v in (ArrayList)x)
{
RetVal += v.Trim();
}
return(RetVal);
}
}
}
/// <summary>
/// Returns the entire packet as a String, for debug purposes only. Note, the body is treated as a UTF-8 string
/// </summary>
public String StringPacket
{
get
{
UTF8Encoding UTF8 = new UTF8Encoding();
return(UTF8.GetString(RawPacket));
}
}
/// <summary>
/// Returns the entire packet as a Byte Array
/// </summary>
public byte[] RawPacket
{
get
{
return(BuildPacket());
}
}
/// <summary>
/// Parses a Byte Array, and build a Packet.
/// </summary>
/// <param name="buffer">The Array of Bytes</param>
/// <returns></returns>
static public HTTPMessage ParseByteArray(byte[] buffer)
{
return(ParseByteArray(buffer,0,buffer.Length));
}
/// <summary>
/// Parses a Byte Array at a specific location, and builds a Packet.
/// </summary>
/// <param name="buffer">The Array of Bytes</param>
/// <param name="indx">The Start Index</param>
/// <param name="count">The number of Bytes to process</param>
/// <returns></returns>
static public HTTPMessage ParseByteArray(byte[] buffer, int indx, int count)
{
HTTPMessage TheMessage = new HTTPMessage();
UTF8Encoding UTF8 = new UTF8Encoding();
String TempData = UTF8.GetString(buffer,indx,count);
DText parser = new DText();
String TempString;
int idx = TempData.IndexOf("\r\n\r\n");
if (idx < 0) return null;
TempData = TempData.Substring(0,idx);
parser.ATTRMARK = "\r\n";
parser.MULTMARK = ":";
parser[0] = TempData;
string CurrentLine = parser[1];
DText HdrParser = new DText();
HdrParser.ATTRMARK = " ";
HdrParser.MULTMARK = "/";
HdrParser[0] = CurrentLine;
if (CurrentLine.ToUpper().StartsWith("HTTP/")==true)
{
TheMessage.ResponseCode = int.Parse(HdrParser[2]);
int s1 = CurrentLine.IndexOf(" ");
s1 = CurrentLine.IndexOf(" ",s1+1);
TheMessage.ResponseData = HTTPMessage.UnEscapeString(CurrentLine.Substring(s1));
try
{
TheMessage.Version = HdrParser[1,2];
}
catch(Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
TheMessage.Version = "0.9";
}
}
else
{
TheMessage.Directive = HdrParser[1];
TempString = CurrentLine.Substring(CurrentLine.LastIndexOf(" ") + 1);
if (TempString.ToUpper().StartsWith("HTTP/")==false)
{
TheMessage.Version = "0.9";
TheMessage.DirectiveObj = HTTPMessage.UnEscapeString(TempString);
}
else
{
TheMessage.Version = TempString.Substring(TempString.IndexOf("/")+1);
int fs = CurrentLine.IndexOf(" ") + 1;
TheMessage.DirectiveObj = HTTPMessage.UnEscapeString(CurrentLine.Substring(
fs,
CurrentLine.Length-fs-TempString.Length-1));
}
}
String Tag="";
String TagData="";
for(int line=2;line<=parser.DCOUNT();++line)
{
if (Tag!="" && parser[line,1].StartsWith(" "))
{
TagData = parser[line,1].Substring(1);
}
else
{
Tag = parser[line,1];
TagData = "";
for(int i=2;i<=parser.DCOUNT(line);++i)
{
if (TagData=="")
{
TagData = parser[line,i];
}
else
{
TagData = TagData + parser.MULTMARK + parser[line,i];
}
}
}
TheMessage.AppendTag(Tag,TagData);
}
int cl=0;
if (TheMessage.HasTag("Content-Length"))
{
try
{
cl = int.Parse(TheMessage.GetTag("Content-Length"));
}
catch(Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
cl = -1;
}
}
else
{
cl = -1;
}
byte[] tbuffer;
if (cl>0)
{
tbuffer = new byte[cl];
if ((idx+4+cl)>count)
{
// NOP
}
else
{
Array.Copy(buffer,idx+4,tbuffer,0,cl);
TheMessage.DataBuffer = tbuffer;
}
}
if (cl==-1)
{
tbuffer = new Byte[count-(idx+4)];
Array.Copy(buffer,idx+4,tbuffer,0,tbuffer.Length);
TheMessage.DataBuffer = tbuffer;
}
if (cl==0)
{
TheMessage.DataBuffer = new byte[0];
}
return(TheMessage);
}
private byte[] BuildPacket()
{
byte[] buffer;
if (DataBuffer==null)
{
DataBuffer = new Byte[0];
}
if (Version=="1.0")
{
if ((Method=="")&&(ResponseCode==-1))
{
return(DataBuffer);
}
}
UTF8Encoding UTF8 = new UTF8Encoding();
String sbuf;
IDictionaryEnumerator en = TheHeaders.GetEnumerator();
en.Reset();
if (Method!="")
{
if (Version!="")
{
sbuf = Method + " " + EscapeString(MethodData) + " HTTP/" + Version + "\r\n";
}
else
{
sbuf = Method + " " + EscapeString(MethodData) + "\r\n";
}
}
else
{
sbuf = "HTTP/" + Version + " " + ResponseCode.ToString() + " " + ResponseData + "\r\n";
}
while(en.MoveNext())
{
if ((String)en.Key!="CONTENT-LENGTH" || OverrideContentLength==true)
{
if (en.Value.GetType()==typeof(string))
{
sbuf += (String)en.Key + ": " + (String)en.Value + "\r\n";
}
else
{
sbuf += (String)en.Key + ":";
foreach(string v in (ArrayList)en.Value)
{
sbuf += (" " + v + "\r\n");
}
}
}
}
if (StatusCode==-1 && DontShowContentLength==false)
{
sbuf += "Content-Length: " + DataBuffer.Length.ToString() + "\r\n";
}
else if (Version!="1.0" && Version!="0.9" && Version!="" && DontShowContentLength==false)
{
if (OverrideContentLength==false)
{
sbuf += "Content-Length: " + DataBuffer.Length.ToString() + "\r\n";
}
}
sbuf += "\r\n";
buffer = new byte[UTF8.GetByteCount(sbuf) + DataBuffer.Length];
UTF8.GetBytes(sbuf,0,sbuf.Length,buffer,0);
Array.Copy(DataBuffer,0,buffer,buffer.Length-DataBuffer.Length,DataBuffer.Length);
return(buffer);
}
/// <summary>
/// Get/Set the HTTP Command
/// </summary>
public string Directive
{
get
{
return(Method);
}
set
{
Method = value;
}
}
/// <summary>
/// Get/Set the Object the Command is operating on
/// </summary>
public String DirectiveObj
{
get
{
return(MethodData);
}
set
{
MethodData = value;
}
}
/// <summary>
/// Get/Set the HTTP Status Code
/// </summary>
public int StatusCode
{
get
{
return(ResponseCode);
}
set
{
ResponseCode = value;
}
}
/// <summary>
/// Get/Set the Extra data associated with the Status Code
/// </summary>
public String StatusData
{
get
{
return(ResponseData);
}
set
{
ResponseData = value;
}
}
/// <summary>
/// Escapes a string
/// </summary>
/// <param name="TheString"></param>
/// <returns></returns>
public static string EscapeString(String TheString)
{
UTF8Encoding UTF8 = new UTF8Encoding();
byte[] buffer = UTF8.GetBytes(TheString);
StringBuilder s = new StringBuilder();
foreach(byte val in buffer)
{
if (((val>=63)&&(val<=90))||
((val>=97)&&(val<=122))||
(val>=47 && val<=57)||
val==59 || val==47 || val==63 ||
val==58 || val==64 || val==61 ||
val==43 || val==36 || val==45 ||
val==95 || val==46 || val==42
)
{
s.Append((char)val);
}
else
{
s.Append("%" + val.ToString("X"));
}
}
return(s.ToString());
}
/// <summary>
/// Unescapes a string
/// </summary>
/// <param name="TheString"></param>
/// <returns></returns>
public static string UnEscapeString(string TheString)
{
IEnumerator en = TheString.GetEnumerator();
string t;
ArrayList Temp = new ArrayList();
UTF8Encoding UTF8 = new UTF8Encoding();
while(en.MoveNext())
{
if ((char)en.Current=='%')
{
en.MoveNext();
t = new string((char)en.Current,1);
en.MoveNext();
t += new string((char)en.Current,1);
int X = int.Parse(t.ToUpper(),System.Globalization.NumberStyles.HexNumber);
Temp.Add((byte)X);
}
else
{
Temp.Add((byte)(int)(char)en.Current);
}
}
return(UTF8.GetString((byte[])Temp.ToArray(typeof(byte))));
}
private String Method;
private String MethodData;
private int ResponseCode;
private String ResponseData;
private Hashtable TheHeaders;
private byte[] DataBuffer;
public string Version = "1.1";
[NonSerialized()] public Object StateObject = null;
public IPEndPoint LocalEndPoint;
public IPEndPoint RemoteEndPoint;
}
}
| |
using Shouldly;
using System;
using Xunit;
namespace Valit.Tests.Double
{
public class Double_IsLessThanOrEqualTo_Tests
{
[Fact]
public void Double_IsLessThanOrEqualTo_For_Not_Nullable_Values_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double>)null)
.IsLessThanOrEqualTo(1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Double_IsLessThanOrEqualTo_For_Not_Nullable_Value_And_Nullable_Value_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double>)null)
.IsLessThanOrEqualTo((double?)1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Double_IsLessThanOrEqualTo_For_Nullable_Value_And_Not_Nullable_Value_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double?>)null)
.IsLessThanOrEqualTo(1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Double_IsLessThanOrEqualTo_For_Nullable_Values_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double?>)null)
.IsLessThanOrEqualTo((double?)1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Theory]
[InlineData(11, true)]
[InlineData(10, true)]
[InlineData(9, false)]
[InlineData(double.NaN, false)]
public void Double_IsLessThanOrEqualTo_Returns_Proper_Results_For_Not_Nullable_Values(double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.Value, _ => _
.IsLessThanOrEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(11, false)]
[InlineData(double.NaN, false)]
public void Double_IsLessThanOrEqualTo_Returns_Proper_Results_For_NaN_And_Value(double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NaN, _ => _
.IsLessThanOrEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(11, false)]
[InlineData(double.NaN, false)]
public void Double_IsLessThanOrEqualTo_Returns_Proper_Results_For_NaN_And_NullableValue(double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NaN, _ => _
.IsLessThanOrEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(11, false)]
[InlineData(double.NaN, false)]
public void Double_IsLessThanOrEqualTo_Returns_Proper_Results_For_NullableNaN_And_Value(double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NullableNaN, _ => _
.IsLessThanOrEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(11, false)]
[InlineData(double.NaN, false)]
public void Double_IsLessThanOrEqualTo_Returns_Proper_Results_For_NullableNaN_And_NullableValue(double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NullableNaN, _ => _
.IsLessThanOrEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData((double)11, true)]
[InlineData((double)10, true)]
[InlineData((double)9, false)]
[InlineData(double.NaN, false)]
[InlineData(null, false)]
public void Double_IsLessThanOrEqualTo_Returns_Proper_Results_For_Not_Nullable_Value_And_Nullable_Value(double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.Value, _ => _
.IsLessThanOrEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(false, 11, true)]
[InlineData(false, 10, true)]
[InlineData(false, 9, false)]
[InlineData(true, 10, false)]
[InlineData(false, double.NaN, false)]
[InlineData(true, double.NaN, false)]
public void Double_IsLessThanOrEqualTo_Returns_Proper_Results_For_Nullable_Value_And_Not_Nullable_Value(bool useNullValue, double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => useNullValue ? m.NullValue : m.NullableValue, _ => _
.IsLessThanOrEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(false, (double)11, true)]
[InlineData(false, (double)10, true)]
[InlineData(false, (double)9, false)]
[InlineData(false, double.NaN, false)]
[InlineData(false, null, false)]
[InlineData(true, (double)10, false)]
[InlineData(true, double.NaN, false)]
[InlineData(true, null, false)]
public void Double_IsLessThanOrEqualTo_Returns_Proper_Results_For_Nullable_Values(bool useNullValue, double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => useNullValue ? m.NullValue : m.NullableValue, _ => _
.IsLessThanOrEqualTo(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
#region ARRANGE
public Double_IsLessThanOrEqualTo_Tests()
{
_model = new Model();
}
private readonly Model _model;
class Model
{
public double Value => 10;
public double NaN => double.NaN;
public double? NullableValue => 10;
public double? NullValue => null;
public double? NullableNaN => double.NaN;
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
//If you want to add new platforms to this enumeration, either put them at the end or give it a unique number
// NOTE: The "EditorPlatform" enum may also need to be updated as well to reflect changes made here
public enum Platform {iPhone=1, WebPlayer=2, iPad=3, iPhoneRetina=4, Standalone=5, Android=6, FlashPlayer=7, NaCl=8, iPadRetina=9, iPhone5=10, WP8=11, Windows8=12, iOS=13, BB10=14, iPhone6and6plus=15};
public class Platforms : MonoBehaviour {
const float ratioTolerance = 0.03f; //Tolerance of calculated ratio to exact ratio
static bool platformCalculated = false;
static Platform calculatedPlatform;
public const string editorPlatformOverrideKey = "editorPlatformOverride";
public static Platform platform {
get {
#if UNITY_EDITOR
//If in editor and platformOverride is set, return override
string platformString = UnityEditor.EditorPrefs.GetString(editorPlatformOverrideKey);
platformCalculated = true;
if(platformString == Platform.iPhone.ToString()) {
calculatedPlatform = Platform.iPhone;
}
else if(platformString == Platform.iPhoneRetina.ToString()) {
calculatedPlatform = Platform.iPhoneRetina;
}
else if(platformString == Platform.Android.ToString()) {
calculatedPlatform = Platform.Android;
}
else if(platformString == Platform.FlashPlayer.ToString()) {
calculatedPlatform = Platform.FlashPlayer;
}
else if(platformString == Platform.NaCl.ToString()) {
calculatedPlatform = Platform.NaCl;
}
else if(platformString == Platform.iPad.ToString()) {
calculatedPlatform = Platform.iPad;
}
else if(platformString == Platform.iPadRetina.ToString()) {
calculatedPlatform = Platform.iPadRetina;
}
else if(platformString == Platform.WebPlayer.ToString()) {
calculatedPlatform = Platform.WebPlayer;
}
else if(platformString == Platform.WP8.ToString()) {
calculatedPlatform = Platform.WP8;
}
else if(platformString == Platform.Windows8.ToString()) {
calculatedPlatform = Platform.Windows8;
}
else if(platformString == Platform.BB10.ToString()) {
calculatedPlatform = Platform.BB10;
}
else if(platformString == Platform.iPhone5.ToString()) {
calculatedPlatform = Platform.iPhone5;
}
else if(platformString == Platform.iPhone6and6plus.ToString()) {
calculatedPlatform = Platform.iPhone6and6plus;
}
else if(platformString == Platform.iOS.ToString()) {
calculatedPlatform = Platform.iOS;
}
else {
calculatedPlatform = Platform.Standalone;
}
#endif
if(!platformCalculated) { //If platform wasn't calculated before, calculate now
if(Application.platform == RuntimePlatform.IPhonePlayer) {
#if UNITY_IPHONE
int screenWidth = (int) Screen.width;
int screenHeight = (int) Screen.height;
if(screenWidth == 480 || screenWidth == 320) {
calculatedPlatform = Platform.iPhone;
} else if((screenWidth == 960 && screenHeight == 640) || (screenWidth == 640 && screenHeight == 960)) {
calculatedPlatform = Platform.iPhoneRetina;
} else if(screenWidth == 1024 || screenWidth == 768) {
calculatedPlatform = Platform.iPad;
} else if(screenWidth == 2048 || screenWidth == 1536) {
calculatedPlatform = Platform.iPadRetina;
} else if((screenWidth == 1136 && screenHeight == 640) || (screenWidth == 640 && screenHeight == 1136)) {
calculatedPlatform = Platform.iPhone5;
} else if((screenWidth == 1334 && screenHeight == 750) || (screenWidth == 750 && screenHeight == 1334) ||
(screenWidth == 1920 && screenHeight == 1080) || (screenWidth == 1080 && screenHeight == 1920)) {
calculatedPlatform = Platform.iPhone6and6plus;
} else {
calculatedPlatform = Platform.iPhone; //Default to iPhone
}
#endif
}
else if(Application.platform == RuntimePlatform.Android) {
calculatedPlatform = Platform.Android; //exact screen size will be calculated per-Aspect Ratio
}
#if !UNITY_5
else if(Application.platform == RuntimePlatform.FlashPlayer) {
calculatedPlatform = Platform.FlashPlayer; //exact screen size will be calculated per-Aspect Ratio
}
else if(Application.platform == RuntimePlatform.NaCl) {
calculatedPlatform = Platform.NaCl; //exact screen size will be calculated per-Aspect Ratio
}
#endif
else if(Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.OSXWebPlayer) {
calculatedPlatform = Platform.WebPlayer; //exact screen size will be calculated per-Aspect Ratio
}
#if !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3
//Starting in Unity 4.5, BB10Player was renamed Blackberry
//we want 4.5 and up
else if(Application.platform == RuntimePlatform.BlackBerryPlayer) {
calculatedPlatform = Platform.BB10; //exact screen size will be calculated per-Aspect Ratio
}
#endif
#if UNITY_4_1 || UNITY_4_2 || UNITY_4_3
//we want 4.1 to 4.3
else if(Application.platform == RuntimePlatform.BB10Player) {
calculatedPlatform = Platform.BB10; //exact screen size will be calculated per-Aspect Ratio
}
#endif
#if !UNITY_4_0 && !UNITY_4_1
//windows8/wp8/bb building wasnt introduced until Unity 4.2
//we want 4.2 and up
else if(Application.platform == RuntimePlatform.WP8Player) {
calculatedPlatform = Platform.WP8; //exact screen size will be calculated per-Aspect Ratio
}
#if UNITY_5
else if(Application.platform == RuntimePlatform.WSAPlayerARM || Application.platform == RuntimePlatform.WSAPlayerX86 || Application.platform == RuntimePlatform.WSAPlayerX64) {
calculatedPlatform = Platform.Windows8; //exact screen size will be calculated per-Aspect Ratio
}
#else
else if(Application.platform == RuntimePlatform.MetroPlayerARM || Application.platform == RuntimePlatform.MetroPlayerX86 || Application.platform == RuntimePlatform.MetroPlayerX64) {
calculatedPlatform = Platform.Windows8; //exact screen size will be calculated per-Aspect Ratio
}
#endif
#endif
else {
calculatedPlatform = Platform.Standalone; //exact screen size will be calculated per-Aspect Ratio
}
platformCalculated = true;
}
return calculatedPlatform;
}
}
public static bool IsPlatformAspectBased(string plat) {
return plat == Platform.Standalone.ToString()
|| plat == Platform.Android.ToString()
|| plat == Platform.FlashPlayer.ToString()
|| plat == Platform.WP8.ToString()
|| plat == Platform.Windows8.ToString()
|| plat == Platform.BB10.ToString()
|| plat == Platform.NaCl.ToString();
}
public static bool IsiOS {
get {
return (Platforms.platform == Platform.iOS || Platforms.platform == Platform.iPad || Platforms.platform == Platform.iPhone || Platforms.platform == Platform.iPadRetina || Platforms.platform == Platform.iPhoneRetina || Platforms.platform == Platform.iPhone5 || Platforms.platform == Platform.iPhone6and6plus);
}
}
public static bool IsiOSPlatform(Platform platform) {
return (platform == Platform.iOS || platform == Platform.iPad || platform == Platform.iPhone || platform == Platform.iPadRetina || platform == Platform.iPhoneRetina || platform == Platform.iPhone5 || platform == Platform.iPhone6and6plus);
}
//detect if we're dealing with an iOS device thats NOT iPhone4S or iPad2 or iPad3 or iPhone 5
//Since we can't guarantee that Unity has the most up to date list of device generations
//we catch the old device generations
public static bool IsiOSSlower {
get {
if(IsiOS){
#if UNITY_IPHONE
#if UNITY_5
if(UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad1Gen
|| UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone
|| UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone3G
|| UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone4
|| UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone3GS
|| UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouch1Gen
|| UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouch2Gen
|| UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouch3Gen
|| UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouch4Gen
)
return true; //we found a comparatively slow iOS device
else
return false; //not slow - its an iPad2 or iPhone4S or newer
#else
if(iPhone.generation == iPhoneGeneration.iPad1Gen
|| iPhone.generation == iPhoneGeneration.iPhone
|| iPhone.generation == iPhoneGeneration.iPhone3G
|| iPhone.generation == iPhoneGeneration.iPhone4
|| iPhone.generation == iPhoneGeneration.iPhone3GS
|| iPhone.generation == iPhoneGeneration.iPodTouch1Gen
|| iPhone.generation == iPhoneGeneration.iPodTouch2Gen
|| iPhone.generation == iPhoneGeneration.iPodTouch3Gen
|| iPhone.generation == iPhoneGeneration.iPodTouch4Gen
)
return true; //we found a comparatively slow iOS device
else
return false; //not slow - its an iPad2 or iPhone4S or newer
#endif
#else
return false;
#endif
} else {
return false; //not slow (or not iOS)
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Microsoft.Msagl.Layout.Layered {
/// <summary>
/// Following "A technique for Drawing Directed Graphs" of Gansner, Koutsofios, North and Vo
/// Works on the layered graph. For explanations of the algorithm here see GraphLayout.pdf.
/// </summary>
internal partial class Ordering {
/// <summary>
/// for each vertex v let P[v] be the array of predeccessors of v
/// </summary>
int[][] predecessors;
/// <summary>
/// The array contains a dictionary per vertex
/// The value POrder[v][u] gives the offset of u in the array P[v]
/// </summary>
Dictionary<int, int>[] pOrder;
/// <summary>
/// for each vertex v let S[v] be the array of successors of v
/// </summary>
int[][] successors;
/// <summary>
/// The array contains a dictionary per vertex
/// The value SOrder[v][u] gives the offset of u in the array S[v]
/// </summary>
Dictionary<int, int>[] sOrder;
Dictionary<int, int>[] inCrossingCount;
/// <summary>
/// Gets or sets the number of of passes over all layers to rung adjacent exchanges, where every pass goes '
/// all way up to the top layer and down to the lowest layer
/// </summary>
const int MaxNumberOfAdjacentExchanges = 50;
Dictionary<int, int>[] outCrossingCount;
bool HeadOfTheCoin() {
return random.Next(2) == 0;
}
void AdjacentExchangeWithBalancingVirtOrigNodes() {
InitArrays();
int count = 0;
bool progress = true;
while (progress && count++ < MaxNumberOfAdjacentExchanges) {
progress = false;
for (int i = 0; i < layers.Length; i++)
progress = AdjExchangeLayerWithBalance(i) || progress;
for (int i = layers.Length - 2; i >= 0; i--)
progress = AdjExchangeLayerWithBalance(i) || progress;
}
}
void AdjacentExchange() {
InitArrays();
int count = 0;
bool progress = true;
while (progress && count++ < MaxNumberOfAdjacentExchanges) {
progress = false;
for (int i = 0; i < layers.Length; i++)
progress = AdjExchangeLayer(i) || progress;
for (int i = layers.Length - 2; i >= 0; i--)
progress = AdjExchangeLayer(i) || progress;
}
}
void AllocArrays() {
int n = properLayeredGraph.NodeCount;
predecessors = new int[n][];
successors = new int[n][];
pOrder = new Dictionary<int, int>[n];
sOrder = new Dictionary<int, int>[n];
if (hasCrossWeights) {
outCrossingCount = new Dictionary<int, int>[n];
inCrossingCount = new Dictionary<int, int>[n];
}
for (int i = 0; i < n; i++) {
int count = properLayeredGraph.InEdgesCount(i);
predecessors[i] = new int[count];
if (hasCrossWeights) {
Dictionary<int, int> inCounts = inCrossingCount[i] = new Dictionary<int, int>(count);
foreach (LayerEdge le in properLayeredGraph.InEdges(i))
inCounts[le.Source] = le.CrossingWeight;
}
pOrder[i] = new Dictionary<int, int>(count);
count = properLayeredGraph.OutEdgesCount(i);
successors[i] = new int[count];
sOrder[i] = new Dictionary<int, int>(count);
if (hasCrossWeights) {
Dictionary<int, int> outCounts = outCrossingCount[i] = new Dictionary<int, int>(count);
foreach (LayerEdge le in properLayeredGraph.OutEdges(i))
outCounts[le.Target] = le.CrossingWeight;
}
}
}
/// <summary>
/// Is called just after median layer swap is done
/// </summary>
void InitArrays() {
if (successors == null)
AllocArrays();
for (int i = 0; i < properLayeredGraph.NodeCount; i++) {
pOrder[i].Clear();
sOrder[i].Clear();
}
foreach (int[] t in layers)
InitPsArraysForLayer(t);
}
/// <summary>
/// calculates the number of intersections between edges adjacent to u and v
/// </summary>
/// <param name="u">a vertex</param>
/// <param name="v">a vertex</param>
/// <param name="cuv">the result when u is to the left of v</param>
/// <param name="cvu">the result when v is to the left of u</param>
void CalcPair(int u, int v, out int cuv, out int cvu) {
int[] su = successors[u], sv = successors[v], pu = predecessors[u], pv = predecessors[v];
if (!hasCrossWeights) {
cuv = CountOnArrays(su, sv) +
CountOnArrays(pu, pv);
cvu = CountOnArrays(sv, su) +
CountOnArrays(pv, pu);
} else {
Dictionary<int, int> uOutCrossCounts = outCrossingCount[u];
Dictionary<int, int> vOutCrossCounts = outCrossingCount[v];
Dictionary<int, int> uInCrossCounts = inCrossingCount[u];
Dictionary<int, int> vInCrossCounts = inCrossingCount[v];
cuv = CountOnArrays(su, sv, uOutCrossCounts, vOutCrossCounts) +
CountOnArrays(pu, pv, uInCrossCounts, vInCrossCounts);
cvu = CountOnArrays(sv, su, vOutCrossCounts, uOutCrossCounts) +
CountOnArrays(pv, pu, vInCrossCounts, uInCrossCounts);
}
}
/// <summary>
/// Sweep layer from left to right and fill S,P arrays as we go.
/// The arrays P and S will be sorted according to X. Note that we will not keep them sorted
/// as we doing adjacent swaps. Initial sorting only needed to calculate initial clr,crl values.
/// </summary>
/// <param name="layer"></param>
void InitPsArraysForLayer(int[] layer) {
this.ProgressStep();
foreach (int l in layer) {
foreach (int p in properLayeredGraph.Pred(l)) {
Dictionary<int, int> so = sOrder[p];
int sHasNow = so.Count;
successors[p][sHasNow] = l; //l takes the first available slot in S[p]
so[l] = sHasNow;
}
foreach (int s in properLayeredGraph.Succ(l)) {
Dictionary<int, int> po = pOrder[s];
int pHasNow = po.Count;
predecessors[s][pHasNow] = l; //l take the first available slot in P[s]
po[l] = pHasNow;
}
}
}
int CountOnArrays(int[] unbs, int[] vnbs) {
int ret = 0;
int vl = vnbs.Length - 1;
int j = -1; //the right most position of vnbs to the left from the current u neighbor
int vnbsSeenAlready = 0;
foreach (int uNeighbor in unbs) {
int xu = X[uNeighbor];
for (; j < vl && X[vnbs[j + 1]] < xu; j++)
vnbsSeenAlready++;
ret += vnbsSeenAlready;
}
return ret;
}
/// <summary>
/// every inversion between unbs and vnbs gives an intersecton
/// </summary>
/// <param name="unbs">neighbors of u but only from one layer</param>
/// <param name="vnbs">neighbors of v from the same layers</param>
/// <returns>number of intersections when u is to the left of v</returns>
/// <param name="uCrossingCounts"></param>
/// <param name="vCrossingCount"></param>
int CountOnArrays(int[] unbs, int[] vnbs, Dictionary<int, int> uCrossingCounts,
Dictionary<int, int> vCrossingCount) {
int ret = 0;
int vl = vnbs.Length - 1;
int j = -1; //the right most position of vnbs to the left from the current u neighbor
int vCrossingNumberSeenAlready = 0;
foreach (int uNeib in unbs) {
int xu = X[uNeib];
int vnb;
for (; j < vl && X[vnb = vnbs[j + 1]] < xu; j++)
vCrossingNumberSeenAlready += vCrossingCount[vnb];
ret += vCrossingNumberSeenAlready*uCrossingCounts[uNeib];
}
return ret;
}
bool AdjExchangeLayer(int i) {
this.ProgressStep();
int[] layer = layers[i];
bool gain = ExchangeWithGainWithNoDisturbance(layer);
if (gain)
return true;
DisturbLayer(layer);
return ExchangeWithGainWithNoDisturbance(layer);
}
bool AdjExchangeLayerWithBalance(int i) {
this.ProgressStep();
int[] layer = layers[i];
bool gain = ExchangeWithGainWithNoDisturbanceWithBalance(layer);
if (gain)
return true;
DisturbLayerWithBalance(layer);
return ExchangeWithGainWithNoDisturbanceWithBalance(layer);
}
//in this routine u and v are adjacent, and u is to the left of v before the swap
void Swap(int u, int v) {
int left = X[u];
int right = X[v];
int ln = layering[u]; //layer number
int[] layer = layers[ln];
layer[left] = v;
layer[right] = u;
X[u] = right;
X[v] = left;
//update sorted arrays POrders and SOrders
//an array should be updated only in case it contains both u and v.
// More than that, v has to follow u in an the array.
UpdateSsContainingUv(u, v);
UpdatePsContainingUv(u, v);
}
void UpdatePsContainingUv(int u, int v) {
if (successors[u].Length <= successors[v].Length)
foreach (int a in successors[u]) {
Dictionary<int, int> porder = pOrder[a];
//of course porder contains u, let us see if it contains v
if (porder.ContainsKey(v)) {
int vOffset = porder[v];
//swap u and v in the array P[coeff]
int[] p = predecessors[a];
p[vOffset - 1] = v;
p[vOffset] = u;
//update sorder itself
porder[v] = vOffset - 1;
porder[u] = vOffset;
}
}
else
foreach (int a in successors[v]) {
Dictionary<int, int> porder = pOrder[a];
//of course porder contains u, let us see if it contains v
if (porder.ContainsKey(u)) {
int vOffset = porder[v];
//swap u and v in the array P[coeff]
int[] p = predecessors[a];
p[vOffset - 1] = v;
p[vOffset] = u;
//update sorder itself
porder[v] = vOffset - 1;
porder[u] = vOffset;
}
}
}
void UpdateSsContainingUv(int u, int v) {
if (predecessors[u].Length <= predecessors[v].Length)
foreach (int a in predecessors[u]) {
Dictionary<int, int> sorder = sOrder[a];
//of course sorder contains u, let us see if it contains v
if (sorder.ContainsKey(v)) {
int vOffset = sorder[v];
//swap u and v in the array S[coeff]
int[] s = successors[a];
s[vOffset - 1] = v;
s[vOffset] = u;
//update sorder itself
sorder[v] = vOffset - 1;
sorder[u] = vOffset;
}
}
else
foreach (int a in predecessors[v]) {
Dictionary<int, int> sorder = sOrder[a];
//of course sorder contains u, let us see if it contains v
if (sorder.ContainsKey(u)) {
int vOffset = sorder[v];
//swap u and v in the array S[coeff]
int[] s = successors[a];
s[vOffset - 1] = v;
s[vOffset] = u;
//update sorder itself
sorder[v] = vOffset - 1;
sorder[u] = vOffset;
}
}
}
void DisturbLayer(int[] layer) {
for (int i = 0; i < layer.Length - 1; i++)
AdjacentSwapToTheRight(layer, i);
}
void DisturbLayerWithBalance(int[] layer) {
for (int i = 0; i < layer.Length - 1; i++)
AdjacentSwapToTheRightWithBalance(layer, i);
}
bool ExchangeWithGainWithNoDisturbance(int[] layer) {
bool wasGain = false;
bool gain;
do {
gain = ExchangeWithGain(layer);
wasGain = wasGain || gain;
} while (gain);
return wasGain;
}
bool ExchangeWithGainWithNoDisturbanceWithBalance(int[] layer) {
bool wasGain = false;
bool gain;
do {
gain = ExchangeWithGainWithBalance(layer);
wasGain = wasGain || gain;
} while (gain);
return wasGain;
}
bool ExchangeWithGain(int[] layer) {
//find a first pair giving some gain
for (int i = 0; i < layer.Length - 1; i++)
if (SwapWithGain(layer[i], layer[i + 1])) {
SwapToTheLeft(layer, i);
SwapToTheRight(layer, i + 1);
return true;
}
return false;
}
bool ExchangeWithGainWithBalance(int[] layer) {
//find a first pair giving some gain
for (int i = 0; i < layer.Length - 1; i++)
if (SwapWithGainWithBalance(layer[i], layer[i + 1])) {
SwapToTheLeftWithBalance(layer, i);
SwapToTheRightWithBalance(layer, i + 1);
return true;
}
return false;
}
void SwapToTheLeft(int[] layer, int i) {
for (int j = i - 1; j >= 0; j--)
AdjacentSwapToTheRight(layer, j);
}
void SwapToTheRight(int[] layer, int i) {
for (int j = i; j < layer.Length - 1; j++)
AdjacentSwapToTheRight(layer, j);
}
void SwapToTheLeftWithBalance(int[] layer, int i) {
for (int j = i - 1; j >= 0; j--)
AdjacentSwapToTheRightWithBalance(layer, j);
}
void SwapToTheRightWithBalance(int[] layer, int i) {
for (int j = i; j < layer.Length - 1; j++)
AdjacentSwapToTheRightWithBalance(layer, j);
}
/// <summary>
/// swaps i-th element with i+1
/// </summary>
/// <param name="layer">the layer to work on</param>
/// <param name="i">the position to start</param>
void AdjacentSwapToTheRight(int[] layer, int i) {
int u = layer[i], v = layer[i + 1];
int gain = SwapGain(u, v);
if (gain > 0 || (gain == 0 && HeadOfTheCoin()))
Swap(u, v);
}
void AdjacentSwapToTheRightWithBalance(int[] layer, int i) {
int u = layer[i], v = layer[i + 1];
int gain = SwapGainWithBalance(u, v);
if (gain > 0 || (gain == 0 && HeadOfTheCoin()))
Swap(u, v);
}
int SwapGain(int u, int v) {
int cuv;
int cvu;
CalcPair(u, v, out cuv, out cvu);
return cuv - cvu;
}
int SwapGainWithBalance(int u, int v) {
int cuv;
int cvu;
CalcPair(u, v, out cuv, out cvu);
int gain = cuv - cvu;
if (gain != 0 && UvAreOfSameKind(u, v))
return gain;
//maybe we gain something in the group sizes
return SwapGroupGain(u, v);
}
bool UvAreOfSameKind(int u, int v) {
return u < startOfVirtNodes && v < startOfVirtNodes || u >= startOfVirtNodes && v >= startOfVirtNodes;
}
int SwapGroupGain(int u, int v) {
int layerIndex = layerArrays.Y[u];
int[] layer = layers[layerIndex];
if (NeighborsForbidTheSwap(u, v))
return -1;
int uPosition = X[u];
bool uIsSeparator;
if (IsOriginal(u))
uIsSeparator = optimalOriginalGroupSize[layerIndex] == 1;
else
uIsSeparator = optimalVirtualGroupSize[layerIndex] == 1;
int delta = CalcDeltaBetweenGroupsToTheLeftAndToTheRightOfTheSeparator(layer,
uIsSeparator
? uPosition
: uPosition + 1,
uIsSeparator ? u : v);
if (uIsSeparator) {
if (delta < -1)
return 1;
if (delta == -1)
return 0;
return -1;
}
if (delta > 1)
return 1;
if (delta == 1)
return 0;
return -1;
}
bool NeighborsForbidTheSwap(int u, int v) {
return UpperNeighborsForbidTheSwap(u, v) || LowerNeighborsForbidTheSwap(u, v);
}
bool LowerNeighborsForbidTheSwap(int u, int v) {
int uCount, vCount;
if (((uCount = properLayeredGraph.OutEdgesCount(u)) == 0) ||
((vCount = properLayeredGraph.OutEdgesCount(v)) == 0))
return false;
return X[successors[u][uCount >> 1]] < X[successors[v][vCount >> 1]];
}
bool UpperNeighborsForbidTheSwap(int u, int v) {
int uCount = properLayeredGraph.InEdgesCount(u);
int vCount = properLayeredGraph.InEdgesCount(v);
if (uCount == 0 || vCount == 0)
return false;
return X[predecessors[u][uCount >> 1]] < X[predecessors[v][vCount >> 1]];
}
int CalcDeltaBetweenGroupsToTheLeftAndToTheRightOfTheSeparator(int[] layer, int separatorPosition, int separator) {
Func<int, bool> kind = GetKindDelegate(separator);
int leftGroupSize = 0;
for (int i = separatorPosition - 1; i >= 0 && !kind(layer[i]); i--)
leftGroupSize++;
int rightGroupSize = 0;
for (int i = separatorPosition + 1; i < layer.Length && !kind(layer[i]); i++)
rightGroupSize++;
return leftGroupSize - rightGroupSize;
}
bool IsOriginal(int v) {
return v < startOfVirtNodes;
}
bool IsVirtual(int v) {
return v >= startOfVirtNodes;
}
Func<int, bool> GetKindDelegate(int v) {
Func<int, bool> kind = IsVirtual(v) ? IsVirtual : new Func<int, bool>(IsOriginal);
return kind;
}
///// <summary>
///// swaps two vertices only if reduces the number of intersections
///// </summary>
///// <param name="layer">the layer to work on</param>
///// <param name="u">left vertex</param>
///// <param name="v">right vertex</param>
///// <returns></returns>
bool SwapWithGain(int u, int v) {
int gain = SwapGain(u, v);
if (gain > 0) {
Swap(u, v);
return true;
}
return false;
}
bool SwapWithGainWithBalance(int u, int v) {
int gain = SwapGainWithBalance(u, v);
if (gain > 0) {
Swap(u, v);
return true;
}
return false;
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.Collections;
using Cassandra.Connections;
using Cassandra.Connections.Control;
using Cassandra.MetadataHelpers;
using Cassandra.Requests;
using Cassandra.Tasks;
namespace Cassandra
{
/// <summary>
/// Keeps metadata on the connected cluster, including known nodes and schema
/// definitions.
/// </summary>
public class Metadata : IDisposable
{
private const string SelectSchemaVersionPeers = "SELECT schema_version FROM system.peers";
private const string SelectSchemaVersionLocal = "SELECT schema_version FROM system.local";
private static readonly Logger Logger = new Logger(typeof(ControlConnection));
private volatile TokenMap _tokenMap;
private volatile ConcurrentDictionary<string, KeyspaceMetadata> _keyspaces = new ConcurrentDictionary<string, KeyspaceMetadata>();
private volatile ISchemaParser _schemaParser;
private readonly int _queryAbortTimeout;
private volatile CopyOnWriteDictionary<IContactPoint, IEnumerable<IConnectionEndPoint>> _resolvedContactPoints =
new CopyOnWriteDictionary<IContactPoint, IEnumerable<IConnectionEndPoint>>();
public event HostsEventHandler HostsEvent;
public event SchemaChangedEventHandler SchemaChangedEvent;
/// <summary>
/// Returns the name of currently connected cluster.
/// </summary>
/// <returns>the Cassandra name of currently connected cluster.</returns>
public String ClusterName { get; internal set; }
/// <summary>
/// Determines whether the cluster is provided as a service (DataStax Astra).
/// </summary>
public bool IsDbaas { get; private set; } = false;
/// <summary>
/// Gets the configuration associated with this instance.
/// </summary>
internal Configuration Configuration { get; private set; }
/// <summary>
/// Control connection to be used to execute the queries to retrieve the metadata
/// </summary>
internal IControlConnection ControlConnection { get; set; }
internal ISchemaParser SchemaParser { get { return _schemaParser; } }
internal string Partitioner { get; set; }
internal Hosts Hosts { get; private set; }
internal IReadOnlyDictionary<IContactPoint, IEnumerable<IConnectionEndPoint>> ResolvedContactPoints => _resolvedContactPoints;
internal IReadOnlyTokenMap TokenToReplicasMap => _tokenMap;
internal Metadata(Configuration configuration)
{
_queryAbortTimeout = configuration.DefaultRequestOptions.QueryAbortTimeout;
Configuration = configuration;
Hosts = new Hosts();
Hosts.Down += OnHostDown;
Hosts.Up += OnHostUp;
}
internal Metadata(Configuration configuration, SchemaParser schemaParser) : this(configuration)
{
_schemaParser = schemaParser;
}
public void Dispose()
{
ShutDown();
}
internal KeyspaceMetadata GetKeyspaceFromCache(string keyspace)
{
_keyspaces.TryGetValue(keyspace, out var ks);
return ks;
}
internal void SetResolvedContactPoints(IDictionary<IContactPoint, IEnumerable<IConnectionEndPoint>> resolvedContactPoints)
{
_resolvedContactPoints = new CopyOnWriteDictionary<IContactPoint, IEnumerable<IConnectionEndPoint>>(resolvedContactPoints);
}
public Host GetHost(IPEndPoint address)
{
if (Hosts.TryGet(address, out var host))
return host;
return null;
}
internal Host AddHost(IPEndPoint address)
{
return Hosts.Add(address);
}
internal Host AddHost(IPEndPoint address, IContactPoint contactPoint)
{
return Hosts.Add(address, contactPoint);
}
internal void RemoveHost(IPEndPoint address)
{
Hosts.RemoveIfExists(address);
}
internal void FireSchemaChangedEvent(SchemaChangedEventArgs.Kind what, string keyspace, string table, object sender = null)
{
SchemaChangedEvent?.Invoke(sender ?? this, new SchemaChangedEventArgs { Keyspace = keyspace, What = what, Table = table });
}
private void OnHostDown(Host h)
{
HostsEvent?.Invoke(this, new HostsEventArgs { Address = h.Address, What = HostsEventArgs.Kind.Down });
}
private void OnHostUp(Host h)
{
HostsEvent?.Invoke(h, new HostsEventArgs { Address = h.Address, What = HostsEventArgs.Kind.Up });
}
/// <summary>
/// Returns all known hosts of this cluster.
/// </summary>
/// <returns>collection of all known hosts of this cluster.</returns>
public ICollection<Host> AllHosts()
{
return Hosts.ToCollection();
}
public IEnumerable<IPEndPoint> AllReplicas()
{
return Hosts.AllEndPointsToCollection();
}
// for tests
internal KeyValuePair<string, KeyspaceMetadata>[] KeyspacesSnapshot => _keyspaces.ToArray();
internal async Task RebuildTokenMapAsync(bool retry, bool fetchKeyspaces)
{
IEnumerable<KeyspaceMetadata> ksList = null;
if (fetchKeyspaces)
{
Metadata.Logger.Info("Retrieving keyspaces metadata");
ksList = await _schemaParser.GetKeyspacesAsync(retry).ConfigureAwait(false);
}
ConcurrentDictionary<string, KeyspaceMetadata> keyspaces;
if (ksList != null)
{
Metadata.Logger.Info("Updating keyspaces metadata");
var ksMap = ksList.Select(ks => new KeyValuePair<string, KeyspaceMetadata>(ks.Name, ks));
keyspaces = new ConcurrentDictionary<string, KeyspaceMetadata>(ksMap);
}
else
{
keyspaces = _keyspaces;
}
Metadata.Logger.Info("Rebuilding token map");
if (Partitioner == null)
{
throw new DriverInternalError("Partitioner can not be null");
}
var tokenMap = TokenMap.Build(Partitioner, Hosts.ToCollection(), keyspaces.Values);
_keyspaces = keyspaces;
_tokenMap = tokenMap;
}
/// <summary>
/// this method should be called by the event debouncer
/// </summary>
internal bool RemoveKeyspaceFromTokenMap(string name)
{
Metadata.Logger.Verbose("Removing keyspace metadata: " + name);
var dropped = _keyspaces.TryRemove(name, out _);
_tokenMap?.RemoveKeyspace(name);
return dropped;
}
internal async Task<KeyspaceMetadata> UpdateTokenMapForKeyspace(string name)
{
var keyspaceMetadata = await _schemaParser.GetKeyspaceAsync(name).ConfigureAwait(false);
var dropped = false;
var updated = false;
if (_tokenMap == null)
{
await RebuildTokenMapAsync(false, false).ConfigureAwait(false);
}
if (keyspaceMetadata == null)
{
Metadata.Logger.Verbose("Removing keyspace metadata: " + name);
dropped = _keyspaces.TryRemove(name, out _);
_tokenMap?.RemoveKeyspace(name);
}
else
{
Metadata.Logger.Verbose("Updating keyspace metadata: " + name);
_keyspaces.AddOrUpdate(keyspaceMetadata.Name, keyspaceMetadata, (k, v) =>
{
updated = true;
return keyspaceMetadata;
});
Metadata.Logger.Info("Rebuilding token map for keyspace {0}", keyspaceMetadata.Name);
if (Partitioner == null)
{
throw new DriverInternalError("Partitioner can not be null");
}
_tokenMap.UpdateKeyspace(keyspaceMetadata);
}
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
if (dropped)
{
FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Dropped, name, null, this);
}
else if (updated)
{
FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Updated, name, null, this);
}
else
{
FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Created, name, null, this);
}
}
return keyspaceMetadata;
}
/// <summary>
/// Get the replicas for a given partition key and keyspace
/// </summary>
public ICollection<Host> GetReplicas(string keyspaceName, byte[] partitionKey)
{
if (_tokenMap == null)
{
Metadata.Logger.Warning("Metadata.GetReplicas was called but there was no token map.");
return new Host[0];
}
return _tokenMap.GetReplicas(keyspaceName, _tokenMap.Factory.Hash(partitionKey));
}
public ICollection<Host> GetReplicas(byte[] partitionKey)
{
return GetReplicas(null, partitionKey);
}
/// <summary>
/// Returns metadata of specified keyspace.
/// </summary>
/// <param name="keyspace"> the name of the keyspace for which metadata should be
/// returned. </param>
/// <returns>the metadata of the requested keyspace or <c>null</c> if
/// <c>* keyspace</c> is not a known keyspace.</returns>
public KeyspaceMetadata GetKeyspace(string keyspace)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
//Use local cache
_keyspaces.TryGetValue(keyspace, out var ksInfo);
return ksInfo;
}
return TaskHelper.WaitToComplete(SchemaParser.GetKeyspaceAsync(keyspace), _queryAbortTimeout);
}
/// <summary>
/// Returns a collection of all defined keyspaces names.
/// </summary>
/// <returns>a collection of all defined keyspaces names.</returns>
public ICollection<string> GetKeyspaces()
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
//Use local cache
return _keyspaces.Keys;
}
return TaskHelper.WaitToComplete(SchemaParser.GetKeyspacesNamesAsync(), _queryAbortTimeout);
}
/// <summary>
/// Returns names of all tables which are defined within specified keyspace.
/// </summary>
/// <param name="keyspace">the name of the keyspace for which all tables metadata should be
/// returned.</param>
/// <returns>an ICollection of the metadata for the tables defined in this
/// keyspace.</returns>
public ICollection<string> GetTables(string keyspace)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? new string[0]
: ksMetadata.GetTablesNames();
}
return TaskHelper.WaitToComplete(SchemaParser.GetTableNamesAsync(keyspace), _queryAbortTimeout);
}
/// <summary>
/// Returns TableMetadata for specified table in specified keyspace.
/// </summary>
/// <param name="keyspace">name of the keyspace within specified table is defined.</param>
/// <param name="tableName">name of table for which metadata should be returned.</param>
/// <returns>a TableMetadata for the specified table in the specified keyspace.</returns>
public TableMetadata GetTable(string keyspace, string tableName)
{
return TaskHelper.WaitToComplete(GetTableAsync(keyspace, tableName), _queryAbortTimeout * 2);
}
internal Task<TableMetadata> GetTableAsync(string keyspace, string tableName)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? Task.FromResult<TableMetadata>(null)
: ksMetadata.GetTableMetadataAsync(tableName);
}
return SchemaParser.GetTableAsync(keyspace, tableName);
}
/// <summary>
/// Returns the view metadata for the provided view name in the keyspace.
/// </summary>
/// <param name="keyspace">name of the keyspace within specified view is defined.</param>
/// <param name="name">name of view.</param>
/// <returns>a MaterializedViewMetadata for the view in the specified keyspace.</returns>
public MaterializedViewMetadata GetMaterializedView(string keyspace, string name)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? null
: ksMetadata.GetMaterializedViewMetadata(name);
}
return TaskHelper.WaitToComplete(SchemaParser.GetViewAsync(keyspace, name), _queryAbortTimeout * 2);
}
/// <summary>
/// Gets the definition associated with a User Defined Type from Cassandra
/// </summary>
public UdtColumnInfo GetUdtDefinition(string keyspace, string typeName)
{
return TaskHelper.WaitToComplete(GetUdtDefinitionAsync(keyspace, typeName), _queryAbortTimeout);
}
/// <summary>
/// Gets the definition associated with a User Defined Type from Cassandra
/// </summary>
public Task<UdtColumnInfo> GetUdtDefinitionAsync(string keyspace, string typeName)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? Task.FromResult<UdtColumnInfo>(null)
: ksMetadata.GetUdtDefinitionAsync(typeName);
}
return SchemaParser.GetUdtDefinitionAsync(keyspace, typeName);
}
/// <summary>
/// Gets the definition associated with a User Defined Function from Cassandra
/// </summary>
/// <returns>The function metadata or null if not found.</returns>
public FunctionMetadata GetFunction(string keyspace, string name, string[] signature)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? null
: ksMetadata.GetFunction(name, signature);
}
var signatureString = SchemaParser.ComputeFunctionSignatureString(signature);
return TaskHelper.WaitToComplete(SchemaParser.GetFunctionAsync(keyspace, name, signatureString), _queryAbortTimeout);
}
/// <summary>
/// Gets the definition associated with a aggregate from Cassandra
/// </summary>
/// <returns>The aggregate metadata or null if not found.</returns>
public AggregateMetadata GetAggregate(string keyspace, string name, string[] signature)
{
if (Configuration.MetadataSyncOptions.MetadataSyncEnabled)
{
return !_keyspaces.TryGetValue(keyspace, out var ksMetadata)
? null
: ksMetadata.GetAggregate(name, signature);
}
var signatureString = SchemaParser.ComputeFunctionSignatureString(signature);
return TaskHelper.WaitToComplete(SchemaParser.GetAggregateAsync(keyspace, name, signatureString), _queryAbortTimeout);
}
/// <summary>
/// Gets the query trace.
/// </summary>
/// <param name="trace">The query trace that contains the id, which properties are going to be populated.</param>
/// <returns></returns>
internal Task<QueryTrace> GetQueryTraceAsync(QueryTrace trace)
{
return _schemaParser.GetQueryTraceAsync(trace, Configuration.Timer);
}
/// <summary>
/// Updates the keyspace and token information
/// </summary>
public bool RefreshSchema(string keyspace = null, string table = null)
{
return TaskHelper.WaitToComplete(RefreshSchemaAsync(keyspace, table), Configuration.DefaultRequestOptions.QueryAbortTimeout * 2);
}
/// <summary>
/// Updates the keyspace and token information
/// </summary>
public async Task<bool> RefreshSchemaAsync(string keyspace = null, string table = null)
{
if (keyspace == null)
{
await ControlConnection.ScheduleAllKeyspacesRefreshAsync(true).ConfigureAwait(false);
return true;
}
await ControlConnection.ScheduleKeyspaceRefreshAsync(keyspace, true).ConfigureAwait(false);
_keyspaces.TryGetValue(keyspace, out var ks);
if (ks == null)
{
return false;
}
if (table != null)
{
ks.ClearTableMetadata(table);
}
return true;
}
public void ShutDown(int timeoutMs = Timeout.Infinite)
{
//it is really not required to be called, left as it is part of the public API
//dereference the control connection
ControlConnection = null;
}
/// <summary>
/// this method should be called by the event debouncer
/// </summary>
internal bool RemoveKeyspace(string name)
{
var existed = RemoveKeyspaceFromTokenMap(name);
if (!existed)
{
return false;
}
FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Dropped, name, null, this);
return true;
}
/// <summary>
/// this method should be called by the event debouncer
/// </summary>
internal Task<KeyspaceMetadata> RefreshSingleKeyspace(string name)
{
return UpdateTokenMapForKeyspace(name);
}
internal void ClearTable(string keyspaceName, string tableName)
{
if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata))
{
ksMetadata.ClearTableMetadata(tableName);
}
}
internal void ClearView(string keyspaceName, string name)
{
if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata))
{
ksMetadata.ClearViewMetadata(name);
}
}
internal void ClearFunction(string keyspaceName, string functionName, string[] signature)
{
if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata))
{
ksMetadata.ClearFunction(functionName, signature);
}
}
internal void ClearAggregate(string keyspaceName, string aggregateName, string[] signature)
{
if (_keyspaces.TryGetValue(keyspaceName, out var ksMetadata))
{
ksMetadata.ClearAggregate(aggregateName, signature);
}
}
/// <summary>
/// Initiates a schema agreement check.
/// <para/>
/// Schema changes need to be propagated to all nodes in the cluster.
/// Once they have settled on a common version, we say that they are in agreement.
/// <para/>
/// This method does not perform retries so
/// <see cref="ProtocolOptions.MaxSchemaAgreementWaitSeconds"/> does not apply.
/// </summary>
/// <returns>True if schema agreement was successful and false if it was not successful.</returns>
public async Task<bool> CheckSchemaAgreementAsync()
{
if (Hosts.Count == 1)
{
// If there is just one node, the schema is up to date in all nodes :)
return true;
}
try
{
var queries = new[]
{
ControlConnection.QueryAsync(SelectSchemaVersionLocal),
ControlConnection.QueryAsync(SelectSchemaVersionPeers)
};
await Task.WhenAll(queries).ConfigureAwait(false);
return CheckSchemaVersionResults(queries[0].Result, queries[1].Result);
}
catch (Exception ex)
{
Logger.Error("Error while checking schema agreement.", ex);
}
return false;
}
/// <summary>
/// Checks if there is only one schema version between the provided query results.
/// </summary>
/// <param name="localVersionQuery">
/// Results obtained from a query to <code>system.local</code> table.
/// Must contain the <code>schema_version</code> column.
/// </param>
/// <param name="peerVersionsQuery">
/// Results obtained from a query to <code>system.peers</code> table.
/// Must contain the <code>schema_version</code> column.
/// </param>
/// <returns><code>True</code> if there is a schema agreement (only 1 schema version). <code>False</code> otherwise.</returns>
private static bool CheckSchemaVersionResults(
IEnumerable<IRow> localVersionQuery, IEnumerable<IRow> peerVersionsQuery)
{
return new HashSet<Guid>(
peerVersionsQuery
.Concat(localVersionQuery)
.Select(r => r.GetValue<Guid>("schema_version"))).Count == 1;
}
/// <summary>
/// Waits until that the schema version in all nodes is the same or the waiting time passed.
/// This method blocks the calling thread.
/// </summary>
internal bool WaitForSchemaAgreement(IConnection connection)
{
if (Hosts.Count == 1)
{
//If there is just one node, the schema is up to date in all nodes :)
return true;
}
var start = DateTime.Now;
var waitSeconds = Configuration.ProtocolOptions.MaxSchemaAgreementWaitSeconds;
Metadata.Logger.Info("Waiting for schema agreement");
try
{
var totalVersions = 0;
while (DateTime.Now.Subtract(start).TotalSeconds < waitSeconds)
{
var serializer = ControlConnection.Serializer.GetCurrentSerializer();
var schemaVersionLocalQuery =
new QueryRequest(
serializer,
Metadata.SelectSchemaVersionLocal,
QueryProtocolOptions.Default,
false,
null);
var schemaVersionPeersQuery =
new QueryRequest(
serializer,
Metadata.SelectSchemaVersionPeers,
QueryProtocolOptions.Default,
false,
null);
var queries = new[] { connection.Send(schemaVersionLocalQuery), connection.Send(schemaVersionPeersQuery) };
// ReSharper disable once CoVariantArrayConversion
Task.WaitAll(queries, Configuration.DefaultRequestOptions.QueryAbortTimeout);
if (Metadata.CheckSchemaVersionResults(
Configuration.MetadataRequestHandler.GetRowSet(queries[0].Result),
Configuration.MetadataRequestHandler.GetRowSet(queries[1].Result)))
{
return true;
}
Thread.Sleep(500);
}
Metadata.Logger.Info($"Waited for schema agreement, still {totalVersions} schema versions in the cluster.");
}
catch (Exception ex)
{
//Exceptions are not fatal
Metadata.Logger.Error("There was an exception while trying to retrieve schema versions", ex);
}
return false;
}
/// <summary>
/// Sets the Cassandra version in order to identify how to parse the metadata information
/// </summary>
/// <param name="version"></param>
internal void SetCassandraVersion(Version version)
{
_schemaParser = Configuration.SchemaParserFactory.Create(version, this, GetUdtDefinitionAsync, _schemaParser);
}
internal void SetProductTypeAsDbaas()
{
IsDbaas = true;
}
internal IEnumerable<IConnectionEndPoint> UpdateResolvedContactPoint(IContactPoint contactPoint, IEnumerable<IConnectionEndPoint> endpoints)
{
return _resolvedContactPoints.AddOrUpdate(contactPoint, _ => endpoints, (_, __) => endpoints);
}
}
}
| |
#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.Reflection;
using Microsoft.Identity.Json.Utilities;
#if !HAVE_LINQ
using Microsoft.Identity.Json.Utilities.LinqBridge;
#endif
namespace Microsoft.Identity.Json.Serialization
{
/// <summary>
/// Maps a JSON property to a .NET member or constructor parameter.
/// </summary>
internal class JsonProperty
{
internal Required? _required;
internal bool _hasExplicitDefaultValue;
private object _defaultValue;
private bool _hasGeneratedDefaultValue;
private string _propertyName;
internal bool _skipPropertyNameEscape;
private Type _propertyType;
// use to cache contract during deserialization
internal JsonContract PropertyContract { get; set; }
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
/// <value>The name of the property.</value>
public string PropertyName
{
get => _propertyName;
set
{
_propertyName = value;
_skipPropertyNameEscape = !JavaScriptUtils.ShouldEscapeJavaScriptString(_propertyName, JavaScriptUtils.HtmlCharEscapeFlags);
}
}
/// <summary>
/// Gets or sets the type that declared this property.
/// </summary>
/// <value>The type that declared this property.</value>
public Type DeclaringType { get; set; }
/// <summary>
/// Gets or sets the order of serialization of a member.
/// </summary>
/// <value>The numeric order of serialization.</value>
public int? Order { get; set; }
/// <summary>
/// Gets or sets the name of the underlying member or parameter.
/// </summary>
/// <value>The name of the underlying member or parameter.</value>
public string UnderlyingName { get; set; }
/// <summary>
/// Gets the <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.
/// </summary>
/// <value>The <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.</value>
public IValueProvider ValueProvider { get; set; }
/// <summary>
/// Gets or sets the <see cref="IAttributeProvider"/> for this property.
/// </summary>
/// <value>The <see cref="IAttributeProvider"/> for this property.</value>
public IAttributeProvider AttributeProvider { get; set; }
/// <summary>
/// Gets or sets the type of the property.
/// </summary>
/// <value>The type of the property.</value>
public Type PropertyType
{
get => _propertyType;
set
{
if (_propertyType != value)
{
_propertyType = value;
_hasGeneratedDefaultValue = false;
}
}
}
/// <summary>
/// Gets or sets the <see cref="JsonConverter" /> for the property.
/// If set this converter takes precedence over the contract converter for the property type.
/// </summary>
/// <value>The converter.</value>
public JsonConverter Converter { get; set; }
/// <summary>
/// Gets or sets the member converter.
/// </summary>
/// <value>The member converter.</value>
[Obsolete("MemberConverter is obsolete. Use Converter instead.")]
public JsonConverter MemberConverter
{
get => Converter;
set => Converter = value;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is ignored.
/// </summary>
/// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value>
public bool Ignored { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is readable.
/// </summary>
/// <value><c>true</c> if readable; otherwise, <c>false</c>.</value>
public bool Readable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is writable.
/// </summary>
/// <value><c>true</c> if writable; otherwise, <c>false</c>.</value>
public bool Writable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> has a member attribute.
/// </summary>
/// <value><c>true</c> if has a member attribute; otherwise, <c>false</c>.</value>
public bool HasMemberAttribute { get; set; }
/// <summary>
/// Gets the default value.
/// </summary>
/// <value>The default value.</value>
public object DefaultValue
{
get
{
if (!_hasExplicitDefaultValue)
{
return null;
}
return _defaultValue;
}
set
{
_hasExplicitDefaultValue = true;
_defaultValue = value;
}
}
internal object GetResolvedDefaultValue()
{
if (_propertyType == null)
{
return null;
}
if (!_hasExplicitDefaultValue && !_hasGeneratedDefaultValue)
{
_defaultValue = ReflectionUtils.GetDefaultValue(PropertyType);
_hasGeneratedDefaultValue = true;
}
return _defaultValue;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JsonProperty"/> is required.
/// </summary>
/// <value>A value indicating whether this <see cref="JsonProperty"/> is required.</value>
public Required Required
{
get => _required ?? Required.Default;
set => _required = value;
}
/// <summary>
/// Gets or sets a value indicating whether this property preserves object references.
/// </summary>
/// <value>
/// <c>true</c> if this instance is reference; otherwise, <c>false</c>.
/// </value>
public bool? IsReference { get; set; }
/// <summary>
/// Gets or sets the property null value handling.
/// </summary>
/// <value>The null value handling.</value>
public NullValueHandling? NullValueHandling { get; set; }
/// <summary>
/// Gets or sets the property default value handling.
/// </summary>
/// <value>The default value handling.</value>
public DefaultValueHandling? DefaultValueHandling { get; set; }
/// <summary>
/// Gets or sets the property reference loop handling.
/// </summary>
/// <value>The reference loop handling.</value>
public ReferenceLoopHandling? ReferenceLoopHandling { get; set; }
/// <summary>
/// Gets or sets the property object creation handling.
/// </summary>
/// <value>The object creation handling.</value>
public ObjectCreationHandling? ObjectCreationHandling { get; set; }
/// <summary>
/// Gets or sets or sets the type name handling.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling? TypeNameHandling { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialized.</value>
public Predicate<object> ShouldSerialize { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be deserialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be deserialized.</value>
public Predicate<object> ShouldDeserialize { get; set; }
/// <summary>
/// Gets or sets a predicate used to determine whether the property should be serialized.
/// </summary>
/// <value>A predicate used to determine whether the property should be serialized.</value>
public Predicate<object> GetIsSpecified { get; set; }
/// <summary>
/// Gets or sets an action used to set whether the property has been deserialized.
/// </summary>
/// <value>An action used to set whether the property has been deserialized.</value>
public Action<object, object> SetIsSpecified { get; set; }
/// <summary>
/// Returns a <see cref="string"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents this instance.
/// </returns>
public override string ToString()
{
return PropertyName;
}
/// <summary>
/// Gets or sets the converter used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items converter.</value>
public JsonConverter ItemConverter { get; set; }
/// <summary>
/// Gets or sets whether this property's collection items are serialized as a reference.
/// </summary>
/// <value>Whether this property's collection items are serialized as a reference.</value>
public bool? ItemIsReference { get; set; }
/// <summary>
/// Gets or sets the type name handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items type name handling.</value>
public TypeNameHandling? ItemTypeNameHandling { get; set; }
/// <summary>
/// Gets or sets the reference loop handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items reference loop handling.</value>
public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; }
internal void WritePropertyName(JsonWriter writer)
{
if (_skipPropertyNameEscape)
{
writer.WritePropertyName(PropertyName, false);
}
else
{
writer.WritePropertyName(PropertyName);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime;
using System.Diagnostics;
namespace System.Text
{
public sealed class EncoderReplacementFallback : EncoderFallback
{
// Our variables
private string _strDefault;
// Construction. Default replacement fallback uses no best fit and ? replacement string
public EncoderReplacementFallback() : this("?")
{
}
public EncoderReplacementFallback(string replacement)
{
// Must not be null
if (replacement == null)
throw new ArgumentNullException(nameof(replacement));
// Make sure it doesn't have bad surrogate pairs
bool bFoundHigh = false;
for (int i = 0; i < replacement.Length; i++)
{
// Found a surrogate?
if (char.IsSurrogate(replacement, i))
{
// High or Low?
if (char.IsHighSurrogate(replacement, i))
{
// if already had a high one, stop
if (bFoundHigh)
break; // break & throw at the bFoundHIgh below
bFoundHigh = true;
}
else
{
// Low, did we have a high?
if (!bFoundHigh)
{
// Didn't have one, make if fail when we stop
bFoundHigh = true;
break;
}
// Clear flag
bFoundHigh = false;
}
}
// If last was high we're in trouble (not surrogate so not low surrogate, so break)
else if (bFoundHigh)
break;
}
if (bFoundHigh)
throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequenceNoIndex, nameof(replacement)));
_strDefault = replacement;
}
public string DefaultString
{
get
{
return _strDefault;
}
}
public override EncoderFallbackBuffer CreateFallbackBuffer()
{
return new EncoderReplacementFallbackBuffer(this);
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return _strDefault.Length;
}
}
public override bool Equals(object? value)
{
if (value is EncoderReplacementFallback that)
{
return _strDefault == that._strDefault;
}
return false;
}
public override int GetHashCode()
{
return _strDefault.GetHashCode();
}
}
public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer
{
// Store our default string
private string _strDefault;
private int _fallbackCount = -1;
private int _fallbackIndex = -1;
// Construction
public EncoderReplacementFallbackBuffer(EncoderReplacementFallback fallback)
{
// 2X in case we're a surrogate pair
_strDefault = fallback.DefaultString + fallback.DefaultString;
}
// Fallback Methods
public override bool Fallback(char charUnknown, int index)
{
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
if (_fallbackCount >= 1)
{
// If we're recursive we may still have something in our buffer that makes this a surrogate
if (char.IsHighSurrogate(charUnknown) && _fallbackCount >= 0 &&
char.IsLowSurrogate(_strDefault[_fallbackIndex + 1]))
ThrowLastCharRecursive(char.ConvertToUtf32(charUnknown, _strDefault[_fallbackIndex + 1]));
// Nope, just one character
ThrowLastCharRecursive(unchecked((int)charUnknown));
}
// Go ahead and get our fallback
// Divide by 2 because we aren't a surrogate pair
_fallbackCount = _strDefault.Length / 2;
_fallbackIndex = -1;
return _fallbackCount != 0;
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
{
// Double check input surrogate pair
if (!char.IsHighSurrogate(charUnknownHigh))
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF));
if (!char.IsLowSurrogate(charUnknownLow))
throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF));
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
// character in our array.
if (_fallbackCount >= 1)
ThrowLastCharRecursive(char.ConvertToUtf32(charUnknownHigh, charUnknownLow));
// Go ahead and get our fallback
_fallbackCount = _strDefault.Length;
_fallbackIndex = -1;
return _fallbackCount != 0;
}
public override char GetNextChar()
{
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
_fallbackCount--;
_fallbackIndex++;
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (_fallbackCount < 0)
return '\0';
// Need to get it out of the buffer.
// Make sure it didn't wrap from the fast count-- path
if (_fallbackCount == int.MaxValue)
{
_fallbackCount = -1;
return '\0';
}
// Now make sure its in the expected range
Debug.Assert(_fallbackIndex < _strDefault.Length && _fallbackIndex >= 0,
"Index exceeds buffer range");
return _strDefault[_fallbackIndex];
}
public override bool MovePrevious()
{
// Back up one, only if we just processed the last character (or earlier)
if (_fallbackCount >= -1 && _fallbackIndex >= 0)
{
_fallbackIndex--;
_fallbackCount++;
return true;
}
// Return false 'cause we couldn't do it.
return false;
}
// How many characters left to output?
public override int Remaining
{
get
{
// Our count is 0 for 1 character left.
return (_fallbackCount < 0) ? 0 : _fallbackCount;
}
}
// Clear the buffer
public override unsafe void Reset()
{
_fallbackCount = -1;
_fallbackIndex = 0;
charStart = null;
bFallingBack = false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Benjamin.React.MVC.Areas.HelpPage.ModelDescriptions;
using Benjamin.React.MVC.Areas.HelpPage.Models;
namespace Benjamin.React.MVC.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
var modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
var apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
var apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
var apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
var modelGenerator = config.GetModelDescriptionGenerator();
var sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
var apiDescription = apiModel.ApiDescription;
foreach (var apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
var parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (var uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
var uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
var defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
var modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
var parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
var apiDescription = apiModel.ApiDescription;
foreach (var apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
var parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
var parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
var response = apiModel.ApiDescription.ResponseDescription;
var responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
var sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
var modelGenerator = new ModelDescriptionGenerator(config);
var apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (var api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
var invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Nether.Web.Features.Analytics;
using Nether.Web.Features.Identity;
using Nether.Web.Features.Leaderboard;
using Nether.Web.Features.PlayerManagement;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using Microsoft.Extensions.PlatformAbstractions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Nether.Web.Utilities;
using Swashbuckle.AspNetCore.Swagger;
using IdentityServer4;
using System.Linq;
using IdentityServer4.Models;
namespace Nether.Web
{
public class Startup
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly ILogger _logger;
public Startup(IHostingEnvironment env, ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<Startup>();
_hostingEnvironment = env;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
loggerFactory.AddTrace(LogLevel.Information);
loggerFactory.AddAzureWebAppDiagnostics(); // docs: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging#appservice
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
// Add framework services.
services
.AddMvc(options =>
{
options.Conventions.Add(new FeatureConvention());
options.Filters.AddService(typeof(ExceptionLoggingFilterAttribute));
})
.AddRazorOptions(options =>
{
// {0} - Action Name
// {1} - Controller Name
// {2} - Area Name
// {3} - Feature Name
options.AreaViewLocationFormats.Clear();
options.AreaViewLocationFormats.Add("/Areas/{2}/Features/{3}/Views/{1}/{0}.cshtml");
options.AreaViewLocationFormats.Add("/Areas/{2}/Features/{3}/Views/{0}.cshtml");
options.AreaViewLocationFormats.Add("/Areas/{2}/Features/Views/Shared/{0}.cshtml");
options.AreaViewLocationFormats.Add("/Areas/Shared/{0}.cshtml");
// replace normal view location entirely
options.ViewLocationFormats.Clear();
options.ViewLocationFormats.Add("/Features/{3}/Views/{1}/{0}.cshtml");
options.ViewLocationFormats.Add("/Features/{3}/Views/Shared/{0}.cshtml");
options.ViewLocationFormats.Add("/Features/{3}/Views/{0}.cshtml");
options.ViewLocationFormats.Add("/Features/Views/Shared/{0}.cshtml");
options.ViewLocationExpanders.Add(new FeatureViewLocationExpander());
})
.AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter
{
CamelCaseText = true
});
});
services.AddCors();
services.ConfigureSwaggerGen(options =>
{
string commentsPath = Path.Combine(
PlatformServices.Default.Application.ApplicationBasePath,
"Nether.Web.xml");
options.IncludeXmlComments(commentsPath);
});
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v0.1", new Info
{
Version = "v0.1",
Title = "Project Nether",
License = new License
{
Name = "MIT",
Url = "https://github.com/MicrosoftDX/nether/blob/master/LICENSE"
}
});
//options.OperationFilter<ApiPrefixFilter>();
options.CustomSchemaIds(type => type.FullName);
options.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = "/identity/connect/authorize",
Scopes = new Dictionary<string, string>
{
{ "nether-all", "nether API access" },
}
});
options.OperationFilter<SecurityRequirementsOperationFilter>();
});
services.AddSingleton<ExceptionLoggingFilterAttribute>();
// TODO make this conditional with feature switches
services.AddIdentityServices(Configuration, _logger, _hostingEnvironment);
services.AddLeaderboardServices(Configuration, _logger);
services.AddPlayerManagementServices(Configuration, _logger);
services.AddAnalyticsServices(Configuration, _logger);
services.AddAuthorization(options =>
{
options.AddPolicy(
PolicyName.NetherIdentityClientId,
policy => policy.RequireClaim(
"client_id",
"nether-identity"
));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger<Startup>();
app.EnsureInitialAdminUser(Configuration, logger);
// Set up separate web pipelines for identity, MVC UI, and API
// as they each have different auth requirements!
app.Map("/identity", idapp =>
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
idapp.UseIdentityServer();
idapp.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
AutomaticAuthenticate = false,
AutomaticChallenge = false
});
var facebookEnabled = bool.Parse(Configuration["Identity:SignInMethods:Facebook:Enabled"] ?? "false");
if (facebookEnabled)
{
var appId = Configuration["Identity:SignInMethods:Facebook:AppId"];
var appSecret = Configuration["Identity:SignInMethods:Facebook:AppSecret"];
idapp.UseFacebookAuthentication(new FacebookOptions()
{
DisplayName = "Facebook",
SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
CallbackPath = "/signin-facebook",
AppId = appId,
AppSecret = appSecret
});
}
idapp.UseStaticFiles();
idapp.UseMvc(routes =>
{
routes.MapRoute(
name: "account",
template: "account/{action}",
defaults: new { controller = "Account" });
});
});
app.Map("/api", apiapp =>
{
apiapp.UseCors(options =>
{
logger.LogInformation("CORS options:");
var config = Configuration.GetSection("Common:Cors");
var allowedOrigins = config.ParseStringArray("AllowedOrigins").ToArray();
logger.LogInformation("AllowedOrigins: {0}", string.Join(",", allowedOrigins));
options.WithOrigins(allowedOrigins);
// TODO - allow configuration of headers/methods
options
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var idsvrConfig = Configuration.GetSection("Identity:IdentityServer");
string authority = idsvrConfig["Authority"];
bool requireHttps = idsvrConfig.GetValue("RequireHttps", true);
apiapp.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = authority,
RequireHttpsMetadata = requireHttps,
ApiName = "nether-all",
AllowedScopes = { "nether-all" },
});
// TODO filter which routes this matches (i.e. only API routes)
apiapp.UseMvc();
apiapp.UseSwagger(options =>
{
options.RouteTemplate = "swagger/{documentName}/swagger.json";
});
apiapp.UseSwaggerUi(options =>
{
options.RoutePrefix = "swagger/ui";
options.SwaggerEndpoint("/api/swagger/v0.1/swagger.json", "v0.1 Docs");
options.ConfigureOAuth2("swaggerui", "swaggeruisecret".Sha256(), "swagger-ui-realm", "Swagger UI");
});
});
app.Map("/ui", uiapp =>
{
uiapp.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies"
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var authority = Configuration["Identity:IdentityServer:Authority"];
var uiBaseUrl = Configuration["Identity:IdentityServer:UiBaseUrl"];
// hybrid
uiapp.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
SignInScheme = "Cookies",
Authority = authority,
RequireHttpsMetadata = false,
PostLogoutRedirectUri = uiBaseUrl,
ClientId = "mvc2",
ClientSecret = "secret",
ResponseType = "code id_token",
Scope = { "api1", "offline_access" },
GetClaimsFromUserInfoEndpoint = true,
SaveTokens = true
});
uiapp.UseDefaultFiles();
uiapp.UseStaticFiles();
uiapp.UseMvc(); // TODO filter which routes this matches (i.e. only non-API routes)
});
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G11_City_Child (editable child object).<br/>
/// This is a generated base class of <see cref="G11_City_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="G10_City"/> collection.
/// </remarks>
[Serializable]
public partial class G11_City_Child : BusinessBase<G11_City_Child>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name");
/// <summary>
/// Gets or sets the CityRoads Child Name.
/// </summary>
/// <value>The CityRoads Child Name.</value>
public string City_Child_Name
{
get { return GetProperty(City_Child_NameProperty); }
set { SetProperty(City_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G11_City_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G11_City_Child"/> object.</returns>
internal static G11_City_Child NewG11_City_Child()
{
return DataPortal.CreateChild<G11_City_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="G11_City_Child"/> object, based on given parameters.
/// </summary>
/// <param name="city_ID1">The City_ID1 parameter of the G11_City_Child to fetch.</param>
/// <returns>A reference to the fetched <see cref="G11_City_Child"/> object.</returns>
internal static G11_City_Child GetG11_City_Child(int city_ID1)
{
return DataPortal.FetchChild<G11_City_Child>(city_ID1);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G11_City_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G11_City_Child()
{
// 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="G11_City_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G11_City_Child"/> object from the database, based on given criteria.
/// </summary>
/// <param name="city_ID1">The City ID1.</param>
protected void Child_Fetch(int city_ID1)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetG11_City_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID1", city_ID1).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, city_ID1);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="G11_City_Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(City_Child_NameProperty, dr.GetString("City_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="G11_City_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G10_City parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddG11_City_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G11_City_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(G10_City parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateG11_City_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="G11_City_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(G10_City parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteG11_City_Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
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
}
}
| |
/*
* Vericred API
*
* Vericred's API allows you to search for Health Plans that a specific doctor
accepts.
## Getting Started
Visit our [Developer Portal](https://developers.vericred.com) to
create an account.
Once you have created an account, you can create one Application for
Production and another for our Sandbox (select the appropriate Plan when
you create the Application).
## SDKs
Our API follows standard REST conventions, so you can use any HTTP client
to integrate with us. You will likely find it easier to use one of our
[autogenerated SDKs](https://github.com/vericred/?query=vericred-),
which we make available for several common programming languages.
## Authentication
To authenticate, pass the API Key you created in the Developer Portal as
a `Vericred-Api-Key` header.
`curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Versioning
Vericred's API default to the latest version. However, if you need a specific
version, you can request it with an `Accept-Version` header.
The current version is `v3`. Previous versions are `v1` and `v2`.
`curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Pagination
Endpoints that accept `page` and `per_page` parameters are paginated. They expose
four additional fields that contain data about your position in the response,
namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988).
For example, to display 5 results per page and view the second page of a
`GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`.
## Sideloading
When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s
we sideload the associated data. In this example, we would provide an Array of
`State`s and a `state_id` for each provider. This is done primarily to reduce the
payload size since many of the `Provider`s will share a `State`
```
{
providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }],
states: [{ id: 1, code: 'NY' }]
}
```
If you need the second level of the object graph, you can just match the
corresponding id.
## Selecting specific data
All endpoints allow you to specify which fields you would like to return.
This allows you to limit the response to contain only the data you need.
For example, let's take a request that returns the following JSON by default
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890',
field_we_dont_care_about: 'value_we_dont_care_about'
},
states: [{
id: 1,
name: 'New York',
code: 'NY',
field_we_dont_care_about: 'value_we_dont_care_about'
}]
}
```
To limit our results to only return the fields we care about, we specify the
`select` query string parameter for the corresponding fields in the JSON
document.
In this case, we want to select `name` and `phone` from the `provider` key,
so we would add the parameters `select=provider.name,provider.phone`.
We also want the `name` and `code` from the `states` key, so we would
add the parameters `select=states.name,staes.code`. The id field of
each document is always returned whether or not it is requested.
Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code`
The response would be
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890'
},
states: [{
id: 1,
name: 'New York',
code: 'NY'
}]
}
```
## Benefits summary format
Benefit cost-share strings are formatted to capture:
* Network tiers
* Compound or conditional cost-share
* Limits on the cost-share
* Benefit-specific maximum out-of-pocket costs
**Example #1**
As an example, we would represent [this Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as:
* **Hospital stay facility fees**:
- Network Provider: `$400 copay/admit plus 20% coinsurance`
- Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance`
- Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible`
* **Rehabilitation services:**
- Network Provider: `20% coinsurance`
- Out-of-Network Provider: `50% coinsurance`
- Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.`
- Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period`
**Example #2**
In [this other Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies.
* **Specialty drugs:**
- Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply`
- Out-of-Network Provider `Not covered`
- Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%`
**BNF**
Here's a description of the benefits summary string, represented as a context-free grammar:
```
<cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit>
<tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:"
<opt-num-prefix> ::= "first" <num> <unit> | ""
<unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)"
<value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable"
<compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible>
<copay> ::= "$" <num>
<coinsurace> ::= <num> "%"
<ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited"
<opt-per-unit> ::= "per day" | "per visit" | "per stay" | ""
<deductible> ::= "before deductible" | "after deductible" | ""
<tier-limit> ::= ", " <limit> | ""
<benefit-limit> ::= <limit> | ""
```
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace IO.Vericred.Model
{
/// <summary>
/// PlanSearchResponse
/// </summary>
[DataContract]
public partial class PlanSearchResponse : IEquatable<PlanSearchResponse>
{
/// <summary>
/// Initializes a new instance of the <see cref="PlanSearchResponse" /> class.
/// </summary>
/// <param name="Meta">Meta-data.</param>
/// <param name="Plans">Plan search results.</param>
/// <param name="Coverages">Coverages associated with the plan..</param>
public PlanSearchResponse(Meta Meta = null, List<Plan> Plans = null, List<DrugCoverage> Coverages = null)
{
this.Meta = Meta;
this.Plans = Plans;
this.Coverages = Coverages;
}
/// <summary>
/// Meta-data
/// </summary>
/// <value>Meta-data</value>
[DataMember(Name="meta", EmitDefaultValue=false)]
public Meta Meta { get; set; }
/// <summary>
/// Plan search results
/// </summary>
/// <value>Plan search results</value>
[DataMember(Name="plans", EmitDefaultValue=false)]
public List<Plan> Plans { get; set; }
/// <summary>
/// Coverages associated with the plan.
/// </summary>
/// <value>Coverages associated with the plan.</value>
[DataMember(Name="coverages", EmitDefaultValue=false)]
public List<DrugCoverage> Coverages { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PlanSearchResponse {\n");
sb.Append(" Meta: ").Append(Meta).Append("\n");
sb.Append(" Plans: ").Append(Plans).Append("\n");
sb.Append(" Coverages: ").Append(Coverages).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as PlanSearchResponse);
}
/// <summary>
/// Returns true if PlanSearchResponse instances are equal
/// </summary>
/// <param name="other">Instance of PlanSearchResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PlanSearchResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Meta == other.Meta ||
this.Meta != null &&
this.Meta.Equals(other.Meta)
) &&
(
this.Plans == other.Plans ||
this.Plans != null &&
this.Plans.SequenceEqual(other.Plans)
) &&
(
this.Coverages == other.Coverages ||
this.Coverages != null &&
this.Coverages.SequenceEqual(other.Coverages)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Meta != null)
hash = hash * 59 + this.Meta.GetHashCode();
if (this.Plans != null)
hash = hash * 59 + this.Plans.GetHashCode();
if (this.Coverages != null)
hash = hash * 59 + this.Coverages.GetHashCode();
return hash;
}
}
}
}
| |
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8
#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.IO;
using System.Xml;
using System.Globalization;
namespace Newtonsoft.Json.Utilities
{
internal static class DateTimeUtils
{
internal static readonly long InitialJavaScriptDateTicks = 621355968000000000;
private const int DaysPer100Years = 36524;
private const int DaysPer400Years = 146097;
private const int DaysPer4Years = 1461;
private const int DaysPerYear = 365;
private const long TicksPerDay = 864000000000L;
private static readonly int[] DaysToMonth365;
private static readonly int[] DaysToMonth366;
static DateTimeUtils()
{
DaysToMonth365 = new[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
DaysToMonth366 = new[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 };
}
public static TimeSpan GetUtcOffset(this DateTime d)
{
return TimeZoneInfo.Local.GetUtcOffset(d);
}
internal static DateTime EnsureDateTime(DateTime value, DateTimeZoneHandling timeZone)
{
switch (timeZone)
{
case DateTimeZoneHandling.Local:
value = SwitchToLocalTime(value);
break;
case DateTimeZoneHandling.Utc:
value = SwitchToUtcTime(value);
break;
case DateTimeZoneHandling.Unspecified:
value = new DateTime(value.Ticks, DateTimeKind.Unspecified);
break;
case DateTimeZoneHandling.RoundtripKind:
break;
default:
throw new ArgumentException("Invalid date time handling value.");
}
return value;
}
private static DateTime SwitchToLocalTime(DateTime value)
{
switch (value.Kind)
{
case DateTimeKind.Unspecified:
return new DateTime(value.Ticks, DateTimeKind.Local);
case DateTimeKind.Utc:
return value.ToLocalTime();
case DateTimeKind.Local:
return value;
}
return value;
}
private static DateTime SwitchToUtcTime(DateTime value)
{
switch (value.Kind)
{
case DateTimeKind.Unspecified:
return new DateTime(value.Ticks, DateTimeKind.Utc);
case DateTimeKind.Utc:
return value;
case DateTimeKind.Local:
return value.ToUniversalTime();
}
return value;
}
private static long ToUniversalTicks(DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Utc)
return dateTime.Ticks;
return ToUniversalTicks(dateTime, dateTime.GetUtcOffset());
}
private static long ToUniversalTicks(DateTime dateTime, TimeSpan offset)
{
// special case min and max value
// they never have a timezone appended to avoid issues
if (dateTime.Kind == DateTimeKind.Utc || dateTime == DateTime.MaxValue || dateTime == DateTime.MinValue)
return dateTime.Ticks;
long ticks = dateTime.Ticks - offset.Ticks;
if (ticks > 3155378975999999999L)
return 3155378975999999999L;
if (ticks < 0L)
return 0L;
return ticks;
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, TimeSpan offset)
{
long universialTicks = ToUniversalTicks(dateTime, offset);
return UniversialTicksToJavaScriptTicks(universialTicks);
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime)
{
return ConvertDateTimeToJavaScriptTicks(dateTime, true);
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, bool convertToUtc)
{
long ticks = (convertToUtc) ? ToUniversalTicks(dateTime) : dateTime.Ticks;
return UniversialTicksToJavaScriptTicks(ticks);
}
private static long UniversialTicksToJavaScriptTicks(long universialTicks)
{
long javaScriptTicks = (universialTicks - InitialJavaScriptDateTicks)/10000;
return javaScriptTicks;
}
internal static DateTime ConvertJavaScriptTicksToDateTime(long javaScriptTicks)
{
DateTime dateTime = new DateTime((javaScriptTicks*10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc);
return dateTime;
}
#region Parse
internal static bool TryParseDateIso(string text, DateParseHandling dateParseHandling, DateTimeZoneHandling dateTimeZoneHandling, out object dt)
{
DateTimeParser dateTimeParser = new DateTimeParser();
if (!dateTimeParser.Parse(text))
{
dt = null;
return false;
}
DateTime d = new DateTime(dateTimeParser.Year, dateTimeParser.Month, dateTimeParser.Day, dateTimeParser.Hour, dateTimeParser.Minute, dateTimeParser.Second);
d = d.AddTicks(dateTimeParser.Fraction);
if (dateParseHandling == DateParseHandling.DateTimeOffset)
{
TimeSpan offset;
switch (dateTimeParser.Zone)
{
case ParserTimeZone.Utc:
offset = new TimeSpan(0L);
break;
case ParserTimeZone.LocalWestOfUtc:
offset = new TimeSpan(-dateTimeParser.ZoneHour, -dateTimeParser.ZoneMinute, 0);
break;
case ParserTimeZone.LocalEastOfUtc:
offset = new TimeSpan(dateTimeParser.ZoneHour, dateTimeParser.ZoneMinute, 0);
break;
default:
offset = TimeZoneInfo.Local.GetUtcOffset(d);
break;
}
long ticks = d.Ticks - offset.Ticks;
if (ticks < 0 || ticks > 3155378975999999999)
{
dt = null;
return false;
}
dt = new DateTimeOffset(d, offset);
return true;
}
else
{
long ticks;
switch (dateTimeParser.Zone)
{
case ParserTimeZone.Utc:
d = new DateTime(d.Ticks, DateTimeKind.Utc);
break;
case ParserTimeZone.LocalWestOfUtc:
{
TimeSpan offset = new TimeSpan(dateTimeParser.ZoneHour, dateTimeParser.ZoneMinute, 0);
ticks = d.Ticks + offset.Ticks;
if (ticks <= DateTime.MaxValue.Ticks)
{
d = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
}
else
{
ticks += d.GetUtcOffset().Ticks;
if (ticks > DateTime.MaxValue.Ticks)
ticks = DateTime.MaxValue.Ticks;
d = new DateTime(ticks, DateTimeKind.Local);
}
break;
}
case ParserTimeZone.LocalEastOfUtc:
{
TimeSpan offset = new TimeSpan(dateTimeParser.ZoneHour, dateTimeParser.ZoneMinute, 0);
ticks = d.Ticks - offset.Ticks;
if (ticks >= DateTime.MinValue.Ticks)
{
d = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime();
}
else
{
ticks += d.GetUtcOffset().Ticks;
if (ticks < DateTime.MinValue.Ticks)
ticks = DateTime.MinValue.Ticks;
d = new DateTime(ticks, DateTimeKind.Local);
}
break;
}
}
dt = EnsureDateTime(d, dateTimeZoneHandling);
return true;
}
}
internal static bool TryParseDateTime(string s, DateParseHandling dateParseHandling, DateTimeZoneHandling dateTimeZoneHandling, out object dt)
{
if (s.Length > 0)
{
if (s[0] == '/')
{
if (s.StartsWith("/Date(", StringComparison.Ordinal) && s.EndsWith(")/", StringComparison.Ordinal))
{
return TryParseDateMicrosoft(s, dateParseHandling, dateTimeZoneHandling, out dt);
}
}
else if (s.Length >= 19 && s.Length <= 40 && char.IsDigit(s[0]) && s[10] == 'T')
{
return TryParseDateIso(s, dateParseHandling, dateTimeZoneHandling, out dt);
}
}
dt = null;
return false;
}
private static bool TryParseDateMicrosoft(string text, DateParseHandling dateParseHandling, DateTimeZoneHandling dateTimeZoneHandling, out object dt)
{
string value = text.Substring(6, text.Length - 8);
DateTimeKind kind = DateTimeKind.Utc;
int index = value.IndexOf('+', 1);
if (index == -1)
index = value.IndexOf('-', 1);
TimeSpan offset = TimeSpan.Zero;
if (index != -1)
{
kind = DateTimeKind.Local;
offset = ReadOffset(value.Substring(index));
value = value.Substring(0, index);
}
long javaScriptTicks = long.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture);
DateTime utcDateTime = ConvertJavaScriptTicksToDateTime(javaScriptTicks);
if (dateParseHandling == DateParseHandling.DateTimeOffset)
{
dt = new DateTimeOffset(utcDateTime.Add(offset).Ticks, offset);
return true;
}
else
{
DateTime dateTime;
switch (kind)
{
case DateTimeKind.Unspecified:
dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified);
break;
case DateTimeKind.Local:
dateTime = utcDateTime.ToLocalTime();
break;
default:
dateTime = utcDateTime;
break;
}
dt = EnsureDateTime(dateTime, dateTimeZoneHandling);
return true;
}
}
private static TimeSpan ReadOffset(string offsetText)
{
bool negative = (offsetText[0] == '-');
int hours = int.Parse(offsetText.Substring(1, 2), NumberStyles.Integer, CultureInfo.InvariantCulture);
int minutes = 0;
if (offsetText.Length >= 5)
minutes = int.Parse(offsetText.Substring(3, 2), NumberStyles.Integer, CultureInfo.InvariantCulture);
TimeSpan offset = TimeSpan.FromHours(hours) + TimeSpan.FromMinutes(minutes);
if (negative)
offset = offset.Negate();
return offset;
}
#endregion
#region Write
internal static void WriteDateTimeString(TextWriter writer, DateTime value, DateFormatHandling format, string formatString, CultureInfo culture)
{
if (string.IsNullOrEmpty(formatString))
{
char[] chars = new char[64];
int pos = WriteDateTimeString(chars, 0, value, null, value.Kind, format);
writer.Write(chars, 0, pos);
}
else
{
writer.Write(value.ToString(formatString, culture));
}
}
internal static int WriteDateTimeString(char[] chars, int start, DateTime value, TimeSpan? offset, DateTimeKind kind, DateFormatHandling format)
{
int pos = start;
if (format == DateFormatHandling.MicrosoftDateFormat)
{
TimeSpan o = offset ?? value.GetUtcOffset();
long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value, o);
@"\/Date(".CopyTo(0, chars, pos, 7);
pos += 7;
string ticksText = javaScriptTicks.ToString(CultureInfo.InvariantCulture);
ticksText.CopyTo(0, chars, pos, ticksText.Length);
pos += ticksText.Length;
switch (kind)
{
case DateTimeKind.Unspecified:
if (value != DateTime.MaxValue && value != DateTime.MinValue)
pos = WriteDateTimeOffset(chars, pos, o, format);
break;
case DateTimeKind.Local:
pos = WriteDateTimeOffset(chars, pos, o, format);
break;
}
@")\/".CopyTo(0, chars, pos, 3);
pos += 3;
}
else
{
pos = WriteDefaultIsoDate(chars, pos, value);
switch (kind)
{
case DateTimeKind.Local:
pos = WriteDateTimeOffset(chars, pos, offset ?? value.GetUtcOffset(), format);
break;
case DateTimeKind.Utc:
chars[pos++] = 'Z';
break;
}
}
return pos;
}
internal static int WriteDefaultIsoDate(char[] chars, int start, DateTime dt)
{
int length = 19;
int year;
int month;
int day;
GetDateValues(dt, out year, out month, out day);
CopyIntToCharArray(chars, start, year, 4);
chars[start + 4] = '-';
CopyIntToCharArray(chars, start + 5, month, 2);
chars[start + 7] = '-';
CopyIntToCharArray(chars, start + 8, day, 2);
chars[start + 10] = 'T';
CopyIntToCharArray(chars, start + 11, dt.Hour, 2);
chars[start + 13] = ':';
CopyIntToCharArray(chars, start + 14, dt.Minute, 2);
chars[start + 16] = ':';
CopyIntToCharArray(chars, start + 17, dt.Second, 2);
int fraction = (int)(dt.Ticks % 10000000L);
if (fraction != 0)
{
int digits = 7;
while ((fraction%10) == 0)
{
digits--;
fraction /= 10;
}
chars[start + 19] = '.';
CopyIntToCharArray(chars, start + 20, fraction, digits);
length += digits + 1;
}
return start + length;
}
private static void CopyIntToCharArray(char[] chars, int start, int value, int digits)
{
while (digits-- != 0)
{
chars[start + digits] = (char) ((value%10) + 48);
value /= 10;
}
}
internal static int WriteDateTimeOffset(char[] chars, int start, TimeSpan offset, DateFormatHandling format)
{
chars[start++] = (offset.Ticks >= 0L) ? '+' : '-';
int absHours = Math.Abs(offset.Hours);
CopyIntToCharArray(chars, start, absHours, 2);
start += 2;
if (format == DateFormatHandling.IsoDateFormat)
chars[start++] = ':';
int absMinutes = Math.Abs(offset.Minutes);
CopyIntToCharArray(chars, start, absMinutes, 2);
start += 2;
return start;
}
internal static void WriteDateTimeOffsetString(TextWriter writer, DateTimeOffset value, DateFormatHandling format, string formatString, CultureInfo culture)
{
if (string.IsNullOrEmpty(formatString))
{
char[] chars = new char[64];
int pos = WriteDateTimeString(chars, 0, (format == DateFormatHandling.IsoDateFormat) ? value.DateTime : value.UtcDateTime, value.Offset, DateTimeKind.Local, format);
writer.Write(chars, 0, pos);
}
else
{
writer.Write(value.ToString(formatString, culture));
}
}
#endregion
private static void GetDateValues(DateTime td, out int year, out int month, out int day)
{
long ticks = td.Ticks;
// n = number of days since 1/1/0001
int n = (int) (ticks/TicksPerDay);
// y400 = number of whole 400-year periods since 1/1/0001
int y400 = n/DaysPer400Years;
// n = day number within 400-year period
n -= y400*DaysPer400Years;
// y100 = number of whole 100-year periods within 400-year period
int y100 = n/DaysPer100Years;
// Last 100-year period has an extra day, so decrement result if 4
if (y100 == 4)
y100 = 3;
// n = day number within 100-year period
n -= y100*DaysPer100Years;
// y4 = number of whole 4-year periods within 100-year period
int y4 = n/DaysPer4Years;
// n = day number within 4-year period
n -= y4*DaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n/DaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4)
y1 = 3;
year = y400*400 + y100*100 + y4*4 + y1 + 1;
// n = day number within year
n -= y1*DaysPerYear;
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = y1 == 3 && (y4 != 24 || y100 == 3);
int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = n >> 5 + 1;
// m = 1-based month number
while (n >= days[m])
{
m++;
}
month = m;
// Return 1-based day-of-month
day = n - days[m - 1] + 1;
}
}
}
#endif
| |
using System;
using System.Collections;
using System.IO;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
{
[TestFixture]
public class PgpKeyRingTest
: SimpleTest
{
private static readonly byte[] pub1 = Base64.Decode(
"mQGiBEA83v0RBADzKVLVCnpWQxX0LCsevw/3OLs0H7MOcLBQ4wMO9sYmzGYn"
+ "xpVj+4e4PiCP7QBayWyy4lugL6Lnw7tESvq3A4v3fefcxaCTkJrryiKn4+Cg"
+ "y5rIBbrSKNtCEhVi7xjtdnDjP5kFKgHYjVOeIKn4Cz/yzPG3qz75kDknldLf"
+ "yHxp2wCgwW1vAE5EnZU4/UmY7l8kTNkMltMEAJP4/uY4zcRwLI9Q2raPqAOJ"
+ "TYLd7h+3k/BxI0gIw96niQ3KmUZDlobbWBI+VHM6H99vcttKU3BgevNf8M9G"
+ "x/AbtW3SS4De64wNSU3189XDG8vXf0vuyW/K6Pcrb8exJWY0E1zZQ1WXT0gZ"
+ "W0kH3g5ro//Tusuil9q2lVLF2ovJA/0W+57bPzi318dWeNs0tTq6Njbc/GTG"
+ "FUAVJ8Ss5v2u6h7gyJ1DB334ExF/UdqZGldp0ugkEXaSwBa2R7d3HBgaYcoP"
+ "Ck1TrovZzEY8gm7JNVy7GW6mdOZuDOHTxyADEEP2JPxh6eRcZbzhGuJuYIif"
+ "IIeLOTI5Dc4XKeV32a+bWrQidGVzdCAoVGVzdCBrZXkpIDx0ZXN0QHViaWNh"
+ "bGwuY29tPohkBBMRAgAkBQJAPN79AhsDBQkB4TOABgsJCAcDAgMVAgMDFgIB"
+ "Ah4BAheAAAoJEJh8Njfhe8KmGDcAoJWr8xgPr75y/Cp1kKn12oCCOb8zAJ4p"
+ "xSvk4K6tB2jYbdeSrmoWBZLdMLACAAC5AQ0EQDzfARAEAJeUAPvUzJJbKcc5"
+ "5Iyb13+Gfb8xBWE3HinQzhGr1v6A1aIZbRj47UPAD/tQxwz8VAwJySx82ggN"
+ "LxCk4jW9YtTL3uZqfczsJngV25GoIN10f4/j2BVqZAaX3q79a3eMiql1T0oE"
+ "AGmD7tO1LkTvWfm3VvA0+t8/6ZeRLEiIqAOHAAQNBACD0mVMlAUgd7REYy/1"
+ "mL99Zlu9XU0uKyUex99sJNrcx1aj8rIiZtWaHz6CN1XptdwpDeSYEOFZ0PSu"
+ "qH9ByM3OfjU/ya0//xdvhwYXupn6P1Kep85efMBA9jUv/DeBOzRWMFG6sC6y"
+ "k8NGG7Swea7EHKeQI40G3jgO/+xANtMyTIhPBBgRAgAPBQJAPN8BAhsMBQkB"
+ "4TOAAAoJEJh8Njfhe8KmG7kAn00mTPGJCWqmskmzgdzeky5fWd7rAKCNCp3u"
+ "ZJhfg0htdgAfIy8ppm05vLACAAA=");
private static readonly byte[] sec1 = Base64.Decode(
"lQHhBEA83v0RBADzKVLVCnpWQxX0LCsevw/3OLs0H7MOcLBQ4wMO9sYmzGYn"
+ "xpVj+4e4PiCP7QBayWyy4lugL6Lnw7tESvq3A4v3fefcxaCTkJrryiKn4+Cg"
+ "y5rIBbrSKNtCEhVi7xjtdnDjP5kFKgHYjVOeIKn4Cz/yzPG3qz75kDknldLf"
+ "yHxp2wCgwW1vAE5EnZU4/UmY7l8kTNkMltMEAJP4/uY4zcRwLI9Q2raPqAOJ"
+ "TYLd7h+3k/BxI0gIw96niQ3KmUZDlobbWBI+VHM6H99vcttKU3BgevNf8M9G"
+ "x/AbtW3SS4De64wNSU3189XDG8vXf0vuyW/K6Pcrb8exJWY0E1zZQ1WXT0gZ"
+ "W0kH3g5ro//Tusuil9q2lVLF2ovJA/0W+57bPzi318dWeNs0tTq6Njbc/GTG"
+ "FUAVJ8Ss5v2u6h7gyJ1DB334ExF/UdqZGldp0ugkEXaSwBa2R7d3HBgaYcoP"
+ "Ck1TrovZzEY8gm7JNVy7GW6mdOZuDOHTxyADEEP2JPxh6eRcZbzhGuJuYIif"
+ "IIeLOTI5Dc4XKeV32a+bWv4CAwJ5KgazImo+sGBfMhDiBcBTqyDGhKHNgHic"
+ "0Pky9FeRvfXTc2AO+jGmFPjcs8BnTWuDD0/jkQnRZpp1TrQidGVzdCAoVGVz"
+ "dCBrZXkpIDx0ZXN0QHViaWNhbGwuY29tPohkBBMRAgAkBQJAPN79AhsDBQkB"
+ "4TOABgsJCAcDAgMVAgMDFgIBAh4BAheAAAoJEJh8Njfhe8KmGDcAn3XeXDMg"
+ "BZgrZzFWU2IKtA/5LG2TAJ0Vf/jjyq0jZNZfGfoqGTvD2MAl0rACAACdAVgE"
+ "QDzfARAEAJeUAPvUzJJbKcc55Iyb13+Gfb8xBWE3HinQzhGr1v6A1aIZbRj4"
+ "7UPAD/tQxwz8VAwJySx82ggNLxCk4jW9YtTL3uZqfczsJngV25GoIN10f4/j"
+ "2BVqZAaX3q79a3eMiql1T0oEAGmD7tO1LkTvWfm3VvA0+t8/6ZeRLEiIqAOH"
+ "AAQNBACD0mVMlAUgd7REYy/1mL99Zlu9XU0uKyUex99sJNrcx1aj8rIiZtWa"
+ "Hz6CN1XptdwpDeSYEOFZ0PSuqH9ByM3OfjU/ya0//xdvhwYXupn6P1Kep85e"
+ "fMBA9jUv/DeBOzRWMFG6sC6yk8NGG7Swea7EHKeQI40G3jgO/+xANtMyTP4C"
+ "AwJ5KgazImo+sGBl2C7CFuI+5KM4ZhbtVie7l+OiTpr5JW2z5VgnV3EX9p04"
+ "LcGKfQvD65+ELwli6yh8B2zGcipqTaYk3QoYNIhPBBgRAgAPBQJAPN8BAhsM"
+ "BQkB4TOAAAoJEJh8Njfhe8KmG7kAniuRkaFFv1pdCBN8JJXpcorHmyouAJ9L"
+ "xxmusffR6OI7WgD3XZ0AL8zUC7ACAAA=");
// private static readonly char[] pass1 = "qwertzuiop".ToCharArray();
private static readonly byte[] pub2 = Base64.Decode(
"mQGiBEBtfW8RBADfWjTxFedIbGBNVgh064D/OCf6ul7x4PGsCl+BkAyheYkr"
+ "mVUsChmBKoeXaY+Fb85wwusXzyM/6JFK58Rg+vEb3Z19pue8Ixxq7cRtCtOA"
+ "tOP1eKXLNtTRWJutvLkQmeOa19UZ6ziIq23aWuWKSq+KKMWek2GUnGycnx5M"
+ "W0pn1QCg/39r9RKhY9cdKYqRcqsr9b2B/AsD/Ru24Q15Jmrsl9zZ6EC47J49"
+ "iNW5sLQx1qf/mgfVWQTmU2j6gq4ND1OuK7+0OP/1yMOUpkjjcqxFgTnDAAoM"
+ "hHDTzCv/aZzIzmMvgLsYU3aIMfbz+ojpuASMCMh+te01cEMjiPWwDtdWWOdS"
+ "OSyX9ylzhO3PiNDks8R83onsacYpA/9WhTcg4bvkjaj66I7wGZkm3BmTxNSb"
+ "pE4b5HZDh31rRYhY9tmrryCfFnU4BS2Enjj5KQe9zFv7pUBCBW2oFo8i8Osn"
+ "O6fa1wVN4fBHC6wqWmmpnkFerNPkiC9V75KUFIfeWHmT3r2DVSO3dfdHDERA"
+ "jFIAioMLjhaX6DnODF5KQrABh7QmU2FpIFB1bGxhYmhvdGxhIDxwc2FpQG15"
+ "amF2YXdvcmxkLmNvbT6wAwP//4kAVwQQEQIAFwUCQG19bwcLCQgHAwIKAhkB"
+ "BRsDAAAAAAoJEKXQf/RT99uYmfAAoMKxV5g2owIfmy2w7vSLvOQUpvvOAJ4n"
+ "jB6xJot523rPAQW9itPoGGekirABZ7kCDQRAbX1vEAgA9kJXtwh/CBdyorrW"
+ "qULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV89AHxstDqZSt90xkhkn4DIO9"
+ "ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50T8X8dryDxUcwYc58yWb/"
+ "Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknbzSC0neSRBzZrM2w4"
+ "DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdXQ6MdGGzeMyEs"
+ "tSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbTCD1mpF1B"
+ "n5x8vYlLIhkmuquiXsNV6TILOwACAgf9F7/nJHDayJ3pBVTTVSq2g5WKUXMg"
+ "xxGKTvOahiVRcbO03w0pKAkH85COakVfe56sMYpWRl36adjNoKOxaciow74D"
+ "1R5snY/hv/kBXPBkzo4UMkbANIVaZ0IcnLp+rkkXcDVbRCibZf8FfCY1zXbq"
+ "d680UtEgRbv1D8wFBqfMt7kLsuf9FnIw6vK4DU06z5ZDg25RHGmswaDyY6Mw"
+ "NGCrKGbHf9I/T7MMuhGF/in8UU8hv8uREOjseOqklG3/nsI1hD/MdUC7fzXi"
+ "MRO4RvahLoeXOuaDkMYALdJk5nmNuCL1YPpbFGttI3XsK7UrP/Fhd8ND6Nro"
+ "wCqrN6keduK+uLABh4kATAQYEQIADAUCQG19bwUbDAAAAAAKCRCl0H/0U/fb"
+ "mC/0AJ4r1yvyu4qfOXlDgmVuCsvHFWo63gCfRIrCB2Jv/N1cgpmq0L8LGHM7"
+ "G/KwAWeZAQ0EQG19owEIAMnavLYqR7ffaDPbbq+lQZvLCK/3uA0QlyngNyTa"
+ "sDW0WC1/ryy2dx7ypOOCicjnPYfg3LP5TkYAGoMjxH5+xzM6xfOR+8/EwK1z"
+ "N3A5+X/PSBDlYjQ9dEVKrvvc7iMOp+1K1VMf4Ug8Yah22Ot4eLGP0HRCXiv5"
+ "vgdBNsAl/uXnBJuDYQmLrEniqq/6UxJHKHxZoS/5p13Cq7NfKB1CJCuJXaCE"
+ "TW2do+cDpN6r0ltkF/r+ES+2L7jxyoHcvQ4YorJoDMlAN6xpIZQ8dNaTYP/n"
+ "Mx/pDS3shUzbU+UYPQrreJLMF1pD+YWP5MTKaZTo+U/qPjDFGcadInhPxvh3"
+ "1ssAEQEAAbABh7QuU2FuZGh5YSBQdWxsYWJob3RsYSA8cHNhbmRoeWFAbXlq"
+ "YXZhd29ybGQuY29tPrADA///iQEtBBABAgAXBQJAbX2jBwsJCAcDAgoCGQEF"
+ "GwMAAAAACgkQx87DL9gOvoeVUwgAkQXYiF0CxhKbDnuabAssnOEwJrutgCRO"
+ "CJRQvIwTe3fe6hQaWn2Yowt8OQtNFiR8GfAY6EYxyFLKzZbAI/qtq5fHmN3e"
+ "RSyNWe6d6e17hqZZL7kf2sVkyGTChHj7Jiuo7vWkdqT2MJN6BW5tS9CRH7Me"
+ "D839STv+4mAAO9auGvSvicP6UEQikAyCy/ihoJxLQlspfbSNpi0vrUjCPT7N"
+ "tWwfP0qF64i9LYkjzLqihnu+UareqOPhXcWnyFKrjmg4ezQkweNU2pdvCLbc"
+ "W24FhT92ivHgpLyWTswXcqjhFjVlRr0+2sIz7v1k0budCsJ7PjzOoH0hJxCv"
+ "sJQMlZR/e7ABZ7kBDQRAbX2kAQgAm5j+/LO2M4pKm/VUPkYuj3eefHkzjM6n"
+ "KbvRZX1Oqyf+6CJTxQskUWKAtkzzKafPdS5Wg0CMqeXov+EFod4bPEYccszn"
+ "cKd1U8NRwacbEpCvvvB84Yl2YwdWpDpkryyyLI4PbCHkeuwx9Dc2z7t4XDB6"
+ "FyAJTMAkia7nzYa/kbeUO3c2snDb/dU7uyCsyKtTZyTyhTgtl/f9L03Bgh95"
+ "y3mOUz0PimJ0Sg4ANczF4d04BpWkjLNVJi489ifWodPlHm1hag5drYekYpWJ"
+ "+3g0uxs5AwayV9BcOkPKb1uU3EoYQw+nn0Kn314Nvx2M1tKYunuVNLEm0PhA"
+ "/+B8PTq8BQARAQABsAGHiQEiBBgBAgAMBQJAbX2kBRsMAAAAAAoJEMfOwy/Y"
+ "Dr6HkLoH/RBY8lvUv1r8IdTs5/fN8e/MnGeThLl+JrlYF/4t3tjXYIf5xUj/"
+ "c9NdjreKYgHfMtrbVM08LlxUVQlkjuF3DIk5bVH9Blq8aXmyiwiM5GrCry+z"
+ "WiqkpZze1G577C38mMJbHDwbqNCLALMzo+W2q04Avl5sniNnDNGbGz9EjhRg"
+ "o7oS16KkkD6Ls4RnHTEZ0vyZOXodDHu+sk/2kzj8K07kKaM8rvR7aDKiI7HH"
+ "1GxJz70fn1gkKuV2iAIIiU25bty+S3wr+5h030YBsUZF1qeKCdGOmpK7e9Of"
+ "yv9U7rf6Z5l8q+akjqLZvej9RnxeH2Um7W+tGg2me482J+z6WOawAWc=");
private static readonly byte[] sec2 = Base64.Decode(
"lQHpBEBtfW8RBADfWjTxFedIbGBNVgh064D/OCf6ul7x4PGsCl+BkAyheYkr"
+ "mVUsChmBKoeXaY+Fb85wwusXzyM/6JFK58Rg+vEb3Z19pue8Ixxq7cRtCtOA"
+ "tOP1eKXLNtTRWJutvLkQmeOa19UZ6ziIq23aWuWKSq+KKMWek2GUnGycnx5M"
+ "W0pn1QCg/39r9RKhY9cdKYqRcqsr9b2B/AsD/Ru24Q15Jmrsl9zZ6EC47J49"
+ "iNW5sLQx1qf/mgfVWQTmU2j6gq4ND1OuK7+0OP/1yMOUpkjjcqxFgTnDAAoM"
+ "hHDTzCv/aZzIzmMvgLsYU3aIMfbz+ojpuASMCMh+te01cEMjiPWwDtdWWOdS"
+ "OSyX9ylzhO3PiNDks8R83onsacYpA/9WhTcg4bvkjaj66I7wGZkm3BmTxNSb"
+ "pE4b5HZDh31rRYhY9tmrryCfFnU4BS2Enjj5KQe9zFv7pUBCBW2oFo8i8Osn"
+ "O6fa1wVN4fBHC6wqWmmpnkFerNPkiC9V75KUFIfeWHmT3r2DVSO3dfdHDERA"
+ "jFIAioMLjhaX6DnODF5KQv4JAwIJH6A/rzqmMGAG4e+b8Whdvp8jaTGVT4CG"
+ "M1b65rbiDyAuf5KTFymQBOIi9towgFzG9NXAZC07nEYSukN56tUTUDNVsAGH"
+ "tCZTYWkgUHVsbGFiaG90bGEgPHBzYWlAbXlqYXZhd29ybGQuY29tPrADA///"
+ "iQBXBBARAgAXBQJAbX1vBwsJCAcDAgoCGQEFGwMAAAAACgkQpdB/9FP325iZ"
+ "8ACgwrFXmDajAh+bLbDu9Iu85BSm+84AnieMHrEmi3nbes8BBb2K0+gYZ6SK"
+ "sAFnnQJqBEBtfW8QCAD2Qle3CH8IF3KiutapQvMF6PlTETlPtvFuuUs4INoB"
+ "p1ajFOmPQFXz0AfGy0OplK33TGSGSfgMg71l6RfUodNQ+PVZX9x2Uk89PY3b"
+ "zpnhV5JZzf24rnRPxfx2vIPFRzBhznzJZv8V+bv9kV7HAarTW56NoKVyOtQa"
+ "8L9GAFgr5fSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPw"
+ "pVsYjY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obE"
+ "AxnIByl6ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpMgs7"
+ "AAICB/0Xv+ckcNrInekFVNNVKraDlYpRcyDHEYpO85qGJVFxs7TfDSkoCQfz"
+ "kI5qRV97nqwxilZGXfpp2M2go7FpyKjDvgPVHmydj+G/+QFc8GTOjhQyRsA0"
+ "hVpnQhycun6uSRdwNVtEKJtl/wV8JjXNdup3rzRS0SBFu/UPzAUGp8y3uQuy"
+ "5/0WcjDq8rgNTTrPlkODblEcaazBoPJjozA0YKsoZsd/0j9Pswy6EYX+KfxR"
+ "TyG/y5EQ6Ox46qSUbf+ewjWEP8x1QLt/NeIxE7hG9qEuh5c65oOQxgAt0mTm"
+ "eY24IvVg+lsUa20jdewrtSs/8WF3w0Po2ujAKqs3qR524r64/gkDAmmp39NN"
+ "U2pqYHokufIOab2VpD7iQo8UjHZNwR6dpjyky9dVfIe4MA0H+t0ju8UDdWoe"
+ "IkRu8guWsI83mjGPbIq8lmsZOXPCA8hPuBmL0iaj8TnuotmsBjIBsAGHiQBM"
+ "BBgRAgAMBQJAbX1vBRsMAAAAAAoJEKXQf/RT99uYL/QAnivXK/K7ip85eUOC"
+ "ZW4Ky8cVajreAJ9EisIHYm/83VyCmarQvwsYczsb8rABZ5UDqARAbX2jAQgA"
+ "ydq8tipHt99oM9tur6VBm8sIr/e4DRCXKeA3JNqwNbRYLX+vLLZ3HvKk44KJ"
+ "yOc9h+Dcs/lORgAagyPEfn7HMzrF85H7z8TArXM3cDn5f89IEOViND10RUqu"
+ "+9zuIw6n7UrVUx/hSDxhqHbY63h4sY/QdEJeK/m+B0E2wCX+5ecEm4NhCYus"
+ "SeKqr/pTEkcofFmhL/mnXcKrs18oHUIkK4ldoIRNbZ2j5wOk3qvSW2QX+v4R"
+ "L7YvuPHKgdy9DhiismgMyUA3rGkhlDx01pNg/+czH+kNLeyFTNtT5Rg9Cut4"
+ "kswXWkP5hY/kxMpplOj5T+o+MMUZxp0ieE/G+HfWywARAQABCWEWL2cKQKcm"
+ "XFTNsWgRoOcOkKyJ/osERh2PzNWvOF6/ir1BMRsg0qhd+hEcoWHaT+7Vt12i"
+ "5Y2Ogm2HFrVrS5/DlV/rw0mkALp/3cR6jLOPyhmq7QGwhG27Iy++pLIksXQa"
+ "RTboa7ZasEWw8zTqa4w17M5Ebm8dtB9Mwl/kqU9cnIYnFXj38BWeia3iFBNG"
+ "PD00hqwhPUCTUAcH9qQPSqKqnFJVPe0KQWpq78zhCh1zPUIa27CE86xRBf45"
+ "XbJwN+LmjCuQEnSNlloXJSPTRjEpla+gWAZz90fb0uVIR1dMMRFxsuaO6aCF"
+ "QMN2Mu1wR/xzTzNCiQf8cVzq7YkkJD8ChJvu/4BtWp3BlU9dehAz43mbMhaw"
+ "Qx3NmhKR/2dv1cJy/5VmRuljuzC+MRtuIjJ+ChoTa9ubNjsT6BF5McRAnVzf"
+ "raZK+KVWCGA8VEZwe/K6ouYLsBr6+ekCKIkGZdM29927m9HjdFwEFjnzQlWO"
+ "NZCeYgDcK22v7CzobKjdo2wdC7XIOUVCzMWMl+ch1guO/Y4KVuslfeQG5X1i"
+ "PJqV+bwJriCx5/j3eE/aezK/vtZU6cchifmvefKvaNL34tY0Myz2bOx44tl8"
+ "qNcGZbkYF7xrNCutzI63xa2ruN1p3hNxicZV1FJSOje6+ITXkU5Jmufto7IJ"
+ "t/4Q2dQefBQ1x/d0EdX31yK6+1z9dF/k3HpcSMb5cAWa2u2g4duAmREHc3Jz"
+ "lHCsNgyzt5mkb6kS43B6og8Mm2SOx78dBIOA8ANzi5B6Sqk3/uN5eQFLY+sQ"
+ "qGxXzimyfbMjyq9DdqXThx4vlp3h/GC39KxL5MPeB0oe6P3fSP3C2ZGjsn3+"
+ "XcYk0Ti1cBwBOFOZ59WYuc61B0wlkiU/WGeaebABh7QuU2FuZGh5YSBQdWxs"
+ "YWJob3RsYSA8cHNhbmRoeWFAbXlqYXZhd29ybGQuY29tPrADA///iQEtBBAB"
+ "AgAXBQJAbX2jBwsJCAcDAgoCGQEFGwMAAAAACgkQx87DL9gOvoeVUwgAkQXY"
+ "iF0CxhKbDnuabAssnOEwJrutgCROCJRQvIwTe3fe6hQaWn2Yowt8OQtNFiR8"
+ "GfAY6EYxyFLKzZbAI/qtq5fHmN3eRSyNWe6d6e17hqZZL7kf2sVkyGTChHj7"
+ "Jiuo7vWkdqT2MJN6BW5tS9CRH7MeD839STv+4mAAO9auGvSvicP6UEQikAyC"
+ "y/ihoJxLQlspfbSNpi0vrUjCPT7NtWwfP0qF64i9LYkjzLqihnu+UareqOPh"
+ "XcWnyFKrjmg4ezQkweNU2pdvCLbcW24FhT92ivHgpLyWTswXcqjhFjVlRr0+"
+ "2sIz7v1k0budCsJ7PjzOoH0hJxCvsJQMlZR/e7ABZ50DqARAbX2kAQgAm5j+"
+ "/LO2M4pKm/VUPkYuj3eefHkzjM6nKbvRZX1Oqyf+6CJTxQskUWKAtkzzKafP"
+ "dS5Wg0CMqeXov+EFod4bPEYccszncKd1U8NRwacbEpCvvvB84Yl2YwdWpDpk"
+ "ryyyLI4PbCHkeuwx9Dc2z7t4XDB6FyAJTMAkia7nzYa/kbeUO3c2snDb/dU7"
+ "uyCsyKtTZyTyhTgtl/f9L03Bgh95y3mOUz0PimJ0Sg4ANczF4d04BpWkjLNV"
+ "Ji489ifWodPlHm1hag5drYekYpWJ+3g0uxs5AwayV9BcOkPKb1uU3EoYQw+n"
+ "n0Kn314Nvx2M1tKYunuVNLEm0PhA/+B8PTq8BQARAQABCXo6bD6qi3s4U8Pp"
+ "Uf9l3DyGuwiVPGuyb2P+sEmRFysi2AvxMe9CkF+CLCVYfZ32H3Fcr6XQ8+K8"
+ "ZGH6bJwijtV4QRnWDZIuhUQDS7dsbGqTh4Aw81Fm0Bz9fpufViM9RPVEysxs"
+ "CZRID+9jDrACthVsbq/xKomkKdBfNTK7XzGeZ/CBr9F4EPlnBWClURi9txc0"
+ "pz9YP5ZRy4XTFgx+jCbHgKWUIz4yNaWQqpSgkHEDrGZwstXeRaaPftcfQN+s"
+ "EO7OGl/Hd9XepGLez4vKSbT35CnqTwMzCK1IwUDUzyB4BYEFZ+p9TI18HQDW"
+ "hA0Wmf6E8pjS16m/SDXoiRY43u1jUVZFNFzz25uLFWitfRNHCLl+VfgnetZQ"
+ "jMFr36HGVQ65fogs3avkgvpgPwDc0z+VMj6ujTyXXgnCP/FdhzgkRFJqgmdJ"
+ "yOlC+wFmZJEs0MX7L/VXEXdpR27XIGYm24CC7BTFKSdlmR1qqenXHmCCg4Wp"
+ "00fV8+aAsnesgwPvxhCbZQVp4v4jqhVuB/rvsQu9t0rZnKdDnWeom/F3StYo"
+ "A025l1rrt0wRP8YS4XlslwzZBqgdhN4urnzLH0/F3X/MfjP79Efj7Zk07vOH"
+ "o/TPjz8lXroPTscOyXWHwtQqcMhnVsj9jvrzhZZSdUuvnT30DR7b8xcHyvAo"
+ "WG2cnF/pNSQX11RlyyAOlw9TOEiDJ4aLbFdkUt+qZdRKeC8mEC2xsQ87HqFR"
+ "pWKWABWaoUO0nxBEmvNOy97PkIeGVFNHDLlIeL++Ry03+JvuNNg4qAnwacbJ"
+ "TwQzWP4vJqre7Gl/9D0tVlD4Yy6Xz3qyosxdoFpeMSKHhgKVt1bk0SQP7eXA"
+ "C1c+eDc4gN/ZWpl+QLqdk2T9vr4wRAaK5LABh4kBIgQYAQIADAUCQG19pAUb"
+ "DAAAAAAKCRDHzsMv2A6+h5C6B/0QWPJb1L9a/CHU7Of3zfHvzJxnk4S5fia5"
+ "WBf+Ld7Y12CH+cVI/3PTXY63imIB3zLa21TNPC5cVFUJZI7hdwyJOW1R/QZa"
+ "vGl5sosIjORqwq8vs1oqpKWc3tRue+wt/JjCWxw8G6jQiwCzM6PltqtOAL5e"
+ "bJ4jZwzRmxs/RI4UYKO6EteipJA+i7OEZx0xGdL8mTl6HQx7vrJP9pM4/CtO"
+ "5CmjPK70e2gyoiOxx9RsSc+9H59YJCrldogCCIlNuW7cvkt8K/uYdN9GAbFG"
+ "RdanignRjpqSu3vTn8r/VO63+meZfKvmpI6i2b3o/UZ8Xh9lJu1vrRoNpnuP"
+ "Nifs+ljmsAFn");
private static readonly char[] sec2pass1 = "sandhya".ToCharArray();
private static readonly char[] sec2pass2 = "psai".ToCharArray();
private static readonly byte[] pub3 = Base64.Decode(
"mQGiBEB9BH0RBACtYQtE7tna6hgGyGLpq+ds3r2cLC0ISn5dNw7tm9vwiNVF"
+ "JA2N37RRrifw4PvgelRSvLaX3M3ZBqC9s1Metg3v4FSlIRtSLWCNpHSvNw7i"
+ "X8C2Xy9Hdlbh6Y/50o+iscojLRE14upfR1bIkcCZQGSyvGV52V2wBImUUZjV"
+ "s2ZngwCg7mu852vK7+euz4WaL7ERVYtq9CMEAJ5swrljerDpz/RQ4Lhp6KER"
+ "KyuI0PUttO57xINGshEINgYlZdGaZHRueHe7uKfI19mb0T4N3NJWaZ0wF+Cn"
+ "rixsq0VrTUfiwfZeGluNG73aTCeY45fVXMGTTSYXzS8T0LW100Xn/0g9HRyA"
+ "xUpuWo8IazxkMqHJis2uwriYKpAfA/9anvj5BS9p5pfPjp9dGM7GTMIYl5f2"
+ "fcP57f+AW1TVR6IZiMJAvAdeWuLtwLnJiFpGlnFz273pfl+sAuqm1yNceImR"
+ "2SDDP4+vtyycWy8nZhgEuhZx3W3cWMQz5WyNJSY1JJHh9TCQkCoN8E7XpVP4"
+ "zEPboB2GzD93mfD8JLHP+7QtVGVzdCBLZXkgKG5vIGNvbW1lbnQpIDx0ZXN0"
+ "QGJvdW5jeWNhc3RsZS5vcmc+iFkEExECABkFAkB9BH0ECwcDAgMVAgMDFgIB"
+ "Ah4BAheAAAoJEKnMV8vjZQOpSRQAnidAQswYkrXQAFcLBzhxQTknI9QMAKDR"
+ "ryV3l6xuCCgHST8JlxpbjcXhlLACAAPRwXPBcQEQAAEBAAAAAAAAAAAAAAAA"
+ "/9j/4AAQSkZJRgABAQEASABIAAD//gAXQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q"
+ "/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZEhMPFB0aHx4dGhwcICQuJyAi"
+ "LCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sAQwEJCQkMCwwYDQ0YMiEcITIy"
+ "MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy"
+ "MjIy/8AAEQgAFAAUAwEiAAIRAQMRAf/EABoAAQACAwEAAAAAAAAAAAAAAAAE"
+ "BQIDBgf/xAAoEAABAgUDBAEFAAAAAAAAAAABAgMABBEhMQUSQQYTIiNhFFGB"
+ "kcH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAgMF/8QAJBEAAQQAAwkAAAAAAAAA"
+ "AAAAAQACERIEIfATMTJBUZGx0fH/2gAMAwEAAhEDEQA/APMuotJlJVxstqaP"
+ "o22NlAUp+YsNO0qSUtBcMu6n6EtOHcfPAHHFI16++oajQtTA3DapK02HFR8U"
+ "pE9pTbQWtKm2WG2rlxVyQTcfGbn7Qm0OIjL77Wrs2NNm9lzTmmSxQ0PX4opS"
+ "prk5tmESF6syggzGwOLG6gXgHFbZhBixk8XlIDcOQLRKt+rX+3qC5ZLTQblp"
+ "Qlvwvxn9CMpZturVGkJHapQJphRH8hCLXbzrqpYsCx1zC5rtpJNuYQhASc0U"
+ "AQv/2YhcBBMRAgAcBQJAfQV+AhsDBAsHAwIDFQIDAxYCAQIeAQIXgAAKCRCp"
+ "zFfL42UDqfa2AJ9hjtEeDTbTEAuuSbzhYFxN/qc0FACgsmzysdbBpuN65yK0"
+ "1tbEaeIMtqCwAgADuM0EQH0EfhADAKpG5Y6vGbm//xZYG08RRmdi67dZjF59"
+ "Eqfo43mRrliangB8qkqoqqf3za2OUbXcZUQ/ajDXUvjJAoY2b5XJURqmbtKk"
+ "wPRIeD2+wnKABat8wmcFhZKATX1bqjdyRRGxawADBgMAoMJKJLELdnn885oJ"
+ "6HDmIez++ZWTlafzfUtJkQTCRKiE0NsgSvKJr/20VdK3XUA/iy0m1nQwfzv/"
+ "okFuIhEPgldzH7N/NyEvtN5zOv/TpAymFKewAQ26luEu6l+lH4FsiEYEGBEC"
+ "AAYFAkB9BH4ACgkQqcxXy+NlA6mtMgCgtQMFBaKymktM+DQmCgy2qjW7WY0A"
+ "n3FaE6UZE9GMDmCIAjhI+0X9aH6CsAIAAw==");
private static readonly byte[] sec3 = Base64.Decode(
"lQHhBEB9BH0RBACtYQtE7tna6hgGyGLpq+ds3r2cLC0ISn5dNw7tm9vwiNVF"
+ "JA2N37RRrifw4PvgelRSvLaX3M3ZBqC9s1Metg3v4FSlIRtSLWCNpHSvNw7i"
+ "X8C2Xy9Hdlbh6Y/50o+iscojLRE14upfR1bIkcCZQGSyvGV52V2wBImUUZjV"
+ "s2ZngwCg7mu852vK7+euz4WaL7ERVYtq9CMEAJ5swrljerDpz/RQ4Lhp6KER"
+ "KyuI0PUttO57xINGshEINgYlZdGaZHRueHe7uKfI19mb0T4N3NJWaZ0wF+Cn"
+ "rixsq0VrTUfiwfZeGluNG73aTCeY45fVXMGTTSYXzS8T0LW100Xn/0g9HRyA"
+ "xUpuWo8IazxkMqHJis2uwriYKpAfA/9anvj5BS9p5pfPjp9dGM7GTMIYl5f2"
+ "fcP57f+AW1TVR6IZiMJAvAdeWuLtwLnJiFpGlnFz273pfl+sAuqm1yNceImR"
+ "2SDDP4+vtyycWy8nZhgEuhZx3W3cWMQz5WyNJSY1JJHh9TCQkCoN8E7XpVP4"
+ "zEPboB2GzD93mfD8JLHP+/4DAwIvYrn+YqRaaGAu19XUj895g/GROyP8WEaU"
+ "Bd/JNqWc4kE/0guetGnPzq7G3bLVwiKfFd4X7BrgHAo3mrQtVGVzdCBLZXkg"
+ "KG5vIGNvbW1lbnQpIDx0ZXN0QGJvdW5jeWNhc3RsZS5vcmc+iFkEExECABkF"
+ "AkB9BH0ECwcDAgMVAgMDFgIBAh4BAheAAAoJEKnMV8vjZQOpSRQAoKZy6YS1"
+ "irF5/Q3JlWiwbkN6dEuLAJ9lldRLOlXsuQ5JW1+SLEc6K9ho4rACAADRwXPB"
+ "cQEQAAEBAAAAAAAAAAAAAAAA/9j/4AAQSkZJRgABAQEASABIAAD//gAXQ3Jl"
+ "YXRlZCB3aXRoIFRoZSBHSU1Q/9sAQwAIBgYHBgUIBwcHCQkICgwUDQwLCwwZ"
+ "EhMPFB0aHx4dGhwcICQuJyAiLCMcHCg3KSwwMTQ0NB8nOT04MjwuMzQy/9sA"
+ "QwEJCQkMCwwYDQ0YMiEcITIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy"
+ "MjIyMjIyMjIyMjIyMjIyMjIyMjIy/8AAEQgAFAAUAwEiAAIRAQMRAf/EABoA"
+ "AQACAwEAAAAAAAAAAAAAAAAEBQIDBgf/xAAoEAABAgUDBAEFAAAAAAAAAAAB"
+ "AgMABBEhMQUSQQYTIiNhFFGBkcH/xAAXAQEAAwAAAAAAAAAAAAAAAAAEAgMF"
+ "/8QAJBEAAQQAAwkAAAAAAAAAAAAAAQACERIEIfATMTJBUZGx0fH/2gAMAwEA"
+ "AhEDEQA/APMuotJlJVxstqaPo22NlAUp+YsNO0qSUtBcMu6n6EtOHcfPAHHF"
+ "I16++oajQtTA3DapK02HFR8UpE9pTbQWtKm2WG2rlxVyQTcfGbn7Qm0OIjL7"
+ "7Wrs2NNm9lzTmmSxQ0PX4opSprk5tmESF6syggzGwOLG6gXgHFbZhBixk8Xl"
+ "IDcOQLRKt+rX+3qC5ZLTQblpQlvwvxn9CMpZturVGkJHapQJphRH8hCLXbzr"
+ "qpYsCx1zC5rtpJNuYQhASc0UAQv/2YhcBBMRAgAcBQJAfQV+AhsDBAsHAwID"
+ "FQIDAxYCAQIeAQIXgAAKCRCpzFfL42UDqfa2AJ9hjtEeDTbTEAuuSbzhYFxN"
+ "/qc0FACgsmzysdbBpuN65yK01tbEaeIMtqCwAgAAnQEUBEB9BH4QAwCqRuWO"
+ "rxm5v/8WWBtPEUZnYuu3WYxefRKn6ON5ka5Ymp4AfKpKqKqn982tjlG13GVE"
+ "P2ow11L4yQKGNm+VyVEapm7SpMD0SHg9vsJygAWrfMJnBYWSgE19W6o3ckUR"
+ "sWsAAwYDAKDCSiSxC3Z5/POaCehw5iHs/vmVk5Wn831LSZEEwkSohNDbIEry"
+ "ia/9tFXSt11AP4stJtZ0MH87/6JBbiIRD4JXcx+zfzchL7Teczr/06QMphSn"
+ "sAENupbhLupfpR+BbP4DAwIvYrn+YqRaaGBjvFK1fbxCt7ZM4I2W/3BC0lCX"
+ "m/NypKNspGflec8u96uUlA0fNCnxm6f9nbB0jpvoKi0g4iqAf+P2iEYEGBEC"
+ "AAYFAkB9BH4ACgkQqcxXy+NlA6mtMgCgvccZA/Sg7BXVpxli47SYhxSHoM4A"
+ "oNCOMplSnYTuh5ikKeBWtz36gC1psAIAAA==");
private static readonly char[] sec3pass1 = "123456".ToCharArray();
//
// GPG comment packets.
//
private static readonly byte[] sec4 = Base64.Decode(
"lQG7BD0PbK8RBAC0cW4Y2MZXmAmqYp5Txyw0kSQsFvwZKHNMFRv996IsN57URVF5"
+ "BGMVPRBi9dNucWbjiSYpiYN13wE9IuLZsvVaQojV4XWGRDc+Rxz9ElsXnsYQ3mZU"
+ "7H1bNQEofstChk4z+dlvPBN4GFahrIzn/CeVUn6Ut7dVdYbiTqviANqNXwCglfVA"
+ "2OEePvqFnGxs1jhJyPSOnTED/RwRvsLH/k43mk6UEvOyN1RIpBXN+Ieqs7h1gFrQ"
+ "kB+WMgeP5ZUsotTffVDSUS9UMxRQggVUW1Xml0geGwQsNfkr/ztWMs/T4xp1v5j+"
+ "QyJx6OqNlkGdqOsoqkzJx0SQ1zBxdinFyyC4H95SDAb/RQOu5LQmxFG7quexztMs"
+ "infEA/9cVc9+qCo92yRAaXRqKNVVQIQuPxeUsGMyVeJQvJBD4An8KTMCdjpF10Cp"
+ "qA3t+n1S0zKr5WRUtvS6y60MOONO+EJWVWBNkx8HJDaIMNkfoqQoz3Krn7w6FE/v"
+ "/5uwMd6jY3N3yJZn5nDZT9Yzv9Nx3j+BrY+henRlSU0c6xDc9QAAnjJYg0Z83VJG"
+ "6HrBcgc4+4K6lHulCqH9JiM6RFNBX2ZhY3RvcjoAAK9hV206agp99GI6x5qE9+pU"
+ "vs6O+Ich/SYjOkRTQV9mYWN0b3I6AACvYAfGn2FGrpBYbjnpTuFOHJMS/T5xg/0m"
+ "IzpEU0FfZmFjdG9yOgAAr0dAQz6XxMwxWIn8xIZR/v2iN2L9C6O0EkZvbyBCYXIg"
+ "PGJhekBxdXV4PohXBBMRAgAXBQI9D2yvBQsHCgMEAxUDAgMWAgECF4AACgkQUGLI"
+ "YCIktfoGogCfZiXMJUKrScqozv5tMwzTTk2AaT8AniM5iRr0Du/Y08SL/NMhtF6H"
+ "hJ89nO4EPQ9ssRADAI6Ggxj6ZBfoavuXd/ye99osW8HsNlbqhXObu5mCMNySX2wa"
+ "HoWyRUEaUkI9eQw+MlHzIwzA32E7y2mU3OQBKdgLcBg4jxtcWVEg8ESKF9MpFXxl"
+ "pExxWrr4DFBfCRcsTwAFEQL9G3OvwJuEZXgx2JSS41D3pG4/qiHYICVa0u3p/14i"
+ "cq0kXajIk5ZJ6frCIAHIzuQ3n7jjzr05yR8s/qCrNbBA+nlkVNa/samk+jCzxxxa"
+ "cR/Dbh2wkvTFuDFFETwQYLuZAADcDck4YGQAmHivVT2NNDCf/aTz0+CJWl+xRc2l"
+ "Qw7D/SQjOkVMR19mYWN0b3I6AACbBnv9m5/bb/pjYAm2PtDp0CysQ9X9JCM6RUxH"
+ "X2ZhY3RvcjoAAJsFyHnSmaWguTFf6lJ/j39LtUNtmf0kIzpFTEdfZmFjdG9yOgAA"
+ "mwfwMD3LxmWtuCWBE9BptWMNH07Z/SQjOkVMR19mYWN0b3I6AACbBdhBrbSiM4UN"
+ "y7khDW2Sk0e4v9mIRgQYEQIABgUCPQ9ssQAKCRBQYshgIiS1+jCMAJ9txwHnb1Kl"
+ "6i/fSoDs8SkdM7w48wCdFvPEV0sSxE73073YhBgPZtMWbBo=");
//
// PGP freeware version 7
//
private static readonly byte[] pub5 = Base64.Decode(
"mQENBEBrBE4BCACjXVcNIFDQSofaIyZnALb2CRg+WY9uUqgHEEAOlPe03Cs5STM5"
+ "HDlNmrh4TdFceJ46rxk1mQOjULES1YfHay8lCIzrD7FX4oj0r4DC14Fs1vXaSar2"
+ "1szIpttOw3obL4A1e0p6N4jjsoG7N/pA0fEL0lSw92SoBrMbAheXRg4qNTZvdjOR"
+ "grcuOuwgJRvPLtRXlhyLBoyhkd5mmrIDGv8QHJ/UjpeIcRXY9kn9oGXnEYcRbMaU"
+ "VwXB4pLzWqz3ZejFI3lOxRWjm760puPOnGYlzSVBxlt2LgzUgSj1Mn+lIpWmAzsa"
+ "xEiU4xUwEomQns72yYRZ6D3euNCibcte4SeXABEBAAG0KXBhbGFzaCBrYXNvZGhh"
+ "biA8cGthc29kaGFuQHRpYWEtY3JlZi5vcmc+iQEuBBABAgAYBQJAawROCAsBAwkI"
+ "BwIKAhkBBRsDAAAAAAoJEOfelumuiOrYqPEH+wYrdP5Tq5j+E5yN1pyCg1rwbSOt"
+ "Dka0y0p7Oq/VIGLk692IWPItLEunnBXQtGBcWqklrvogvlhxtf16FgoyScfLJx1e"
+ "1cJa+QQnVuH+VOESN6iS9Gp9lUfVOHv74mEMXw0l2Djfy/lnrkAMBatggyGnF9xF"
+ "VXOLk1J2WVFm9KUE23o6qdB7RGkf31pN2eA7SWmkdJSkUH7o/QSFBI+UTRZ/IY5P"
+ "ZIJpsdiIOqd9YMG/4RoSZuPqNRR6x7BSs8nQVR9bYs4PPlp4GfdRnOcRonoTeJCZ"
+ "83RnsraWJnJTg34gRLBcqumhTuFKc8nuCNK98D6zkQESdcHLLTquCOaF5L+5AQ0E"
+ "QGsETwEIAOVwNCTaDZvW4dowPbET1bI5UeYY8rAGLYsWSUfgaFv2srMiApyBVltf"
+ "i6OLcPjcUCHDBjCv4pwx/C4qcHWb8av4xQIpqQXOpO9NxYE1eZnel/QB7DtH12ZO"
+ "nrDNmHtaXlulcKNGe1i1utlFhgzfFx6rWkRL0ENmkTkaQmPY4gTGymJTUhBbsSRq"
+ "2ivWqQA1TPwBuda73UgslIAHRd/SUaxjXoLpMbGOTeqzcKGjr5XMPTs7/YgBpWPP"
+ "UxMlEQIiU3ia1bxpEhx05k97ceK6TSH2oCPQA7gumjxOSjKT+jEm+8jACVzymEmc"
+ "XRy4D5Ztqkw/Z16pvNcu1DI5m6xHwr8AEQEAAYkBIgQYAQIADAUCQGsETwUbDAAA"
+ "AAAKCRDn3pbprojq2EynB/4/cEOtKbI5UisUd3vkTzvWOcqWUqGqi5wjjioNtIM5"
+ "pur2nFvhQE7SZ+PbAa87HRJU/4WcWMcoLkHD48JrQwHCHOLHSV5muYowb78X4Yh9"
+ "epYtSJ0uUahcn4Gp48p4BkhgsPYXkxEImSYzAOWStv21/7WEMqItMYl89BV6Upm8"
+ "HyTJx5MPTDbMR7X51hRg3OeQs6po3WTCWRzFIMyGm1rd/VK1L5ZDFPqO3S6YUJ0z"
+ "cxecYruvfK0Wp7q834wE8Zkl/PQ3NhfEPL1ZiLr/L00Ty+77/FZqt8SHRCICzOfP"
+ "OawcVGI+xHVXW6lijMpB5VaVIH8i2KdBMHXHtduIkPr9");
private static readonly byte[] sec5 = Base64.Decode(
"lQOgBEBrBE4BCACjXVcNIFDQSofaIyZnALb2CRg+WY9uUqgHEEAOlPe03Cs5STM5"
+ "HDlNmrh4TdFceJ46rxk1mQOjULES1YfHay8lCIzrD7FX4oj0r4DC14Fs1vXaSar2"
+ "1szIpttOw3obL4A1e0p6N4jjsoG7N/pA0fEL0lSw92SoBrMbAheXRg4qNTZvdjOR"
+ "grcuOuwgJRvPLtRXlhyLBoyhkd5mmrIDGv8QHJ/UjpeIcRXY9kn9oGXnEYcRbMaU"
+ "VwXB4pLzWqz3ZejFI3lOxRWjm760puPOnGYlzSVBxlt2LgzUgSj1Mn+lIpWmAzsa"
+ "xEiU4xUwEomQns72yYRZ6D3euNCibcte4SeXABEBAAEB8wqP7JkKN6oMNi1xJNqU"
+ "vvt0OV4CCnrIFiOPCjebjH/NC4T/9pJ6BYSjYdo3VEPNhPhRS9U3071Kqbdt35J5"
+ "kmzMq1yNStC1jkxHRCNTMsb1yIEY1v+fv8/Cy+tBpvAYiJKaox8jW3ppi9vTHZjW"
+ "tYYq0kwAVojMovz1O3wW/pEF69UPBmPYsze+AHA1UucYYqdWO8U2tsdFJET/hYpe"
+ "o7ppHJJCdqWzeiE1vDUrih9pP3MPpzcRS/gU7HRDb5HbfP7ghSLzByEa+2mvg5eK"
+ "eLwNAx2OUtrVg9rJswXX7DOLa1nKPhdGrSV/qwuK4rBdaqJ/OvszVJ0Vln0T/aus"
+ "it1PAuVROLUPqTVVN8/zkMenFbf5vtryC3GQYXvvZq+l3a4EXwrR/1pqrTfnfOuD"
+ "GwlFhRJAqPfthxZS68/xC8qAmTtkl7j4nscNM9kSoZ3BFwSyD9B/vYHPWGlqnpGF"
+ "k/hBXuIgl07KIeNIyEC3f1eRyaiMFqEz5yXbbTfEKirSVpHM/mpeKxG8w96aK3Je"
+ "AV0X6ZkC4oLTp6HCG2TITUIeNxCh2rX3fhr9HvBDXBbMHgYlIcLwzNkwDX74cz/7"
+ "nIclcubaWjEkDHP20XFicuChFc9zx6kBYuYy170snltTBgTWSuRH15W4NQqrLo37"
+ "zyzZQubX7CObgQJu4ahquiOg4SWl6uEI7+36U0SED7sZzw8ns1LxrwOWbXuHie1i"
+ "xCvsJ4RpJJ03iEdNdUIb77qf6AriqE92tXzcVXToBv5S2K5LdFYNJ1rWdwaKJRkt"
+ "kmjCL67KM9WT/IagsUyU+57ao3COtqw9VWZi6ev+ubM6fIV0ZK46NEggOLph1hi2"
+ "gZ9ew9uVuruYg7lG2Ku82N0fjrQpcGFsYXNoIGthc29kaGFuIDxwa2Fzb2RoYW5A"
+ "dGlhYS1jcmVmLm9yZz6dA6AEQGsETwEIAOVwNCTaDZvW4dowPbET1bI5UeYY8rAG"
+ "LYsWSUfgaFv2srMiApyBVltfi6OLcPjcUCHDBjCv4pwx/C4qcHWb8av4xQIpqQXO"
+ "pO9NxYE1eZnel/QB7DtH12ZOnrDNmHtaXlulcKNGe1i1utlFhgzfFx6rWkRL0ENm"
+ "kTkaQmPY4gTGymJTUhBbsSRq2ivWqQA1TPwBuda73UgslIAHRd/SUaxjXoLpMbGO"
+ "TeqzcKGjr5XMPTs7/YgBpWPPUxMlEQIiU3ia1bxpEhx05k97ceK6TSH2oCPQA7gu"
+ "mjxOSjKT+jEm+8jACVzymEmcXRy4D5Ztqkw/Z16pvNcu1DI5m6xHwr8AEQEAAQF7"
+ "osMrvQieBAJFYY+x9jKPVclm+pVaMaIcHKwCTv6yUZMqbHNRTfwdCVKTdAzdlh5d"
+ "zJNXXRu8eNwOcfnG3WrWAy59cYE389hA0pQPOh7iL2V1nITf1qdLru1HJqqLC+dy"
+ "E5GtkNcgvQYbv7ACjQacscvnyBioYC6TATtPnHipMO0S1sXEnmUugNlW88pDln4y"
+ "VxCtQXMBjuqMt0bURqmb+RoYhHhoCibo6sexxSnbEAPHBaW1b1Rm7l4UBSW6S5U0"
+ "MXURE60IHfP1TBe1l/xOIxOi8qdBQCyaFW2up00EhRBy/WOO6KAYXQrRRpOs9TBq"
+ "ic2wquwZePmErTbIttnnBcAKmpodrM/JBkn/we5fVg+FDTP8sM/Ubv0ZuM70aWmF"
+ "v0/ZKbkCkh2YORLWl5+HR/RKShdkmmFgZZ5uzbOGxxEGKhw+Q3+QFUF7PmYOnOtv"
+ "s9PZE3dV7ovRDoXIjfniD1+8sLUWwW5d+3NHAQnCHJrLnPx4sTHx6C0yWMcyZk6V"
+ "fNHpLK4xDTbgoTmxJa/4l+wa0iD69h9K/Nxw/6+X/GEM5w3d/vjlK1Da6urN9myc"
+ "GMsfiIll5DNIWdLLxCBPFmhJy653CICQLY5xkycWB7JOZUBTOEVrYr0AbBZSTkuB"
+ "fq5p9MfH4N51M5TWnwlJnqEiGnpaK+VDeP8GniwCidTYyiocNPvghvWIzG8QGWMY"
+ "PFncRpjFxmcY4XScYYpyRme4qyPbJhbZcgGpfeLvFKBPmNxVKJ2nXTdx6O6EbHDj"
+ "XctWqNd1EQas7rUN728u7bk8G7m37MGqQuKCpNvOScH4TnPROBY8get0G3bC4mWz"
+ "6emPeENnuyElfWQiHEtCZr1InjnNbb/C97O+vWu9PfsE");
private static readonly char[] sec5pass1 = "12345678".ToCharArray();
//
// Werner Koch "odd keys"
//
private static readonly byte[] pub6 = Base64.Decode(
"mQGiBDWiHh4RBAD+l0rg5p9rW4M3sKvmeyzhs2mDxhRKDTVVUnTwpMIR2kIA9pT4"
+ "3No/coPajDvhZTaDM/vSz25IZDZWJ7gEu86RpoEdtr/eK8GuDcgsWvFs5+YpCDwW"
+ "G2dx39ME7DN+SRvEE1xUm4E9G2Nnd2UNtLgg82wgi/ZK4Ih9CYDyo0a9awCgisn3"
+ "RvZ/MREJmQq1+SjJgDx+c2sEAOEnxGYisqIKcOTdPOTTie7o7x+nem2uac7uOW68"
+ "N+wRWxhGPIxsOdueMIa7U94Wg/Ydn4f2WngJpBvKNaHYmW8j1Q5zvZXXpIWRXSvy"
+ "TR641BceGHNdYiR/PiDBJsGQ3ac7n7pwhV4qex3IViRDJWz5Dzr88x+Oju63KtxY"
+ "urUIBACi7d1rUlHr4ok7iBRlWHYXU2hpUIQ8C+UOE1XXT+HB7mZLSRONQnWMyXnq"
+ "bAAW+EUUX2xpb54CevAg4eOilt0es8GZMmU6c0wdUsnMWWqOKHBFFlDIvyI27aZ9"
+ "quf0yvby63kFCanQKc0QnqGXQKzuXbFqBYW2UQrYgjXji8rd8bQnV2VybmVyIEtv"
+ "Y2ggKGdudXBnIHNpZykgPGRkOWpuQGdudS5vcmc+iGUEExECAB0FAjZVoKYFCQht"
+ "DIgDCwQDBRUDAgYBAxYCAQIXgAASCRBot6uJV1SNzQdlR1BHAAEBLj4AoId15gcy"
+ "YpBX2YLtEQTlXPp3mtEGAJ9UxzJE/t3EHCHK2bAIOkBwIW8ItIkBXwMFEDWiHkMD"
+ "bxG4/z6qCxADYzIFHR6I9Si9gzPQNRcFs2znrTp5pV5Mk6f1aqRgZxL3E4qUZ3xe"
+ "PQhwAo3fSy3kCwLmFGqvzautSMHn8K5V1u+T5CSHqLFYKqj5FGtuB/xwoKDXH6UO"
+ "P0+l5IP8H1RTjme3Fhqahec+zPG3NT57vc2Ru2t6PmuAwry2BMuSFMBs7wzXkyC3"
+ "DbI54MV+IKPjHMORivK8uI8jmna9hdNVyBifCk1GcxkHBSCFvU8xJePsA/Q//zCe"
+ "lvrnrIiMfY4CQTmKzke9MSzbAZQIRddgrGAsiX1tE8Z3YMd8lDpuujHLVEdWZo6s"
+ "54OJuynHrtFFObdapu0uIrT+dEXSASMUbEuNCLL3aCnrEtGJCwxB2TPQvCCvR2BK"
+ "zol6MGWxA+nmddeQib2r+GXoKXLdnHcpsAjA7lkXk3IFyJ7MLFK6uDrjGbGJs2FK"
+ "SduUjS/Ib4hGBBARAgAGBQI1oic8AAoJEGx+4bhiHMATftYAn1fOaKDUOt+dS38r"
+ "B+CJ2Q+iElWJAKDRPpp8q5GylbM8DPlMpClWN3TYqYhGBBARAgAGBQI27U5sAAoJ"
+ "EF3iSZZbA1iiarYAn35qU3ZOlVECELE/3V6q98Q30eAaAKCtO+lacH0Qq1E6v4BP"
+ "/9y6MoLIhohiBBMRAgAiAhsDBAsHAwIDFQIDAxYCAQIeAQIXgAUCP+mCaQUJDDMj"
+ "ywAKCRBot6uJV1SNzaLvAJwLsPV1yfc2D+yT+2W11H/ftNMDvwCbBweORhCb/O/E"
+ "Okg2UTXJBR4ekoCIXQQTEQIAHQMLBAMFFQMCBgEDFgIBAheABQI/6YJzBQkMMyPL"
+ "AAoJEGi3q4lXVI3NgroAn2Z+4KgVo2nzW72TgCJwkAP0cOc2AJ0ZMilsOWmxmEG6"
+ "B4sHMLkB4ir4GIhdBBMRAgAdAwsEAwUVAwIGAQMWAgECF4AFAj/pgnMFCQwzI8sA"
+ "CgkQaLeriVdUjc2CugCfRrOIfllp3mSmGpHgIxvg5V8vtMcAn0BvKVehOn+12Yvn"
+ "9BCHfg34jUZbiF0EExECAB0DCwQDBRUDAgYBAxYCAQIXgAUCP+mCcwUJDDMjywAK"
+ "CRBot6uJV1SNzYK6AJ9x7R+daNIjkieNW6lJeVUIoj1UHgCeLZm025uULML/5DFs"
+ "4tUvXs8n9XiZAaIENaIg8xEEALYPe0XNsPjx+inTQ+Izz527ZJnoc6BhWik/4a2b"
+ "ZYENSOQXAMKTDQMv2lLeI0i6ceB967MNubhHeVdNeOWYHFSM1UGRfhmZERISho3b"
+ "p+wVZvVG8GBVwpw34PJjgYU/0tDwnJaJ8BzX6j0ecTSTjQPnaUEtdJ/u/gmG9j02"
+ "18TzAKDihdNoKJEU9IKUiSjdGomSuem/VwQArHfaucSiDmY8+zyZbVLLnK6UJMqt"
+ "sIv1LvAg20xwXoUk2bY8H3tXL4UZ8YcoSXYozwALq3cIo5UZJ0q9Of71mI8WLK2i"
+ "FSYVplpTX0WMClAdkGt3HgVb7xtOhGt1mEKeRQjNZ2LteUQrRDD9MTQ+XxcvEN0I"
+ "pAj4kBJe9bR6HzAD/iecCmGwSlHUZZrgqWzv78o79XxDdcuLdl4i2fL7kwEOf9js"
+ "De7hGs27yrdJEmAG9QF9TOF9LJFmE1CqkgW+EpKxsY01Wjm0BFJB1R7iPUaUtFRZ"
+ "xYqfgXarmPjql2iBi+cVjLzGu+4BSojVAPgP/hhcnIowf4M4edPiICMP1GVjtCFX"
+ "ZXJuZXIgS29jaCA8d2VybmVyLmtvY2hAZ3V1Zy5kZT6IYwQTEQIAGwUCNs8JNwUJ"
+ "CCCxRAMLCgMDFQMCAxYCAQIXgAASCRBsfuG4YhzAEwdlR1BHAAEBaSAAn3YkpT5h"
+ "xgehGFfnX7izd+c8jI0SAJ9qJZ6jJvXnGB07p60aIPYxgJbLmYkAdQMFEDWjdxQd"
+ "GfTBDJhXpQEBPfMC/0cxo+4xYVAplFO0nIYyjQgP7D8O0ufzPsIwF3kvb7b5FNNj"
+ "fp+DAhN6G0HOIgkL3GsWtCfH5UHali+mtNFIKDpTtr+F/lPpZP3OPzzsLZS4hYTq"
+ "mMs1O/ACq8axKgAilYkBXwMFEDWiJw4DbxG4/z6qCxADB9wFH0i6mmn6rWYKFepJ"
+ "hXyhE4wWqRPJAnvfoiWUntDp4aIQys6lORigVXIWo4k4SK/FH59YnzF7578qrTZW"
+ "/RcA0bIqJqzqaqsOdTYEFa49cCjvLnBW4OebJlLTUs/nnmU0FWKW8OwwL+pCu8d7"
+ "fLSSnggBsrUQwbepuw0cJoctFPAz5T1nQJieQKVsHaCNwL2du0XefOgF5ujB1jK1"
+ "q3p4UysF9hEcBR9ltE3THr+iv4jtZXmC1P4at9W5LFWsYuwr0U3yJcaKSKp0v/wG"
+ "EWe2J/gFQZ0hB1+35RrCZPgiWsEv87CHaG6XtQ+3HhirBCJsYhmOikVKoEan6PhU"
+ "VR1qlXEytpAt389TBnvyceAX8hcHOE3diuGvILEgYes3gw3s5ZmM7bUX3jm2BrX8"
+ "WchexUFUQIuKW2cL379MFXR8TbxpVxrsRYE/4jHZBYhGBBARAgAGBQI27U4LAAoJ"
+ "EF3iSZZbA1iifJoAoLEsGy16hV/CfmDku6D1CBUIxXvpAJ9GBApdC/3OXig7sBrV"
+ "CWOb3MQzcLkBjQQ2zwcIEAYA9zWEKm5eZpMMBRsipL0IUeSKEyeKUjABX4vYNurl"
+ "44+2h6Y8rHn7rG1l/PNj39UJXBkLFj1jk8Q32v+3BQDjvwv8U5e/kTgGlf7hH3WS"
+ "W38RkZw18OXYCvnoWkYneIuDj6/HH2bVNXmTac05RkBUPUv4yhqlaFpkVcswKGuE"
+ "NRxujv/UWvVF+/2P8uSQgkmGp/cbwfMTkC8JBVLLBRrJhl1uap2JjZuSVklUUBez"
+ "Vf3NJMagVzx47HPqLVl4yr4bAAMGBf9PujlH5I5OUnvZpz+DXbV/WQVfV1tGRCra"
+ "kIj3mpN6GnUDF1LAbe6vayUUJ+LxkM1SqQVcmuy/maHXJ+qrvNLlPqUZPmU5cINl"
+ "sA7bCo1ljVUp54J1y8PZUx6HxfEl/LzLVkr+ITWnyqeiRikDecUf4kix2teTlx6I"
+ "3ecqT5oNqZSRXWwnN4SbkXtAd7rSgEptUYhQXgSEarp1pXJ4J4rgqFa49jKISDJq"
+ "rn/ElltHe5Fx1bpfkCIYlYk45Cga9bOIVAQYEQIADAUCNs8HCAUJBvPJAAASCRBs"
+ "fuG4YhzAEwdlR1BHAAEBeRUAoIGpCDmMy195TatlloHAJEjZu5KaAJwOvW989hOb"
+ "8cg924YIFVA1+4/Ia7kBjQQ1oiE8FAYAkQmAlOXixb8wra83rE1i7LCENLzlvBZW"
+ "KBXN4ONelZAnnkOm7IqRjMhtKRJN75zqVyKUaUwDKjpf9J5K2t75mSxBtnbNRqL3"
+ "XodjHK93OcAUkz3ci7iuC/b24JI2q4XeQG/v4YR1VodM0zEQ1IC0JCq4Pl39QZyX"
+ "JdZCrUFvMcXq5ruNSldztBqTFFUiFbkw1Fug/ZyXJve2FVcbsRXFrB7EEuy+iiU/"
+ "kZ/NViKk0L4T6KRHVsEiriNlCiibW19fAAMFBf9Tbv67KFMDrLqQan/0oSSodjDQ"
+ "KDGqtoh7KQYIKPXqfqT8ced9yd5MLFwPKf3t7AWG1ucW2x118ANYkPSU122UTndP"
+ "sax0cY4XkaHxaNwpNFCotGQ0URShxKNpcqbdfvy+1d8ppEavgOyxnV1JOkLjZJLw"
+ "K8bgxFdbPWcsJJnjuuH3Pwz87CzTgOSYQxMPnIwQcx5buZIV5NeELJtcbbd3RVua"
+ "K/GQht8QJpuXSji8Nl1FihYDjACR8TaRlAh50GmIRgQoEQIABgUCOCv7gwAKCRBs"
+ "fuG4YhzAE9hTAJ9cRHu+7q2hkxpFfnok4mRisofCTgCgzoPjNIuYiiV6+wLB5o11"
+ "7MNWPZCIVAQYEQIADAUCNaIhPAUJB4TOAAASCRBsfuG4YhzAEwdlR1BHAAEBDfUA"
+ "oLstR8cg5QtHwSQ3nFCOKEREUFIwAKDID3K3hM+b6jW1o+tNX9dnjb+YMZkAbQIw"
+ "bYOUAAABAwC7ltmO5vdKssohwzXEZeYvDW2ll3CYD2I+ruiNq0ybxkfFBopq9cxt"
+ "a0OvVML4LK/TH+60f/Fqx9wg2yk9APXyaomdLrXfWyfZ91YtNCfj3ElC4XB4qqm0"
+ "HRn0wQyYV6UABRG0IVdlcm5lciBLb2NoIDx3ZXJuZXIua29jaEBndXVnLmRlPokA"
+ "lQMFEDRfoOmOB31Gi6BmjQEBzwgD/2fHcdDXuRRY+SHvIVESweijstB+2/sVRp+F"
+ "CDjR74Kg576sJHfTJCxtSSmzpaVpelb5z4URGJ/Byi5L9AU7hC75S1ZnJ+MjBT6V"
+ "ePyk/r0uBrMkU/lMG7lk/y2By3Hll+edjzJsdwn6aoNPiyen4Ch4UGTEguxYsLq0"
+ "HES/UvojiQEVAwUTNECE2gnp+QqKck5FAQH+1Af/QMlYPlLG+5E19qP6AilKQUzN"
+ "kd1TWMenXTS66hGIVwkLVQDi6RCimhnLMq/F7ENA8bSbyyMuncaBz5dH4kjfiDp1"
+ "o64LULcTmN1LW9ctpTAIeLLJZnwxoJLkUbLUYKADKqIBXHMt2B0zRmhFOqEjRN+P"
+ "hI7XCcHeHWHiDeUB58QKMyeoJ/QG/7zLwnNgDN2PVqq2E72C3ye5FOkYLcHfWKyB"
+ "Rrn6BdUphAB0LxZujSGk8ohZFbia+zxpWdE8xSBhZbjVGlwLurmS2UTjjxByBNih"
+ "eUD6IC3u5P6psld0OfqnpriZofP0CBP2oTk65r529f/1lsy2kfWrVPYIFJXEnIkA"
+ "lQMFEDQyneGkWMS9SnJfMQEBMBMD/1ADuhhuY9kyN7Oj6DPrDt5SpPQDGS0Jtw3y"
+ "uIPoed+xyzlrEuL2HeaOj1O9urpn8XLN7V21ajkzlqsxnGkOuifbE9UT67o2b2vC"
+ "ldCcY4nV5n+U1snMDwNv+RkcEgNa8ANiWkm03UItd7/FpHDQP0FIgbPEPwRoBN87"
+ "I4gaebfRiQCVAwUQNDUSwxRNm5Suj3z1AQGMTAP/UaXXMhPzcjjLxBW0AccTdHUt"
+ "Li+K+rS5PNxxef2nnasEhCdK4GkM9nwJgsP0EZxCG3ZSAIlWIgQ3MK3ZAV1Au5pL"
+ "KolRjFyEZF420wAtiE7V+4lw3FCqNoXDJEFC3BW431kx1wAhDk9VaIHHadYcof4d"
+ "dmMLQOW2cJ7LDEEBW/WJAJUDBRA0M/VQImbGhU33abUBARcoA/9eerDBZGPCuGyE"
+ "mQBcr24KPJHWv/EZIKl5DM/Ynz1YZZbzLcvEFww34mvY0jCfoVcCKIeFFBMKiSKr"
+ "OMtoVC6cQMKpmhE9hYRStw4E0bcf0BD/stepdVtpwRnG8SDP2ZbmtgyjYT/7T4Yt"
+ "6/0f6N/0NC7E9qfq4ZlpU3uCGGu/44kAlQMFEDQz8kp2sPVxuCQEdQEBc5YD/Rix"
+ "vFcLTO1HznbblrO0WMzQc+R4qQ50CmCpWcFMwvVeQHo/bxoxGggNMmuVT0bqf7Mo"
+ "lZDSJNS96IAN32uf25tYHgERnQaMhmi1aSHvRDh4jxFu8gGVgL6lWit/vBDW/BiF"
+ "BCH6sZJJrGSuSdpecTtaWC8OJGDoKTO9PqAA/HQRiQB1AwUQNDJSx011eFs7VOAZ"
+ "AQGdKQL/ea3qD2OP3wVTzXvfjQL1CosX4wyKusBBhdt9u2vOT+KWkiRk1o35nIOG"
+ "uZLHtSFQDY8CVDOkqg6g4sVbOcTl8QUwHA+A4AVDInwTm1m4Bk4oeCIwk4Bp6mDd"
+ "W11g28k/iQEVAgUSNDIWPm/Y4wPDeaMxAQGvBQgAqGhzA/21K7oL/L5S5Xz//eO7"
+ "J8hgvqqGXWd13drNy3bHbKPn7TxilkA3ca24st+6YPZDdSUHLMCqg16YOMyQF8gE"
+ "kX7ZHWPacVoUpCmSz1uQ3p6W3+u5UCkRpgQN8wBbJx5ZpBBqeq5q/31okaoNjzA2"
+ "ghEWyR5Ll+U0C87MY7pc7PlNHGCr0ZNOhhtf1jU+H9ag5UyT6exIYim3QqWYruiC"
+ "LSUcim0l3wK7LMW1w/7Q6cWfAFQvl3rGjt3rg6OWg9J4H2h5ukf5JNiRybkupmat"
+ "UM+OVMRkf93jzU62kbyZpJBHiQZuxxJaLkhpv2RgWib9pbkftwEy/ZnmjkxlIIkA"
+ "lQMFEDQvWjh4313xYR8/NQEB37QEAIi9vR9h9ennz8Vi7RNU413h1ZoZjxfEbOpk"
+ "QAjE/LrZ/L5WiWdoStSiyqCLPoyPpQafiU8nTOr1KmY4RgceJNgxIW4OiSMoSvrh"
+ "c2kqP+skb8A2B4+47Aqjr5fSAVfVfrDMqDGireOguhQ/hf9BOYsM0gs+ROdtyLWP"
+ "tMjRnFlviD8DBRAz8qQSj6lRT5YOKXIRAntSAJ9StSEMBoFvk8iRWpXb6+LDNLUW"
+ "zACfT8iY3IxwvMF6jjCHrbuxQkL7chSJARUDBRA0MMO7569NIyeqD3EBATIAB/4t"
+ "CPZ1sLWO07g2ZCpiP1HlYpf5PENaXtaasFvhWch7eUe3DksuMEPzB5GnauoQZAku"
+ "hEGkoEfrfL3AXtXH+WMm2t7dIcTBD4p3XkeZ+PgJpKiASXDyul9rumXXvMxSL4KV"
+ "7ar+F1ZJ0ycCx2r2au0prPao70hDAzLTy16hrWgvdHSK7+wwaYO5TPCL5JDmcB+d"
+ "HKW72qNUOD0pxbe0uCkkb+gDxeVX28pZEkIIOMMV/eAs5bs/smV+eJqWT/EyfVBD"
+ "o7heF2aeyJj5ecxNOODr88xKF7qEpqazCQ4xhvFY+Yn6+vNCcYfkoZbOn0XQAvqf"
+ "a2Vab9woVIVSaDji/mlPiQB1AwUQNDC233FfeD4HYGBJAQFh6QL/XCgm5O3q9kWp"
+ "gts1MHKoHoh7vxSSQGSP2k7flNP1UB2nv4sKvyGM8eJKApuROIodcTkccM4qXaBu"
+ "XunMr5kJlvDJPm+NLzKyhtQP2fWI7xGYwiCiB29gm1GFMjdur4amiQEVAwUQNDBR"
+ "9fjDdqGixRdJAQE+mAf+JyqJZEVFwNwZ2hSIMewekC1r7N97p924nqfZKnzn6weF"
+ "pE80KIJSWtEVzI0XvHlVCOnS+WRxn7zxwrOTbrcEOy0goVbNgUsP5ypZa2/EM546"
+ "uyyJTvgD0nwA45Q4bP5sGhjh0G63r9Vwov7itFe4RDBGM8ibGnZTr9hHo469jpom"
+ "HSNeavcaUYyEqcr4GbpQmdpJTnn/H0A+fMl7ZHRoaclNx9ZksxihuCRrkQvUOb3u"
+ "RD9lFIhCvNwEardN62dKOKJXmn1TOtyanZvnmWigU5AmGuk6FpsClm3p5vvlid64"
+ "i49fZt9vW5krs2XfUevR4oL0IyUl+qW2HN0DIlDiAYkAlQMFEDQvbv2wcgJwUPMh"
+ "JQEBVBID/iOtS8CQfMxtG0EmrfaeVUU8R/pegBmVWDBULAp8CLTtdfxjVzs/6DXw"
+ "0RogXMRRl2aFfu1Yp0xhBYjII6Kque/FzAFXY9VNF1peqnPt7ADdeptYMppZa8sG"
+ "n9BBRu9Fsw69z6JkyqvMiVxGcKy3XEpVGr0JHx8Xt6BYdrULiKr2iQB1AwUQNC68"
+ "n6jZR/ntlUftAQFaYgL+NUYEj/sX9M5xq1ORX0SsVPMpNamHO3JBSmZSIzjiox5M"
+ "AqoFOCigAkonuzk5aBy/bRHy1cmDBOxf4mNhzrH8N6IkGvPE70cimDnbFvr+hoZS"
+ "jIqxtELNZsLuLVavLPAXiQCVAwUQNC6vWocCuHlnLQXBAQHb1gQAugp62aVzDCuz"
+ "4ntfXsmlGbLY7o5oZXYIKdPP4riOj4imcJh6cSgYFL6OMzeIp9VW/PHo2mk8kkdk"
+ "z5uif5LqOkEuIxgra7p1Yq/LL4YVhWGQeD8hwpmu+ulYoPOw40dVYS36PwrHIH9a"
+ "fNhl8Or5O2VIHIWnoQ++9r6gwngFQOyJAJUDBRAzHnkh1sNKtX1rroUBAWphBACd"
+ "huqm7GHoiXptQ/Y5F6BivCjxr9ch+gPSjaLMhq0kBHVO+TbXyVefVVGVgCYvFPjo"
+ "zM8PEVykQAtY//eJ475aGXjF+BOAhl2z0IMkQKCJMExoEDHbcj0jIIMZ2/+ptgtb"
+ "FSyJ2DQ3vvCdbw/1kyPHTPfP+L2u40GWMIYVBbyouokAlQMFEDMe7+UZsymln7HG"
+ "2QEBzMED/3L0DyPK/u6PyAd1AdpjUODTkWTZjZ6XA2ubc6IXXsZWpmCgB/24v8js"
+ "J3DIsvUD3Ke55kTr6xV+au+mAkwOQqWUTUWfQCkSrSDlbUJ1VPBzhyTpuzjBopte"
+ "7o3R6XXfcLiC5jY6eCX0QtLGhKpLjTr5uRhf1fYODGsAGXmCByDviQB1AgUQMy6U"
+ "MB0Z9MEMmFelAQHV4AMAjdFUIyFtpTr5jkyZSd3y//0JGO0z9U9hLVxeBBCwvdEQ"
+ "xsrpeTtVdqpeKZxHN1GhPCYvgLFZAQlcPh/Gc8u9uO7wVSgJc3zYKFThKpQevdF/"
+ "rzjTCHfgigf5Iui0qiqBiQCVAwUQMx22bAtzgG/ED06dAQFi0gQAkosqTMWy+1eU"
+ "Xbi2azFK3RX5ERf9wlN7mqh7TvwcPXvVWzUARnwRv+4kk3uOWI18q5UPis7KH3KY"
+ "OVeRrPd8bbp6SjhBh82ourTEQUXLBDQiI1V1cZZmwwEdlnAnhFnkXgMBNM2q7oBe"
+ "fRHADfYDfGo90wXyrVVL+GihDNpzUwOJAJUDBRAzHUFnOWvfULwOR3EBAbOYA/90"
+ "JIrKmxhwP6quaheFOjjPoxDGEZpGJEOwejEByYj+AgONCRmQS3BydtubA+nm/32D"
+ "FeG8pe/dnFvGc+QgNW560hK21C2KJj72mhjRlg/na7jz4/MmBAv5k61Q7roWi0rw"
+ "x+R9NSHxpshC8A92zmvo8w/XzVSogC8pJ04jcnY6YokAlQMFEDMdPtta9LwlvuSC"
+ "3QEBvPMD/3TJGroHhHYjHhiEpDZZVszeRQ0cvVI/uLLi5yq3W4F6Jy47DF8VckA7"
+ "mw0bXrOMNACN7Je7uyaU85qvJC2wgoQpFGdFlkjmkAwDAjR+koEysiE8FomiOHhv"
+ "EpEY/SjSS4jj4IPmgV8Vq66XjPw+i7Z0RsPLOIf67yZHxypNiBiYiQCVAwUQMxxw"
+ "pKrq6G7/78D5AQHo2QQAjnp6KxOl6Vvv5rLQ/4rj3OemvF7IUUq34xb25i/BSvGB"
+ "UpDQVUmhv/qIfWvDqWGZedyM+AlNSfUWPWnP41S8OH+lcERH2g2dGKGl7kH1F2Bx"
+ "ByZlqREHm2q624wPPA35RLXtXIx06yYjLtJ7b+FCAX6PUgZktZYk5gwjdoAGrC2J"
+ "AJUDBRAzGvcCKC6c7f53PGUBAUozA/9l/qKmcqbi8RtLsKQSh3vHds9d22zcbkuJ"
+ "PBSoOv2D7i2VLshaQFjq+62uYZGE6nU1WP5sZcBDuWjoX4t4NrffnOG/1R9D0t1t"
+ "9F47D77HJzjvo+J52SN520YHcbT8VoHdPRoEOXPN4tzhvn2GapVVdaAlWM0MLloh"
+ "NH3I9jap9okAdQMFEDMZlUAnyXglSykrxQEBnuwC/jXbFL+jzs2HQCuo4gyVrPlU"
+ "ksQCLYZjNnZtw1ca697GV3NhBhSXR9WHLQH+ZWnpTzg2iL3WYSdi9tbPs78iY1FS"
+ "d4EG8H9V700oQG8dlICF5W2VjzR7fByNosKM70WSXYkBFQMFEDMWBsGCy1t9eckW"
+ "HQEBHzMH/jmrsHwSPrA5R055VCTuDzdS0AJ+tuWkqIyqQQpqbost89Hxper3MmjL"
+ "Jas/VJv8EheuU3vQ9a8sG2SnlWKLtzFqpk7TCkyq/H3blub0agREbNnYhHHTGQFC"
+ "YJb4lWjWvMjfP+N5jvlLcnDqQPloXfAOgy7W90POoqFrsvhxdpnXgoLrzyNNja1O"
+ "1NRj+Cdv/GmJYNi6sQe43zmXWeA7syLKMw6058joDqEJFKndgSp3Zy/yXmObOZ/H"
+ "C2OJwA3gzEaAu8Pqd1svwGIGznqtTNCn9k1+rMvJPaxglg7PXIJS282hmBl9AcJl"
+ "wmh2GUCswl9/sj+REWTb8SgJUbkFcp6JAJUDBRAwdboVMPfsgxioXMEBAQ/LA/9B"
+ "FTZ9T95P/TtsxeC7lm9imk2mpNQCBEvXk286FQnGFtDodGfBfcH5SeKHaUNxFaXr"
+ "39rDGUtoTE98iAX3qgCElf4V2rzgoHLpuQzCg3U35dfs1rIxlpcSDk5ivaHpPV3S"
+ "v+mlqWL049y+3bGaZeAnwM6kvGMP2uccS9U6cbhpw4hGBBARAgAGBQI3GtRfAAoJ"
+ "EF3iSZZbA1iikWUAoIpSuXzuN/CI63dZtT7RL7c/KtWUAJ929SAtTr9SlpSgxMC8"
+ "Vk1T1i5/SYkBFQMFEzccnFnSJilEzmrGwQEBJxwH/2oauG+JlUC3zBUsoWhRQwqo"
+ "7DdqaPl7sH5oCGDKS4x4CRA23U15NicDI7ox6EizkwCjk0dRr1EeRK+RqL1b/2T4"
+ "2B6nynOLhRG2A0BPHRRJLcoL4nKfoPSo/6dIC+3iVliGEl90KZZD5bnONrVJQkRj"
+ "ZL8Ao+9IpmoYh8XjS5xMLEF9oAQqAkA93nVBm56lKmaL1kl+M3dJFtNKtVB8de1Z"
+ "XifDs8HykD42qYVtcseCKxZXhC3UTG5YLNhPvgZKH8WBCr3zcR13hFDxuecUmu0M"
+ "VhvEzoKyBYYt0rrqnyWrxwbv4gSTUWH5ZbgsTjc1SYKZxz6hrPQnfYWzNkznlFWJ"
+ "ARUDBRM0xL43CdxwOTnzf10BATOCB/0Q6WrpzwPMofjHj54MiGLKVP++Yfwzdvns"
+ "HxVpTZLZ5Ux8ErDsnLmvUGphnLVELZwEkEGRjln7a19h9oL8UYZaV+IcR6tQ06Fb"
+ "1ldR+q+3nXtBYzGhleXdgJQSKLJkzPF72tvY0DHUB//GUV9IBLQMvfG8If/AFsih"
+ "4iXi96DOtUAbeuIhnMlWwLJFeGjLLsX1u6HSX33xy4bGX6v/UcHbTSSYaxzb92GR"
+ "/xpP2Xt332hOFRkDZL52g27HS0UrEJWdAVZbh25KbZEl7C6zX/82OZ5nTEziHo20"
+ "eOS6Nrt2+gLSeA9X5h/+qUx30kTPz2LUPBQyIqLCJkHM8+0q5j9ciQCiAwUTNMS+"
+ "HZFeTizbCJMJAQFrGgRlEAkG1FYU4ufTxsaxhFZy7xv18527Yxpls6mSCi1HL55n"
+ "Joce6TI+Z34MrLOaiZljeQP3EUgzA+cs1sFRago4qz2wS8McmQ9w0FNQQMz4vVg9"
+ "CVi1JUVd4EWYvJpA8swDd5b9+AodYFEsfxt9Z3aP+AcWFb10RlVVsNw9EhObc6IM"
+ "nwAOHCEI9vp5FzzFiQCVAwUQNxyr6UyjTSyISdw9AQHf+wP+K+q6hIQ09tkgaYaD"
+ "LlWKLbuxePXqM4oO72qi70Gkg0PV5nU4l368R6W5xgR8ZkxlQlg85sJ0bL6wW/Sj"
+ "Mz7pP9hkhNwk0x3IFkGMTYG8i6Gt8Nm7x70dzJoiC+A496PryYC0rvGVf+Om8j5u"
+ "TexBBjb/jpJhAQ/SGqeDeCHheOC0Lldlcm5lciBLb2NoIChtZWluIGFsdGVyIGtl"
+ "eSkgPHdrQGNvbXB1dGVyLm9yZz6JAHUDBRM2G2MyHRn0wQyYV6UBASKKAv4wzmK7"
+ "a9Z+g0KH+6W8ffIhzrQo8wDAU9X1WJKzJjS205tx4mmdnAt58yReBc/+5HXTI8IK"
+ "R8IgF+LVXKWAGv5P5AqGhnPMeQSCs1JYdf9MPvbe34jD8wA1LTWFXn9e/cWIRgQQ"
+ "EQIABgUCNxrUaQAKCRBd4kmWWwNYovRiAJ9dJBVfjx9lGARoFXmAieYrMGDrmwCZ"
+ "AQyO4Wo0ntQ+iq4do9M3/FTFjiCZAaIENu1I6REEAJRGEqcYgXJch5frUYBj2EkD"
+ "kWAbhRqVXnmiF3PjCEGAPMMYsTddiU7wcKfiCAqKWWXow7BjTJl6Do8RT1jdKpPO"
+ "lBJXqqPYzsyBxLzE6mLps0K7SLJlSKTQqSVRcx0jx78JWYGlAlP0Kh9sPV2w/rPh"
+ "0LrPeOKXT7lZt/DrIhfPAKDL/sVqCrmY3QfvrT8kSKJcgtLWfQP/cfbqVNrGjW8a"
+ "m631N3UVA3tWfpgM/T9OjmKmw44NE5XfPJTAXlCV5j7zNMUkDeoPkrFF8DvbpYQs"
+ "4XWYHozDjhR2Q+eI6gZ0wfmhLHqqc2eVVkEG7dT57Wp9DAtCMe7RZfhnarTQMqlY"
+ "tOEa/suiHk0qLo59NsyF8eh68IDNCeYD/Apzonwaq2EQ1OEpfFlp6LcSnS34+UGZ"
+ "tTO4BgJdmEjr/QrIPp6bJDstgho+/2oR8yQwuHGJwbS/8ADA4IFEpLduSpzrABho"
+ "7RuNQcm96bceRY+7Hza3zf7pg/JGdWOb+bC3S4TIpK+3sx3YNWs7eURwpGREeJi5"
+ "/Seic+GXlGzltBpXZXJuZXIgS29jaCA8d2tAZ251cGcub3JnPohjBBMRAgAbBQI3"
+ "Gs+QBQkMyXyAAwsKAwMVAwIDFgIBAheAABIJEF3iSZZbA1iiB2VHUEcAAQFdwgCe"
+ "O/s43kCLDMIsHCb2H3LC59clC5UAn1EyrqWk+qcOXLpQIrP6Qa3QSmXIiEYEEBEC"
+ "AAYFAjca0T0ACgkQbH7huGIcwBOF9ACeNwO8G2G0ei03z0g/n3QZIpjbzvEAnRaE"
+ "qX2PuBbClWoIP6h9yrRlAEbUiQB1AwUQNxrRYx0Z9MEMmFelAQHRrgL/QDNKPV5J"
+ "gWziyzbHvEKfTIw/Ewv6El2MadVvQI8kbPN4qkPr2mZWwPzuc9rneCPQ1eL8AOdC"
+ "8+ZyxWzx2vsrk/FcU5donMObva2ct4kqJN6xl8xjsxDTJhBSFRaiBJjxiEYEEBEC"
+ "AAYFAjca0aMACgkQaLeriVdUjc0t+ACghK37H2vTYeXXieNJ8aZkiPJSte4An0WH"
+ "FOotQdTW4NmZJK+Uqk5wbWlgiEYEEBECAAYFAjdPH10ACgkQ9u7fIBhLxNktvgCe"
+ "LnQ5eOxAJz+Cvkb7FnL/Ko6qc5YAnjhWWW5c1o3onvKEH2Je2wQa8T6iiEYEEBEC"
+ "AAYFAjenJv4ACgkQmDRl2yFDlCJ+yQCfSy1zLftEfLuIHZsUHis9U0MlqLMAn2EI"
+ "f7TI1M5OKysQcuFLRC58CfcfiEUEEBECAAYFAjfhQTMACgkQNmdg8X0u14h55wCf"
+ "d5OZCV3L8Ahi4QW/JoXUU+ZB0M0AmPe2uw7WYDLOzv48H76tm6cy956IRgQQEQIA"
+ "BgUCOCpiDwAKCRDj8lhUEo8OeRsdAJ9FHupRibBPG2t/4XDqF+xiMLL/8ACfV5F2"
+ "SR0ITE4k/C+scS1nJ1KZUDW0C1dlcm5lciBLb2NoiGMEExECABsFAjbtSOoFCQzJ"
+ "fIADCwoDAxUDAgMWAgECF4AAEgkQXeJJllsDWKIHZUdQRwABAbXWAJ9SCW0ieOpL"
+ "7AY6vF+OIaMmw2ZW1gCgkto0eWfgpjAuVg6jXqR1wHt2pQOJAh4EEBQDAAYFAjcv"
+ "WdQACgkQbEwxpbHVFWcNxQf/bg14WGJ0GWMNSuuOOR0WYzUaNtzYpiLSVyLrreXt"
+ "o8LBNwzbgzj2ramW7Ri+tYJAHLhtua8ZgSeibmgBuZasF8db1m5NN1ZcHBXGTysA"
+ "jp+KnicTZ9Orj75D9o3oSmMyRcisEhr+gkj0tVhGfOAOC6eKbufVuyYFDVIyOyUB"
+ "GlW7ApemzAzYemfs3DdjHn87lkjHMVESO4fM5rtLuSc7cBfL/e6ljaWQc5W8S0gI"
+ "Dv0VtL39pMW4BlpKa25r14oJywuUpvWCZusvDm7ZJnqZ/WmgOHQUsyYudTROpGIb"
+ "lsNg8iqC6huWpGSBRdu3oRQRhkqpfVdszz6BB/nAx01q2wf/Q+U9XId1jyzxUL1S"
+ "GgaYMf6QdyjHQ1oxuFLNxzM6C/M069twbNgXJ71RsDDXVxFZfSTjSiH100AP9+9h"
+ "b5mycaXLUOXYDvOSFzHBd/LsjFNVrrFbDs5Xw+cLGVHOIgR5IWAfgu5d1PAZU9uQ"
+ "VgdGnQfmZg383RSPxvR3fnZz1rHNUGmS6w7x6FVbxa1QU2t38gNacIwHATAPcBpy"
+ "JLfXoznbpg3ADbgCGyDjBwnuPQEQkYwRakbczRrge8IaPZbt2HYPoUsduXMZyJI8"
+ "z5tvu7pUDws51nV1EX15BcN3++aY5pUyA1ItaaDymQVmoFbQC0BNMzMO53dMnFko"
+ "4i42kohGBBARAgAGBQI3OvmjAAoJEHUPZJXInZM+hosAnRntCkj/70shGTPxgpUF"
+ "74zA+EbzAKCcMkyHXIz2W0Isw3gDt27Z9ggsE4hGBBARAgAGBQI3NyPFAAoJEPbu"
+ "3yAYS8TZh2UAoJVmzw85yHJzsXQ1vpO2IAPfv59NAJ9WY0oiYqb3q1MSxBRwG0gV"
+ "iNCJ7YkBFQMFEDdD3tNSgFdEdlNAHQEByHEH/2JMfg71GgiyGJTKxCAymdyf2j2y"
+ "fH6wI782JK4BWV4c0E/V38q+jpIYslihV9t8s8w1XK5niMaLwlCOyBWOkDP3ech6"
+ "+GPPtfB3cmlL2hS896PWZ1adQHgCeQpB837n56yj0aTs4L1xarbSVT22lUwMiU6P"
+ "wYdH2Rh8nh8FvN0IZsbln2nOj73qANQzNflmseUKF1Xh4ck8yLrRd4r6amhxAVAf"
+ "cYFRJN4zdLL3cmhgkt0ADZlzAwXnEjwdHHy7SvAJk1ecNOA9pFsOJbvnzufd1afs"
+ "/CbG78I+0JDhg75Z2Nwq8eKjsKqiO0zz/vG5yWSndZvWkTWz3D3b1xr1Id2IRgQQ"
+ "EQIABgUCOCpiHgAKCRDj8lhUEo8OeQ+QAKCbOTscyUnWHSrDo4fIy0MThEjhOgCe"
+ "L4Kb7TWkd/OHQScVBO8sTUz0+2g=");
// private static readonly byte[] pub6check = Base64.Decode("62O9");
//
// revoked sub key
//
private static readonly byte[] pub7 = Base64.Decode(
"mQGiBEFOsIwRBADcjRx7nAs4RaWsQU6p8/ECLZD9sSeYc6CN6UDI96RKj0/hCzMs"
+ "qlA0+9fzGZ7ZEJ34nuvDKlhKGC7co5eOiE0a9EijxgcrZU/LClZWa4YfyNg/ri6I"
+ "yTyfOfrPQ33GNQt2iImDf3FKp7XKuY9nIxicGQEaW0kkuAmbV3oh0+9q8QCg/+fS"
+ "epDEqEE/+nKONULGizKUjMED/RtL6RThRftZ9DOSdBytGYd48z35pca/qZ6HA36K"
+ "PVQwi7V77VKQyKFLTOXPLnVyO85hyYB/Nv4DFHN+vcC7/49lfoyYMZlN+LarckHi"
+ "NL154wmmzygB/KKysvWBLgkErEBCD0xBDd89iTQNlDtVQAWGORVffl6WWjOAkliG"
+ "3dL6A/9A288HfFRnywqi3xddriV6wCPmStC3dkCS4vHk2ofS8uw4ZNoRlp1iEPna"
+ "ai2Xa9DX1tkhaGk2k96MqqbBdGpbW8sMA9otJ9xdMjWEm/CgJUFUFQf3zaVy3mkM"
+ "S2Lvb6P4Wc2l/diEEIyK8+PqJItSh0OVU3K9oM7ngHwVcalKILQVUkV2b2tlZCA8"
+ "UmV2b2tlZEB0ZWQ+iQBOBBARAgAOBQJBTrCMBAsDAgECGQEACgkQvglkcFA/c63+"
+ "QgCguh8rsJbPTtbhZcrqBi5Mo1bntLEAoPZQ0Kjmu2knRUpHBeUemHDB6zQeuQIN"
+ "BEFOsIwQCAD2Qle3CH8IF3KiutapQvMF6PlTETlPtvFuuUs4INoBp1ajFOmPQFXz"
+ "0AfGy0OplK33TGSGSfgMg71l6RfUodNQ+PVZX9x2Uk89PY3bzpnhV5JZzf24rnRP"
+ "xfx2vIPFRzBhznzJZv8V+bv9kV7HAarTW56NoKVyOtQa8L9GAFgr5fSI/VhOSdvN"
+ "ILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsYjY67VYy4XTjTNP18F1dD"
+ "ox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMI"
+ "PWakXUGfnHy9iUsiGSa6q6Jew1XpMgs7AAICB/93zriSvSHqsi1FeEmUBo431Jkh"
+ "VerIzb6Plb1j6FIq+s3vyvx9K+dMvjotZqylWZj4GXpH+2xLJTjWkrGSfUZVI2Nk"
+ "nyOFxUCKLLqaqVBFAQIjULfvQfGEWiGQKk9aRLkdG+D+8Y2N9zYoBXoQ9arvvS/t"
+ "4mlOsiuaTe+BZ4x+BXTpF4b9sKZl7V8QP/TkoJWUdydkvxciHdWp7ssqyiKOFRhG"
+ "818knDfFQ3cn2w/RnOb+7AF9wDncXDPYLfpPv9b2qZoLrXcyvlLffGDUdWs553ut"
+ "1F5AprMURs8BGmY9BnjggfVubHdhTUoA4gVvrdaf+D9NwZAl0xK/5Y/oPuMZiQBG"
+ "BBgRAgAGBQJBTrCMAAoJEL4JZHBQP3Ot09gAoMmLKloVDP+WhDXnsM5VikxysZ4+"
+ "AKCrJAUO+lYAyPYwEwgK+bKmUGeKrIkARgQoEQIABgUCQU6wpQAKCRC+CWRwUD9z"
+ "rQK4AJ98kKFxGU6yhHPr6jYBJPWemTNOXgCfeGB3ox4PXeS4DJDuLy9yllytOjo=");
// private static readonly byte[] pub7check = Base64.Decode("f/YQ");
private static readonly byte[] pub8 = Base64.Decode(
"mQGiBEEcraYRBADFYj+uFOhHz5SdECvJ3Z03P47gzmWLQ5HH8fPYC9rrv7AgqFFX"
+ "aWlJJVMLua9e6xoCiDWJs/n4BbZ/weL/11ELg6XqUnzFhYyz0H2KFsPgQ/b9lWLY"
+ "MtcPMFy5jE33hv/ixHgYLFqoNaAIbg0lzYEW/otQ9IhRl16fO1Q/CQZZrQCg/9M2"
+ "V2BTmm9RYog86CXJtjawRBcD/RIqU0zulxZ2Zt4javKVxrGIwW3iBU935ebmJEIK"
+ "Y5EVkGKBOCvsApZ+RGzpYeR2uMsTnQi8RJgiAnjaoVPCdsVJE7uQ0h8XuJ5n5mJ2"
+ "kLCFlF2hj5ViicZzse+crC12CGtgRe8z23ubLRcd6IUGhVutK8/b5knZ22vE14JD"
+ "ykKdA/96ObzJQdiuuPsEWN799nUUCaYWPAoLAmiXuICSP4GEnxLbYHWo8zhMrVMT"
+ "9Q5x3h8cszUz7Acu2BXjP1m96msUNoxPOZtt88NlaFz1Q/JSbQTsVOMd9b/IRN6S"
+ "A/uU0BiKEMHXuT8HUHVPK49oCKhZrGFP3RT8HZxDKLmR/qrgZ7ABh7QhSmlhIFlp"
+ "eXUgPHl5amlhQG5vd21lZGlhdGVjaC5jb20+sAMD//+JAF0EEBECAB0FAkEcraYH"
+ "CwkIBwMCCgIZAQUbAwAAAAUeAQAAAAAKCRD0/lb4K/9iFJlhAKCRMifQewiX5o8F"
+ "U099FG3QnLVUZgCfWpMOsHulGHfNrxdBSkE5Urqh1ymwAWe5Ag0EQRytphAIAPZC"
+ "V7cIfwgXcqK61qlC8wXo+VMROU+28W65Szgg2gGnVqMU6Y9AVfPQB8bLQ6mUrfdM"
+ "ZIZJ+AyDvWXpF9Sh01D49Vlf3HZSTz09jdvOmeFXklnN/biudE/F/Ha8g8VHMGHO"
+ "fMlm/xX5u/2RXscBqtNbno2gpXI61Brwv0YAWCvl9Ij9WE5J280gtJ3kkQc2azNs"
+ "OA1FHQ98iLMcfFstjvbzySPAQ/ClWxiNjrtVjLhdONM0/XwXV0OjHRhs3jMhLLUq"
+ "/zzhsSlAGBGNfISnCnLWhsQDGcgHKXrKlQzZlp+r0ApQmwJG0wg9ZqRdQZ+cfL2J"
+ "SyIZJrqrol7DVekyCzsAAgIH/3K2wKRSzkIpDfZR25+tnQ8brv3TYoDZo3/wN3F/"
+ "r6PGjx0150Q8g8EAC0bqm4rXWzOqdSxYxvIPOAGm5P4y+884yS6j3vKcXitT7vj+"
+ "ODc2pVwGDLDjrMRrosSK89ycPCK6R/5pD7Rv4l9DWi2fgLvXqJHS2/ujUf2uda9q"
+ "i9xNMnBXIietR82Sih4undFUOwh6Mws/o3eed9DIdaqv2Y2Aw43z/rJ6cjSGV3C7"
+ "Rkf9x85AajYA3LwpS8d99tgFig2u6V/A16oi6/M51oT0aR/ZAk50qUc4WBk9uRUX"
+ "L3Y+P6v6FCBE/06fgVltwcQHO1oKYKhH532tDL+9mW5/dYGwAYeJAEwEGBECAAwF"
+ "AkEcraYFGwwAAAAACgkQ9P5W+Cv/YhShrgCg+JW8m5nF3R/oZGuG87bXQBszkjMA"
+ "oLhGPncuGKowJXMRVc70/8qwXQJLsAFnmQGiBD2K5rYRBADD6kznWZA9nH/pMlk0"
+ "bsG4nI3ELgyI7KpgRSS+Dr17+CCNExxCetT+fRFpiEvUcSxeW4pOe55h0bQWSqLo"
+ "MNErXVJEXrm1VPkC08W8D/gZuPIsdtKJu4nowvdoA+WrI473pbeONGjaEDbuIJak"
+ "yeKM1VMSGhsImdKtxqhndq2/6QCg/xARUIzPRvKr2TJ52K393895X1kEAMCdjSs+"
+ "vABnhaeNNR5+NNkkIOCCjCS8qZRZ4ZnIayvn9ueG3KrhZeBIHoajUHrlTXBVj7XO"
+ "wXVfGpW17jCDiqhU8Pu6VwEwX1iFbuUwqBffiRLXKg0zfcN+MyFKToi+VsJi4jiZ"
+ "zcwUFMb8jE8tvR/muXti7zKPRPCbNBExoCt4A/0TgkzAosG/W4dUkkbc6XoHrjob"
+ "iYuy6Xbs/JYlV0vf2CyuKCZC6UoznO5x2GkvOyVtAgyG4HSh1WybdrutZ8k0ysks"
+ "mOthE7n7iczdj9Uwg2h+TfgDUnxcCAwxnOsX5UaBqGdkX1PjCWs+O3ZhUDg6UsZc"
+ "7O5a3kstf16lHpf4q7ABAIkAYQQfEQIAIQUCPYrmtgIHABcMgBHRi/xlIgI+Q6LT"
+ "kNJ7zKvTd87NHAAKCRDJM3gHb/sRj7bxAJ9f6mdlXQH7gMaYiY5tBe/FRtPr1gCf"
+ "UhDJQG0ARvORFWHjwhhBMLxW7j2wAWC0KkRlc21vbmQgS2VlIDxkZXNtb25kLmtl"
+ "ZUBub3dtZWRpYXRlY2guY29tPrADAQD9iQBYBBARAgAYBQI9iua2CAsDCQgHAgEK"
+ "AhkBBRsDAAAAAAoJEMkzeAdv+xGP7v4An19iqadBCCgDIe2DTpspOMidwQYPAJ4/"
+ "5QXbcn4ClhOKTO3ZEZefQvvL27ABYLkCDQQ9iua2EAgA9kJXtwh/CBdyorrWqULz"
+ "Bej5UxE5T7bxbrlLOCDaAadWoxTpj0BV89AHxstDqZSt90xkhkn4DIO9ZekX1KHT"
+ "UPj1WV/cdlJPPT2N286Z4VeSWc39uK50T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq"
+ "01uejaClcjrUGvC/RgBYK+X0iP1YTknbzSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O"
+ "9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdXQ6MdGGzeMyEstSr/POGxKUAYEY18hKcK"
+ "ctaGxAMZyAcpesqVDNmWn6vQClCbAkbTCD1mpF1Bn5x8vYlLIhkmuquiXsNV6TIL"
+ "OwACAgf/SO+bbg+owbFKVN5HgOjOElQZVnCsegwCLqTeQzPPzsWmkGX2qZJPDIRN"
+ "RZfJzti6+oLJwaRA/3krjviUty4VKhZ3lKg8fd9U0jEdnw+ePA7yJ6gZmBHL15U5"
+ "OKH4Zo+OVgDhO0c+oetFpend+eKcvtoUcRoQoi8VqzYUNG0b/nmZGDlxQe1/ZNbP"
+ "HpNf1BAtJXivCEKMD6PVzsLPg2L4tFIvD9faeeuKYQ4jcWtTkBLuIaZba3i3a4wG"
+ "xTN20j9HpISVuLW/EfZAK1ef4DNjLmHEU9dMzDqfi+hPmMbGlFqcKr+VjcYIDuje"
+ "o+92xm/EWAmlti88r2hZ3MySamHDrLABAIkATAQYEQIADAUCPYrmtgUbDAAAAAAK"
+ "CRDJM3gHb/sRjzVTAKDVS+OJLMeS9VLAmT8atVCB42MwIQCgoh1j3ccWnhc/h6B7"
+ "9Uqz3fUvGoewAWA=");
private static readonly byte[] sec8 = Base64.Decode(
"lQHpBEEcraYRBADFYj+uFOhHz5SdECvJ3Z03P47gzmWLQ5HH8fPYC9rrv7AgqFFX"
+ "aWlJJVMLua9e6xoCiDWJs/n4BbZ/weL/11ELg6XqUnzFhYyz0H2KFsPgQ/b9lWLY"
+ "MtcPMFy5jE33hv/ixHgYLFqoNaAIbg0lzYEW/otQ9IhRl16fO1Q/CQZZrQCg/9M2"
+ "V2BTmm9RYog86CXJtjawRBcD/RIqU0zulxZ2Zt4javKVxrGIwW3iBU935ebmJEIK"
+ "Y5EVkGKBOCvsApZ+RGzpYeR2uMsTnQi8RJgiAnjaoVPCdsVJE7uQ0h8XuJ5n5mJ2"
+ "kLCFlF2hj5ViicZzse+crC12CGtgRe8z23ubLRcd6IUGhVutK8/b5knZ22vE14JD"
+ "ykKdA/96ObzJQdiuuPsEWN799nUUCaYWPAoLAmiXuICSP4GEnxLbYHWo8zhMrVMT"
+ "9Q5x3h8cszUz7Acu2BXjP1m96msUNoxPOZtt88NlaFz1Q/JSbQTsVOMd9b/IRN6S"
+ "A/uU0BiKEMHXuT8HUHVPK49oCKhZrGFP3RT8HZxDKLmR/qrgZ/4JAwLXyWhb4pf4"
+ "nmCmD0lDwoYvatLiR7UQVM2MamxClIiT0lCPN9C2AYIFgRWAJNS215Tjx7P/dh7e"
+ "8sYfh5XEHErT3dMbsAGHtCFKaWEgWWl5dSA8eXlqaWFAbm93bWVkaWF0ZWNoLmNv"
+ "bT6wAwP//4kAXQQQEQIAHQUCQRytpgcLCQgHAwIKAhkBBRsDAAAABR4BAAAAAAoJ"
+ "EPT+Vvgr/2IUmWEAoJEyJ9B7CJfmjwVTT30UbdCctVRmAJ9akw6we6UYd82vF0FK"
+ "QTlSuqHXKbABZ50CawRBHK2mEAgA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlL"
+ "OCDaAadWoxTpj0BV89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N"
+ "286Z4VeSWc39uK50T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/"
+ "RgBYK+X0iP1YTknbzSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2O"
+ "u1WMuF040zT9fBdXQ6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqV"
+ "DNmWn6vQClCbAkbTCD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwACAgf/crbApFLO"
+ "QikN9lHbn62dDxuu/dNigNmjf/A3cX+vo8aPHTXnRDyDwQALRuqbitdbM6p1LFjG"
+ "8g84Aabk/jL7zzjJLqPe8pxeK1Pu+P44NzalXAYMsOOsxGuixIrz3Jw8IrpH/mkP"
+ "tG/iX0NaLZ+Au9eokdLb+6NR/a51r2qL3E0ycFciJ61HzZKKHi6d0VQ7CHozCz+j"
+ "d5530Mh1qq/ZjYDDjfP+snpyNIZXcLtGR/3HzkBqNgDcvClLx3322AWKDa7pX8DX"
+ "qiLr8znWhPRpH9kCTnSpRzhYGT25FRcvdj4/q/oUIET/Tp+BWW3BxAc7WgpgqEfn"
+ "fa0Mv72Zbn91gf4JAwITijME9IlFBGAwH6YmBtWIlnDiRbsq/Pxozuhbnes831il"
+ "KmdpUKXkiIfHY0MqrEWl3Dfn6PMJGTnhgqXMrDxx3uHrq0Jl2swRnAWIIO8gID7j"
+ "uPetUqEviPiwAYeJAEwEGBECAAwFAkEcraYFGwwAAAAACgkQ9P5W+Cv/YhShrgCg"
+ "+JW8m5nF3R/oZGuG87bXQBszkjMAoLhGPncuGKowJXMRVc70/8qwXQJLsAFn");
private static readonly char[] sec8pass = "qwertyui".ToCharArray();
private static readonly byte[] sec9 = Base64.Decode(
"lQGqBEHCokERBAC9rh5SzC1sX1y1zoFuBB/v0SGhoKMEvLYf8Qv/j4deAMrc"
+ "w5dxasYoD9oxivIUfTbZKo8cqr+dKLgu8tycigTM5b/T2ms69SUAxSBtj2uR"
+ "LZrh4vjC/93kF+vzYJ4fNaBs9DGfCnsTouKjXqmfN3SlPMKNcGutO7FaUC3d"
+ "zcpYfwCg7qyONHvXPhS0Iw4QL3mJ/6wMl0UD/0PaonqW0lfGeSjJSM9Jx5Bt"
+ "fTSlwl6GmvYmI8HKvOBXAUSTZSbEkMsMVcIgf577iupzgWCgNF6WsNqQpKaq"
+ "QIq1Kjdd0Y00xU1AKflOkhl6eufTigjviM+RdDlRYsOO5rzgwDTRTu9giErs"
+ "XIyJAIZIdu2iaBHX1zHTfJ1r7nlAA/9H4T8JIhppUk/fLGsoPNZzypzVip8O"
+ "mFb9PgvLn5GmuIC2maiocT7ibbPa7XuXTO6+k+323v7PoOUaKD3uD93zHViY"
+ "Ma4Q5pL5Ajc7isnLXJgJb/hvvB1oo+wSDo9vJX8OCSq1eUPUERs4jm90/oqy"
+ "3UG2QVqs5gcKKR4o48jTiv4DZQJHTlUBtB1mb28ga2V5IDxmb28ua2V5QGlu"
+ "dmFsaWQuY29tPoheBBMRAgAeBQJBwqJCAhsDBgsJCAcDAgMVAgMDFgIBAh4B"
+ "AheAAAoJEOKcXvehtw4ajJMAoK9nLfsrRY6peq56l/KzmjzuaLacAKCXnmiU"
+ "waI7+uITZ0dihJ3puJgUz50BWARBwqJDEAQA0DPcNIn1BQ4CDEzIiQkegNPY"
+ "mkYyYWDQjb6QFUXkuk1WEB73TzMoemsA0UKXwNuwrUgVhdpkB1+K0OR/e5ik"
+ "GhlFdrDCqyT+mw6dRWbJ2i4AmFXZaRKO8AozZeWojsfP1/AMxQoIiBEteMFv"
+ "iuXnZ3pGxSfZYm2+33IuPAV8KKMAAwUD/0C2xZQXgVWTiVz70HUviOmeTQ+f"
+ "b1Hj0U9NMXWB383oQRBZCvQDM12cqGsvPZuZZ0fkGehGAIoyXtIjJ9lejzZN"
+ "1TE9fnXZ9okXI4yCl7XLSE26OAbNsis4EtKTNScNaU9Dk3CS5XD/pkRjrkPN"
+ "2hdUFtshuGmYkqhb9BIlrwE7/gMDAglbVSwecr9mYJcDYCH62U9TScWDTzsQ"
+ "NFEfhMez3hGnNHNfHe+7yN3+Q9/LIhbba3IJEN5LsE5BFvudLbArp56EusIn"
+ "JCxgiEkEGBECAAkFAkHCokMCGwwACgkQ4pxe96G3Dho2UQCeN3VPwx3dROZ+"
+ "4Od8Qj+cLrBndGEAn0vaQdy6eIGeDw2I9u3Quwy6JnROnQHhBEHCozMRBADH"
+ "ZBlB6xsAnqFYtYQOHr4pX6Q8TrqXCiHHc/q56G2iGbI9IlbfykQzaPHgWqZw"
+ "9P0QGgF/QZh8TitiED+imLlGDqj3nhzpazqDh5S6sg6LYkQPqhwG/wT5sZQQ"
+ "fzdeupxupjI5YN8RdIqkWF+ILOjk0+awZ4z0TSY/f6OSWpOXlwCgjIquR3KR"
+ "tlCLk+fBlPnOXaOjX+kEAJw7umykNIHNaoY/2sxNhQhjqHVxKyN44y6FCSv9"
+ "jRyW8Q/Qc8YhqBIHdmlcXoNWkDtlvErjdYMvOKFqKB1e2bGpjvhtIhNVQWdk"
+ "oHap9ZuM1nV0+fD/7g/NM6D9rOOVCahBG2fEEeIwxa2CQ7zHZYfg9Umn3vbh"
+ "TYi68R3AmgLOA/wKIVkfFKioI7iX4crQviQHJK3/A90SkrjdMQwLoiUjdgtk"
+ "s7hJsTP1OPb2RggS1wCsh4sv9nOyDULj0T0ySGv7cpyv5Nq0FY8gw2oogHs5"
+ "fjUnG4VeYW0zcIzI8KCaJT4UhR9An0A1jF6COrYCcjuzkflFbQLtQb9uNj8a"
+ "hCpU4/4DAwIUxXlRMYE8uWCranzPo83FnBPRnGJ2aC9SqZWJYVUKIn4Vf2nu"
+ "pVvCGFja0usl1WfV72hqlNKEONq7lohJBBgRAgAJBQJBwqMzAhsCAAoJEOKc"
+ "Xvehtw4afisAoME/t8xz/rj/N7QRN9p8Ji8VPGSqAJ9K8eFJ+V0mxR+octJr"
+ "6neEEX/i1Q==");
public char[] sec9pass = "foo".ToCharArray();
// version 4 keys with expiry dates
private static readonly byte[] pub10 = Base64.Decode(
"mQGiBEKqia0RBACc3hkufmscRSC4UvPZqMDsHm4+d/GXIr+3iNMSSEySJu8yk+k0"
+ "Xs11C/K+n+v1rnn2jGGknv+1lDY6w75TIcTE6o6HGKeIDxsAm8P3MhoGU1GNPamA"
+ "eTDeNybtrN/g6C65fCY9uI11hsUboYgQZ8ND22PB0VtvdOgq9D85qNUzxwCg1BbJ"
+ "ycAKd4VqEvQ2Zglp3dCSrFMD/Ambq1kZqYa69sp3b9BPKuAgUgUPoytOArEej3Bk"
+ "easAgAxNhWJy4GxigES3vk50rVi7w8XBuqbD1mQCzldF0HX0/A7PxLBv6od5uqqF"
+ "HFxIyxg/KBZLd9ZOrsSaoUWH58jZq98X/sFtJtRi5VuJagMxCIJD4mLgtMv7Unlb"
+ "/GrsA/9DEnObA/fNTgK70T+ZmPIS5tSt+bio30Aw4YGpPCGqpnm1u73b5kqX3U3B"
+ "P+vGDvFuqZYpqQA8byAueH0MbaDHI4CFugvShXvgysJxN7ov7/8qsZZUMfK1t2Nr"
+ "SAsPuKRbcY4gNKXIElKeXbyaET7vX7uAEKuxEwdYGFp/lNTkHLQgdGVzdCBrZXkg"
+ "KHRlc3QpIDx0ZXN0QHRlc3QudGVzdD6IZAQTEQIAJAUCQqqJrQIbAwUJACTqAAYL"
+ "CQgHAwIDFQIDAxYCAQIeAQIXgAAKCRDjDROQZRqIzDzLAJ42AeCRIBBjv8r8qw9y"
+ "laNj2GZ1sACgiWYHVXMA6B1H9I1kS3YsCd3Oq7qwAgAAuM0EQqqJrhADAKWkix8l"
+ "pJN7MMTXob4xFF1TvGll0UD1bDGOMMbes6aeXSbT9QXee/fH3GnijLY7wB+qTPv9"
+ "ohubrSpnv3yen3CEBW6Q2YK+NlCskma42Py8YMV2idmYjtJi1ckvHFWt5wADBQL/"
+ "fkB5Q5xSGgspMaTZmtmX3zG7ZDeZ0avP8e8mRL8UszCTpqs6vMZrXwyQLZPbtMYv"
+ "PQpuRGEeKj0ysimwYRA5rrLQjnRER3nyuuEUUgc4j+aeRxPf9WVsJ/a1FCHtaAP1"
+ "iE8EGBECAA8FAkKqia4CGwwFCQAk6gAACgkQ4w0TkGUaiMzdqgCfd66H7DL7kFGd"
+ "IoS+NIp8JO+noxAAn25si4QAF7og8+4T5YQUuhIhx/NesAIAAA==");
private static readonly byte[] sec10 = Base64.Decode(
"lQHhBEKqia0RBACc3hkufmscRSC4UvPZqMDsHm4+d/GXIr+3iNMSSEySJu8yk+k0"
+ "Xs11C/K+n+v1rnn2jGGknv+1lDY6w75TIcTE6o6HGKeIDxsAm8P3MhoGU1GNPamA"
+ "eTDeNybtrN/g6C65fCY9uI11hsUboYgQZ8ND22PB0VtvdOgq9D85qNUzxwCg1BbJ"
+ "ycAKd4VqEvQ2Zglp3dCSrFMD/Ambq1kZqYa69sp3b9BPKuAgUgUPoytOArEej3Bk"
+ "easAgAxNhWJy4GxigES3vk50rVi7w8XBuqbD1mQCzldF0HX0/A7PxLBv6od5uqqF"
+ "HFxIyxg/KBZLd9ZOrsSaoUWH58jZq98X/sFtJtRi5VuJagMxCIJD4mLgtMv7Unlb"
+ "/GrsA/9DEnObA/fNTgK70T+ZmPIS5tSt+bio30Aw4YGpPCGqpnm1u73b5kqX3U3B"
+ "P+vGDvFuqZYpqQA8byAueH0MbaDHI4CFugvShXvgysJxN7ov7/8qsZZUMfK1t2Nr"
+ "SAsPuKRbcY4gNKXIElKeXbyaET7vX7uAEKuxEwdYGFp/lNTkHP4DAwLssmOjVC+d"
+ "mWB783Lpzjb9evKzsxisTdx8/jHpUSS+r//6/Guyx3aA/zUw5bbftItW57mhuNNb"
+ "JTu7WrQgdGVzdCBrZXkgKHRlc3QpIDx0ZXN0QHRlc3QudGVzdD6IZAQTEQIAJAUC"
+ "QqqJrQIbAwUJACTqAAYLCQgHAwIDFQIDAxYCAQIeAQIXgAAKCRDjDROQZRqIzDzL"
+ "AJ0cYPwKeoSReY14LqJtAjnkX7URHACgsRZWfpbalrSyDnq3TtZeGPUqGX+wAgAA"
+ "nQEUBEKqia4QAwClpIsfJaSTezDE16G+MRRdU7xpZdFA9WwxjjDG3rOmnl0m0/UF"
+ "3nv3x9xp4oy2O8Afqkz7/aIbm60qZ798np9whAVukNmCvjZQrJJmuNj8vGDFdonZ"
+ "mI7SYtXJLxxVrecAAwUC/35AeUOcUhoLKTGk2ZrZl98xu2Q3mdGrz/HvJkS/FLMw"
+ "k6arOrzGa18MkC2T27TGLz0KbkRhHio9MrIpsGEQOa6y0I50REd58rrhFFIHOI/m"
+ "nkcT3/VlbCf2tRQh7WgD9f4DAwLssmOjVC+dmWDXVLRopzxbBGOvodp/LZoSDb56"
+ "gNJjDMJ1aXqWW9qTAg1CFjBq73J3oFpVzInXZ8+Q8inxv7bnWiHbiE8EGBECAA8F"
+ "AkKqia4CGwwFCQAk6gAACgkQ4w0TkGUaiMzdqgCgl2jw5hfk/JsyjulQqe1Nps1q"
+ "Lx0AoMdnFMZmTMLHn8scUW2j9XO312tmsAIAAA==");
// private static readonly char[] sec10pass = "test".ToCharArray();
private static readonly byte[] subKeyBindingKey = Base64.Decode(
"mQGiBDWagYwRBAD7UcH4TAIp7tmUoHBNxVxCVz2ZrNo79M6fV63riOiH2uDxfIpr"
+ "IrL0cM4ehEKoqlhngjDhX60eJrOw1nC5BpYZRnDnyDYT4wTWRguxObzGq9pqA1dM"
+ "oPTJhkFZVIBgFY99/ULRqaUYIhFGgBtnwS70J8/L/PGVc3DmWRLMkTDjSQCg/5Nh"
+ "MCjMK++MdYMcMl/ziaKRT6EEAOtw6PnU9afdohbpx9CK4UvCCEagfbnUtkSCQKSk"
+ "6cUp6VsqyzY0pai/BwJ3h4apFMMMpVrtBAtchVgqo4xTr0Sve2j0k+ase6FSImiB"
+ "g+AR7hvTUTcBjwtIExBc8TuCTqmn4GG8F7UMdl5Z0AZYj/FfAQYaRVZYP/pRVFNx"
+ "Lw65BAC/Fi3qgiGCJFvXnHIckTfcAmZnKSEXWY9NJ4YQb4+/nH7Vsw0wR/ZObUHR"
+ "bWgTc9Vw1uZIMe0XVj6Yk1dhGRehUnrm3mE7UJxu7pgkBCbFECFSlSSqP4MEJwZV"
+ "09YP/msu50kjoxyoTpt+16uX/8B4at24GF1aTHBxwDLd8X0QWrQsTWVycmlsbCBM"
+ "eW5jaCBDTEVBUiBzeXN0ZW0gREggPGNsZWFyQG1sLmNvbT6JAEsEEBECAAsFAjWa"
+ "gYwECwMBAgAKCRDyAGjiP47/XanfAKCs6BPURWVQlGh635VgL+pdkUVNUwCdFcNa"
+ "1isw+eAcopXPMj6ACOapepu5Ag0ENZqBlBAIAPZCV7cIfwgXcqK61qlC8wXo+VMR"
+ "OU+28W65Szgg2gGnVqMU6Y9AVfPQB8bLQ6mUrfdMZIZJ+AyDvWXpF9Sh01D49Vlf"
+ "3HZSTz09jdvOmeFXklnN/biudE/F/Ha8g8VHMGHOfMlm/xX5u/2RXscBqtNbno2g"
+ "pXI61Brwv0YAWCvl9Ij9WE5J280gtJ3kkQc2azNsOA1FHQ98iLMcfFstjvbzySPA"
+ "Q/ClWxiNjrtVjLhdONM0/XwXV0OjHRhs3jMhLLUq/zzhsSlAGBGNfISnCnLWhsQD"
+ "GcgHKXrKlQzZlp+r0ApQmwJG0wg9ZqRdQZ+cfL2JSyIZJrqrol7DVekyCzsAAgIH"
+ "/RYtVo+HROZ6jrNjrATEwQm1fUQrk6n5+2dniN881lF0CNkB4NkHw1Xxz4Ejnu/0"
+ "iLg8fkOAsmanOsKpOkRtqUnVpsVL5mLJpFEyCY5jbcfj+KY9/25bs0ga7kLHNZia"
+ "zbCxJdF+W179z3nudQxRaXG/0XISIH7ziZbSVni69sKc1osk1+OoOMbSuZ86z535"
+ "Pln4fXclkFE927HxfbWoO+60hkOLKh7x+8fC82b3x9vCETujEaxrscO2xS7/MYXP"
+ "8t1ffriTDmhuIuQS2q4fLgeWdqrODrMhrD8Dq7e558gzp30ZCqpiS7EmKGczL7B8"
+ "gXxbBCVSTxYMJheXt2xMXsuJAD8DBRg1moGU8gBo4j+O/10RAgWdAKCPhaFIXuC8"
+ "/cdiNMxTDw9ug3De5QCfYXmDzRSFUu/nrCi8yz/l09wsnxo=");
// private static readonly byte[] subKeyBindingCheckSum = Base64.Decode("3HU+");
//
// PGP8 with SHA1 checksum.
//
private static readonly byte[] rewrapKey = Base64.Decode(
"lQOWBEUPOQgBCADdjPTtl8oOwqJFA5WU8p7oDK5KRWfmXeXUZr+ZJipemY5RSvAM"
+ "rxqsM47LKYbmXOJznXCQ8+PPa+VxXAsI1CXFHIFqrXSwvB/DUmb4Ec9EuvNd18Zl"
+ "hJAybzmV2KMkaUp9oG/DUvxZJqkpUddNfwqZu0KKKZWF5gwW5Oy05VCpaJxQVXFS"
+ "whdbRfwEENJiNx4RB3OlWhIjY2p+TgZfgQjiGB9i15R+37sV7TqzBUZF4WWcnIRQ"
+ "DnpUfxHgxQ0wO/h/aooyRHSpIx5i4oNpMYq9FNIyakEx/Bomdbs5hW9dFxhrE8Es"
+ "UViAYITgTsyROxmgGatGG09dcmVDJVYF4i7JAAYpAAf/VnVyUDs8HrxYTOIt4rYY"
+ "jIHToBsV0IiLpA8fEA7k078L1MwSwERVVe6oHVTjeR4A9OxE52Vroh2eOLnF3ftf"
+ "6QThVVZr+gr5qeG3yvQ36N7PXNEVOlkyBzGmFQNe4oCA+NR2iqnAIspnekVmwJV6"
+ "xVvPCjWw/A7ZArDARpfthspwNcJAp4SWfoa2eKzvUTznTyqFu2PSS5fwQZUgOB0P"
+ "Y2FNaKeqV8vEZu4SUWwLOqXBQIZXiaLvdKNgwFvUe3kSHdCNsrVzW7SYxFwaEog2"
+ "o6YLKPVPqjlGX1cMOponGp+7n9nDYkQjtEsGSSMQkQRDAcBdSVJmLO07kFOQSOhL"
+ "WQQA49BcgTZyhyH6TnDBMBHsGCYj43FnBigypGT9FrQHoWybfX47yZaZFROAaaMa"
+ "U6man50YcYZPwzDzXHrK2MoGALY+DzB3mGeXVB45D/KYtlMHPLgntV9T5b14Scbc"
+ "w1ES2OUtsSIUs0zelkoXqjLuKnSIYK3mMb67Au7AEp6LXM8EAPj2NypvC86VEnn+"
+ "FH0QHvUwBpmDw0EZe25xQs0brvAG00uIbiZnTH66qsIfRhXV/gbKK9J5DTGIqQ15"
+ "DuPpz7lcxg/n2+SmjQLNfXCnG8hmtBjhTe+udXAUrmIcfafXyu68SAtebgm1ga56"
+ "zUfqsgN3FFuMUffLl3myjyGsg5DnA/oCFWL4WCNClOgL6A5VkNIUait8QtSdCACT"
+ "Y7jdSOguSNXfln0QT5lTv+q1AjU7zjRl/LsFNmIJ5g2qdDyK937FOXM44FEEjZty"
+ "/4P2dzYpThUI4QUohIj8Qi9f2pZQueC5ztH6rpqANv9geZKcciAeAbZ8Md0K2TEU"
+ "RD3Lh+RSBzILtBtUZXN0IEtleSA8dGVzdEBleGFtcGxlLmNvbT6JATYEEwECACAF"
+ "AkUPOQgCGwMGCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAKCRDYpknHeQaskD9NB/9W"
+ "EbFuLaqZAl3yjLU5+vb75BdvcfL1lUs44LZVwobNp3/0XbZdY76xVPNZURtU4u3L"
+ "sJfGlaF+EqZDE0Mqc+vs5SIb0OnCzNJ00KaUFraUtkByRV32T5ECHK0gMBjCs5RT"
+ "I0vVv+Qmzl4+X1Y2bJ2mlpBejHIrOzrBD5NTJimTAzyfnNfipmbqL8p/cxXKKzS+"
+ "OM++ZFNACj6lRM1W9GioXnivBRC88gFSQ4/GXc8yjcrMlKA27JxV+SZ9kRWwKH2f"
+ "6o6mojUQxnHr+ZFKUpo6ocvTgBDlC57d8IpwJeZ2TvqD6EdA8rZ0YriVjxGMDrX1"
+ "8esfw+iLchfEwXtBIRwS");
private static readonly char[] rewrapPass = "voltage123".ToCharArray();
private static readonly byte[] pubWithX509 = Base64.Decode(
"mQENBERabjABCACtmfyo6Nph9MQjv4nmCWjZrRYnhXbivomAdIwYkLZUj1bjqE+j"
+ "uaLzjZV8xSI59odZvrmOiqlzOc4txitQ1OX7nRgbOJ7qku0dvwjtIn46+HQ+cAFn"
+ "2mTi81RyXEpO2uiZXfsNTxUtMi+ZuFLufiMc2kdk27GZYWEuasdAPOaPJnA+wW6i"
+ "ZHlt0NfXIGNz864gRwhD07fmBIr1dMFfATWxCbgMd/rH7Z/j4rvceHD2n9yrhPze"
+ "YN7W4Nuhsr2w/Ft5Cm9xO7vXT/cpto45uxn8f7jERep6bnUwNOhH8G+6xLQgTLD0"
+ "qFBGVSIneK3lobs6+xn6VaGN8W0tH3UOaxA1ABEBAAG0D0NOPXFhLWRlZXBzaWdo"
+ "dIkFDgQQZAIFAQUCRFpuMAUDCWdU0gMF/3gCGwPELGQBAQQwggTkMIIDzKADAgEC"
+ "AhBVUMV/M6rIiE+IzmnPheQWMA0GCSqGSIb3DQEBBQUAMG4xEzARBgoJkiaJk/Is"
+ "ZAEZFgNjb20xEjAQBgoJkiaJk/IsZAEZFgJxYTEVMBMGCgmSJomT8ixkARkWBXRt"
+ "czAxMRUwEwYKCZImiZPyLGQBGRYFV2ViZmUxFTATBgNVBAMTDHFhLWRlZXBzaWdo"
+ "dDAeFw0wNjA1MDQyMTEyMTZaFw0xMTA1MDQyMTIwMDJaMG4xEzARBgoJkiaJk/Is"
+ "ZAEZFgNjb20xEjAQBgoJkiaJk/IsZAEZFgJxYTEVMBMGCgmSJomT8ixkARkWBXRt"
+ "czAxMRUwEwYKCZImiZPyLGQBGRYFV2ViZmUxFTATBgNVBAMTDHFhLWRlZXBzaWdo"
+ "dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK2Z/Kjo2mH0xCO/ieYJ"
+ "aNmtFieFduK+iYB0jBiQtlSPVuOoT6O5ovONlXzFIjn2h1m+uY6KqXM5zi3GK1DU"
+ "5fudGBs4nuqS7R2/CO0ifjr4dD5wAWfaZOLzVHJcSk7a6Jld+w1PFS0yL5m4Uu5+"
+ "IxzaR2TbsZlhYS5qx0A85o8mcD7BbqJkeW3Q19cgY3PzriBHCEPTt+YEivV0wV8B"
+ "NbEJuAx3+sftn+Piu9x4cPaf3KuE/N5g3tbg26GyvbD8W3kKb3E7u9dP9ym2jjm7"
+ "Gfx/uMRF6npudTA06Efwb7rEtCBMsPSoUEZVIid4reWhuzr7GfpVoY3xbS0fdQ5r"
+ "EDUCAwEAAaOCAXwwggF4MAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0G"
+ "A1UdDgQWBBSmFTRv5y65DHtTYae48zl0ExNWZzCCASUGA1UdHwSCARwwggEYMIIB"
+ "FKCCARCgggEMhoHFbGRhcDovLy9DTj1xYS1kZWVwc2lnaHQsQ049cWEtd3VtYW4x"
+ "LWRjLENOPUNEUCxDTj1QdWJsaWMlMjBLZXklMjBTZXJ2aWNlcyxDTj1TZXJ2aWNl"
+ "cyxDTj1Db25maWd1cmF0aW9uLERDPVdlYmZlLERDPXRtczAxLERDPXFhLERDPWNv"
+ "bT9jZXJ0aWZpY2F0ZVJldm9jYXRpb25MaXN0P2Jhc2U/b2JqZWN0Q2xhc3M9Y1JM"
+ "RGlzdHJpYnV0aW9uUG9pbnSGQmh0dHA6Ly9xYS13dW1hbjEtZGMud2ViZmUudG1z"
+ "MDEucWEuY29tL0NlcnRFbnJvbGwvcWEtZGVlcHNpZ2h0LmNybDAQBgkrBgEEAYI3"
+ "FQEEAwIBADANBgkqhkiG9w0BAQUFAAOCAQEAfuZCW3XlB7Eok35zQbvYt9rhAndT"
+ "DNw3wPNI4ZzD1nXoYWnwhNNvWRpsOt4ExOSNdaHErfgDXAMyyg66Sro0TkAx8eAj"
+ "fPQsyRAh0nm0glzFmJN6TdOZbj7hqGZjc4opQ6nZo8h/ULnaEwMIUW4gcSkZt0ww"
+ "CuErl5NUrN3DpkREeCG/fVvQZ8ays3ibQ5ZCZnYBkLYq/i0r3NLW34WfYhjDY48J"
+ "oQWtvFSAxvRfz2NGmqnrCHPQZxqlfdta97kDa4VQ0zSeBaC70gZkLmD1GJMxWoXW"
+ "6tmEcgPY5SghInUf+L2u52V55MjyAFzVp7kTK2KY+p7qw35vzckrWkwu8AAAAAAA"
+ "AQE=");
private static readonly byte[] secWithPersonalCertificate = Base64.Decode(
"lQOYBEjGLGsBCACp1I1dZKsK4N/I0/4g02hDVNLdQkDZfefduJgyJUyBGo/I"
+ "/ZBpc4vT1YwVIdic4ADjtGB4+7WohN4v8siGzwRSeXardSdZVIw2va0JDsQC"
+ "yeoTnwVkUgn+w/MDgpL0BBhTpr9o3QYoo28/qKMni3eA8JevloZqlAbQ/sYq"
+ "rToMAqn0EIdeVVh6n2lRQhUJaNkH/kA5qWBpI+eI8ot/Gm9kAy3i4e0Xqr3J"
+ "Ff1lkGlZuV5H5p/ItZui9BDIRn4IDaeR511NQnKlxFalM/gP9R9yDVI1aXfy"
+ "STcp3ZcsTOTGNzACtpvMvl6LZyL42DyhlOKlJQJS81wp4dg0LNrhMFOtABEB"
+ "AAEAB/0QIH5UEg0pTqAG4r/3v1uKmUbKJVJ3KhJB5xeSG3dKWIqy3AaXR5ZN"
+ "mrJfXK7EfC5ZcSAqx5br1mzVl3PHVBKQVQxvIlmG4r/LKvPVhQYZUFyJWckZ"
+ "9QMR+EA0Dcran9Ds5fa4hH84jgcwalkj64XWRAKDdVh098g17HDw+IYnQanl"
+ "7IXbYvh+1Lr2HyPo//vHX8DxXIJBv+E4skvqGoNfCIfwcMeLsrI5EKo+D2pu"
+ "kAuBYI0VBiZkrJHFXWmQLW71Mc/Bj7wTG8Q1pCpu7YQ7acFSv+/IOCsB9l9S"
+ "vdB7pNhB3lEjYFGoTgr03VfeixA7/x8uDuSXjnBdTZqmGqkZBADNwCqlzdaQ"
+ "X6CjS5jc3vzwDSPgM7ovieypEL6NU3QDEUhuP6fVvD2NYOgVnAEbJzgOleZS"
+ "W2AFXKAf5NDxfqHnBmo/jlYb5yZV5Y+8/poLLj/m8t7sAfAmcZqGXfYMbSbe"
+ "tr6TGTUXcXgbRyU5oH1e4iq691LOwZ39QjL8lNQQywQA006XYEr/PS9uJkyM"
+ "Cg+M+nmm40goW4hU/HboFh9Ru6ataHj+CLF42O9sfMAV02UcD3Agj6w4kb5L"
+ "VswuwfmY+17IryT81d+dSmDLhpo6ufKoAp4qrdP+bzdlbfIim4Rdrw5vF/Yk"
+ "rC/Nfm3CLJxTimHJhqFx4MG7yEC89lxgdmcD/iJ3m41fwS+bPN2rrCAf7j1u"
+ "JNr/V/8GAnoXR8VV9150BcOneijftIIYKKyKkV5TGwcTfjaxRKp87LTeC3MV"
+ "szFDw04MhlIKRA6nBdU0Ay8Yu+EjXHK2VSpLG/Ny+KGuNiFzhqgBxM8KJwYA"
+ "ISa1UEqWjXoLU3qu1aD7cCvANPVCOASwAYe0GlBHUCBEZXNrdG9wIDxpbmZv"
+ "QHBncC5jb20+sAMD//+JAW4EEAECAFgFAkjGLGswFIAAAAAAIAAHcHJlZmVy"
+ "cmVkLWVtYWlsLWVuY29kaW5nQHBncC5jb21wZ3BtaW1lBwsJCAcDAgoCGQEF"
+ "GwMAAAADFgECBR4BAAAABRUCCAkKAAoJEHHHqp2m1tlWsx8H/icpHl1Nw17A"
+ "D6MJN6zJm+aGja+5BOFxOsntW+IV6JI+l5WwiIVE8xTDhoXW4zdH3IZTqoyY"
+ "frtkqLGpvsPtAQmV6eiPgE3+25ahL+MmjXKsceyhbZeCPDtM2M382VCHYCZK"
+ "DZ4vrHVgK/BpyTeP/mqoWra9+F5xErhody71/cLyIdImLqXgoAny6YywjuAD"
+ "2TrFnzPEBmZrkISHVEso+V9sge/8HsuDqSI03BAVWnxcg6aipHtxm907sdVo"
+ "jzl2yFbxCCCaDIKR7XVbmdX7VZgCYDvNSxX3WEOgFq9CYl4ZlXhyik6Vr4XP"
+ "7EgqadtfwfMcf4XrYoImSQs0gPOd4QqwAWedA5gESMYsawEIALiazFREqBfi"
+ "WouTjIdLuY09Ks7PCkn0eo/i40/8lEj1R6JKFQ5RlHNnabh+TLvjvb3nOSU0"
+ "sDg+IKK/JUc8/Fo7TBdZvARX6BmltEGakqToDC3eaF9EQgHLEhyE/4xXiE4H"
+ "EeIQeCHdC7k0pggEuWUn5lt6oeeiPUWhqdlUOvzjG+jqMPJL0bk9STbImHUR"
+ "EiugCPTekC0X0Zn0yrwyqlJQMWnh7wbSl/uo4q45K7qOhxcijo+hNNrkRAMi"
+ "fdNqD4s5qDERqqHdAAgpWqydo7zV5tx0YSz5fjh59Z7FxkUXpcu1WltT6uVn"
+ "hubiMTWpXzXOQI8wZL2fb12JmRY47BEAEQEAAQAH+wZBeanj4zne+fBHrWAS"
+ "2vx8LYiRV9EKg8I/PzKBVdGUnUs0vTqtXU1dXGXsAsPtu2r1bFh0TQH06gR1"
+ "24iq2obgwkr6x54yj+sZlE6SU0SbF/mQc0NCNAXtSKV2hNXvy+7P+sVJR1bn"
+ "b5ukuvkj1tgEln/0W4r20qJ60F+M5QxXg6kGh8GAlo2tetKEv1NunAyWY6iv"
+ "FTnSaIJ/YaKQNcudNvOJjeIakkIzfzBL+trUiI5n1LTBB6+u3CF/BdZBTxOy"
+ "QwjAh6epZr+GnQqeaomFxBc3mU00sjrsB1Loso84UIs6OKfjMkPoZWkQrQQW"
+ "+xvQ78D33YwqNfXk/5zQAxkEANZxJGNKaAeDpN2GST/tFZg0R5GPC7uWYC7T"
+ "pG100mir9ugRpdeIFvfAa7IX2jujxo9AJWo/b8hq0q0koUBdNAX3xxUaWy+q"
+ "KVCRxBifpYVBfEViD3lsbMy+vLYUrXde9087YD0c0/XUrj+oowWJavblmZtS"
+ "V9OjkQW9zoCigpf5BADcYV+6bkmJtstxJopJG4kD/lr1o35vOEgLkNsMLayc"
+ "NuzES084qP+8yXPehkzSsDB83kc7rKfQCQMZ54V7KCCz+Rr4wVG7FCrFAw4e"
+ "4YghfGVU/5whvbJohl/sXXCYGtVljvY/BSQrojRdP+/iZxFbeD4IKiTjV+XL"
+ "WKSS56Fq2QQAzeoKBJFUq8nqc8/OCmc52WHSOLnB4AuHL5tNfdE9tjqfzZAE"
+ "tx3QB7YGGP57tPQxPFDFJVRJDqw0YxI2tG9Pum8iriKGjHg+oEfFhxvCmPxf"
+ "zDKaGibkLeD7I6ATpXq9If+Nqb5QjzPjFbXBIz/q2nGjamZmp4pujKt/aZxF"
+ "+YRCebABh4kCQQQYAQIBKwUCSMYsbAUbDAAAAMBdIAQZAQgABgUCSMYsawAK"
+ "CRCrkqZshpdZSNAiB/9+5nAny2O9/lp2K2z5KVXqlNAHUmd4S/dpqtsZCbAo"
+ "8Lcr/VYayrNojga1U7cyhsvFky3N9wczzPHq3r9Z+R4WnRM1gpRWl+9+xxtd"
+ "ZxGfGzMRlxX1n5rCqltKKk6IKuBAr2DtTnxThaQiISO2hEw+P1MT2HnSzMXt"
+ "zse5CZ5OiOd/bm/rdvTRD/JmLqhXmOFaIwzdVP0dR9Ld4Dug2onOlIelIntC"
+ "cywY6AmnL0DThaTy5J8MiMSPamSmATl4Bicm8YRbHHz58gCYxI5UMLwtwR1+"
+ "rSEmrB6GwVHZt0/BzOpuGpvFZI5ZmC5yO/waR1hV+VYj025cIz+SNuDPyjy4"
+ "AAoJEHHHqp2m1tlW/w0H/3w38SkB5n9D9JL3chp+8fex03t7CQowVMdsBYNY"
+ "qI4QoVQkakkxzCz5eF7rijXt5eC3NE/quWhlMigT8LARiwBROBWgDRFW4WuX"
+ "6MwYtjKKUkZSkBKxP3lmaqZrJpF6jfhPEN76zr/NxWPC/nHRNldUdqkzSu/r"
+ "PeJyePMofJevzMkUzw7EVtbtWhZavCz+EZXRTZXub9M4mDMj64BG6JHMbVZI"
+ "1iDF2yka5RmhXz9tOhYgq80m7UQUb1ttNn86v1zVbe5lmB8NG4Ndv+JaaSuq"
+ "SBZOYQ0ZxtMAB3vVVLZCWxma1P5HdXloegh+hosqeu/bl0Wh90z5Bspt6eI4"
+ "imqwAWeVAdgESMYtmwEEAM9ZeMFxor7oSoXnhQAXD9lXLLfBky6IcIWISY4F"
+ "JWc8sK8+XiVzpOrefKro0QvmEGSYcDFQMHdScBLOTsiVJiqenA7fg1bkBr/M"
+ "bnD7vTKMJe0DARlU27tE5hsWCDYTluxIFjGcAcecY2UqHkqpctYKY0WY9EIm"
+ "dBA5TYaw3c0PABEBAAEAA/0Zg6318nC57cWLIp5dZiO/dRhTPZD0hI+BWZrg"
+ "zJtPT8rXVY+qK3Jwquig8z29/r+nppEE+xQWVWDlv4M28BDJAbGE+qWKAZqT"
+ "67lyKgc0c50W/lfbGvvs+F7ldCcNpFvlk79GODKxcEeTGDQKb9R6FnHFee/K"
+ "cZum71O3Ku3vUQIA3B3PNM+tKocIUNDHnInuLyqLORwQBNGfjU/pLMM0MkpP"
+ "lWeIfgUmn2zL/e0JrRoO0LQqX1LN/TlfcurDM0SEtwIA8Sba9OpDq99Yz360"
+ "FiePJiGNNlbj9EZsuGJyMVXL1mTLA6WHnz5XZOfYqJXHlmKvaKDbARW4+0U7"
+ "0/vPdYWSaQIAwYeo2Ce+b7M5ifbGMDWYBisEvGISg5xfvbe6qApmHS4QVQzE"
+ "Ym81rdJJ8OfvgSbHcgn37S3OBXIQvNdejF4BWqM9sAGHtCBIeW5lay1JbnRy"
+ "YW5ldCA8aHluZWtAYWxzb2Z0LmN6PrADA///iQDrBBABAgBVBQJIxi2bBQkB"
+ "mgKAMBSAAAAAACAAB3ByZWZlcnJlZC1lbWFpbC1lbmNvZGluZ0BwZ3AuY29t"
+ "cGdwbWltZQULBwgJAgIZAQUbAQAAAAUeAQAAAAIVAgAKCRDlTa3BE84gWVKW"
+ "BACcoCFKvph9r9QiHT1Z3N4wZH36Uxqu/059EFALnBkEdVudX/p6S9mynGRk"
+ "EfhmWFC1O6dMpnt+ZBEed/4XyFWVSLPwirML+6dxfXogdUsdFF1NCRHc3QGc"
+ "txnNUT/zcZ9IRIQjUhp6RkIvJPHcyfTXKSbLviI+PxzHU2Padq8pV7ABZ7kA"
+ "jQRIfg8tAQQAutJR/aRnfZYwlVv+KlUDYjG8YQUfHpTxpnmVu7W6N0tNg/Xr"
+ "5dg50wq3I4HOamRxUwHpdPkXyNF1szpDSRZmlM+VmiIvJDBnyH5YVlxT6+zO"
+ "8LUJ2VTbfPxoLFp539SQ0oJOm7IGMAGO7c0n/QV0N3hKUfWgCyJ+sENDa0Ft"
+ "JycAEQEAAbABj4kEzQQYAQIENwUCSMYtnAUJAeEzgMLFFAAAAAAAFwNleDUw"
+ "OWNlcnRpZmljYXRlQHBncC5jb20wggNhMIICyqADAgECAgkA1AoCoRKJCgsw"
+ "DQYJKoZIhvcNAQEFBQAwgakxCzAJBgNVBAYTAkNaMRcwFQYDVQQIEw5DemVj"
+ "aCBSZXB1YmxpYzESMBAGA1UEChQJQSYmTCBzb2Z0MSAwHgYDVQQLExdJbnRl"
+ "cm5hbCBEZXZlbG9wbWVudCBDQTEqMCgGA1UEAxQhQSYmTCBzb2Z0IEludGVy"
+ "bmFsIERldmVsb3BtZW50IENBMR8wHQYJKoZIhvcNAQkBFhBrYWRsZWNAYWxz"
+ "b2Z0LmN6MB4XDTA4MDcxNjE1MDkzM1oXDTA5MDcxNjE1MDkzM1owaTELMAkG"
+ "A1UEBhMCQ1oxFzAVBgNVBAgTDkN6ZWNoIFJlcHVibGljMRIwEAYDVQQKFAlB"
+ "JiZMIHNvZnQxFDASBgNVBAsTC0RldmVsb3BtZW50MRcwFQYDVQQDEw5IeW5l"
+ "ay1JbnRyYW5ldDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAutJR/aRn"
+ "fZYwlVv+KlUDYjG8YQUfHpTxpnmVu7W6N0tNg/Xr5dg50wq3I4HOamRxUwHp"
+ "dPkXyNF1szpDSRZmlM+VmiIvJDBnyH5YVlxT6+zO8LUJ2VTbfPxoLFp539SQ"
+ "0oJOm7IGMAGO7c0n/QV0N3hKUfWgCyJ+sENDa0FtJycCAwEAAaOBzzCBzDAJ"
+ "BgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBD"
+ "ZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUNaw7A6r10PtYZzAvr9CrSKeRYJgwHwYD"
+ "VR0jBBgwFoAUmqSRM8rN3+T1+tkGiqef8S5suYgwGgYDVR0RBBMwEYEPaHlu"
+ "ZWtAYWxzb2Z0LmN6MCgGA1UdHwQhMB8wHaAboBmGF2h0dHA6Ly9wZXRyazIv"
+ "Y2EvY2EuY3JsMAsGA1UdDwQEAwIF4DANBgkqhkiG9w0BAQUFAAOBgQCUdOWd"
+ "7mBLWj1/GSiYgfwgdTrgk/VZOJvMKBiiFyy1iFEzldz6Xx+mAexnFJKfZXZb"
+ "EMEGWHfWPmgJzAtuTT0Jz6tUwDmeLH3MP4m8uOZtmyUJ2aq41kciV3rGxF0G"
+ "BVlZ/bWTaOzHdm6cjylt6xxLt6MJzpPBA/9ZfybSBh1DaAUbDgAAAJ0gBBkB"
+ "AgAGBQJIxi2bAAoJEAdYkEWLb2R2fJED/RK+JErZ98uGo3Z81cHkdP3rk8is"
+ "DUL/PR3odBPFH2SIA5wrzklteLK/ZXmBUzcvxqHEgI1F7goXbsBgeTuGgZdx"
+ "pINErxkNpcMl9FTldWKGiapKrhkZ+G8knDizF/Y7Lg6uGd2nKVxzutLXdHJZ"
+ "pU89Q5nzq6aJFAZo5TBIcchQAAoJEOVNrcETziBZXvQD/1mvFqBfWqwXxoj3"
+ "8fHUuFrE2pcp32y3ciO2i+uNVEkNDoaVVNw5eHQaXXWpllI/Pe6LnBl4vkyc"
+ "n3pjONa4PKrePkEsCUhRbIySqXIHuNwZumDOlKzZHDpCUw72LaC6S6zwuoEf"
+ "ucOcxTeGIUViANWXyTIKkHfo7HfigixJIL8nsAFn");
[Test]
public void PerformTest1()
{
PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub1);
int count = 0;
foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpPub1.GetEncoded();
PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);
foreach (PgpPublicKey pubKey in pgpPub2.GetPublicKeys())
{
keyCount++;
foreach (PgpSignature sig in pubKey.GetSignatures())
{
if (sig == null)
Fail("null signature found");
}
}
if (keyCount != 2)
{
Fail("wrong number of public keys");
}
}
if (count != 1)
{
Fail("wrong number of public keyrings");
}
//
// exact match
//
count = 0;
foreach (PgpPublicKeyRing pgpPub3 in pubRings.GetKeyRings("test (Test key) <test@ubicall.com>"))
{
if (pgpPub3 == null)
Fail("null keyring found");
count++;
}
if (count != 1)
{
Fail("wrong number of public keyrings on exact match");
}
//
// partial match 1 expected
//
count = 0;
foreach (PgpPublicKeyRing pgpPub4 in pubRings.GetKeyRings("test", true))
{
if (pgpPub4 == null)
Fail("null keyring found");
count++;
}
if (count != 1)
{
Fail("wrong number of public keyrings on partial match 1");
}
//
// partial match 0 expected
//
count = 0;
foreach (PgpPublicKeyRing pgpPub5 in pubRings.GetKeyRings("XXX", true))
{
if (pgpPub5 == null)
Fail("null keyring found");
count++;
}
if (count != 0)
{
Fail("wrong number of public keyrings on partial match 0");
}
//
// case-insensitive partial match
//
count = 0;
foreach (PgpPublicKeyRing pgpPub6 in pubRings.GetKeyRings("TEST@ubicall.com", true, true))
{
if (pgpPub6 == null)
Fail("null keyring found");
count++;
}
if (count != 1)
{
Fail("wrong number of public keyrings on case-insensitive partial match");
}
PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(sec1);
count = 0;
foreach (PgpSecretKeyRing pgpSec1 in secretRings.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpSec1.GetEncoded();
PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);
foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
{
keyCount++;
PgpPublicKey pk = k.PublicKey;
pk.GetSignatures();
byte[] pkBytes = pk.GetEncoded();
PgpPublicKeyRing pkR = new PgpPublicKeyRing(pkBytes);
}
if (keyCount != 2)
{
Fail("wrong number of secret keys");
}
}
if (count != 1)
{
Fail("wrong number of secret keyrings");
}
//
// exact match
//
count = 0;
foreach (PgpSecretKeyRing o1 in secretRings.GetKeyRings("test (Test key) <test@ubicall.com>"))
{
if (o1 == null)
Fail("null keyring found");
count++;
}
if (count != 1)
{
Fail("wrong number of secret keyrings on exact match");
}
//
// partial match 1 expected
//
count = 0;
foreach (PgpSecretKeyRing o2 in secretRings.GetKeyRings("test", true))
{
if (o2 == null)
Fail("null keyring found");
count++;
}
if (count != 1)
{
Fail("wrong number of secret keyrings on partial match 1");
}
//
// exact match 0 expected
//
count = 0;
foreach (PgpSecretKeyRing o3 in secretRings.GetKeyRings("test", false))
{
if (o3 == null)
Fail("null keyring found");
count++;
}
if (count != 0)
{
Fail("wrong number of secret keyrings on partial match 0");
}
//
// case-insensitive partial match
//
count = 0;
foreach (PgpSecretKeyRing o4 in secretRings.GetKeyRings("TEST@ubicall.com", true, true))
{
if (o4 == null)
Fail("null keyring found");
count++;
}
if (count != 1)
{
Fail("wrong number of secret keyrings on case-insensitive partial match");
}
}
[Test]
public void PerformTest2()
{
PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub2);
int count = 0;
byte[] encRing = pubRings.GetEncoded();
pubRings = new PgpPublicKeyRingBundle(encRing);
foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpPub1.GetEncoded();
PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);
foreach (PgpPublicKey pk in pgpPub2.GetPublicKeys())
{
byte[] pkBytes = pk.GetEncoded();
PgpPublicKeyRing pkR = new PgpPublicKeyRing(pkBytes);
keyCount++;
}
if (keyCount != 2)
{
Fail("wrong number of public keys");
}
}
if (count != 2)
{
Fail("wrong number of public keyrings");
}
PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(sec2);
count = 0;
encRing = secretRings2.GetEncoded();
PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(encRing);
foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpSec1.GetEncoded();
PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);
foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
{
keyCount++;
PgpPublicKey pk = k.PublicKey;
if (pk.KeyId == -1413891222336124627L)
{
int sCount = 0;
foreach (PgpSignature pgpSignature in pk.GetSignaturesOfType(PgpSignature.SubkeyBinding))
{
int type = pgpSignature.SignatureType;
if (type != PgpSignature.SubkeyBinding)
{
Fail("failed to return correct signature type");
}
sCount++;
}
if (sCount != 1)
{
Fail("failed to find binding signature");
}
}
pk.GetSignatures();
if (k.KeyId == -4049084404703773049L
|| k.KeyId == -1413891222336124627L)
{
k.ExtractPrivateKey(sec2pass1);
}
else if (k.KeyId == -6498553574938125416L
|| k.KeyId == 59034765524361024L)
{
k.ExtractPrivateKey(sec2pass2);
}
}
if (keyCount != 2)
{
Fail("wrong number of secret keys");
}
}
if (count != 2)
{
Fail("wrong number of secret keyrings");
}
}
[Test]
public void PerformTest3()
{
PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub3);
int count = 0;
byte[] encRing = pubRings.GetEncoded();
pubRings = new PgpPublicKeyRingBundle(encRing);
foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpPub1.GetEncoded();
PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);
foreach (PgpPublicKey pubK in pgpPub2.GetPublicKeys())
{
keyCount++;
pubK.GetSignatures();
}
if (keyCount != 2)
{
Fail("wrong number of public keys");
}
}
if (count != 1)
{
Fail("wrong number of public keyrings");
}
PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(sec3);
count = 0;
encRing = secretRings2.GetEncoded();
PgpSecretKeyRingBundle secretRings = new PgpSecretKeyRingBundle(encRing);
foreach (PgpSecretKeyRing pgpSec1 in secretRings2.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpSec1.GetEncoded();
PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);
foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
{
keyCount++;
k.ExtractPrivateKey(sec3pass1);
}
if (keyCount != 2)
{
Fail("wrong number of secret keys");
}
}
if (count != 1)
{
Fail("wrong number of secret keyrings");
}
}
[Test]
public void PerformTest4()
{
PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec4);
int count = 0;
byte[] encRing = secretRings1.GetEncoded();
PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing);
foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpSec1.GetEncoded();
PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);
foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
{
keyCount++;
k.ExtractPrivateKey(sec3pass1);
}
if (keyCount != 2)
{
Fail("wrong number of secret keys");
}
}
if (count != 1)
{
Fail("wrong number of secret keyrings");
}
}
[Test]
public void PerformTest5()
{
PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub5);
int count = 0;
byte[] encRing = pubRings.GetEncoded();
pubRings = new PgpPublicKeyRingBundle(encRing);
foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpPub1.GetEncoded();
PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);
foreach (PgpPublicKey o in pgpPub2.GetPublicKeys())
{
if (o == null)
Fail("null keyring found");
keyCount++;
}
if (keyCount != 2)
{
Fail("wrong number of public keys");
}
}
if (count != 1)
{
Fail("wrong number of public keyrings");
}
#if INCLUDE_IDEA
PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec5);
count = 0;
encRing = secretRings1.GetEncoded();
PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing);
foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpSec1.GetEncoded();
PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);
foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
{
keyCount++;
k.ExtractPrivateKey(sec5pass1);
}
if (keyCount != 2)
{
Fail("wrong number of secret keys");
}
}
if (count != 1)
{
Fail("wrong number of secret keyrings");
}
#endif
}
[Test]
public void PerformTest6()
{
PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub6);
foreach (PgpPublicKeyRing pgpPub in pubRings.GetKeyRings())
{
foreach (PgpPublicKey k in pgpPub.GetPublicKeys())
{
if (k.KeyId == 0x5ce086b5b5a18ff4L)
{
int count = 0;
foreach (PgpSignature sig in k.GetSignaturesOfType(PgpSignature.SubkeyRevocation))
{
if (sig == null)
Fail("null signature found");
count++;
}
if (count != 1)
{
Fail("wrong number of revocations in test6.");
}
}
}
}
byte[] encRing = pubRings.GetEncoded();
}
[Test, Explicit]
public void PerformTest7()
{
PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(pub7);
PgpPublicKey masterKey = null;
foreach (PgpPublicKey k in pgpPub.GetPublicKeys())
{
if (k.IsMasterKey)
{
masterKey = k;
continue;
}
int count = 0;
PgpSignature sig = null;
foreach (PgpSignature sigTemp in k.GetSignaturesOfType(PgpSignature.SubkeyRevocation))
{
sig = sigTemp;
count++;
}
if (count != 1)
{
Fail("wrong number of revocations in test7.");
}
sig.InitVerify(masterKey);
if (!sig.VerifyCertification(k))
{
Fail("failed to verify revocation certification");
}
}
}
[Test]
public void PerformTest8()
{
PgpPublicKeyRingBundle pubRings = new PgpPublicKeyRingBundle(pub8);
int count = 0;
byte[] encRing = pubRings.GetEncoded();
pubRings = new PgpPublicKeyRingBundle(encRing);
foreach (PgpPublicKeyRing pgpPub1 in pubRings.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpPub1.GetEncoded();
PgpPublicKeyRing pgpPub2 = new PgpPublicKeyRing(bytes);
foreach (PgpPublicKey o in pgpPub2.GetPublicKeys())
{
if (o == null)
Fail("null key found");
keyCount++;
}
if (keyCount != 2)
{
Fail("wrong number of public keys");
}
}
if (count != 2)
{
Fail("wrong number of public keyrings");
}
PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec8);
count = 0;
encRing = secretRings1.GetEncoded();
PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing);
foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpSec1.GetEncoded();
PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);
foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
{
keyCount++;
k.ExtractPrivateKey(sec8pass);
}
if (keyCount != 2)
{
Fail("wrong number of secret keys");
}
}
if (count != 1)
{
Fail("wrong number of secret keyrings");
}
}
[Test]
public void PerformTest9()
{
PgpSecretKeyRingBundle secretRings1 = new PgpSecretKeyRingBundle(sec9);
int count = 0;
byte[] encRing = secretRings1.GetEncoded();
PgpSecretKeyRingBundle secretRings2 = new PgpSecretKeyRingBundle(encRing);
foreach (PgpSecretKeyRing pgpSec1 in secretRings1.GetKeyRings())
{
count++;
int keyCount = 0;
byte[] bytes = pgpSec1.GetEncoded();
PgpSecretKeyRing pgpSec2 = new PgpSecretKeyRing(bytes);
foreach (PgpSecretKey k in pgpSec2.GetSecretKeys())
{
keyCount++;
PgpPrivateKey pKey = k.ExtractPrivateKey(sec9pass);
if (keyCount == 1 && pKey != null)
{
Fail("primary secret key found, null expected");
}
}
if (keyCount != 3)
{
Fail("wrong number of secret keys");
}
}
if (count != 1)
{
Fail("wrong number of secret keyrings");
}
}
[Test]
public void PerformTest10()
{
PgpSecretKeyRing secretRing = new PgpSecretKeyRing(sec10);
foreach (PgpSecretKey secretKey in secretRing.GetSecretKeys())
{
PgpPublicKey pubKey = secretKey.PublicKey;
if (pubKey.ValidDays != 28)
{
Fail("days wrong on secret key ring");
}
if (pubKey.GetValidSeconds() != 28 * 24 * 60 * 60)
{
Fail("seconds wrong on secret key ring");
}
}
PgpPublicKeyRing publicRing = new PgpPublicKeyRing(pub10);
foreach (PgpPublicKey pubKey in publicRing.GetPublicKeys())
{
if (pubKey.ValidDays != 28)
{
Fail("days wrong on public key ring");
}
if (pubKey.GetValidSeconds() != 28 * 24 * 60 * 60)
{
Fail("seconds wrong on public key ring");
}
}
}
[Test]
public void PerformTest11()
{
PgpPublicKeyRing pubRing = new PgpPublicKeyRing(subKeyBindingKey);
foreach (PgpPublicKey key in pubRing.GetPublicKeys())
{
if (key.GetValidSeconds() != 0)
{
Fail("expiration time non-zero");
}
}
}
[Test]
public void GenerateTest()
{
char[] passPhrase = "hello".ToCharArray();
DsaParametersGenerator pGen = new DsaParametersGenerator();
pGen.Init(512, 80, new SecureRandom());
DsaParameters dsaParams = pGen.GenerateParameters();
DsaKeyGenerationParameters dsaKgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA");
dsaKpg.Init(dsaKgp);
//
// this takes a while as the key generator has to Generate some DSA parameters
// before it Generates the key.
//
AsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair();
IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");
BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);
ElGamalParameters elParams = new ElGamalParameters(p, g);
ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams);
elgKpg.Init(elKgp);
//
// this is quicker because we are using preGenerated parameters.
//
AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair();
PgpKeyPair dsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, dsaKp, DateTime.UtcNow);
PgpKeyPair elgKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalEncrypt, elgKp, DateTime.UtcNow);
PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, dsaKeyPair,
"test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, new SecureRandom());
keyRingGen.AddSubKey(elgKeyPair);
PgpSecretKeyRing keyRing = keyRingGen.GenerateSecretKeyRing();
keyRing.GetSecretKey().ExtractPrivateKey(passPhrase);
PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();
PgpPublicKey vKey = null;
PgpPublicKey sKey = null;
foreach (PgpPublicKey pk in pubRing.GetPublicKeys())
{
if (pk.IsMasterKey)
{
vKey = pk;
}
else
{
sKey = pk;
}
}
foreach (PgpSignature sig in sKey.GetSignatures())
{
if (sig.KeyId == vKey.KeyId
&& sig.SignatureType == PgpSignature.SubkeyBinding)
{
sig.InitVerify(vKey);
if (!sig.VerifyCertification(vKey, sKey))
{
Fail("failed to verify sub-key signature.");
}
}
}
}
[Test]
public void InsertMasterTest()
{
SecureRandom random = new SecureRandom();
char[] passPhrase = "hello".ToCharArray();
IAsymmetricCipherKeyPairGenerator rsaKpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
rsaKpg.Init(new KeyGenerationParameters(random, 512));
//
// this is quicker because we are using pregenerated parameters.
//
AsymmetricCipherKeyPair rsaKp = rsaKpg.GenerateKeyPair();
PgpKeyPair rsaKeyPair1 = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, rsaKp, DateTime.UtcNow);
rsaKp = rsaKpg.GenerateKeyPair();
PgpKeyPair rsaKeyPair2 = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, rsaKp, DateTime.UtcNow);
PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification,
rsaKeyPair1, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, random);
PgpSecretKeyRing secRing1 = keyRingGen.GenerateSecretKeyRing();
PgpPublicKeyRing pubRing1 = keyRingGen.GeneratePublicKeyRing();
keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification,
rsaKeyPair2, "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, random);
PgpSecretKeyRing secRing2 = keyRingGen.GenerateSecretKeyRing();
PgpPublicKeyRing pubRing2 = keyRingGen.GeneratePublicKeyRing();
try
{
PgpPublicKeyRing.InsertPublicKey(pubRing1, pubRing2.GetPublicKey());
Fail("adding second master key (public) should throw an ArgumentException");
}
catch (ArgumentException e)
{
if (!e.Message.Equals("cannot add a master key to a ring that already has one"))
{
Fail("wrong message in public test");
}
}
try
{
PgpSecretKeyRing.InsertSecretKey(secRing1, secRing2.GetSecretKey());
Fail("adding second master key (secret) should throw an ArgumentException");
}
catch (ArgumentException e)
{
if (!e.Message.Equals("cannot add a master key to a ring that already has one"))
{
Fail("wrong message in secret test");
}
}
}
[Test]
public void GenerateSha1Test()
{
char[] passPhrase = "hello".ToCharArray();
IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA");
DsaParametersGenerator pGen = new DsaParametersGenerator();
pGen.Init(512, 80, new SecureRandom());
DsaParameters dsaParams = pGen.GenerateParameters();
DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
dsaKpg.Init(kgp);
//
// this takes a while as the key generator has to generate some DSA params
// before it generates the key.
//
AsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair();
IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");
BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);
ElGamalParameters elParams = new ElGamalParameters(p, g);
ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams);
elgKpg.Init(elKgp);
//
// this is quicker because we are using preGenerated parameters.
//
AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair();
PgpKeyPair dsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, dsaKp, DateTime.UtcNow);
PgpKeyPair elgKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalEncrypt, elgKp, DateTime.UtcNow);
PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, dsaKeyPair,
"test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, new SecureRandom());
keyRingGen.AddSubKey(elgKeyPair);
PgpSecretKeyRing keyRing = keyRingGen.GenerateSecretKeyRing();
keyRing.GetSecretKey().ExtractPrivateKey(passPhrase);
PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();
PgpPublicKey vKey = null;
PgpPublicKey sKey = null;
foreach (PgpPublicKey pk in pubRing.GetPublicKeys())
{
if (pk.IsMasterKey)
{
vKey = pk;
}
else
{
sKey = pk;
}
}
foreach (PgpSignature sig in sKey.GetSignatures())
{
if (sig.KeyId == vKey.KeyId
&& sig.SignatureType == PgpSignature.SubkeyBinding)
{
sig.InitVerify(vKey);
if (!sig.VerifyCertification(vKey, sKey))
{
Fail("failed to verify sub-key signature.");
}
}
}
}
[Test]
public void RewrapTest()
{
SecureRandom rand = new SecureRandom();
// Read the secret key rings
PgpSecretKeyRingBundle privRings = new PgpSecretKeyRingBundle(
new MemoryStream(rewrapKey, false));
foreach (PgpSecretKeyRing pgpPrivEnum in privRings.GetKeyRings())
{
foreach (PgpSecretKey pgpKeyEnum in pgpPrivEnum.GetSecretKeys())
{
// re-encrypt the key with an empty password
PgpSecretKeyRing pgpPriv = PgpSecretKeyRing.RemoveSecretKey(pgpPrivEnum, pgpKeyEnum);
PgpSecretKey pgpKey = PgpSecretKey.CopyWithNewPassword(
pgpKeyEnum,
rewrapPass,
null,
SymmetricKeyAlgorithmTag.Null,
rand);
pgpPriv = PgpSecretKeyRing.InsertSecretKey(pgpPriv, pgpKey);
// this should succeed
PgpPrivateKey privTmp = pgpKey.ExtractPrivateKey(null);
}
}
}
[Test]
public void PublicKeyRingWithX509Test()
{
checkPublicKeyRingWithX509(pubWithX509);
PgpPublicKeyRing pubRing = new PgpPublicKeyRing(pubWithX509);
checkPublicKeyRingWithX509(pubRing.GetEncoded());
}
[Test]
public void SecretKeyRingWithPersonalCertificateTest()
{
checkSecretKeyRingWithPersonalCertificate(secWithPersonalCertificate);
PgpSecretKeyRingBundle secRing = new PgpSecretKeyRingBundle(secWithPersonalCertificate);
checkSecretKeyRingWithPersonalCertificate(secRing.GetEncoded());
}
private void checkSecretKeyRingWithPersonalCertificate(
byte[] keyRing)
{
PgpSecretKeyRingBundle secCol = new PgpSecretKeyRingBundle(keyRing);
int count = 0;
foreach (PgpSecretKeyRing ring in secCol.GetKeyRings())
{
IEnumerator e = ring.GetExtraPublicKeys().GetEnumerator();
while (e.MoveNext())
{
++count;
}
}
if (count != 1)
{
Fail("personal certificate data subkey not found - count = " + count);
}
}
private void checkPublicKeyRingWithX509(
byte[] keyRing)
{
PgpPublicKeyRing pubRing = new PgpPublicKeyRing(keyRing);
IEnumerator en = pubRing.GetPublicKeys().GetEnumerator();
if (en.MoveNext())
{
PgpPublicKey key = (PgpPublicKey) en.Current;
IEnumerator sEn = key.GetSignatures().GetEnumerator();
if (sEn.MoveNext())
{
PgpSignature sig = (PgpSignature) sEn.Current;
if (sig.KeyAlgorithm != PublicKeyAlgorithmTag.Experimental_1)
{
Fail("experimental signature not found");
}
if (!AreEqual(sig.GetSignature(), Hex.Decode("000101")))
{
Fail("experimental encoding check failed");
}
}
else
{
Fail("no signature found");
}
}
else
{
Fail("no key found");
}
}
public override void PerformTest()
{
PerformTest1();
PerformTest2();
PerformTest3();
PerformTest4();
PerformTest5();
PerformTest6();
// NB: This was commented out in the original Java source
//PerformTest7();
PerformTest8();
PerformTest9();
PerformTest10();
PerformTest11();
GenerateTest();
GenerateSha1Test();
RewrapTest();
PublicKeyRingWithX509Test();
SecretKeyRingWithPersonalCertificateTest();
InsertMasterTest();
}
public override string Name
{
get { return "PgpKeyRingTest"; }
}
public static void Main(
string[] args)
{
RunTest(new PgpKeyRingTest());
}
}
}
| |
using System;
using System.IO;
using Raksha.Crypto;
using Raksha.Crypto.Engines;
using Raksha.Crypto.Generators;
using Raksha.Crypto.Modes;
using Raksha.Crypto.Paddings;
using Raksha.Crypto.Parameters;
using Raksha.Security;
using Raksha.Utilities.Encoders;
namespace Raksha.Tests.Crypto.Examples
{
/**
* DesExample is a simple DES based encryptor/decryptor.
* <p>
* The program is command line driven, with the input
* and output files specified on the command line.
* <pre>
* java org.bouncycastle.crypto.examples.DesExample infile outfile [keyfile]
* </pre>
* A new key is generated for each encryption, if key is not specified,
* then the example will assume encryption is required, and as output
* create deskey.dat in the current directory. This key is a hex
* encoded byte-stream that is used for the decryption. The output
* file is Hex encoded, 60 characters wide text file.
* </p>
* <p>
* When encrypting;
* <ul>
* <li>the infile is expected to be a byte stream (text or binary)</li>
* <li>there is no keyfile specified on the input line</li>
* </ul>
* </p>
* <p>
* When decrypting;
* <li>the infile is expected to be the 60 character wide base64
* encoded file</li>
* <li>the keyfile is expected to be a base64 encoded file</li>
* </p>
* <p>
* This example shows how to use the light-weight API, DES and
* the filesystem for message encryption and decryption.
* </p>
*/
public class DesExample
{
// Encrypting or decrypting ?
private bool encrypt = true;
// To hold the initialised DESede cipher
private PaddedBufferedBlockCipher cipher = null;
// The input stream of bytes to be processed for encryption
private Stream inStr = null;
// The output stream of bytes to be procssed
private Stream outStr = null;
// The key
private byte[] key = null;
/*
* start the application
*/
public static int Main(
string[] args)
{
bool encrypt = true;
string infile = null;
string outfile = null;
string keyfile = null;
if (args.Length < 2)
{
// Console.Error.WriteLine("Usage: java " + typeof(DesExample).Name + " infile outfile [keyfile]");
Console.Error.WriteLine("Usage: " + typeof(DesExample).Name + " infile outfile [keyfile]");
return 1;
}
keyfile = "deskey.dat";
infile = args[0];
outfile = args[1];
if (args.Length > 2)
{
encrypt = false;
keyfile = args[2];
}
try
{
DesExample de = new DesExample(infile, outfile, keyfile, encrypt);
de.process();
}
catch (Exception)
{
return 1;
}
return 0;
}
// Default constructor, used for the usage message
public DesExample()
{
}
/*
* Constructor, that takes the arguments appropriate for
* processing the command line directives.
*/
public DesExample(
string infile,
string outfile,
string keyfile,
bool encrypt)
{
/*
* First, determine that infile & keyfile exist as appropriate.
*
* This will also create the BufferedInputStream as required
* for reading the input file. All input files are treated
* as if they are binary, even if they contain text, it's the
* bytes that are encrypted.
*/
this.encrypt = encrypt;
try
{
inStr = File.OpenRead(infile);
}
catch (FileNotFoundException e)
{
Console.Error.WriteLine("Input file not found ["+infile+"]");
throw e;
}
try
{
outStr = File.Create(outfile);
}
catch (IOException e)
{
Console.Error.WriteLine("Output file not created ["+outfile+"]");
throw e;
}
if (encrypt)
{
try
{
/*
* The process of creating a new key requires a
* number of steps.
*
* First, create the parameters for the key generator
* which are a secure random number generator, and
* the length of the key (in bits).
*/
SecureRandom sr = new SecureRandom();
KeyGenerationParameters kgp = new KeyGenerationParameters(
sr,
DesEdeParameters.DesEdeKeyLength * 8);
/*
* Second, initialise the key generator with the parameters
*/
DesEdeKeyGenerator kg = new DesEdeKeyGenerator();
kg.Init(kgp);
/*
* Third, and finally, generate the key
*/
key = kg.GenerateKey();
/*
* We can now output the key to the file, but first
* hex Encode the key so that we can have a look
* at it with a text editor if we so desire
*/
using (Stream keystream = File.Create(keyfile))
{
Hex.Encode(key, keystream);
}
}
catch (IOException e)
{
Console.Error.WriteLine("Could not decryption create key file "+
"["+keyfile+"]");
throw e;
}
}
else
{
try
{
// TODO This block is a bit dodgy
// read the key, and Decode from hex encoding
Stream keystream = File.OpenRead(keyfile);
// int len = keystream.available();
int len = (int) keystream.Length;
byte[] keyhex = new byte[len];
keystream.Read(keyhex, 0, len);
key = Hex.Decode(keyhex);
}
catch (IOException e)
{
Console.Error.WriteLine("Decryption key file not found, "
+ "or not valid ["+keyfile+"]");
throw e;
}
}
}
private void process()
{
/*
* Setup the DESede cipher engine, create a PaddedBufferedBlockCipher
* in CBC mode.
*/
cipher = new PaddedBufferedBlockCipher(
new CbcBlockCipher(new DesEdeEngine()));
/*
* The input and output streams are currently set up
* appropriately, and the key bytes are ready to be
* used.
*
*/
if (encrypt)
{
performEncrypt(key);
}
else
{
performDecrypt(key);
}
// after processing clean up the files
try
{
inStr.Close();
outStr.Flush();
outStr.Close();
}
catch (IOException)
{
}
}
/*
* This method performs all the encryption and writes
* the cipher text to the buffered output stream created
* previously.
*/
private void performEncrypt(byte[] key)
{
// initialise the cipher with the key bytes, for encryption
cipher.Init(true, new KeyParameter(key));
/*
* Create some temporary byte arrays for use in
* encryption, make them a reasonable size so that
* we don't spend forever reading small chunks from
* a file.
*
* There is no particular reason for using getBlockSize()
* to determine the size of the input chunk. It just
* was a convenient number for the example.
*/
// int inBlockSize = cipher.getBlockSize() * 5;
int inBlockSize = 47;
int outBlockSize = cipher.GetOutputSize(inBlockSize);
byte[] inblock = new byte[inBlockSize];
byte[] outblock = new byte[outBlockSize];
/*
* now, read the file, and output the chunks
*/
try
{
int inL;
int outL;
while ((inL = inStr.Read(inblock, 0, inBlockSize)) > 0)
{
outL = cipher.ProcessBytes(inblock, 0, inL, outblock, 0);
/*
* Before we write anything out, we need to make sure
* that we've got something to write out.
*/
if (outL > 0)
{
Hex.Encode(outblock, 0, outL, outStr);
outStr.WriteByte((byte)'\n');
}
}
try
{
/*
* Now, process the bytes that are still buffered
* within the cipher.
*/
outL = cipher.DoFinal(outblock, 0);
if (outL > 0)
{
Hex.Encode(outblock, 0, outL, outStr);
outStr.WriteByte((byte) '\n');
}
}
catch (CryptoException)
{
}
}
catch (IOException ioeread)
{
Console.Error.WriteLine(ioeread.StackTrace);
}
}
/*
* This method performs all the decryption and writes
* the plain text to the buffered output stream created
* previously.
*/
private void performDecrypt(byte[] key)
{
// initialise the cipher for decryption
cipher.Init(false, new KeyParameter(key));
/*
* As the decryption is from our preformatted file,
* and we know that it's a hex encoded format, then
* we wrap the InputStream with a BufferedReader
* so that we can read it easily.
*/
// BufferedReader br = new BufferedReader(new StreamReader(inStr));
StreamReader br = new StreamReader(inStr); // 'inStr' already buffered
/*
* now, read the file, and output the chunks
*/
try
{
int outL;
byte[] inblock = null;
byte[] outblock = null;
string rv = null;
while ((rv = br.ReadLine()) != null)
{
inblock = Hex.Decode(rv);
outblock = new byte[cipher.GetOutputSize(inblock.Length)];
outL = cipher.ProcessBytes(inblock, 0, inblock.Length, outblock, 0);
/*
* Before we write anything out, we need to make sure
* that we've got something to write out.
*/
if (outL > 0)
{
outStr.Write(outblock, 0, outL);
}
}
try
{
/*
* Now, process the bytes that are still buffered
* within the cipher.
*/
outL = cipher.DoFinal(outblock, 0);
if (outL > 0)
{
outStr.Write(outblock, 0, outL);
}
}
catch (CryptoException)
{
}
}
catch (IOException ioeread)
{
Console.Error.WriteLine(ioeread.StackTrace);
}
}
}
}
| |
//*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudioTools.Project;
namespace Microsoft.VisualStudioTools.Navigation {
/// <summary>
/// Inplementation of the service that builds the information to expose to the symbols
/// navigation tools (class view or object browser) from the source files inside a
/// hierarchy.
/// </summary>
internal abstract partial class LibraryManager : IDisposable, IVsRunningDocTableEvents {
private readonly CommonPackage/*!*/ _package;
private readonly Dictionary<uint, TextLineEventListener> _documents;
private readonly Dictionary<IVsHierarchy, HierarchyInfo> _hierarchies = new Dictionary<IVsHierarchy, HierarchyInfo>();
private readonly Dictionary<ModuleId, LibraryNode> _files;
private readonly Library _library;
private readonly IVsEditorAdaptersFactoryService _adapterFactory;
private uint _objectManagerCookie;
private uint _runningDocTableCookie;
public LibraryManager(CommonPackage/*!*/ package) {
Contract.Assert(package != null);
_package = package;
_documents = new Dictionary<uint, TextLineEventListener>();
_library = new Library(new Guid(CommonConstants.LibraryGuid));
_library.LibraryCapabilities = (_LIB_FLAGS2)_LIB_FLAGS.LF_PROJECT;
_files = new Dictionary<ModuleId, LibraryNode>();
var model = ((IServiceContainer)package).GetService(typeof(SComponentModel)) as IComponentModel;
_adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>();
// Register our library now so it'll be available for find all references
RegisterLibrary();
}
public Library Library {
get { return _library; }
}
protected abstract LibraryNode CreateLibraryNode(LibraryNode parent, IScopeNode subItem, string namePrefix, IVsHierarchy hierarchy, uint itemid);
public virtual LibraryNode CreateFileLibraryNode(LibraryNode parent, HierarchyNode hierarchy, string name, string filename, LibraryNodeType libraryNodeType) {
return new LibraryNode(null, name, filename, libraryNodeType);
}
private object GetPackageService(Type/*!*/ type) {
return ((System.IServiceProvider)_package).GetService(type);
}
private void RegisterForRDTEvents() {
if (0 != _runningDocTableCookie) {
return;
}
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null != rdt) {
// Do not throw here in case of error, simply skip the registration.
rdt.AdviseRunningDocTableEvents(this, out _runningDocTableCookie);
}
}
private void UnregisterRDTEvents() {
if (0 == _runningDocTableCookie) {
return;
}
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null != rdt) {
// Do not throw in case of error.
rdt.UnadviseRunningDocTableEvents(_runningDocTableCookie);
}
_runningDocTableCookie = 0;
}
#region ILibraryManager Members
public void RegisterHierarchy(IVsHierarchy hierarchy) {
if ((null == hierarchy) || _hierarchies.ContainsKey(hierarchy)) {
return;
}
RegisterLibrary();
var commonProject = hierarchy.GetProject().GetCommonProject();
HierarchyListener listener = new HierarchyListener(hierarchy, this);
var node = _hierarchies[hierarchy] = new HierarchyInfo(
listener,
new ProjectLibraryNode(commonProject)
);
_library.AddNode(node.ProjectLibraryNode);
listener.StartListening(true);
RegisterForRDTEvents();
}
private void RegisterLibrary() {
if (0 == _objectManagerCookie) {
IVsObjectManager2 objManager = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (null == objManager) {
return;
}
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
objManager.RegisterSimpleLibrary(_library, out _objectManagerCookie));
}
}
public void UnregisterHierarchy(IVsHierarchy hierarchy) {
if ((null == hierarchy) || !_hierarchies.ContainsKey(hierarchy)) {
return;
}
HierarchyInfo info = _hierarchies[hierarchy];
if (null != info) {
info.Listener.Dispose();
}
_hierarchies.Remove(hierarchy);
_library.RemoveNode(info.ProjectLibraryNode);
if (0 == _hierarchies.Count) {
UnregisterRDTEvents();
}
lock (_files) {
ModuleId[] keys = new ModuleId[_files.Keys.Count];
_files.Keys.CopyTo(keys, 0);
foreach (ModuleId id in keys) {
if (hierarchy.Equals(id.Hierarchy)) {
_library.RemoveNode(_files[id]);
_files.Remove(id);
}
}
}
// Remove the document listeners.
uint[] docKeys = new uint[_documents.Keys.Count];
_documents.Keys.CopyTo(docKeys, 0);
foreach (uint id in docKeys) {
TextLineEventListener docListener = _documents[id];
if (hierarchy.Equals(docListener.FileID.Hierarchy)) {
_documents.Remove(id);
docListener.Dispose();
}
}
}
public void RegisterLineChangeHandler(uint document,
TextLineChangeEvent lineChanged, Action<IVsTextLines> onIdle) {
_documents[document].OnFileChangedImmediate += delegate(object sender, TextLineChange[] changes, int fLast) {
lineChanged(sender, changes, fLast);
};
_documents[document].OnFileChanged += (sender, args) => onIdle(args.TextBuffer);
}
#endregion
#region Library Member Production
/// <summary>
/// Overridden in the base class to receive notifications of when a file should
/// be analyzed for inclusion in the library. The derived class should queue
/// the parsing of the file and when it's complete it should call FileParsed
/// with the provided LibraryTask and an IScopeNode which provides information
/// about the members of the file.
/// </summary>
protected virtual void OnNewFile(LibraryTask task) {
}
/// <summary>
/// Called by derived class when a file has been parsed. The caller should
/// provide the LibraryTask received from the OnNewFile call and an IScopeNode
/// which represents the contents of the library.
///
/// It is safe to call this method from any thread.
/// </summary>
protected void FileParsed(LibraryTask task, IScopeNode scope) {
try {
var project = task.ModuleID.Hierarchy.GetProject().GetCommonProject();
HierarchyNode fileNode = fileNode = project.NodeFromItemId(task.ModuleID.ItemID);
HierarchyInfo parent;
if (fileNode == null || !_hierarchies.TryGetValue(task.ModuleID.Hierarchy, out parent)) {
return;
}
LibraryNode module = CreateFileLibraryNode(
parent.ProjectLibraryNode,
fileNode,
System.IO.Path.GetFileName(task.FileName),
task.FileName,
LibraryNodeType.Package | LibraryNodeType.Classes
);
// TODO: Creating the module tree should be done lazily as needed
// Currently we replace the entire tree and rely upon the libraries
// update count to invalidate the whole thing. We could do this
// finer grained and only update the changed nodes. But then we
// need to make sure we're not mutating lists which are handed out.
CreateModuleTree(module, scope, task.FileName + ":", task.ModuleID);
if (null != task.ModuleID) {
LibraryNode previousItem = null;
lock (_files) {
if (_files.TryGetValue(task.ModuleID, out previousItem)) {
_files.Remove(task.ModuleID);
parent.ProjectLibraryNode.RemoveNode(previousItem);
}
}
}
parent.ProjectLibraryNode.AddNode(module);
_library.Update();
if (null != task.ModuleID) {
lock (_files) {
_files.Add(task.ModuleID, module);
}
}
} catch (COMException) {
// we're shutting down and can't get the project
}
}
private void CreateModuleTree(LibraryNode current, IScopeNode scope, string namePrefix, ModuleId moduleId) {
if ((null == scope) || (null == scope.NestedScopes)) {
return;
}
foreach (IScopeNode subItem in scope.NestedScopes) {
LibraryNode newNode = CreateLibraryNode(current, subItem, namePrefix, moduleId.Hierarchy, moduleId.ItemID);
string newNamePrefix = namePrefix;
current.AddNode(newNode);
if ((newNode.NodeType & LibraryNodeType.Classes) != LibraryNodeType.None) {
newNamePrefix = namePrefix + newNode.Name + ".";
}
// Now use recursion to get the other types.
CreateModuleTree(newNode, subItem, newNamePrefix, moduleId);
}
}
#endregion
#region Hierarchy Events
private void OnNewFile(object sender, HierarchyEventArgs args) {
IVsHierarchy hierarchy = sender as IVsHierarchy;
if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) {
return;
}
ITextBuffer buffer = null;
if (null != args.TextBuffer) {
buffer = _adapterFactory.GetDocumentBuffer(args.TextBuffer);
}
var id = new ModuleId(hierarchy, args.ItemID);
OnNewFile(new LibraryTask(args.CanonicalName, buffer, new ModuleId(hierarchy, args.ItemID)));
}
/// <summary>
/// Handles the delete event, checking to see if this is a project item.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void OnDeleteFile(object sender, HierarchyEventArgs args) {
IVsHierarchy hierarchy = sender as IVsHierarchy;
if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) {
return;
}
OnDeleteFile(hierarchy, args);
}
/// <summary>
/// Does a delete w/o checking if it's a non-meber item, for handling the
/// transition from member item to non-member item.
/// </summary>
private void OnDeleteFile(IVsHierarchy hierarchy, HierarchyEventArgs args) {
ModuleId id = new ModuleId(hierarchy, args.ItemID);
LibraryNode node = null;
lock (_files) {
if (_files.TryGetValue(id, out node)) {
_files.Remove(id);
HierarchyInfo parent;
if (_hierarchies.TryGetValue(hierarchy, out parent)) {
parent.ProjectLibraryNode.RemoveNode(node);
}
}
}
if (null != node) {
_library.RemoveNode(node);
}
}
private void IsNonMemberItemChanged(object sender, HierarchyEventArgs args) {
IVsHierarchy hierarchy = sender as IVsHierarchy;
if (null == hierarchy) {
return;
}
if (!IsNonMemberItem(hierarchy, args.ItemID)) {
OnNewFile(hierarchy, args);
} else {
OnDeleteFile(hierarchy, args);
}
}
/// <summary>
/// Checks whether this hierarchy item is a project member (on disk items from show all
/// files aren't considered project members).
/// </summary>
protected bool IsNonMemberItem(IVsHierarchy hierarchy, uint itemId) {
object val;
int hr = hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_IsNonMemberItem, out val);
return ErrorHandler.Succeeded(hr) && (bool)val;
}
#endregion
#region IVsRunningDocTableEvents Members
public int OnAfterAttributeChange(uint docCookie, uint grfAttribs) {
if ((grfAttribs & (uint)(__VSRDTATTRIB.RDTA_MkDocument)) == (uint)__VSRDTATTRIB.RDTA_MkDocument) {
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (rdt != null) {
uint flags, readLocks, editLocks, itemid;
IVsHierarchy hier;
IntPtr docData = IntPtr.Zero;
string moniker;
int hr;
try {
hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out editLocks, out moniker, out hier, out itemid, out docData);
TextLineEventListener listner;
if (_documents.TryGetValue(docCookie, out listner)) {
listner.FileName = moniker;
}
} finally {
if (IntPtr.Zero != docData) {
Marshal.Release(docData);
}
}
}
}
return VSConstants.S_OK;
}
public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame) {
return VSConstants.S_OK;
}
public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) {
return VSConstants.S_OK;
}
public int OnAfterSave(uint docCookie) {
return VSConstants.S_OK;
}
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame) {
// Check if this document is in the list of the documents.
if (_documents.ContainsKey(docCookie)) {
return VSConstants.S_OK;
}
// Get the information about this document from the RDT.
IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null != rdt) {
// Note that here we don't want to throw in case of error.
uint flags;
uint readLocks;
uint writeLoks;
string documentMoniker;
IVsHierarchy hierarchy;
uint itemId;
IntPtr unkDocData;
int hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out writeLoks,
out documentMoniker, out hierarchy, out itemId, out unkDocData);
try {
if (Microsoft.VisualStudio.ErrorHandler.Failed(hr) || (IntPtr.Zero == unkDocData)) {
return VSConstants.S_OK;
}
// Check if the herarchy is one of the hierarchies this service is monitoring.
if (!_hierarchies.ContainsKey(hierarchy)) {
// This hierarchy is not monitored, we can exit now.
return VSConstants.S_OK;
}
// Check the file to see if a listener is required.
if (_package.IsRecognizedFile(documentMoniker)) {
return VSConstants.S_OK;
}
// Create the module id for this document.
ModuleId docId = new ModuleId(hierarchy, itemId);
// Try to get the text buffer.
IVsTextLines buffer = Marshal.GetObjectForIUnknown(unkDocData) as IVsTextLines;
// Create the listener.
TextLineEventListener listener = new TextLineEventListener(buffer, documentMoniker, docId);
// Set the event handler for the change event. Note that there is no difference
// between the AddFile and FileChanged operation, so we can use the same handler.
listener.OnFileChanged += new EventHandler<HierarchyEventArgs>(OnNewFile);
// Add the listener to the dictionary, so we will not create it anymore.
_documents.Add(docCookie, listener);
} finally {
if (IntPtr.Zero != unkDocData) {
Marshal.Release(unkDocData);
}
}
}
// Always return success.
return VSConstants.S_OK;
}
public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) {
if ((0 != dwEditLocksRemaining) || (0 != dwReadLocksRemaining)) {
return VSConstants.S_OK;
}
TextLineEventListener listener;
if (!_documents.TryGetValue(docCookie, out listener) || (null == listener)) {
return VSConstants.S_OK;
}
using (listener) {
_documents.Remove(docCookie);
// Now make sure that the information about this file are up to date (e.g. it is
// possible that Class View shows something strange if the file was closed without
// saving the changes).
HierarchyEventArgs args = new HierarchyEventArgs(listener.FileID.ItemID, listener.FileName);
OnNewFile(listener.FileID.Hierarchy, args);
}
return VSConstants.S_OK;
}
#endregion
public void OnIdle(IOleComponentManager compMgr) {
foreach (TextLineEventListener listener in _documents.Values) {
if (compMgr.FContinueIdle() == 0) {
break;
}
listener.OnIdle();
}
}
#region IDisposable Members
public void Dispose() {
// Dispose all the listeners.
foreach (var info in _hierarchies.Values) {
info.Listener.Dispose();
}
_hierarchies.Clear();
foreach (TextLineEventListener textListener in _documents.Values) {
textListener.Dispose();
}
_documents.Clear();
// Remove this library from the object manager.
if (0 != _objectManagerCookie) {
IVsObjectManager2 mgr = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2;
if (null != mgr) {
mgr.UnregisterLibrary(_objectManagerCookie);
}
_objectManagerCookie = 0;
}
// Unregister this object from the RDT events.
UnregisterRDTEvents();
}
#endregion
class HierarchyInfo {
public readonly HierarchyListener Listener;
public readonly ProjectLibraryNode ProjectLibraryNode;
public HierarchyInfo(HierarchyListener listener, ProjectLibraryNode projectLibNode) {
Listener = listener;
ProjectLibraryNode = projectLibNode;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Saber.Domain;
namespace Saber.Extensions
{
/// <summary>
/// Extension methods on lists
/// </summary>
public static class EnumerableExtensions
{
///<summary>
/// Returns the passed enumerable as a ReadOnlyCollection.
///</summary>
///<param name="enumerable">The enumeration of items.</param>
///<typeparam name="T">The type of items the enumerable contains.</typeparam>
///<returns>A ReadOnlyCollection of the passed enumerable.</returns>
public static ReadOnlyCollection<T> AsReadOnly<T>(this IEnumerable<T> enumerable)
{
return enumerable.ToList().AsReadOnly();
}
/// <summary>
/// Adds the item in case it's not already present in the list using the default equality comparer.
/// </summary>
/// <typeparam name="T">The type of item to add.</typeparam>
/// <param name="enumerable">The enumerable to add it to.</param>
/// <param name="value">The value to add.</param>
public static void AddUnique<T>(this ICollection<T> enumerable, T value)
{
enumerable.AddUnique(value, EqualityComparer<T>.Default);
}
/// <summary>
/// Adds the item in case it's not already present in the list.
/// </summary>
/// <typeparam name="T">The type of item to add.</typeparam>
/// <param name="enumerable">The enumerable to add it to.</param>
/// <param name="value">The value to add.</param>
/// <param name="comparer">The comparer to use.</param>
public static void AddUnique<T>(this ICollection<T> enumerable, T value, IEqualityComparer<T> comparer)
{
if (!enumerable.Contains(value, comparer))
{
enumerable.Add(value);
}
}
/// <summary>
/// Adds the passed items to the enumerable.
/// </summary>
/// <typeparam name="T">The type of item to add.</typeparam>
/// <param name="enumerable">The enumerable to add it to.</param>
/// <param name="values">The values to add.</param>
public static void AddRange<T>(this ICollection<T> enumerable, IEnumerable<T> values)
{
if (values == null)
return;
foreach (var item in values)
{
enumerable.AddUnique(item);
}
}
/// <summary>
/// Appends a list to another one without ordering.
/// </summary>
/// <remarks>This resembles LINQ's union, except it doesn't distinct.</remarks>
/// <param name="source">The first list.</param>
/// <param name="additionals">The list to append.</param>
/// <returns>An combined version of the two enumerables.</returns>
public static IEnumerable Append(this IEnumerable source, IEnumerable additionals)
{
foreach (var item in source)
yield return item;
foreach (var item in additionals)
yield return item;
}
/// <summary>
/// Appends a list to another one without ordering.
/// </summary>
/// <remarks>This resembles LINQ's union, except it doesn't distinct.</remarks>
/// <param name="source">The first list.</param>
/// <param name="additionals">The list to append.</param>
/// <typeparam name="T">The type of items in the list</typeparam>
/// <returns>An combined version of the two enumerables.</returns>
public static IEnumerable<T> Append<T>(this IEnumerable<T> source, IEnumerable<T> additionals)
{
foreach (var item in source)
yield return item;
foreach (var item in additionals)
yield return item;
}
/// <summary>
/// Flattens an enumerable and its children into a single list.
/// </summary>
/// <remarks>This is recursive unlike Delve</remarks>
/// <param name="source">The parent enumerable.</param>
/// <param name="selector">The child selector</param>
/// <typeparam name="T">The type of items in the enumerables.</typeparam>
/// <returns>A flat list</returns>
public static IEnumerable<T> AsFlat<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{
if (source == null) yield break;
foreach (var entity in source)
{
yield return entity;
foreach (var child in selector(entity).AsFlat(selector))
yield return child;
}
}
/// <summary>
/// Transforms array of structs into an array of objects.
/// </summary>
/// <typeparam name="T">The type of struct.</typeparam>
/// <param name="enumerable">The arguments.</param>
/// <returns>An array of objects.</returns>
public static object[] BoxToArray<T>(this IEnumerable<T> enumerable)
where T : struct
{
return enumerable == null
? null
: enumerable.Cast<object>().ToArray();
}
///<summary>
///Determines whether the dictionary (where each value is a list of values) contains a specified value.
///</summary>
///<typeparam name="TKey">The type of keys in the dictionary.</typeparam>
///<typeparam name="TValues">The type of the list of values in the dictionary.</typeparam>
///<typeparam name="TValue">The type of the searched value.</typeparam>
///<param name="dictionary">The dictionary.</param>
///<param name="value">The searced value.</param>
///<returns>
/// <c>true</c> if the specified dictionary contains value; otherwise, <c>false</c>.
///</returns>
public static bool ContainsValue<TKey, TValues, TValue>(this IDictionary<TKey, TValues> dictionary, TValue value)
where TValues : IEnumerable<TValue>
{
return dictionary.Values.SelectMany(x => x).Contains(value);
}
/// <summary>
/// Completely consumes the given sequence. This method uses immediate execution,
/// and doesn't store any data during execution.
/// </summary>
/// <typeparam name="T">Element type of the sequence</typeparam>
/// <param name="source">Source to consume</param>
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "element",
Justification = "The point is to just iterate the list. We don't want to do anything with it.")]
public static void Consume<T>(this IEnumerable<T> source)
{
if (source == null)
return;
foreach (var element in source) { }
}
/// <summary>
/// Converts an IEnumerable to a type of choice.
/// </summary>
/// <typeparam name="TItem">The type of item.</typeparam>
/// <typeparam name="TList">The type of list to convert to.</typeparam>
/// <param name="enumerable">The original values.</param>
/// <returns>A list of type TList, with all the values from the original list.</returns>
public static TList ConvertTo<TItem, TList>(this IEnumerable<TItem> enumerable)
where TList : ICollection<TItem>, new()
{
var list = new TList();
if (enumerable != null)
{
foreach (var value in enumerable)
{
list.Add(value);
}
}
return list;
}
/// <summary>
/// Distinct, based on a key.
/// </summary>
/// <param name="source">The original enumerable</param>
/// <param name="selector">The key used to distinct.</param>
/// <typeparam name="T">The type of list.</typeparam>
/// <typeparam name="TKey">The type of key</typeparam>
/// <returns>A distinct version of the original source.</returns>
public static IEnumerable<T> Distinct<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector)
{
var set = new HashSet<TKey>();
return source.Where(x => set.Add(selector(x)))
//It's important that we call ToList, since the hash set will be used more than once otherwise, giving a false result.
.ToList();
}
/// <summary>
/// Returns a list of all parents and delves into the selected children.
/// </summary>
/// <remarks>This is not recursive, unlike AsFlat</remarks>
/// <param name="source">The original list</param>
/// <param name="childrenSelector">Child selector</param>
/// <typeparam name="T">The type of items in the list</typeparam>
/// <returns>A single level flat list</returns>
public static IEnumerable<T> Delve<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> childrenSelector)
{
if (source == null) yield break;
foreach (var entity in source)
{
yield return entity;
var children = childrenSelector(entity);
if (children == null) continue;
foreach (var child in children)
yield return child;
}
}
/// <summary>
/// Returns a list of the parent and delves into the selected children.
/// </summary>
/// <remarks>This is not recursive, unlike AsFlat</remarks>
/// <param name="entity"></param>
/// <param name="childrenSelector">Child selector</param>
/// <typeparam name="T">The type of items in the list</typeparam>
/// <returns>A single level flat list</returns>
public static IEnumerable<T> Delve<T>(this T entity, Func<T, IEnumerable<T>> childrenSelector)
{
yield return entity;
var children = childrenSelector(entity);
if (children == null) yield break;
foreach (var child in children)
yield return child;
}
///<summary>
/// Counts a list, keeping in mind the check you are planning to do on it.
/// This way you don't have to count every item when you don't need to, resulting in less overhead.
///</summary>
///<param name="enumerable">The list with items getting counted.</param>
///<param name="comparePredicate">The comparison function.</param>
///<param name="numberOfItems">The number of items that you are going to check for. The same number should be used in the predicate.</param>
///<param name="wherePredicate">The filter predicate.</param>
///<typeparam name="T">The type of item getting counted. This is of no relevance, just to keep the method generic.</typeparam>
///<exception cref="OverflowException">An overflow exception will be thrown when 'numberOfItems' equals int.MaxValue</exception>
///<returns>The result of the passed predicate.</returns>
private static bool OptimizedCount<T>(IEnumerable<T> enumerable, int numberOfItems, Func<T, bool> wherePredicate,
Func<int, bool> comparePredicate)
{
if (enumerable == null || numberOfItems < 0) return false;
if (wherePredicate != null)
{
enumerable = enumerable.Where(wherePredicate);
}
var numberOfItemsToCount = checked(numberOfItems + 1);
var countedItems = 0;
var enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext() && countedItems < numberOfItemsToCount)
{
countedItems++;
}
var returnValue = comparePredicate(countedItems);
return returnValue;
}
///<summary>
/// Counts a list, keeping in mind the check you are planning to do on it.
/// This way you don't have to count every item when you don't need to, resulting in less overhead.
///</summary>
///<param name="enumerable">The list with items getting counted.</param>
///<param name="numberOfItems">The number of items that you are going to check for. The same number should be used in the predicate.</param>
///<typeparam name="T">The type of item getting counted. This is of no relevance, just to keep the method generic.</typeparam>
///<exception cref="OverflowException">An overflow exception will be thrown when 'numberOfItems' equals int.MaxValue</exception>
///<returns>True if the list contains the same amount of items as defined in 'numberOfItems'.</returns>
public static bool CountEqualTo<T>(this IEnumerable<T> enumerable, int numberOfItems)
{
return CountEqualTo(enumerable, numberOfItems, null);
}
///<summary>
/// Counts a list, keeping in mind the check you are planning to do on it.
/// This way you don't have to count every item when you don't need to, resulting in less overhead.
///</summary>
///<param name="enumerable">The list with items getting counted.</param>
///<param name="numberOfItems">The number of items that you are going to check for. The same number should be used in the predicate.</param>
///<param name="wherePredicate">The filter predicate to apply to the list.</param>
///<typeparam name="T">The type of item getting counted. This is of no relevance, just to keep the method generic.</typeparam>
///<exception cref="OverflowException">An overflow exception will be thrown when 'numberOfItems' equals int.MaxValue</exception>
///<returns>True if the list contains the same amount of items as defined in 'numberOfItems'.</returns>
public static bool CountEqualTo<T>(this IEnumerable<T> enumerable, int numberOfItems, Func<T, bool> wherePredicate)
{
return OptimizedCount(enumerable, numberOfItems, wherePredicate, x => x == numberOfItems);
}
///<summary>
/// Counts a list, keeping in mind the check you are planning to do on it.
/// This way you don't have to count every item when you don't need to, resulting in less overhead.
///</summary>
///<param name="enumerable">The list with items getting counted.</param>
///<param name="numberOfItems">The number of items that you are going to check for. The same number should be used in the predicate.</param>
///<typeparam name="T">The type of item getting counted. This is of no relevance, just to keep the method generic.</typeparam>
///<exception cref="OverflowException">An overflow exception will be thrown when 'numberOfItems' equals int.MaxValue</exception>
///<returns>True if the list contains less items than defined in 'numberOfItems'.</returns>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "CountLess")]
public static bool CountLessThan<T>(this IEnumerable<T> enumerable, int numberOfItems)
{
return CountLessThan(enumerable, numberOfItems, null);
}
///<summary>
/// Counts a list, keeping in mind the check you are planning to do on it.
/// This way you don't have to count every item when you don't need to, resulting in less overhead.
///</summary>
///<param name="enumerable">The list with items getting counted.</param>
///<param name="numberOfItems">The number of items that you are going to check for. The same number should be used in the predicate.</param>
///<param name="wherePredicate">The filter predicate to apply to the list.</param>
///<typeparam name="T">The type of item getting counted. This is of no relevance, just to keep the method generic.</typeparam>
///<exception cref="OverflowException">An overflow exception will be thrown when 'numberOfItems' equals int.MaxValue</exception>
///<returns>True if the list contains less items than defined in 'numberOfItems'.</returns>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "CountLess")]
public static bool CountLessThan<T>(this IEnumerable<T> enumerable, int numberOfItems, Func<T, bool> wherePredicate)
{
return OptimizedCount(enumerable, numberOfItems, wherePredicate, x => x < numberOfItems);
}
///<summary>
/// Counts a list, keeping in mind the check you are planning to do on it.
/// This way you don't have to count every item when you don't need to, resulting in less overhead.
///</summary>
///<param name="enumerable">The list with items getting counted.</param>
///<param name="numberOfItems">The number of items that you are going to check for. The same number should be used in the predicate.</param>
///<typeparam name="T">The type of item getting counted. This is of no relevance, just to keep the method generic.</typeparam>
///<exception cref="OverflowException">An overflow exception will be thrown when 'numberOfItems' equals int.MaxValue</exception>
///<returns>True if the list contains more items than defined in 'numberOfItems'.</returns>
public static bool CountGreaterThan<T>(this IEnumerable<T> enumerable, int numberOfItems)
{
return CountGreaterThan(enumerable, numberOfItems, null);
}
///<summary>
/// Counts a list, keeping in mind the check you are planning to do on it.
/// This way you don't have to count every item when you don't need to, resulting in less overhead.
///</summary>
///<param name="enumerable">The list with items getting counted.</param>
///<param name="numberOfItems">The number of items that you are going to check for. The same number should be used in the predicate.</param>
///<param name="wherePredicate">The filter predicate to apply to the list.</param>
///<typeparam name="T">The type of item getting counted. This is of no relevance, just to keep the method generic.</typeparam>
///<exception cref="OverflowException">An overflow exception will be thrown when 'numberOfItems' equals int.MaxValue</exception>
///<returns>True if the list contains more items than defined in 'numberOfItems'.</returns>
public static bool CountGreaterThan<T>(this IEnumerable<T> enumerable, int numberOfItems, Func<T, bool> wherePredicate)
{
return OptimizedCount(enumerable, numberOfItems, wherePredicate, x => x > numberOfItems);
}
///<summary>
/// Counts a list, keeping in mind the check you are planning to do on it.
/// This way you don't have to count every item when you don't need to, resulting in less overhead.
///</summary>
///<param name="enumerable">The list with items getting counted.</param>
///<param name="numberOfItems">The number of items that you are going to check for. The same number should be used in the predicate.</param>
///<typeparam name="T">The type of item getting counted. This is of no relevance, just to keep the method generic.</typeparam>
///<exception cref="OverflowException">An overflow exception will be thrown when 'numberOfItems' equals int.MaxValue</exception>
///<returns>True if the list contains less or the same amount of items as defined in 'numberOfItems'.</returns>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "CountLess")]
public static bool CountLessOrEqualTo<T>(this IEnumerable<T> enumerable, int numberOfItems)
{
return CountLessOrEqualTo(enumerable, numberOfItems, null);
}
///<summary>
/// Counts a list, keeping in mind the check you are planning to do on it.
/// This way you don't have to count every item when you don't need to, resulting in less overhead.
///</summary>
///<param name="enumerable">The list with items getting counted.</param>
///<param name="numberOfItems">The number of items that you are going to check for. The same number should be used in the predicate.</param>
///<param name="wherePredicate">The filter predicate to apply to the list.</param>
///<typeparam name="T">The type of item getting counted. This is of no relevance, just to keep the method generic.</typeparam>
///<exception cref="OverflowException">An overflow exception will be thrown when 'numberOfItems' equals int.MaxValue</exception>
///<returns>True if the list contains less or the same amount of items as defined in 'numberOfItems'.</returns>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "CountLess")]
public static bool CountLessOrEqualTo<T>(this IEnumerable<T> enumerable, int numberOfItems,
Func<T, bool> wherePredicate)
{
return OptimizedCount(enumerable, numberOfItems, wherePredicate, x => x <= numberOfItems);
}
///<summary>
/// Counts a list, keeping in mind the check you are planning to do on it.
/// This way you don't have to count every item when you don't need to, resulting in less overhead.
///</summary>
///<param name="enumerable">The list with items getting counted.</param>
///<param name="numberOfItems">The number of items that you are going to check for. The same number should be used in the predicate.</param>
///<typeparam name="T">The type of item getting counted. This is of no relevance, just to keep the method generic.</typeparam>
///<exception cref="OverflowException">An overflow exception will be thrown when 'numberOfItems' equals int.MaxValue</exception>
///<returns>True if the list contains more or the same amount of items as defined in 'numberOfItems'.</returns>
public static bool CountGreaterOrEqualTo<T>(this IEnumerable<T> enumerable, int numberOfItems)
{
return CountGreaterOrEqualTo(enumerable, numberOfItems, null);
}
///<summary>
/// Counts a list, keeping in mind the check you are planning to do on it.
/// This way you don't have to count every item when you don't need to, resulting in less overhead.
///</summary>
///<param name="enumerable">The list with items getting counted.</param>
///<param name="numberOfItems">The number of items that you are going to check for. The same number should be used in the predicate.</param>
///<param name="wherePredicate">The filter predicate to apply to the list.</param>
///<typeparam name="T">The type of item getting counted. This is of no relevance, just to keep the method generic.</typeparam>
///<exception cref="OverflowException">An overflow exception will be thrown when 'numberOfItems' equals int.MaxValue</exception>
///<returns>True if the list contains more or the same amount of items as defined in 'numberOfItems'.</returns>
public static bool CountGreaterOrEqualTo<T>(this IEnumerable<T> enumerable, int numberOfItems,
Func<T, bool> wherePredicate)
{
return OptimizedCount(enumerable, numberOfItems, wherePredicate, x => x >= numberOfItems);
}
/// <summary>
/// Groups the adjacent elements of a sequence according to a specified key selector function.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <param name="keySelector">The key selector.</param>
/// <returns></returns>
public static IEnumerable<IGrouping<TKey, TSource>> GroupAdjacent<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
return GroupAdjacent(source, keySelector, EqualityComparer<TKey>.Default);
}
/// <summary>
/// Groups the adjacent elements of a sequence according to a specified key selector function.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <param name="source">The source.</param>
/// <param name="keySelector">The key selector.</param>
/// <param name="comparer">The comparer.</param>
/// <returns></returns>
public static IEnumerable<IGrouping<TKey, TSource>> GroupAdjacent<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
return new GroupedAdjacentEnumerable<TSource, TKey>(source, keySelector, comparer);
}
///<summary>
/// Uses the most optimized way of checking if a list of items is empty or not.
///</summary>
///<param name="collection">The collection to check</param>
///<typeparam name="T">The type of items in the collection</typeparam>
///<returns>True if not empty</returns>
public static bool IsNullOrEmpty<T>(this ICollection<T> collection)
{
return collection == null || collection.Count == 0;
}
/// <summary>
/// Uses the most optimized way of checking if a list of items is empty or not.
/// </summary>
///<param name="array">The array to check</param>
///<typeparam name="T">The type of items in the array</typeparam>
///<returns>True if not empty</returns>
public static bool IsNullOrEmpty<T>(this T[] array)
{
return array == null || array.Length == 0;
}
/// <summary>
/// Uses the most optimized way of checking if a list of items is empty or not.
/// </summary>
///<param name="enumerable">The enumeration to check</param>
///<typeparam name="T">The type of items in the enumeration</typeparam>
///<returns>True if not empty</returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
return enumerable == null || !enumerable.Any();
}
/// <summary>
/// Selects the minimum from a list after applying a selector.
/// </summary>
/// <typeparam name="TSource">The source type.</typeparam>
/// <typeparam name="TResult">The result type.</typeparam>
/// <param name="enumerable">The original list.</param>
/// <param name="selector">The selector used to select items from the list.</param>
/// <returns>The maximum from the selected items.</returns>
public static TResult Min<TSource, TResult>(this IEnumerable<TSource> enumerable, Func<TSource, TResult> selector)
{
return enumerable.Select(selector).Min();
}
/// <summary>
/// Selects the maximum from a list after applying a selector.
/// </summary>
/// <typeparam name="TSource">The source type.</typeparam>
/// <typeparam name="TResult">The result type.</typeparam>
/// <param name="enumerable">The original list.</param>
/// <param name="selector">The selector used to select items from the list.</param>
/// <returns>The maximum from the selected items.</returns>
public static TResult Max<TSource, TResult>(this IEnumerable<TSource> enumerable, Func<TSource, TResult> selector)
{
return enumerable.Select(selector).Max();
}
/// <summary>
/// Retrieves both min and max from a list of values.
/// </summary>
/// <typeparam name="TSource">The source type.</typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static MinMax<TSource> MinAndMax<TSource>(this IEnumerable<TSource> source)
{
if (source == null) throw new ArgumentNullException("source");
var comparer = Comparer<TSource>.Default;
TSource min, max;
min = max = default(TSource);
if (ReferenceEquals(null, min))
{
foreach (var x in source.Where(x => x != null))
{
if (ReferenceEquals(null, min) || comparer.Compare(x, min) < 0)
min = x;
if (ReferenceEquals(null, min) || comparer.Compare(x, max) > 0)
max = x;
}
return new MinMax<TSource>(min, max);
}
var hasValue = false;
foreach (var x in source)
{
if (hasValue)
{
if (comparer.Compare(x, min) < 0)
min = x;
if (comparer.Compare(x, max) > 0)
max = x;
}
else
{
min = x;
max = x;
hasValue = true;
}
}
if (hasValue) return new MinMax<TSource>(min, max);
throw new InvalidOperationException("No Elements");
}
/// <summary>
/// Performs the passed action on each item in the enumeration.
/// </summary>
/// <typeparam name="T">The type of items the enumeration contains.</typeparam>
/// <param name="enumerable">The enumeration.</param>
/// <param name="action">The action.</param>
/// <returns>The enumeration.</returns>
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
if (enumerable != null)
{
foreach (var item in enumerable)
{
action(item);
}
}
return enumerable;
}
/// <summary>
/// Returns a value that is inbetween the min and max values of the supplied list.
/// </summary>
/// <typeparam name="T">The source type</typeparam>
/// <param name="value">The value to check</param>
/// <param name="values">The source of values used for min and max (inclusive)</param>
/// <returns>A value between min and max</returns>
public static T InBetween<T>(this T value, IEnumerable<T> values)
{
var minAndMax = values.MinAndMax();
return value.InBetween(minAndMax);
}
/// <summary>
/// Returns a value that is inbetween the min and max values.
/// </summary>
/// <typeparam name="T">The source type</typeparam>
/// <param name="value">The value to check</param>
/// <param name="minAndMax">The minimum and maximum value (inclusive)</param>
/// <returns>A value between min and max</returns>
public static T InBetween<T>(this T value, MinMax<T> minAndMax)
{
var min = minAndMax.Min;
var max = minAndMax.Max;
return value.InBetween(min, max);
}
/// <summary>
/// Returns a value that is inbetween the min and max values.
/// </summary>
/// <typeparam name="T">The source type</typeparam>
/// <param name="value">The value to check</param>
/// <param name="min">The minimum value (inclusive)</param>
/// <param name="max">The maximum value (inclusive)</param>
/// <returns>A value between min and max</returns>
public static T InBetween<T>(this T value, T min, T max)
{
var comparer = Comparer<T>.Default;
if (comparer.Compare(value, min) <= 0)
return min;
if (comparer.Compare(value, max) >= 0)
return max;
return value;
}
/// <summary>
/// Skips items from the input sequence until the given predicate returns true
/// when applied to the current source item; that item will be the last skipped.
/// </summary>
/// <typeparam name="TSource">Type of the source sequence</typeparam>
/// <param name="source">Source sequence</param>
/// <param name="predicate">Predicate used to determine when to stop yielding results from the source.</param>
/// <returns>Items from the source sequence after the predicate first returns true when applied to the item.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null</exception>
public static IEnumerable<TSource> SkipUntil<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
using (var iterator = source.GetEnumerator())
{
while (iterator.MoveNext())
{
if (predicate(iterator.Current))
{
break;
}
}
while (iterator.MoveNext())
{
yield return iterator.Current;
}
}
}
///<summary>
/// Strips null values from the enumerable.
///</summary>
///<param name="enumerable">The enumeration.</param>
///<typeparam name="T">The type of items the enumeration contains. This has to be a class.</typeparam>
///<returns>An enumerable stripped of all null-values.</returns>
public static IEnumerable<T> StripNulls<T>(this IEnumerable<T> enumerable) where T : class
{
return enumerable == null
? null
: enumerable.Where(x => x != null);
}
/// <summary>
/// Select all items from several lists.
/// </summary>
/// <typeparam name="TSource">The source type.</typeparam>
/// <typeparam name="TResult">The result type.</typeparam>
/// <param name="source">The source list.</param>
/// <returns>An enumerable that contains all items from the passed lists.</returns>
public static IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource> source)
where TSource : IEnumerable<TResult>
{
return source.SelectMany(x => x);
}
/// <summary>
/// Returns every N-th element of a source sequence.
/// </summary>
/// <typeparam name="T">Type of the source sequence</typeparam>
/// <param name="source">Source sequence</param>
/// <param name="step">Number of elements to bypass before returning the next element.</param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> that contains every N-th element in the list.
/// </returns>
public static IEnumerable<T> TakeEvery<T>(this IEnumerable<T> source, int step)
{
return source == null
? null
: source.Where((e, i) => i%step == 0);
}
/// <summary>
/// Returns a specified number of contiguous elements from the end of
/// a sequence.
/// </summary>
/// <typeparam name="T">The type of the elements of <paramref name="source"/>.</typeparam>
/// <param name="source">The sequence to pad.</param>
/// <param name="count">The number of elements to return.</param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> that contains the specified number of
/// elements from the end of the input sequence.
/// </returns>
public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> source, int count)
{
if (source == null || count <= 0)
yield break;
var queue = new Queue<T>(count);
foreach (var item in source)
{
if (queue.Count == count)
queue.Dequeue();
queue.Enqueue(item);
}
foreach (var item in queue)
yield return item;
}
/// <summary>
/// Returns items from the input sequence until the given predicate returns true
/// when applied to the current source item; that item will be the last returned.
/// </summary>
/// <typeparam name="T">Type of the source sequence</typeparam>
/// <param name="source">Source sequence</param>
/// <param name="predicate">Predicate used to determine when to stop yielding results from the source.</param>
/// <returns>Items from the source sequence, until the predicate returns true when applied to the item.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="predicate"/> is null</exception>
public static IEnumerable<T> TakeUntil<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
if (source == null || predicate == null)
yield break;
foreach (var item in source)
{
yield return item;
if (predicate(item))
{
yield break;
}
}
}
/// <summary>
/// Turns an IEnumerable into a string using a certain delimiter.
/// Returns an empty string incase the enumeration is null or empty.
/// </summary>
/// <typeparam name="T">The type of items the enumeration contains.</typeparam>
/// <param name="enumerable">The enumeration.</param>
/// <param name="delimiter">The delimiter.</param>
/// <returns>A string representation of the list.</returns>
public static string ToString<T>(this IEnumerable<T> enumerable, string delimiter)
{
return enumerable == null
? null
: string.Join(delimiter, enumerable.Select(data => data.ToString()).ToArray());
}
/// <summary>
/// Produces the union of two sequences by using a certain key.
/// </summary>
///
/// <returns>
/// An <see cref="T:System.Collections.Generic.IEnumerable`1"/> that contains the elements from both input sequences, excluding duplicates.
/// </returns>
/// <param name="first">An <see cref="T:System.Collections.Generic.IEnumerable`1"/> whose distinct elements form the first set for the union.</param><param name="second">An <see cref="T:System.Collections.Generic.IEnumerable`1"/> whose distinct elements form the second set for the union.</param>
/// <param name="keySelector">The key selector</param>
/// <typeparam name="TSource">The type of the elements of the input sequences.</typeparam>
/// <typeparam name="TKey">The type of the key of the input sequences.</typeparam>
/// <exception cref="T:System.ArgumentNullException"><paramref name="first"/> or <paramref name="second"/> is null.</exception>
public static IEnumerable<TSource> Union<TSource, TKey>(this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector)
{
var set = new HashSet<TKey>();
var firstFiltered = first.Where(element => set.Add(keySelector(element)));
var secondFiltered = second.Where(element => set.Add(keySelector(element)));
//It's important that we call ToList, since the hash set will be used more than once otherwise, giving a false result.
return firstFiltered.Append(secondFiltered).ToList();
}
/// <summary>
/// Produces the union of two sequences by using a certain key.
/// </summary>
///
/// <returns>
/// An <see cref="T:System.Collections.Generic.IEnumerable`1"/> that contains the elements from both input sequences, excluding duplicates.
/// </returns>
/// <param name="source">An <see cref="T:System.Collections.Generic.IEnumerable`1"/> whose distinct elements form the first set for the union.</param><param name="additionals">An <see cref="T:System.Collections.Generic.IEnumerable`1"/> whose distinct elements form the second set for the union.</param>
/// <typeparam name="T">The type of the elements of the input sequences.</typeparam>
/// <exception cref="T:System.ArgumentNullException"><paramref name="source"/> or <paramref name="additionals"/> is null.</exception>
public static IEnumerable<T> Union<T>(this IEnumerable<T> source, params T[] additionals)
{
return Enumerable.Union(source, additionals);
}
/// <summary>
/// Produces the union of two sequences by using a certain key.
/// </summary>
///
/// <returns>
/// An <see cref="T:System.Collections.Generic.IEnumerable`1"/> that contains the elements from both input sequences, excluding duplicates.
/// </returns>
/// <param name="first">An <see cref="T:System.Collections.Generic.IEnumerable`1"/> whose distinct elements form the first set for the union.</param><param name="second">An <see cref="T:System.Collections.Generic.IEnumerable`1"/> whose distinct elements form the second set for the union.</param>
/// <param name="keySelector">The key selector</param>
/// <typeparam name="TSource">The type of the elements of the input sequences.</typeparam>
/// <typeparam name="TKey">The type of the key of the input sequences.</typeparam>
/// <exception cref="T:System.ArgumentNullException"><paramref name="first"/> or <paramref name="second"/> is null.</exception>
public static IEnumerable<TSource> Union<TSource, TKey>(this IEnumerable<TSource> first, Func<TSource, TKey> keySelector, params TSource[] second)
{
return first.Union(second, keySelector);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Xml.XPath;
namespace Geocoding.Google
{
/// <remarks>
/// http://code.google.com/apis/maps/documentation/geocoding/
/// </remarks>
public class GoogleGeocoder : IGeocoder, IAsyncGeocoder
{
string apiKey;
BusinessKey businessKey;
const string keyMessage = "Only one of BusinessKey or ApiKey should be set on the GoogleGeocoder.";
public GoogleGeocoder() { }
public GoogleGeocoder(BusinessKey businessKey)
{
BusinessKey = businessKey;
}
public GoogleGeocoder(string apiKey)
{
ApiKey = apiKey;
}
public string ApiKey
{
get { return apiKey; }
set
{
if (businessKey != null)
throw new InvalidOperationException(keyMessage);
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("ApiKey can not be null or empty");
apiKey = value;
}
}
public BusinessKey BusinessKey
{
get { return businessKey; }
set
{
if (!string.IsNullOrEmpty(apiKey))
throw new InvalidOperationException(keyMessage);
if (value == null)
throw new ArgumentException("BusinessKey can not be null");
businessKey = value;
}
}
public IWebProxy Proxy { get; set; }
public string Language { get; set; }
public string RegionBias { get; set; }
public Bounds BoundsBias { get; set; }
public string ServiceUrl
{
get
{
var builder = new StringBuilder();
builder.Append("https://maps.googleapis.com/maps/api/geocode/xml?{0}={1}&sensor=false");
if (!string.IsNullOrEmpty(Language))
{
builder.Append("&language=");
builder.Append(HttpUtility.UrlEncode(Language));
}
if (!string.IsNullOrEmpty(RegionBias))
{
builder.Append("®ion=");
builder.Append(HttpUtility.UrlEncode(RegionBias));
}
if (!string.IsNullOrEmpty(ApiKey))
{
builder.Append("&key=");
builder.Append(HttpUtility.UrlEncode(ApiKey));
}
if (BusinessKey != null)
{
builder.Append("&client=");
builder.Append(HttpUtility.UrlEncode(BusinessKey.ClientId));
}
if (BoundsBias != null)
{
builder.Append("&bounds=");
builder.Append(BoundsBias.SouthWest.Latitude.ToString(CultureInfo.InvariantCulture));
builder.Append(",");
builder.Append(BoundsBias.SouthWest.Longitude.ToString(CultureInfo.InvariantCulture));
builder.Append("|");
builder.Append(BoundsBias.NorthEast.Latitude.ToString(CultureInfo.InvariantCulture));
builder.Append(",");
builder.Append(BoundsBias.NorthEast.Longitude.ToString(CultureInfo.InvariantCulture));
}
return builder.ToString();
}
}
public IEnumerable<GoogleAddress> Geocode(string address)
{
if (string.IsNullOrEmpty(address))
throw new ArgumentNullException("address");
HttpWebRequest request = BuildWebRequest("address", HttpUtility.UrlEncode(address));
return ProcessRequest(request);
}
public IEnumerable<GoogleAddress> ReverseGeocode(Location location)
{
if (location == null)
throw new ArgumentNullException("location");
return ReverseGeocode(location.Latitude, location.Longitude);
}
public IEnumerable<GoogleAddress> ReverseGeocode(double latitude, double longitude)
{
HttpWebRequest request = BuildWebRequest("latlng", BuildGeolocation(latitude, longitude));
return ProcessRequest(request);
}
public Task<IEnumerable<GoogleAddress>> GeocodeAsync(string address)
{
if (string.IsNullOrEmpty(address))
throw new ArgumentNullException("address");
HttpWebRequest request = BuildWebRequest("address", HttpUtility.UrlEncode(address));
return ProcessRequestAsync(request);
}
public Task<IEnumerable<GoogleAddress>> GeocodeAsync(string address, CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(address))
throw new ArgumentNullException("address");
HttpWebRequest request = BuildWebRequest("address", HttpUtility.UrlEncode(address));
return ProcessRequestAsync(request, cancellationToken);
}
public Task<IEnumerable<GoogleAddress>> ReverseGeocodeAsync(double latitude, double longitude)
{
HttpWebRequest request = BuildWebRequest("latlng", BuildGeolocation(latitude, longitude));
return ProcessRequestAsync(request);
}
public Task<IEnumerable<GoogleAddress>> ReverseGeocodeAsync(double latitude, double longitude, CancellationToken cancellationToken)
{
HttpWebRequest request = BuildWebRequest("latlng", BuildGeolocation(latitude, longitude));
return ProcessRequestAsync(request, cancellationToken);
}
private string BuildAddress(string street, string city, string state, string postalCode, string country)
{
return string.Format("{0} {1}, {2} {3}, {4}", street, city, state, postalCode, country);
}
private string BuildGeolocation(double latitude, double longitude)
{
return string.Format(CultureInfo.InvariantCulture, "{0},{1}", latitude, longitude);
}
private IEnumerable<GoogleAddress> ProcessRequest(HttpWebRequest request)
{
try
{
using (WebResponse response = request.GetResponse())
{
return ProcessWebResponse(response);
}
}
catch (GoogleGeocodingException)
{
//let these pass through
throw;
}
catch (Exception ex)
{
//wrap in google exception
throw new GoogleGeocodingException(ex);
}
}
private Task<IEnumerable<GoogleAddress>> ProcessRequestAsync(HttpWebRequest request, CancellationToken? cancellationToken = null)
{
if (cancellationToken != null)
{
cancellationToken.Value.ThrowIfCancellationRequested();
cancellationToken.Value.Register(() => request.Abort());
}
var requestState = new RequestState(request, cancellationToken);
return Task.Factory.FromAsync(
(callback, asyncState) => SendRequestAsync((RequestState)asyncState, callback),
result => ProcessResponseAsync((RequestState)result.AsyncState, result),
requestState
);
}
private IAsyncResult SendRequestAsync(RequestState requestState, AsyncCallback callback)
{
try
{
return requestState.request.BeginGetResponse(callback, requestState);
}
catch (Exception ex)
{
throw new GoogleGeocodingException(ex);
}
}
private IEnumerable<GoogleAddress> ProcessResponseAsync(RequestState requestState, IAsyncResult result)
{
if (requestState.cancellationToken != null)
requestState.cancellationToken.Value.ThrowIfCancellationRequested();
try
{
using (var response = (HttpWebResponse)requestState.request.EndGetResponse(result))
{
return ProcessWebResponse(response);
}
}
catch (GoogleGeocodingException)
{
//let these pass through
throw;
}
catch (Exception ex)
{
//wrap in google exception
throw new GoogleGeocodingException(ex);
}
}
IEnumerable<Address> IGeocoder.Geocode(string address)
{
return Geocode(address).Cast<Address>();
}
IEnumerable<Address> IGeocoder.Geocode(string street, string city, string state, string postalCode, string country)
{
return Geocode(BuildAddress(street, city, state, postalCode, country)).Cast<Address>();
}
IEnumerable<Address> IGeocoder.ReverseGeocode(Location location)
{
return ReverseGeocode(location).Cast<Address>();
}
IEnumerable<Address> IGeocoder.ReverseGeocode(double latitude, double longitude)
{
return ReverseGeocode(latitude, longitude).Cast<Address>();
}
Task<IEnumerable<Address>> IAsyncGeocoder.GeocodeAsync(string address)
{
return GeocodeAsync(address)
.ContinueWith(task => task.Result.Cast<Address>());
}
Task<IEnumerable<Address>> IAsyncGeocoder.GeocodeAsync(string address, CancellationToken cancellationToken)
{
return GeocodeAsync(address, cancellationToken)
.ContinueWith(task => task.Result.Cast<Address>(), cancellationToken);
}
Task<IEnumerable<Address>> IAsyncGeocoder.GeocodeAsync(string street, string city, string state, string postalCode, string country)
{
return GeocodeAsync(BuildAddress(street, city, state, postalCode, country))
.ContinueWith(task => task.Result.Cast<Address>());
}
Task<IEnumerable<Address>> IAsyncGeocoder.GeocodeAsync(string street, string city, string state, string postalCode, string country, CancellationToken cancellationToken)
{
return GeocodeAsync(BuildAddress(street, city, state, postalCode, country), cancellationToken)
.ContinueWith(task => task.Result.Cast<Address>(), cancellationToken);
}
Task<IEnumerable<Address>> IAsyncGeocoder.ReverseGeocodeAsync(double latitude, double longitude)
{
return ReverseGeocodeAsync(latitude, longitude)
.ContinueWith(task => task.Result.Cast<Address>());
}
Task<IEnumerable<Address>> IAsyncGeocoder.ReverseGeocodeAsync(double latitude, double longitude, CancellationToken cancellationToken)
{
return ReverseGeocodeAsync(latitude, longitude, cancellationToken)
.ContinueWith(task => task.Result.Cast<Address>(), cancellationToken);
}
private HttpWebRequest BuildWebRequest(string type, string value)
{
string url = string.Format(ServiceUrl, type, value);
if (BusinessKey != null)
url = BusinessKey.GenerateSignature(url);
var req = WebRequest.Create(url) as HttpWebRequest;
if (this.Proxy != null)
{
req.Proxy = Proxy;
}
req.Method = "GET";
return req;
}
private IEnumerable<GoogleAddress> ProcessWebResponse(WebResponse response)
{
XPathDocument xmlDoc = LoadXmlResponse(response);
XPathNavigator nav = xmlDoc.CreateNavigator();
GoogleStatus status = EvaluateStatus((string)nav.Evaluate("string(/GeocodeResponse/status)"));
if (status != GoogleStatus.Ok && status != GoogleStatus.ZeroResults)
throw new GoogleGeocodingException(status);
if (status == GoogleStatus.Ok)
return ParseAddresses(nav.Select("/GeocodeResponse/result")).ToArray();
return new GoogleAddress[0];
}
private XPathDocument LoadXmlResponse(WebResponse response)
{
using (Stream stream = response.GetResponseStream())
{
XPathDocument doc = new XPathDocument(stream);
return doc;
}
}
private IEnumerable<GoogleAddress> ParseAddresses(XPathNodeIterator nodes)
{
while (nodes.MoveNext())
{
XPathNavigator nav = nodes.Current;
GoogleAddressType type = EvaluateType((string)nav.Evaluate("string(type)"));
string formattedAddress = (string)nav.Evaluate("string(formatted_address)");
var components = ParseComponents(nav.Select("address_component")).ToArray();
double latitude = (double)nav.Evaluate("number(geometry/location/lat)");
double longitude = (double)nav.Evaluate("number(geometry/location/lng)");
Location coordinates = new Location(latitude, longitude);
double neLatitude = (double)nav.Evaluate("number(geometry/viewport/northeast/lat)");
double neLongitude = (double)nav.Evaluate("number(geometry/viewport/northeast/lng)");
Location neCoordinates = new Location(neLatitude, neLongitude);
double swLatitude = (double)nav.Evaluate("number(geometry/viewport/southwest/lat)");
double swLongitude = (double)nav.Evaluate("number(geometry/viewport/southwest/lng)");
Location swCoordinates = new Location(swLatitude, swLongitude);
var viewport = new GoogleViewport { Northeast = neCoordinates, Southwest = swCoordinates };
bool isPartialMatch;
bool.TryParse((string)nav.Evaluate("string(partial_match)"), out isPartialMatch);
yield return new GoogleAddress(type, formattedAddress, components, coordinates, viewport, isPartialMatch);
}
}
private IEnumerable<GoogleAddressComponent> ParseComponents(XPathNodeIterator nodes)
{
while (nodes.MoveNext())
{
XPathNavigator nav = nodes.Current;
string longName = (string)nav.Evaluate("string(long_name)");
string shortName = (string)nav.Evaluate("string(short_name)");
var types = ParseComponentTypes(nav.Select("type")).ToArray();
if (types.Any()) //don't return an address component with no type
yield return new GoogleAddressComponent(types, longName, shortName);
}
}
private IEnumerable<GoogleAddressType> ParseComponentTypes(XPathNodeIterator nodes)
{
while (nodes.MoveNext())
yield return EvaluateType(nodes.Current.InnerXml);
}
/// <remarks>
/// http://code.google.com/apis/maps/documentation/geocoding/#StatusCodes
/// </remarks>
private GoogleStatus EvaluateStatus(string status)
{
switch (status)
{
case "OK": return GoogleStatus.Ok;
case "ZERO_RESULTS": return GoogleStatus.ZeroResults;
case "OVER_QUERY_LIMIT": return GoogleStatus.OverQueryLimit;
case "REQUEST_DENIED": return GoogleStatus.RequestDenied;
case "INVALID_REQUEST": return GoogleStatus.InvalidRequest;
default: return GoogleStatus.Error;
}
}
/// <remarks>
/// http://code.google.com/apis/maps/documentation/geocoding/#Types
/// </remarks>
private GoogleAddressType EvaluateType(string type)
{
switch (type)
{
case "street_address": return GoogleAddressType.StreetAddress;
case "route": return GoogleAddressType.Route;
case "intersection": return GoogleAddressType.Intersection;
case "political": return GoogleAddressType.Political;
case "country": return GoogleAddressType.Country;
case "administrative_area_level_1": return GoogleAddressType.AdministrativeAreaLevel1;
case "administrative_area_level_2": return GoogleAddressType.AdministrativeAreaLevel2;
case "administrative_area_level_3": return GoogleAddressType.AdministrativeAreaLevel3;
case "colloquial_area": return GoogleAddressType.ColloquialArea;
case "locality": return GoogleAddressType.Locality;
case "sublocality": return GoogleAddressType.SubLocality;
case "neighborhood": return GoogleAddressType.Neighborhood;
case "premise": return GoogleAddressType.Premise;
case "subpremise": return GoogleAddressType.Subpremise;
case "postal_code": return GoogleAddressType.PostalCode;
case "natural_feature": return GoogleAddressType.NaturalFeature;
case "airport": return GoogleAddressType.Airport;
case "park": return GoogleAddressType.Park;
case "point_of_interest": return GoogleAddressType.PointOfInterest;
case "post_box": return GoogleAddressType.PostBox;
case "street_number": return GoogleAddressType.StreetNumber;
case "floor": return GoogleAddressType.Floor;
case "room": return GoogleAddressType.Room;
case "postal_town": return GoogleAddressType.PostalTown;
case "establishment": return GoogleAddressType.Establishment;
case "sublocality_level_1": return GoogleAddressType.SubLocalityLevel1;
case "sublocality_level_2": return GoogleAddressType.SubLocalityLevel2;
case "sublocality_level_3": return GoogleAddressType.SubLocalityLevel3;
case "sublocality_level_4": return GoogleAddressType.SubLocalityLevel4;
case "sublocality_level_5": return GoogleAddressType.SubLocalityLevel5;
case "postal_code_suffix": return GoogleAddressType.PostalCodeSuffix;
default: return GoogleAddressType.Unknown;
}
}
protected class RequestState
{
public readonly HttpWebRequest request;
public readonly CancellationToken? cancellationToken;
public RequestState(HttpWebRequest request, CancellationToken? cancellationToken)
{
if (request == null) throw new ArgumentNullException("request");
this.request = request;
this.cancellationToken = cancellationToken;
}
}
}
}
| |
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 MamTipoMotivoConsultum class.
/// </summary>
[Serializable]
public partial class MamTipoMotivoConsultumCollection : ActiveList<MamTipoMotivoConsultum, MamTipoMotivoConsultumCollection>
{
public MamTipoMotivoConsultumCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>MamTipoMotivoConsultumCollection</returns>
public MamTipoMotivoConsultumCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
MamTipoMotivoConsultum o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the MAM_TipoMotivoConsulta table.
/// </summary>
[Serializable]
public partial class MamTipoMotivoConsultum : ActiveRecord<MamTipoMotivoConsultum>, IActiveRecord
{
#region .ctors and Default Settings
public MamTipoMotivoConsultum()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public MamTipoMotivoConsultum(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public MamTipoMotivoConsultum(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public MamTipoMotivoConsultum(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
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("MAM_TipoMotivoConsulta", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdTipoMotivoConsulta = new TableSchema.TableColumn(schema);
colvarIdTipoMotivoConsulta.ColumnName = "idTipoMotivoConsulta";
colvarIdTipoMotivoConsulta.DataType = DbType.Int32;
colvarIdTipoMotivoConsulta.MaxLength = 0;
colvarIdTipoMotivoConsulta.AutoIncrement = true;
colvarIdTipoMotivoConsulta.IsNullable = false;
colvarIdTipoMotivoConsulta.IsPrimaryKey = true;
colvarIdTipoMotivoConsulta.IsForeignKey = false;
colvarIdTipoMotivoConsulta.IsReadOnly = false;
colvarIdTipoMotivoConsulta.DefaultSetting = @"";
colvarIdTipoMotivoConsulta.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTipoMotivoConsulta);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "descripcion";
colvarDescripcion.DataType = DbType.AnsiString;
colvarDescripcion.MaxLength = 50;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = false;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"('')";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("MAM_TipoMotivoConsulta",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdTipoMotivoConsulta")]
[Bindable(true)]
public int IdTipoMotivoConsulta
{
get { return GetColumnValue<int>(Columns.IdTipoMotivoConsulta); }
set { SetColumnValue(Columns.IdTipoMotivoConsulta, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.MamMotivoConsultumCollection colMamMotivoConsulta;
public DalSic.MamMotivoConsultumCollection MamMotivoConsulta
{
get
{
if(colMamMotivoConsulta == null)
{
colMamMotivoConsulta = new DalSic.MamMotivoConsultumCollection().Where(MamMotivoConsultum.Columns.IdTipoMotivoConsulta, IdTipoMotivoConsulta).Load();
colMamMotivoConsulta.ListChanged += new ListChangedEventHandler(colMamMotivoConsulta_ListChanged);
}
return colMamMotivoConsulta;
}
set
{
colMamMotivoConsulta = value;
colMamMotivoConsulta.ListChanged += new ListChangedEventHandler(colMamMotivoConsulta_ListChanged);
}
}
void colMamMotivoConsulta_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colMamMotivoConsulta[e.NewIndex].IdTipoMotivoConsulta = IdTipoMotivoConsulta;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varDescripcion)
{
MamTipoMotivoConsultum item = new MamTipoMotivoConsultum();
item.Descripcion = varDescripcion;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdTipoMotivoConsulta,string varDescripcion)
{
MamTipoMotivoConsultum item = new MamTipoMotivoConsultum();
item.IdTipoMotivoConsulta = varIdTipoMotivoConsulta;
item.Descripcion = varDescripcion;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdTipoMotivoConsultaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdTipoMotivoConsulta = @"idTipoMotivoConsulta";
public static string Descripcion = @"descripcion";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colMamMotivoConsulta != null)
{
foreach (DalSic.MamMotivoConsultum item in colMamMotivoConsulta)
{
if (item.IdTipoMotivoConsulta != IdTipoMotivoConsulta)
{
item.IdTipoMotivoConsulta = IdTipoMotivoConsulta;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colMamMotivoConsulta != null)
{
colMamMotivoConsulta.SaveAll();
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.QualityGuidelines.PreferJaggedArraysOverMultidimensionalAnalyzer,
Microsoft.CodeQuality.CSharp.Analyzers.QualityGuidelines.CSharpPreferJaggedArraysOverMultidimensionalFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.QualityGuidelines.PreferJaggedArraysOverMultidimensionalAnalyzer,
Microsoft.CodeQuality.VisualBasic.Analyzers.QualityGuidelines.BasicPreferJaggedArraysOverMultidimensionalFixer>;
namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests
{
public class PreferJaggedArraysOverMultidimensionalTests
{
[Fact]
public async Task CSharpSimpleMembersAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Class1
{
public int[,] MultidimensionalArrayField;
public int[,] MultidimensionalArrayProperty
{
get { return null; }
}
public int[,] MethodReturningMultidimensionalArray()
{
return null;
}
public void MethodWithMultidimensionalArrayParameter(int[,] multidimensionalParameter) { }
public void MethodWithMultidimensionalArrayCode()
{
int[,] multiDimVariable = new int[5, 5];
multiDimVariable[1, 1] = 3;
}
public int[,][] JaggedMultidimensionalField;
}
public interface IInterface
{
int[,] InterfaceMethod(int[,] array);
}
",
GetCSharpDefaultResultAt(4, 19, "MultidimensionalArrayField"),
GetCSharpDefaultResultAt(6, 19, "MultidimensionalArrayProperty"),
GetCSharpReturnResultAt(11, 19, "MethodReturningMultidimensionalArray", "int[*,*]"),
GetCSharpDefaultResultAt(16, 65, "multidimensionalParameter"),
GetCSharpBodyResultAt(20, 35, "MethodWithMultidimensionalArrayCode", "int[*,*]"),
GetCSharpDefaultResultAt(24, 21, "JaggedMultidimensionalField"),
GetCSharpReturnResultAt(29, 12, "InterfaceMethod", "int[*,*]"),
GetCSharpDefaultResultAt(29, 35, "array"));
}
[Fact]
public async Task BasicSimpleMembersAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Class1
Public MultidimensionalArrayField As Integer(,)
Public ReadOnly Property MultidimensionalArrayProperty As Integer(,)
Get
Return Nothing
End Get
End Property
Public Function MethodReturningMultidimensionalArray() As Integer(,)
Return Nothing
End Function
Public Sub MethodWithMultidimensionalArrayParameter(multidimensionalParameter As Integer(,))
End Sub
Public Sub MethodWithMultidimensionalArrayCode()
Dim multiDimVariable(5, 5) As Integer
multiDimVariable(1, 1) = 3
End Sub
Public JaggedMultidimensionalField As Integer(,)()
End Class
Public Interface IInterface
Function InterfaceMethod(array As Integer(,)) As Integer(,)
End Interface
",
GetBasicDefaultResultAt(3, 12, "MultidimensionalArrayField"),
GetBasicDefaultResultAt(5, 30, "MultidimensionalArrayProperty"),
GetBasicReturnResultAt(11, 21, "MethodReturningMultidimensionalArray", "Integer(*,*)"),
GetBasicDefaultResultAt(15, 57, "multidimensionalParameter"),
GetBasicBodyResultAt(19, 13, "MethodWithMultidimensionalArrayCode", "Integer(*,*)"),
GetBasicDefaultResultAt(23, 12, "JaggedMultidimensionalField"),
GetBasicReturnResultAt(27, 14, "InterfaceMethod", "Integer(*,*)"),
GetBasicDefaultResultAt(27, 30, "array"));
}
[Fact]
public async Task CSharpNoDiagosticsAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Class1
{
public int[][] JaggedArrayField;
public int[][] JaggedArrayProperty
{
get { return null; }
}
public int[][] MethodReturningJaggedArray()
{
return null;
}
public void MethodWithJaggedArrayParameter(int[][] jaggedParameter) { }
}
");
}
[Fact]
public async Task BasicNoDiangnosticsAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Class1
Public JaggedArrayField As Integer()()
Public ReadOnly Property JaggedArrayProperty As Integer()()
Get
Return Nothing
End Get
End Property
Public Function MethodReturningJaggedArray() As Integer()()
Return Nothing
End Function
Public Sub MethodWithJaggedArrayParameter(jaggedParameter As Integer()())
End Sub
End Class
");
}
[Fact]
public async Task CSharpOverridenMembersAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Class1
{
public virtual int[,] MultidimensionalArrayProperty
{
get { return null; }
}
public virtual int[,] MethodReturningMultidimensionalArray()
{
return null;
}
}
public class Class2 : Class1
{
public override int[,] MultidimensionalArrayProperty
{
get { return null; }
}
public override int[,] MethodReturningMultidimensionalArray()
{
return null;
}
}
",
GetCSharpDefaultResultAt(4, 27, "MultidimensionalArrayProperty"),
GetCSharpReturnResultAt(9, 27, "MethodReturningMultidimensionalArray", "int[*,*]"));
}
[Fact]
public async Task BasicOverriddenMembersAsync()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Class1
Public Overridable ReadOnly Property MultidimensionalArrayProperty As Integer(,)
Get
Return Nothing
End Get
End Property
Public Overridable Function MethodReturningMultidimensionalArray() As Integer(,)
Return Nothing
End Function
End Class
Public Class Class2
Inherits Class1
Public Overrides ReadOnly Property MultidimensionalArrayProperty As Integer(,)
Get
Return Nothing
End Get
End Property
Public Overrides Function MethodReturningMultidimensionalArray() As Integer(,)
Return Nothing
End Function
End Class
",
GetBasicDefaultResultAt(3, 42, "MultidimensionalArrayProperty"),
GetBasicReturnResultAt(9, 33, "MethodReturningMultidimensionalArray", "Integer(*,*)"));
}
[Fact, WorkItem(3650, "https://github.com/dotnet/roslyn-analyzers/issues/3650")]
public async Task Method_WhenInterfaceImplementation_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public interface IC
{
int[,] {|#0:MethodReturningMultidimensionalArray|}(int[,] {|#1:array|});
}
public class C : IC
{
public int[,] MethodReturningMultidimensionalArray(int[,] array)
=> null;
}",
VerifyCS.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.ReturnRule).WithLocation(0).WithArguments("MethodReturningMultidimensionalArray", "int[*,*]"),
VerifyCS.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.DefaultRule).WithLocation(1).WithArguments("array"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Interface IC
Function {|#0:MethodReturningMultidimensionalArray|}(ByVal {|#1:array|} As Integer(,)) As Integer(,)
End Interface
Public Class C
Implements IC
Public Function MethodReturningMultidimensionalArray(ByVal array As Integer(,)) As Integer(,) Implements IC.MethodReturningMultidimensionalArray
Return Nothing
End Function
End Class
",
VerifyVB.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.ReturnRule).WithLocation(0).WithArguments("MethodReturningMultidimensionalArray", "Integer(*,*)"),
VerifyVB.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.DefaultRule).WithLocation(1).WithArguments("array"));
}
[Fact, WorkItem(3650, "https://github.com/dotnet/roslyn-analyzers/issues/3650")]
public async Task Property_WhenInterfaceImplementation_NoDiagnosticAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public interface IC
{
int[,] {|#0:MultidimensionalArrayProperty|} { get; }
}
public class C : IC
{
public int[,] MultidimensionalArrayProperty { get; set; }
}",
VerifyCS.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.DefaultRule).WithLocation(0).WithArguments("MultidimensionalArrayProperty"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Interface IC
ReadOnly Property {|#0:MultidimensionalArrayProperty|} As Integer(,)
End Interface
Public Class C
Implements IC
Public Property MultidimensionalArrayProperty As Integer(,) Implements IC.MultidimensionalArrayProperty
End Class
",
VerifyVB.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.DefaultRule).WithLocation(0).WithArguments("MultidimensionalArrayProperty"));
}
private static DiagnosticResult GetCSharpDefaultResultAt(int line, int column, string symbolName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.DefaultRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(symbolName);
private static DiagnosticResult GetCSharpReturnResultAt(int line, int column, string symbolName, string typeName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.ReturnRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(symbolName, typeName);
private static DiagnosticResult GetCSharpBodyResultAt(int line, int column, string symbolName, string typeName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.BodyRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(symbolName, typeName);
private static DiagnosticResult GetBasicDefaultResultAt(int line, int column, string symbolName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.DefaultRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(symbolName);
private static DiagnosticResult GetBasicReturnResultAt(int line, int column, string symbolName, string typeName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.ReturnRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(symbolName, typeName);
private static DiagnosticResult GetBasicBodyResultAt(int line, int column, string symbolName, string typeName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(PreferJaggedArraysOverMultidimensionalAnalyzer.BodyRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(symbolName, typeName);
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows.Forms;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.BlogClient.Providers;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.Controls.Wizard;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Localization;
using System.Runtime.InteropServices;
namespace OpenLiveWriter.PostEditor.Configuration.Wizard
{
public class WeblogConfigurationWizardController : WizardController, IBlogClientUIContext, IDisposable
{
#region Creation and Initialization and Disposal
public static string Welcome(IWin32Window owner)
{
TemporaryBlogSettings temporarySettings = TemporaryBlogSettings.CreateNew();
using (WeblogConfigurationWizardController controller = new WeblogConfigurationWizardController(temporarySettings))
{
return controller.WelcomeWeblog(owner);
}
}
public static string Add(IWin32Window owner, bool permitSwitchingWeblogs)
{
bool switchToWeblog;
return Add(owner, permitSwitchingWeblogs, out switchToWeblog);
}
public static string Add(IWin32Window owner, bool permitSwitchingWeblogs, out bool switchToWeblog)
{
TemporaryBlogSettings temporarySettings = TemporaryBlogSettings.CreateNew();
temporarySettings.IsNewWeblog = true;
temporarySettings.SwitchToWeblog = true;
using (WeblogConfigurationWizardController controller = new WeblogConfigurationWizardController(temporarySettings))
{
return controller.AddWeblog(owner, ApplicationEnvironment.ProductNameQualified, permitSwitchingWeblogs, out switchToWeblog);
}
}
public static string AddBlog(IWin32Window owner, Uri blogToAdd)
{
TemporaryBlogSettings temporarySettings = TemporaryBlogSettings.CreateNew();
temporarySettings.IsNewWeblog = true;
temporarySettings.SwitchToWeblog = true;
string username;
string password;
Uri homepageUrl;
ParseAddBlogUri(blogToAdd, out username, out password, out homepageUrl);
temporarySettings.HomepageUrl = homepageUrl.ToString();
temporarySettings.Credentials.Username = username;
temporarySettings.Credentials.Password = password;
temporarySettings.SavePassword = false;
using (WeblogConfigurationWizardController controller = new WeblogConfigurationWizardController(temporarySettings))
{
bool dummy;
return controller.AddWeblogSkipType(owner, ApplicationEnvironment.ProductNameQualified, false, out dummy);
}
}
public static bool EditTemporarySettings(IWin32Window owner, TemporaryBlogSettings settings)
{
using (WeblogConfigurationWizardController controller = new WeblogConfigurationWizardController(settings))
return controller.EditWeblogTemporarySettings(owner);
}
private WeblogConfigurationWizardController(TemporaryBlogSettings settings)
: base()
{
_temporarySettings = settings;
}
public void Dispose()
{
//clear any cached credential information that may have been set by the wizard
ClearTransientCredentials();
System.GC.SuppressFinalize(this);
}
~WeblogConfigurationWizardController()
{
Debug.Fail("Wizard controller was not disposed");
}
private string WelcomeWeblog(IWin32Window owner)
{
_preventSwitchingToWeblog = true;
// welcome is the same as add with one additional step on the front end
WizardStep wizardStep;
addWizardStep(
wizardStep = new WizardStep(new WeblogConfigurationWizardPanelWelcome(),
StringId.ConfigWizardWelcome,
null, null, new NextCallback(OnWelcomeCompleted), null, null));
wizardStep.WantsFocus = false;
addWizardStep(
new WizardStep(new WeblogConfigurationWizardPanelConfirmation(),
StringId.ConfigWizardComplete,
new DisplayCallback(OnConfirmationDisplayed),
new VerifyStepCallback(OnValidatePanel),
new NextCallback(OnConfirmationCompleted),
null,
null));
bool switchToWeblog;
return ShowBlogWizard(ApplicationEnvironment.ProductNameQualified, owner, out switchToWeblog);
}
private string AddWeblogSkipType(IWin32Window owner, string caption, bool permitSwitchingWeblogs, out bool switchToWeblog)
{
_preventSwitchingToWeblog = !permitSwitchingWeblogs;
_temporarySettings.IsSpacesBlog = false;
_temporarySettings.IsSharePointBlog = false;
AddBasicInfoSubStep();
AddConfirmationStep();
return ShowBlogWizard(caption, owner, out switchToWeblog);
}
private string AddWeblog(IWin32Window owner, string caption, bool permitSwitchingWeblogs, out bool switchToWeblog)
{
_preventSwitchingToWeblog = !permitSwitchingWeblogs;
AddChooseBlogTypeStep();
AddConfirmationStep();
return ShowBlogWizard(caption, owner, out switchToWeblog);
}
private string ShowBlogWizard(string caption, IWin32Window owner, out bool switchToWeblog)
{
// blog id to return
string blogId = null;
if (ShowDialog(owner, caption) == DialogResult.OK)
{
// save the blog settings
using (BlogSettings blogSettings = BlogSettings.ForBlogId(_temporarySettings.Id))
{
_temporarySettings.Save(blogSettings);
blogId = blogSettings.Id;
}
// note the last added weblog (for re-selection in subsequent invocations of the dialog)
WeblogConfigurationWizardSettings.LastServiceName = _temporarySettings.ServiceName;
}
switchToWeblog = _temporarySettings.SwitchToWeblog;
return blogId;
}
private bool EditWeblogTemporarySettings(IWin32Window owner)
{
// first step conditional on blog type
if (_temporarySettings.IsSharePointBlog)
AddSharePointBasicInfoSubStep(true);
else
AddBasicInfoSubStep();
AddConfirmationStep();
if (ShowDialog(owner, Res.Get(StringId.UpdateAccountConfigurationTitle)) == DialogResult.OK)
{
return true;
}
else
{
return false;
}
}
private void AddChooseBlogTypeStep()
{
addWizardStep(
new WizardStep(new WeblogConfigurationWizardPanelBlogType(),
StringId.ConfigWizardChooseWeblogType,
new DisplayCallback(OnChooseBlogTypeDisplayed),
null,
new NextCallback(OnChooseBlogTypeCompleted),
null,
null));
}
private void AddBasicInfoSubStep()
{
WeblogConfigurationWizardPanelBasicInfo panel = new WeblogConfigurationWizardPanelBasicInfo();
addWizardSubStep(
new WizardSubStep(panel,
StringId.ConfigWizardBasicInfo,
new DisplayCallback(OnBasicInfoDisplayed),
new VerifyStepCallback(OnValidatePanel),
new NextCallback(OnBasicInfoCompleted),
null,
null));
}
private void AddSharePointBasicInfoSubStep(bool showAuthenticationStep)
{
addWizardSubStep(
new WizardSubStep(new WeblogConfigurationWizardPanelSharePointBasicInfo(),
StringId.ConfigWizardSharePointHomepage,
new DisplayCallback(OnBasicInfoDisplayed),
new VerifyStepCallback(OnValidatePanel),
new NextCallback(OnSharePointBasicInfoCompleted),
new NextCallback(OnSharePointBasicInfoUndone),
null));
_authenticationRequired = showAuthenticationStep;
}
private void AddConfirmationStep()
{
addWizardStep(
new WizardStep(new WeblogConfigurationWizardPanelConfirmation(),
StringId.ConfigWizardComplete,
new DisplayCallback(OnConfirmationDisplayed),
new VerifyStepCallback(OnValidatePanel),
new NextCallback(OnConfirmationCompleted),
null,
null));
}
private DialogResult ShowDialog(IWin32Window owner, string title)
{
using (new WaitCursor())
{
DialogResult result;
using (_wizardForm = new WeblogConfigurationWizard(this))
{
using (new BlogClientUIContextScope(_wizardForm))
{
_owner = _wizardForm;
_wizardForm.Text = title;
// Show in taskbar if it's a top-level window. This is true during welcome
if (owner == null)
{
_wizardForm.ShowInTaskbar = true;
_wizardForm.StartPosition = FormStartPosition.CenterScreen;
}
result = _wizardForm.ShowDialog(owner);
_owner = null;
}
}
_wizardForm = null;
if (_detectionOperation != null && !_detectionOperation.IsDone)
_detectionOperation.Cancel();
return result;
}
}
#endregion
#region Welcome Panel
private void OnWelcomeCompleted(Object stepControl)
{
//setup the next steps based on which choice the user selected.
addWizardSubStep(
new WizardSubStep(new WeblogConfigurationWizardPanelBlogType(),
StringId.ConfigWizardChooseWeblogType,
new DisplayCallback(OnChooseBlogTypeDisplayed),
null,
new NextCallback(OnChooseBlogTypeCompleted),
null,
null));
}
#endregion
#region Choose Blog Type Panel
private void OnChooseBlogTypeDisplayed(Object stepControl)
{
// Fixes for 483356: In account configuration wizard, hitting back in select provider or success screens causes anomalous behavior
// Need to clear cached credentials and cached blogname otherwise they'll be used downstream in the wizard...
ClearTransientCredentials();
_temporarySettings.BlogName = string.Empty;
// Bug 681904: Insure that the next and cancel are always available when this panel is displayed.
NextEnabled = true;
CancelEnabled = true;
// get reference to panel
WeblogConfigurationWizardPanelBlogType panelBlogType = stepControl as WeblogConfigurationWizardPanelBlogType;
// notify it that it is being displayed (reset dirty state)
panelBlogType.OnDisplayPanel();
}
private void OnChooseBlogTypeCompleted(Object stepControl)
{
// get reference to panel
WeblogConfigurationWizardPanelBlogType panelBlogType = stepControl as WeblogConfigurationWizardPanelBlogType;
// if the user is changing types then blank out the blog info
if (panelBlogType.UserChangedSelection)
{
_temporarySettings.HomepageUrl = String.Empty;
_temporarySettings.Credentials.Clear();
}
// set the user's choice
_temporarySettings.IsSharePointBlog = panelBlogType.IsSharePointBlog;
// did this bootstrap a custom account wizard?
_providerAccountWizard = panelBlogType.ProviderAccountWizard;
// add the next wizard sub step as appropriate
if (_temporarySettings.IsSharePointBlog)
{
AddSharePointBasicInfoSubStep(false);
}
else
{
AddBasicInfoSubStep();
}
}
#endregion
private static void ParseAddBlogUri(Uri blogToAdd, out string username, out string password, out Uri homepageUrl)
{
// The URL is in the format http://username:password@blogUrl/;
// We use the Uri class to extract the username:password (comes as a single string) and then parse it.
// We strip the username:password from the remaining url and return it.
username = null;
password = null;
string[] userInfoSplit = System.Web.HttpUtility.UrlDecode(blogToAdd.UserInfo).Split(':');
if (userInfoSplit.Length > 0)
{
username = userInfoSplit[0];
if (userInfoSplit.Length > 1)
{
password = userInfoSplit[1];
}
}
homepageUrl = new Uri(blogToAdd.GetComponents(UriComponents.HttpRequestUrl, UriFormat.UriEscaped));
}
#region Basic Info Panel
private void OnBasicInfoDisplayed(Object stepControl)
{
// Fixes for 483356: In account configuration wizard, hitting back in select provider or success screens causes anomalous behavior
// Need to clear cached credentials and cached blogname otherwise they'll be used downstream in the wizard...
_temporarySettings.BlogName = string.Empty;
// get reference to data interface for panel
IAccountBasicInfoProvider basicInfo = stepControl as IAccountBasicInfoProvider;
// populate basic data
basicInfo.ProviderAccountWizard = _providerAccountWizard;
basicInfo.AccountId = _temporarySettings.Id;
basicInfo.HomepageUrl = _temporarySettings.HomepageUrl;
basicInfo.ForceManualConfiguration = _temporarySettings.ForceManualConfig;
basicInfo.Credentials = _temporarySettings.Credentials;
basicInfo.SavePassword = basicInfo.Credentials.Password != String.Empty && (_temporarySettings.SavePassword ?? true);
}
private delegate void PerformBlogAutoDetection();
private void OnBasicInfoCompleted(Object stepControl)
{
OnBasicInfoAndAuthenticationCompleted((IAccountBasicInfoProvider)stepControl, new PerformBlogAutoDetection(PerformWeblogAndSettingsAutoDetectionSubStep));
}
private void OnBasicInfoAndAuthenticationCompleted(IAccountBasicInfoProvider basicInfo, PerformBlogAutoDetection performBlogAutoDetection)
{
// copy the settings
_temporarySettings.HomepageUrl = basicInfo.HomepageUrl;
_temporarySettings.ForceManualConfig = basicInfo.ForceManualConfiguration;
_temporarySettings.Credentials = basicInfo.Credentials;
_temporarySettings.SavePassword = basicInfo.SavePassword;
// clear the transient credentials so we don't accidentally use cached credentials
ClearTransientCredentials();
if (!_temporarySettings.ForceManualConfig)
{
// perform auto-detection
performBlogAutoDetection();
}
else
{
PerformSelectProviderSubStep();
}
}
private void OnSharePointBasicInfoCompleted(Object stepControl)
{
if (_authenticationRequired)
AddSharePointAuthenticationStep((IAccountBasicInfoProvider)stepControl);
else
OnBasicInfoAndAuthenticationCompleted((IAccountBasicInfoProvider)stepControl, new PerformBlogAutoDetection(PerformSharePointAutoDetectionSubStep));
}
private void OnSharePointBasicInfoUndone(Object stepControl)
{
if (_authenticationRequired && !_authenticationStepAdded)
{
AddSharePointAuthenticationStep((IAccountBasicInfoProvider)stepControl);
next();
}
}
private void AddSharePointAuthenticationStep(IAccountBasicInfoProvider basicInfoProvider)
{
if (!_authenticationStepAdded)
{
addWizardSubStep(new WizardSubStep(new WeblogConfigurationWizardPanelSharePointAuthentication(basicInfoProvider),
StringId.ConfigWizardSharePointLogin,
new WizardController.DisplayCallback(OnSharePointAuthenticationDisplayed),
new VerifyStepCallback(OnValidatePanel),
new WizardController.NextCallback(OnSharePointAuthenticationComplete),
null,
new WizardController.BackCallback(OnSharePointAuthenticationBack)));
_authenticationStepAdded = true;
}
}
#endregion
#region Weblog and Settings Auto Detection
private void PerformWeblogAndSettingsAutoDetectionSubStep()
{
// Clear the provider so the user will be forced to do autodetection
// until we have successfully configured a publishing interface
_temporarySettings.ClearProvider();
_detectionOperation = new WizardWeblogAndSettingsAutoDetectionOperation(_editWithStyleStep);
// performe the step
addWizardSubStep(new WizardAutoDetectionStep(
(IBlogClientUIContext)this,
_temporarySettings,
new NextCallback(OnWeblogAndSettingsAutoDetectionCompleted),
_detectionOperation));
}
private WizardWeblogAndSettingsAutoDetectionOperation _detectionOperation;
private void PerformSharePointAutoDetectionSubStep()
{
// Clear the provider so the user will be forced to do autodetection
// until we have successfully configured a publishing interface
_temporarySettings.ClearProvider();
AddAutoDetectionStep();
}
private void AddAutoDetectionStep()
{
_detectionOperation = new WizardSharePointAutoDetectionOperation(_editWithStyleStep);
WizardSharePointAutoDetectionStep sharePointDetectionStep =
new WizardSharePointAutoDetectionStep(
(IBlogClientUIContext)this,
_temporarySettings,
new NextCallback(OnWeblogAndSettingsAutoDetectionCompleted),
_detectionOperation);
if (!_authenticationStepAdded)
sharePointDetectionStep.AuthenticationErrorOccurred += new EventHandler(sharePointDetectionStep_AuthenticationErrorOccurred);
addWizardSubStep(sharePointDetectionStep);
}
private void sharePointDetectionStep_AuthenticationErrorOccurred(object sender, EventArgs e)
{
this._authenticationRequired = true;
}
private void OnSharePointAuthenticationDisplayed(Object stepControl)
{
// get reference to panel
WeblogConfigurationWizardPanelSharePointAuthentication panelBlogType = stepControl as WeblogConfigurationWizardPanelSharePointAuthentication;
// set value
panelBlogType.Credentials = _temporarySettings.Credentials;
panelBlogType.SavePassword = _temporarySettings.Credentials.Password != String.Empty;
}
private void OnSharePointAuthenticationComplete(Object stepControl)
{
OnBasicInfoAndAuthenticationCompleted((IAccountBasicInfoProvider)stepControl, new PerformBlogAutoDetection(PerformSharePointAutoDetectionSubStep));
}
private void OnSharePointAuthenticationBack(Object stepControl)
{
_authenticationStepAdded = false;
}
private void OnWeblogAndSettingsAutoDetectionCompleted(Object stepControl)
{
// if we weren't able to identify a specific weblog
if (_temporarySettings.HostBlogId == String.Empty)
{
// if we have a list of weblogs then show the blog list
if (_temporarySettings.HostBlogs.Length > 0)
{
PerformSelectBlogSubStep();
}
else // kick down to select a provider
{
PerformSelectProviderSubStep();
}
}
else
{
PerformSelectImageEndpointIfNecessary();
}
}
private void PerformSelectImageEndpointIfNecessary()
{
if (_temporarySettings.HostBlogId != string.Empty
&& _temporarySettings.AvailableImageEndpoints != null
&& _temporarySettings.AvailableImageEndpoints.Length > 0)
{
/*
if (_temporarySettings.AvailableImageEndpoints.Length == 1)
{
IDictionary optionOverrides = _temporarySettings.OptionOverrides;
optionOverrides[BlogClientOptions.IMAGE_ENDPOINT] = _temporarySettings.AvailableImageEndpoints[0].Id;
_temporarySettings.OptionOverrides = optionOverrides;
}
else
PerformSelectImageEndpointSubStep();
*/
// currently we always show the image endpoint selection UI if we find at least one.
PerformSelectImageEndpointSubStep();
}
}
#endregion
#region Select Provider Panel
void PerformSelectProviderSubStep()
{
addWizardSubStep(new WizardSubStep(
new WeblogConfigurationWizardPanelSelectProvider(),
StringId.ConfigWizardSelectProvider,
new DisplayCallback(OnSelectProviderDisplayed),
new VerifyStepCallback(OnValidatePanel),
new NextCallback(OnSelectProviderCompleted),
null,
null));
}
void OnSelectProviderDisplayed(Object stepControl)
{
// get reference to panel
WeblogConfigurationWizardPanelSelectProvider panelSelectProvider = stepControl as WeblogConfigurationWizardPanelSelectProvider;
// show the panel
panelSelectProvider.ShowPanel(
_temporarySettings.ServiceName,
_temporarySettings.HomepageUrl,
_temporarySettings.Id,
_temporarySettings.Credentials);
}
void OnSelectProviderCompleted(Object stepControl)
{
// get reference to panel
WeblogConfigurationWizardPanelSelectProvider panelSelectProvider = stepControl as WeblogConfigurationWizardPanelSelectProvider;
// record the provider and blog info
IBlogProviderDescription provider = panelSelectProvider.SelectedBlogProvider;
_temporarySettings.SetProvider(provider.Id, provider.Name, provider.PostApiUrl, provider.ClientType);
_temporarySettings.HostBlogId = String.Empty;
if (panelSelectProvider.TargetBlog != null)
_temporarySettings.SetBlogInfo(panelSelectProvider.TargetBlog);
_temporarySettings.HostBlogs = panelSelectProvider.UsersBlogs;
// If we don't yet have a HostBlogId then the user needs to choose from
// among available weblogs
if (_temporarySettings.HostBlogId == String.Empty)
{
PerformSelectBlogSubStep();
}
else
{
// if we have not downloaded an editing template yet for this
// weblog then execute this now
PerformSettingsAutoDetectionSubStepIfNecessary();
}
}
#endregion
#region Select Blog Panel
void PerformSelectBlogSubStep()
{
addWizardSubStep(new WizardSubStep(
new WeblogConfigurationWizardPanelSelectBlog(),
StringId.ConfigWizardSelectWeblog,
new DisplayCallback(OnSelectBlogDisplayed),
new VerifyStepCallback(OnValidatePanel),
new NextCallback(OnSelectBlogCompleted),
null,
null));
}
void OnSelectBlogDisplayed(Object stepControl)
{
// get reference to panel
WeblogConfigurationWizardPanelSelectBlog panelSelectBlog = stepControl as WeblogConfigurationWizardPanelSelectBlog;
// show the panel
panelSelectBlog.ShowPanel(_temporarySettings.HostBlogs, _temporarySettings.HostBlogId);
}
private void OnSelectBlogCompleted(Object stepControl)
{
// get reference to panel
WeblogConfigurationWizardPanelSelectBlog panelSelectBlog = stepControl as WeblogConfigurationWizardPanelSelectBlog;
// get the selected blog
_temporarySettings.SetBlogInfo(panelSelectBlog.SelectedBlog);
// if we have not downloaded an editing template yet for this
// weblog then execute this now
PerformSettingsAutoDetectionSubStepIfNecessary();
}
#endregion
#region Select Image Endpoint Panel
void PerformSelectImageEndpointSubStep()
{
WeblogConfigurationWizardPanelSelectBlog panel = new WeblogConfigurationWizardPanelSelectBlog();
panel.LabelText = Res.Get(StringId.CWSelectImageEndpointText);
addWizardSubStep(new WizardSubStep(
panel,
StringId.ConfigWizardSelectImageEndpoint,
new DisplayCallback(OnSelectImageEndpointDisplayed),
new VerifyStepCallback(OnValidatePanel),
new NextCallback(OnSelectImageEndpointCompleted),
null,
null));
}
void OnSelectImageEndpointDisplayed(Object stepControl)
{
// get reference to panel
WeblogConfigurationWizardPanelSelectBlog panelSelectImageEndpoint = stepControl as WeblogConfigurationWizardPanelSelectBlog;
// show the panel
panelSelectImageEndpoint.ShowPanel(_temporarySettings.AvailableImageEndpoints, _temporarySettings.OptionOverrides[BlogClientOptions.IMAGE_ENDPOINT] as string);
}
private void OnSelectImageEndpointCompleted(Object stepControl)
{
// get reference to panel
WeblogConfigurationWizardPanelSelectBlog panelSelectBlog = stepControl as WeblogConfigurationWizardPanelSelectBlog;
// get the selected blog
IDictionary optionOverrides = _temporarySettings.HomePageOverrides;
optionOverrides[BlogClientOptions.IMAGE_ENDPOINT] = panelSelectBlog.SelectedBlog.Id;
_temporarySettings.HomePageOverrides = optionOverrides;
}
#endregion
#region Weblog Settings Auto Detection
private void PerformSettingsAutoDetectionSubStepIfNecessary()
{
if (_temporarySettings.TemplateFiles.Length == 0)
{
PerformSettingsAutoDetectionSubStep();
}
}
private void PerformSettingsAutoDetectionSubStep()
{
// performe the step
addWizardSubStep(new WizardAutoDetectionStep(
(IBlogClientUIContext)this,
_temporarySettings, new NextCallback(OnPerformSettingsAutoDetectionCompleted),
new WizardSettingsAutoDetectionOperation(_editWithStyleStep)));
}
private void OnPerformSettingsAutoDetectionCompleted(object stepControl)
{
PerformSelectImageEndpointIfNecessary();
}
#endregion
#region Confirmation Panel
void OnConfirmationDisplayed(Object stepControl)
{
// get reference to panel
WeblogConfigurationWizardPanelConfirmation panelConfirmation = stepControl as WeblogConfigurationWizardPanelConfirmation;
// show the panel
panelConfirmation.ShowPanel(_temporarySettings, _preventSwitchingToWeblog);
}
void OnConfirmationCompleted(Object stepControl)
{
// get reference to panel
WeblogConfigurationWizardPanelConfirmation panelConfirmation = stepControl as WeblogConfigurationWizardPanelConfirmation;
// save settings
_temporarySettings.BlogName = panelConfirmation.WeblogName;
_temporarySettings.SwitchToWeblog = panelConfirmation.SwitchToWeblog;
}
#endregion
#region Generic Helpers
private bool OnValidatePanel(Object panelControl)
{
WeblogConfigurationWizardPanel wizardPanel = panelControl as WeblogConfigurationWizardPanel;
return wizardPanel.ValidatePanel();
}
/// <summary>
/// Clear any cached credential information for the blog
/// </summary>
private void ClearTransientCredentials()
{
//clear any cached credential information associated with this blog (fixes bug 373063)
new BlogCredentialsAccessor(_temporarySettings.Id, _temporarySettings.Credentials).TransientCredentials = null;
}
#endregion
#region Private Members
private IWin32Window _owner = null;
private WeblogConfigurationWizard _wizardForm;
private TemporaryBlogSettings _temporarySettings;
private bool _preventSwitchingToWeblog = false;
private WizardStep _editWithStyleStep = null;
private IBlogProviderAccountWizardDescription _providerAccountWizard;
private bool _authenticationRequired = false;
private bool _authenticationStepAdded;
#endregion
#region IBlogClientUIContext Members
IntPtr IWin32Window.Handle { get { return _wizardForm.Handle; } }
bool ISynchronizeInvoke.InvokeRequired { get { return _wizardForm.InvokeRequired; } }
IAsyncResult ISynchronizeInvoke.BeginInvoke(Delegate method, object[] args) { return _wizardForm.BeginInvoke(method, args); }
object ISynchronizeInvoke.EndInvoke(IAsyncResult result) { return _wizardForm.EndInvoke(result); }
object ISynchronizeInvoke.Invoke(Delegate method, object[] args) { return _wizardForm.Invoke(method, args); }
#endregion
}
internal interface IAccountBasicInfoProvider
{
IBlogProviderAccountWizardDescription ProviderAccountWizard { set; }
string AccountId { set; }
string HomepageUrl { get; set; }
bool SavePassword { get; set; }
IBlogCredentials Credentials { get; set; }
bool ForceManualConfiguration { get; set; }
bool IsDirty(TemporaryBlogSettings settings);
BlogInfo BlogAccount { get; }
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.Reflection;
#if !(NET_1_1)
using System.Collections.Generic;
#endif
#if !SILVERLIGHT
using log4net;
#endif
using FluorineFx.Util;
using FluorineFx.Invocation;
using FluorineFx.Collections;
using FluorineFx.Messaging;
using FluorineFx.Messaging.Api;
using FluorineFx.Messaging.Api.Event;
using FluorineFx.Messaging.Rtmp;
using FluorineFx.Messaging.Rtmp.SO;
namespace FluorineFx.Net
{
/// <summary>
/// Represents the method that will handle the Sync event of a RemoteSharedObject object.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A SyncEventArgs object that contains the event data.</param>
public delegate void SyncHandler(object sender, SyncEventArgs e);
/// <summary>
/// Represents the method that will handle messages sent from the server (when a custom RemoteSharedObject type does not declare the corresponding client side methods).
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">A SendMessageEventArgs object that contains the event data.</param>
public delegate void SendMessageHandler(object sender, SendMessageEventArgs e);
/// <summary>
/// The SharedObject class is used to access, read and store data on remote shared objects,
/// that are shared in real-time by all clients connected to your application.
/// </summary>
[CLSCompliant(false)]
public class RemoteSharedObject : AttributeStore
{
#if !SILVERLIGHT
private static readonly ILog log = LogManager.GetLogger(typeof(RemoteSharedObject));
#endif
bool _secure;
ObjectEncoding _objectEncoding;
NetConnection _connection;
/// <summary>
/// Initial synchronization flag.
/// </summary>
bool _initialSyncReceived;
string _name = string.Empty;
string _path = string.Empty;
/// <summary>
/// true if the client / server created the SO to be persistent
/// </summary>
bool _persistentSO = false;
int _version = 1;
int _updateCounter = 0;
bool _modified = false;
long _lastModified = -1;
SharedObjectMessage _ownerMessage;
/// <summary>
/// Event listener, actually RTMP connection
/// </summary>
IEventListener _source = null;
event ConnectHandler _connectHandler;
event DisconnectHandler _disconnectHandler;
event NetStatusHandler _netStatusHandler;
event SyncHandler _syncHandler;
event SendMessageHandler _sendMessageHandler;
#if !(NET_1_1)
static Dictionary<string, RemoteSharedObject> SharedObjects;
#else
static Hashtable SharedObjects;
#endif
static RemoteSharedObject()
{
#if !(NET_1_1)
SharedObjects = new Dictionary<string, RemoteSharedObject>();
#else
SharedObjects = new Hashtable();
#endif
}
/// <summary>
/// Initializes a new instance of the NetConnection class.
/// </summary>
/// <remarks>Do not create directly RemoteSharedObject objects, use the RemoteSharedObject.GetRemote method instead.</remarks>
public RemoteSharedObject()
{
}
private RemoteSharedObject(string name, string remotePath, object persistence, bool secure)
{
_name = name;
_path = remotePath;
_persistentSO = !false.Equals(persistence);
_secure = secure;
_objectEncoding = ObjectEncoding.AMF0;
_initialSyncReceived = false;
_ownerMessage = new SharedObjectMessage(null, null, -1, false);
}
/// <summary>
/// Gets or sets the object encoding (AMF version) for this shared object. Default is ObjectEncoding.AMF0
/// </summary>
public ObjectEncoding ObjectEncoding
{
get { return _objectEncoding; }
set { _objectEncoding = value; }
}
/// <summary>
/// Dispatched when a SharedObject instance is reporting its status or error condition.
/// </summary>
public event NetStatusHandler NetStatus
{
add { _netStatusHandler += value; }
remove { _netStatusHandler -= value; }
}
/// <summary>
/// Dispatched when a SharedObject instance has been updated by the server.
/// </summary>
public event SyncHandler Sync
{
add { _syncHandler += value; }
remove { _syncHandler -= value; }
}
/// <summary>
/// Dispatched when a SharedObject instance receives a message from the server.
/// </summary>
public event SendMessageHandler SendMessage
{
add { _sendMessageHandler += value; }
remove { _sendMessageHandler -= value; }
}
/// <summary>
/// Dispatched when a SharedObject instance is connected.
/// </summary>
public event ConnectHandler OnConnect
{
add { _connectHandler += value; }
remove { _connectHandler -= value; }
}
/// <summary>
/// Dispatched when a SharedObject instance is disconnected.
/// </summary>
public event DisconnectHandler OnDisconnect
{
add { _disconnectHandler += value; }
remove { _disconnectHandler -= value; }
}
/// <summary>
/// Indicates whether the shared object data is persistent.
/// </summary>
public bool IsPersistentObject
{
get { return _persistentSO; }
}
/// <summary>
/// Indicates whether this SharedObject has connected to the server.
/// </summary>
public bool Connected
{
get
{
return _initialSyncReceived;
}
}
/// <summary>
/// Returns a reference to an object that can be shared across multiple clients by means of a server, such as Flash Media Server.
/// </summary>
/// <param name="name">The name of the object.</param>
/// <param name="remotePath">The URI of the server on which the shared object will be stored. This URI must be identical to the URI of the NetConnection object passed to the SharedObject.Connect() method.</param>
/// <param name="persistence">Specifies whether the attributes of the shared object's data property are persistent locally, remotely, or both.</param>
/// <returns>A reference to an object that can be shared across multiple clients.</returns>
/// <example>
/// NetConnection myNC = new NetConnection();
/// myNC.Connect("rtmp://[yourDomain].com/applicationName");
/// ...
/// RemoteSharedObject myRemoteSO = SharedObject.GetRemote("mo", myNC.uri, false);
/// myRemoteSO.Connect(myNC);
/// </example>
public static RemoteSharedObject GetRemote(string name, string remotePath, object persistence)
{
return GetRemote(typeof(RemoteSharedObject), name, remotePath, persistence, false);
}
/// <summary>
/// Returns a reference to an object that can be shared across multiple clients by means of a server, such as Flash Media Server.
/// </summary>
/// <param name="type">Custom RemoteSharedObject type.</param>
/// <param name="name">The name of the object.</param>
/// <param name="remotePath">The URI of the server on which the shared object will be stored. This URI must be identical to the URI of the NetConnection object passed to the SharedObject.Connect() method.</param>
/// <param name="persistence">Specifies whether the attributes of the shared object's data property are persistent locally, remotely, or both.</param>
/// <returns>A reference to an object that can be shared across multiple clients.</returns>
/// <example>
/// NetConnection myNC = new NetConnection();
/// myNC.Connect("rtmp://[yourDomain].com/applicationName");
/// ...
/// RemoteSharedObject myRemoteSO = SharedObject.GetRemote("mo", myNC.uri, false);
/// myRemoteSO.Connect(myNC);
/// </example>
public static RemoteSharedObject GetRemote(Type type, string name, string remotePath, object persistence)
{
return GetRemote(type, name, remotePath, persistence, false);
}
/// <summary>
/// Returns a reference to an object that can be shared across multiple clients by means of a server, such as Flash Media Server.
/// </summary>
/// <param name="name">The name of the object.</param>
/// <param name="remotePath">The URI of the server on which the shared object will be stored. This URI must be identical to the URI of the NetConnection object passed to the SharedObject.Connect() method.</param>
/// <param name="persistence">Specifies whether the attributes of the shared object's data property are persistent locally, remotely, or both.</param>
/// <param name="secure">Not supported.</param>
/// <returns>A reference to an object that can be shared across multiple clients.</returns>
/// <example>
/// NetConnection myNC = new NetConnection();
/// myNC.Connect("rtmp://[yourDomain].com/applicationName");
/// SharedObject myRemoteSO = SharedObject.GetRemote("mo", myNC.uri, false);
/// myRemoteSO.Connect(myNC);
/// </example>
public static RemoteSharedObject GetRemote(string name, string remotePath, object persistence, bool secure)
{
return GetRemote(typeof(RemoteSharedObject), name, remotePath, persistence, secure);
}
private static RemoteSharedObject GetRemote(Type type, string name, string remotePath, object persistence, bool secure)
{
lock ((SharedObjects as ICollection).SyncRoot)
{
if (SharedObjects.ContainsKey(name))
return SharedObjects[name] as RemoteSharedObject;
RemoteSharedObject rso = Activator.CreateInstance(type) as RemoteSharedObject;
ValidationUtils.ArgumentConditionTrue(rso != null, "type", "Expecting a RemoteSharedObject type");
rso._name = name;
rso._path = remotePath;
rso._persistentSO = !false.Equals(persistence);
rso._secure = secure;
rso._objectEncoding = ObjectEncoding.AMF0;
rso._initialSyncReceived = false;
rso._ownerMessage = new SharedObjectMessage(null, null, -1, false);
SharedObjects[name] = rso;
return rso;
}
}
/// <summary>
/// Connects to a remote shared object on the server through the specified connection. Use this method after
/// issuing SharedObject.GetRemote(...). After a successful connection, the sync event is dispatched.
/// </summary>
/// <param name="connection">A NetConnection object (such as one used to communicate with Flash Media Server) that is using the Real-Time Messaging Protocol (RTMP).</param>
public void Connect(NetConnection connection)
{
Connect(connection, null);
}
/// <summary>
/// Connects to a remote shared object on the server through the specified connection. Use this method after
/// issuing SharedObject.GetRemote(...). After a successful connection, the sync event is dispatched.
/// </summary>
/// <param name="connection">A NetConnection object (such as one used to communicate with Flash Media Server) that is using the Real-Time Messaging Protocol (RTMP).</param>
/// <param name="parameters">Parameters.</param>
public void Connect(NetConnection connection, string parameters)
{
if (_initialSyncReceived)
throw new InvalidOperationException("SharedObject already connected");
ValidationUtils.ArgumentNotNull(connection, "connection");
ValidationUtils.ArgumentNotNull(connection.Uri, "connection");
ValidationUtils.ArgumentConditionTrue(connection.Uri.Scheme == "rtmp", "connection", "NetConnection object must use the Real-Time Messaging Protocol (RTMP)");
ValidationUtils.ArgumentConditionTrue(connection.Connected, "connection", "NetConnection object must be connected");
_connection = connection;
_initialSyncReceived = false;
FluorineFx.Messaging.Rtmp.SO.SharedObjectMessage message;
if (connection.ObjectEncoding == ObjectEncoding.AMF0)
message = new FluorineFx.Messaging.Rtmp.SO.SharedObjectMessage(_name, _version, _persistentSO);
else
message = new FluorineFx.Messaging.Rtmp.SO.FlexSharedObjectMessage(_name, _version, _persistentSO);
FluorineFx.Messaging.Rtmp.SO.SharedObjectEvent evt = new FluorineFx.Messaging.Rtmp.SO.SharedObjectEvent(FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.SERVER_CONNECT, null, null);
message.AddEvent(evt);
_connection.NetConnectionClient.Write(message);
}
/// <summary>
/// Closes the connection between a remote shared object and the server.
/// </summary>
public void Close()
{
if (_initialSyncReceived && _connection != null && _connection.Connected)
{
FluorineFx.Messaging.Rtmp.SO.SharedObjectMessage message;
if (_connection.ObjectEncoding == ObjectEncoding.AMF0)
message = new FluorineFx.Messaging.Rtmp.SO.SharedObjectMessage(_name, _version, _persistentSO);
else
message = new FluorineFx.Messaging.Rtmp.SO.FlexSharedObjectMessage(_name, _version, _persistentSO);
FluorineFx.Messaging.Rtmp.SO.SharedObjectEvent evt = new FluorineFx.Messaging.Rtmp.SO.SharedObjectEvent(FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.SERVER_DISCONNECT, null, null);
message.AddEvent(evt);
_connection.NetConnectionClient.Write(message);
// clear collections
base.RemoveAttributes();
_ownerMessage.Events.Clear();
}
_initialSyncReceived = false;
}
/// <summary>
/// Updates the value of a property in a shared object and indicates to the server that the value of the property has changed.
/// The SetProperty() method explicitly marks properties as changed, or dirty.
/// </summary>
/// <param name="propertyName">The name of the property in the shared object.</param>
/// <param name="value">The value of the property or null to delete the property.</param>
public void SetProperty(string propertyName, object value)
{
SetAttribute(propertyName, value);
}
/// <summary>
/// Indicates to the server that the value of a property in the shared object has changed. This method marks properties as dirty, which means changed.
/// </summary>
/// <param name="propertyName">The name of the property that has changed.</param>
public void SetDirty(string propertyName)
{
_source = _connection.NetConnectionClient.Connection;
_ownerMessage.AddEvent(SharedObjectEventType.SERVER_SET_ATTRIBUTE, propertyName, GetAttribute(propertyName));
_modified = true;
NotifyModified();
}
/// <summary>
/// Broadcasts a message to all clients connected to a remote shared object, including the client that sent the message.
/// </summary>
/// <param name="handler">A string that identifies the message; the name of a handler functions attached to the shared object.</param>
/// <param name="arguments">One or more arguments.</param>
public void Send(string handler, params object[] arguments)
{
_ownerMessage.AddEvent(SharedObjectEventType.SERVER_SEND_MESSAGE, handler, arguments);
_modified = true;
NotifyModified();
}
internal static void Dispatch(SharedObjectMessage message)
{
RemoteSharedObject rso = null;
lock ((SharedObjects as ICollection).SyncRoot)
{
if( SharedObjects.ContainsKey(message.Name) )
rso = SharedObjects[message.Name] as RemoteSharedObject;
}
if (rso != null)
{
try
{
rso.DispatchSharedObjectMessage(message);
}
catch (Exception ex)
{
rso.RaiseNetStatus(ex);
}
}
}
internal void DispatchSharedObjectMessage(SharedObjectMessage message)
{
#if !(NET_1_1)
List<ASObject> changeList = null;
List<ASObject> notifications = null;
List<SendMessageEventArgs> messages = null;
#else
ArrayList changeList = null;
ArrayList notifications = null;
ArrayList messages = null;
#endif
bool raiseOnConnect = false;
foreach (ISharedObjectEvent sharedObjectEvent in message.Events)
{
switch (sharedObjectEvent.Type)
{
case FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.CLIENT_INITIAL_DATA:
if (message.Version > 0)
_version = message.Version;
_attributes.Clear();
_initialSyncReceived = true;
//Delay the connection notification until the attribute store has been populated
//RaiseOnConnect();
raiseOnConnect = true;
break;
case FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.CLIENT_UPDATE_DATA:
case FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.CLIENT_UPDATE_ATTRIBUTE:
{
ASObject infoObject = new ASObject();
infoObject["code"] = "change";
infoObject["name"] = sharedObjectEvent.Key;
infoObject["oldValue"] = this.GetAttribute(sharedObjectEvent.Key);
//Do not update the attribute store if this is a notification that the SetAttribute is accepted
if (sharedObjectEvent.Type != FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.CLIENT_UPDATE_ATTRIBUTE)
_attributes[sharedObjectEvent.Key] = sharedObjectEvent.Value;
if (changeList == null)
#if !(NET_1_1)
changeList = new List<ASObject>();
#else
changeList = new ArrayList();
#endif
changeList.Add(infoObject);
}
break;
case FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.CLIENT_CLEAR_DATA:
{
ASObject infoObject = new ASObject();
infoObject["code"] = "clear";
if (changeList == null)
#if !(NET_1_1)
changeList = new List<ASObject>();
#else
changeList = new ArrayList();
#endif
changeList.Add(infoObject);
_attributes.Clear();
}
break;
case FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.CLIENT_DELETE_ATTRIBUTE:
case FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.CLIENT_DELETE_DATA:
{
_attributes.Remove(sharedObjectEvent.Key);
ASObject infoObject = new ASObject();
infoObject["code"] = "delete";
infoObject["name"] = sharedObjectEvent.Key;
if (changeList == null)
#if !(NET_1_1)
changeList = new List<ASObject>();
#else
changeList = new ArrayList();
#endif
changeList.Add(infoObject);
}
break;
case FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.CLIENT_STATUS:
{
ASObject infoObject = new ASObject();
infoObject["level"] = sharedObjectEvent.Value;
infoObject["code"] = sharedObjectEvent.Key;
if( notifications == null )
#if !(NET_1_1)
notifications = new List<ASObject>();
#else
notifications = new ArrayList();
#endif
notifications.Add(infoObject);
}
break;
case FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.CLIENT_SEND_MESSAGE:
case FluorineFx.Messaging.Rtmp.SO.SharedObjectEventType.SERVER_SEND_MESSAGE:
{
string handler = sharedObjectEvent.Key;
IList arguments = sharedObjectEvent.Value as IList;
MethodInfo mi = MethodHandler.GetMethod(this.GetType(), handler, arguments);
if (mi != null)
{
ParameterInfo[] parameterInfos = mi.GetParameters();
object[] args = new object[parameterInfos.Length];
arguments.CopyTo(args, 0);
TypeHelper.NarrowValues(args, parameterInfos);
try
{
InvocationHandler invocationHandler = new InvocationHandler(mi);
object result = invocationHandler.Invoke(this, args);
}
catch (Exception exception)
{
#if !SILVERLIGHT
log.Error("Error while invoking method " + handler + " on shared object", exception);
#endif
}
}
else
{
if (messages == null)
#if !(NET_1_1)
messages = new List<SendMessageEventArgs>();
#else
messages = new ArrayList();
#endif
messages.Add(new SendMessageEventArgs(handler, arguments));
}
}
break;
default:
break;
}
}
if (raiseOnConnect)
RaiseOnConnect();
if (changeList != null && changeList.Count > 0)
{
#if !(NET_1_1)
RaiseSync(changeList.ToArray());
#else
RaiseSync(changeList.ToArray(typeof(ASObject)) as ASObject[]);
#endif
}
if (notifications != null )
{
foreach (ASObject infoObject in notifications)
RaiseNetStatus(infoObject);
}
if (messages != null)
{
foreach (SendMessageEventArgs e in messages)
RaiseSendMessage(e);
}
}
internal static void DispatchDisconnect(NetConnection connection)
{
lock ((SharedObjects as ICollection).SyncRoot)
{
foreach (RemoteSharedObject rso in SharedObjects.Values)
{
if (rso._connection == connection)
rso.RaiseDisconnect();
}
}
}
internal void RaiseOnConnect()
{
if (_connectHandler != null)
{
_connectHandler(this, new EventArgs());
}
}
internal void RaiseDisconnect()
{
_initialSyncReceived = false;//Disconnected RSO
if (_disconnectHandler != null)
{
_disconnectHandler(this, new EventArgs());
}
}
internal void RaiseSync(ASObject[] changeList)
{
if (_syncHandler != null)
{
_syncHandler(this, new SyncEventArgs(changeList));
}
}
internal void RaiseNetStatus(ASObject info)
{
if (_netStatusHandler != null)
{
_netStatusHandler(this, new NetStatusEventArgs(info));
}
}
internal void RaiseNetStatus(Exception exception)
{
if (_netStatusHandler != null)
{
_netStatusHandler(this, new NetStatusEventArgs(exception));
}
}
internal void RaiseSendMessage(SendMessageEventArgs e)
{
if (_sendMessageHandler != null)
{
_sendMessageHandler(this, e);
}
}
/// <summary>
/// Sets an attribute on this object.
/// </summary>
/// <param name="name">The attribute name.</param>
/// <param name="value">The attribute value.</param>
/// <returns>true if the attribute value changed otherwise false</returns>
public sealed override bool SetAttribute(string name, object value)
{
_ownerMessage.AddEvent(SharedObjectEventType.SERVER_SET_ATTRIBUTE, name, value);
if (value == null)
{
RemoveAttribute(name);
return true;
}
if (base.SetAttribute(name, value))
{
_modified = true;
NotifyModified();
return true;
}
NotifyModified();
return false;
}
/// <summary>
/// Removes an attribute.
/// </summary>
/// <param name="name">The attribute name.</param>
/// <returns>true if the attribute was found and removed otherwise false.</returns>
public sealed override bool RemoveAttribute(string name)
{
if (base.RemoveAttribute(name))
{
_modified = true;
_ownerMessage.AddEvent(SharedObjectEventType.SERVER_DELETE_ATTRIBUTE, name, null);
NotifyModified();
return true;
}
return false;
}
/// <summary>
/// Removes all attributes.
/// </summary>
public sealed override void RemoveAttributes()
{
foreach(string key in GetAttributeNames())
{
_ownerMessage.AddEvent(SharedObjectEventType.SERVER_DELETE_ATTRIBUTE, key, null);
}
// Clear data
base.RemoveAttributes();
// Mark as modified
_modified = true;
NotifyModified();
}
/// <summary>
/// Returns the value for a given attribute and sets it if it doesn't exist.
/// </summary>
/// <param name="name">The attribute name.</param>
/// <param name="value">Attribute's default value.</param>
/// <returns>The attribute value.</returns>
public sealed override object GetAttribute(string name, object value)
{
if (name == null)
return null;
if (!HasAttribute(name))
SetAttribute(name, value);
return GetAttribute(name);
}
/// <summary>
/// Sets multiple attributes on this object.
/// </summary>
/// <param name="values">Dictionary of attributes.</param>
#if !(NET_1_1)
public sealed override void SetAttributes(IDictionary<string, object> values)
{
if (values == null)
return;
BeginUpdate();
try
{
foreach (KeyValuePair<string, object> entry in values)
{
SetAttribute(entry.Key, entry.Value);
}
}
finally
{
EndUpdate();
}
}
#else
public sealed override void SetAttributes(IDictionary values)
{
if (values == null)
return;
BeginUpdate();
try
{
foreach (DictionaryEntry entry in values)
{
SetAttribute(entry.Key.ToString(), entry.Value);
}
}
finally
{
EndUpdate();
}
}
#endif
/// <summary>
/// Sets multiple attributes on this object.
/// </summary>
/// <param name="values">Attribute store.</param>
public sealed override void SetAttributes(IAttributeStore values)
{
if (values == null)
return;
BeginUpdate();
try
{
foreach (string name in values.GetAttributeNames())
{
SetAttribute(name, values.GetAttribute(name));
}
}
finally
{
EndUpdate();
}
}
/// <summary>
/// Start performing multiple updates to the shared object.
/// </summary>
public void BeginUpdate()
{
_updateCounter += 1;
}
/// <summary>
/// The multiple updates are complete, notify server about all changes at once.
/// </summary>
public void EndUpdate()
{
_updateCounter -= 1;
if (_updateCounter == 0)
{
NotifyModified();
}
}
private void UpdateVersion()
{
_version += 1;
}
private void NotifyModified()
{
if (_updateCounter > 0)
{
// Inside a BeginUpdate/EndUpdate block
return;
}
if (_modified)
{
_modified = false;
// increase version of SO
UpdateVersion();
_lastModified = System.Environment.TickCount;
}
SendUpdates();
}
/// <summary>
/// Send update notification over data channel of RTMP connection
/// </summary>
private void SendUpdates()
{
if (_ownerMessage.Events.Count != 0)
{
if (_connection.NetConnectionClient.Connection != null)
{
RtmpConnection connection = _connection.NetConnectionClient.Connection as RtmpConnection;
// Only send updates when issued through RTMP request
RtmpChannel channel = connection.GetChannel((byte)3);
// Send update to "owner" of this update request
SharedObjectMessage syncOwner;
if (connection.ObjectEncoding == ObjectEncoding.AMF0)
syncOwner = new SharedObjectMessage(null, _name, _version, this.IsPersistentObject);
else
syncOwner = new FlexSharedObjectMessage(null, _name, _version, this.IsPersistentObject);
syncOwner.AddEvents(_ownerMessage.Events);
if (channel != null)
{
channel.Write(syncOwner);
}
else
{
#if !SILVERLIGHT
log.Warn(__Res.GetString(__Res.Channel_NotFound));
#endif
}
}
_ownerMessage.Events.Clear();
}
}
}
}
| |
using eFormCore;
using eFormCore.Helpers;
using eFormData;
using eFormShared;
using eFormSqlController;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace eFormSDK.Integration.Tests
{
[TestFixture]
public class SqlControllerTestAnswerValue : DbTestFixture
{
private SqlController sut;
private TestHelpers testHelpers;
private string path;
public override void DoSetup()
{
#region Setup SettingsTableContent
SqlController sql = new SqlController(ConnectionString);
sql.SettingUpdate(Settings.token, "abc1234567890abc1234567890abcdef");
sql.SettingUpdate(Settings.firstRunDone, "true");
sql.SettingUpdate(Settings.knownSitesDone, "true");
#endregion
sut = new SqlController(ConnectionString);
sut.StartLog(new CoreBase());
testHelpers = new TestHelpers();
sut.SettingUpdate(Settings.fileLocationPicture, path + @"\output\dataFolder\picture\");
sut.SettingUpdate(Settings.fileLocationPdf, path + @"\output\dataFolder\pdf\");
sut.SettingUpdate(Settings.fileLocationJasper, path + @"\output\dataFolder\reports\");
}
[Test]
public void SQL_answerValues_Create_DoesCreate()
{
// Arrange
Random rnd = new Random();
sites site1 = testHelpers.CreateSite(Guid.NewGuid().ToString(), rnd.Next(1, 255));
units unit1 = testHelpers.CreateUnit(rnd.Next(1, 255), rnd.Next(1, 255), site1, rnd.Next(1, 255));
languages language = new languages();
language.name = Guid.NewGuid().ToString();
language.description = Guid.NewGuid().ToString();
language.Create(DbContext);
#region surveyConfiguration
survey_configurations surveyConfiguration = new survey_configurations();
surveyConfiguration.name = Guid.NewGuid().ToString();
surveyConfiguration.stop = DateTime.Now;
surveyConfiguration.start = DateTime.Now;
surveyConfiguration.timeOut = rnd.Next(1, 255);
surveyConfiguration.timeToLive = rnd.Next(1, 255);
surveyConfiguration.Create(DbContext);
#endregion
#region QuestionSet
string name = Guid.NewGuid().ToString();
question_sets questionSet = new question_sets();
questionSet.name = name;
questionSet.share = false;
questionSet.hasChild = false;
questionSet.posiblyDeployed = false;
questionSet.Create(DbContext);
#endregion
#region Answer
answers answer = new answers();
answer.siteId = site1.id;
answer.questionSetId = questionSet.id;
answer.surveyConfigurationId = surveyConfiguration.id;
answer.unitId = unit1.id;
answer.timeZone = Guid.NewGuid().ToString();
answer.finishedAt = rnd.Next(1, 255);
answer.languageId = language.id;
answer.answerDuration = rnd.Next(1, 255);
answer.UTCAdjusted = true;
answer.Create(DbContext);
#endregion
#region question
string type = Guid.NewGuid().ToString();
string questionType = Guid.NewGuid().ToString();
string imagePosition = Guid.NewGuid().ToString();
string fontSize = Guid.NewGuid().ToString();
questions question = new questions();
question.type = type;
question.questionType = questionType;
question.imagePostion = imagePosition;
question.fontSize = fontSize;
question.questionSetId = questionSet.id;
question.maximum = rnd.Next(1, 255);
question.minimum = rnd.Next(1, 255);
question.refId = rnd.Next(1, 255);
question.maxDuration = rnd.Next(1, 255);
question.minDuration = rnd.Next(1, 255);
question.questionIndex = rnd.Next(1, 255);
question.continuousQuestionId = rnd.Next(1, 255);
question.prioritised = false;
question.validDisplay = false;
question.backButtonEnabled = false;
question.image = false;
question.Create(DbContext);
#endregion
#region Option
options option = new options();
option.weightValue = rnd.Next(1, 255);
option.questionId = question.id;
option.weight = rnd.Next(1, 255);
option.optionsIndex = rnd.Next(1, 255);
option.nextQuestionId = rnd.Next(1, 255);
option.continuousOptionId = rnd.Next(1, 255);
option.Create(DbContext);
#endregion
answer_values answerValue = new answer_values();
answerValue.questionId = question.id;
answerValue.value = rnd.Next(1, 255);
answerValue.Answer = answer;
answerValue.Option = option;
answerValue.answerId = answer.id;
answerValue.Question = question;
answerValue.optionsId = option.id;
// Act
answerValue.Create(DbContext);
answer_values dbAnswerValue = DbContext.answer_values.AsNoTracking().First();
answer_value_versions dbVersion = DbContext.answer_value_versions.AsNoTracking().First();
// Assert
Assert.NotNull(dbAnswerValue);
Assert.NotNull(dbVersion);
Assert.AreEqual(dbAnswerValue.questionId, answerValue.questionId);
Assert.AreEqual(dbAnswerValue.answerId, answerValue.answerId);
Assert.AreEqual(dbAnswerValue.optionsId, answerValue.optionsId);
Assert.AreEqual(dbAnswerValue.value, answerValue.value);
}
[Test]
public void SQL_answerValues_Update_DoesUpdate()
{
// Arrange
Random rnd = new Random();
sites site1 = testHelpers.CreateSite(Guid.NewGuid().ToString(), rnd.Next(1, 255));
units unit1 = testHelpers.CreateUnit(rnd.Next(1, 255), rnd.Next(1, 255), site1, rnd.Next(1, 255));
languages language = new languages();
language.name = Guid.NewGuid().ToString();
language.description = Guid.NewGuid().ToString();
language.Create(DbContext);
#region surveyConfiguration
survey_configurations surveyConfiguration = new survey_configurations();
surveyConfiguration.name = Guid.NewGuid().ToString();
surveyConfiguration.stop = DateTime.Now;
surveyConfiguration.start = DateTime.Now;
surveyConfiguration.timeOut = rnd.Next(1, 255);
surveyConfiguration.timeToLive = rnd.Next(1, 255);
surveyConfiguration.Create(DbContext);
#endregion
#region QuestionSet
string name = Guid.NewGuid().ToString();
question_sets questionSet = new question_sets();
questionSet.name = name;
questionSet.share = false;
questionSet.hasChild = false;
questionSet.posiblyDeployed = false;
questionSet.Create(DbContext);
#endregion
#region Answer
answers answer = new answers();
answer.siteId = site1.id;
answer.questionSetId = questionSet.id;
answer.surveyConfigurationId = surveyConfiguration.id;
answer.unitId = unit1.id;
answer.timeZone = Guid.NewGuid().ToString();
answer.finishedAt = rnd.Next(1, 255);
answer.languageId = language.id;
answer.answerDuration = rnd.Next(1, 255);
answer.UTCAdjusted = true;
answer.Create(DbContext);
#endregion
#region question
string type = Guid.NewGuid().ToString();
string questionType = Guid.NewGuid().ToString();
string imagePosition = Guid.NewGuid().ToString();
string fontSize = Guid.NewGuid().ToString();
questions question = new questions();
question.type = type;
question.questionType = questionType;
question.imagePostion = imagePosition;
question.fontSize = fontSize;
question.questionSetId = questionSet.id;
question.maximum = rnd.Next(1, 255);
question.minimum = rnd.Next(1, 255);
question.refId = rnd.Next(1, 255);
question.maxDuration = rnd.Next(1, 255);
question.minDuration = rnd.Next(1, 255);
question.questionIndex = rnd.Next(1, 255);
question.continuousQuestionId = rnd.Next(1, 255);
question.prioritised = false;
question.validDisplay = false;
question.backButtonEnabled = false;
question.image = false;
question.Create(DbContext);
#endregion
#region Option
options option = new options();
option.weightValue = rnd.Next(1, 255);
option.questionId = question.id;
option.weight = rnd.Next(1, 255);
option.optionsIndex = rnd.Next(1, 255);
option.nextQuestionId = rnd.Next(1, 255);
option.continuousOptionId = rnd.Next(1, 255);
option.Create(DbContext);
#endregion
#region Answer2
answers answer2 = new answers();
answer2.siteId = site1.id;
answer2.questionSetId = questionSet.id;
answer2.surveyConfigurationId = surveyConfiguration.id;
answer2.unitId = unit1.id;
answer2.timeZone = Guid.NewGuid().ToString();
answer2.finishedAt = rnd.Next(1, 255);
answer2.languageId = language.id;
answer2.answerDuration = rnd.Next(1, 255);
answer2.UTCAdjusted = true;
answer2.Create(DbContext);
#endregion
#region question2
string type2 = Guid.NewGuid().ToString();
string questionType2 = Guid.NewGuid().ToString();
string imagePosition2 = Guid.NewGuid().ToString();
string fontSize2 = Guid.NewGuid().ToString();
questions question2 = new questions();
question2.type = type2;
question2.questionType = questionType2;
question2.imagePostion = imagePosition2;
question2.fontSize = fontSize2;
question2.questionSetId = questionSet.id;
question2.maximum = rnd.Next(1, 255);
question2.minimum = rnd.Next(1, 255);
question2.refId = rnd.Next(1, 255);
question2.maxDuration = rnd.Next(1, 255);
question2.minDuration = rnd.Next(1, 255);
question2.questionIndex = rnd.Next(1, 255);
question2.continuousQuestionId = rnd.Next(1, 255);
question2.prioritised = false;
question2.validDisplay = false;
question2.backButtonEnabled = false;
question2.image = false;
#endregion
#region Option2
options option2 = new options();
option2.weightValue = rnd.Next(1, 255);
option2.questionId = question.id;
option2.weight = rnd.Next(1, 255);
option2.optionsIndex = rnd.Next(1, 255);
option2.nextQuestionId = rnd.Next(1, 255);
option2.continuousOptionId = rnd.Next(1, 255);
option2.Create(DbContext);
#endregion
answer_values answerValue = new answer_values();
answerValue.questionId = question.id;
answerValue.value = rnd.Next(1, 255);
answerValue.Answer = answer;
answerValue.Option = option;
answerValue.answerId = answer.id;
answerValue.Question = question;
answerValue.optionsId = option.id;
answerValue.Create(DbContext);
// Act
answerValue.questionId = question2.id;
answerValue.value = rnd.Next(1, 255);
answerValue.Answer = answer2;
answerValue.Option = option2;
answerValue.answerId = answer2.id;
answerValue.Question = question2;
answerValue.optionsId = option2.id;
answerValue.Update(DbContext);
answer_values dbAnswerValue = DbContext.answer_values.AsNoTracking().First();
answer_value_versions dbVersion = DbContext.answer_value_versions.AsNoTracking().First();
// Assert
Assert.NotNull(dbAnswerValue);
Assert.NotNull(dbVersion);
Assert.AreEqual(dbAnswerValue.questionId, answerValue.questionId);
Assert.AreEqual(dbAnswerValue.answerId, answerValue.answerId);
Assert.AreEqual(dbAnswerValue.optionsId, answerValue.optionsId);
Assert.AreEqual(dbAnswerValue.value, answerValue.value);
}
[Test]
public void SQL_answerValues_Delete_DoesDelete()
{
// Arrange
Random rnd = new Random();
sites site1 = testHelpers.CreateSite(Guid.NewGuid().ToString(), rnd.Next(1, 255));
units unit1 = testHelpers.CreateUnit(rnd.Next(1, 255), rnd.Next(1, 255), site1, rnd.Next(1, 255));
languages language = new languages();
language.name = Guid.NewGuid().ToString();
language.description = Guid.NewGuid().ToString();
language.Create(DbContext);
#region surveyConfiguration
survey_configurations surveyConfiguration = new survey_configurations();
surveyConfiguration.name = Guid.NewGuid().ToString();
surveyConfiguration.stop = DateTime.Now;
surveyConfiguration.start = DateTime.Now;
surveyConfiguration.timeOut = rnd.Next(1, 255);
surveyConfiguration.timeToLive = rnd.Next(1, 255);
surveyConfiguration.Create(DbContext);
#endregion
#region QuestionSet
string name = Guid.NewGuid().ToString();
question_sets questionSet = new question_sets();
questionSet.name = name;
questionSet.share = false;
questionSet.hasChild = false;
questionSet.posiblyDeployed = false;
questionSet.Create(DbContext);
#endregion
#region Answer
answers answer = new answers();
answer.siteId = site1.id;
answer.questionSetId = questionSet.id;
answer.surveyConfigurationId = surveyConfiguration.id;
answer.unitId = unit1.id;
answer.timeZone = Guid.NewGuid().ToString();
answer.finishedAt = rnd.Next(1, 255);
answer.languageId = language.id;
answer.answerDuration = rnd.Next(1, 255);
answer.UTCAdjusted = true;
answer.Create(DbContext);
#endregion
#region question
string type = Guid.NewGuid().ToString();
string questionType = Guid.NewGuid().ToString();
string imagePosition = Guid.NewGuid().ToString();
string fontSize = Guid.NewGuid().ToString();
questions question = new questions();
question.type = type;
question.questionType = questionType;
question.imagePostion = imagePosition;
question.fontSize = fontSize;
question.questionSetId = questionSet.id;
question.maximum = rnd.Next(1, 255);
question.minimum = rnd.Next(1, 255);
question.refId = rnd.Next(1, 255);
question.maxDuration = rnd.Next(1, 255);
question.minDuration = rnd.Next(1, 255);
question.questionIndex = rnd.Next(1, 255);
question.continuousQuestionId = rnd.Next(1, 255);
question.prioritised = false;
question.validDisplay = false;
question.backButtonEnabled = false;
question.image = false;
question.Create(DbContext);
#endregion
#region Option
options option = new options();
option.weightValue = rnd.Next(1, 255);
option.questionId = question.id;
option.weight = rnd.Next(1, 255);
option.optionsIndex = rnd.Next(1, 255);
option.nextQuestionId = rnd.Next(1, 255);
option.continuousOptionId = rnd.Next(1, 255);
option.Create(DbContext);
#endregion
answer_values answerValue = new answer_values();
answerValue.questionId = question.id;
answerValue.value = rnd.Next(1, 255);
answerValue.Answer = answer;
answerValue.Option = option;
answerValue.answerId = answer.id;
answerValue.Question = question;
answerValue.optionsId = option.id;
answerValue.Create(DbContext);
// Act
answerValue.Delete(DbContext);
answer_values dbAnswerValue = DbContext.answer_values.AsNoTracking().First();
answer_value_versions dbVersion = DbContext.answer_value_versions.AsNoTracking().First();
// Assert
Assert.NotNull(dbAnswerValue);
Assert.NotNull(dbVersion);
Assert.AreEqual(dbAnswerValue.questionId, answerValue.questionId);
Assert.AreEqual(dbAnswerValue.answerId, answerValue.answerId);
Assert.AreEqual(dbAnswerValue.optionsId, answerValue.optionsId);
Assert.AreEqual(dbAnswerValue.value, answerValue.value);
Assert.AreEqual(Constants.WorkflowStates.Removed, dbAnswerValue.workflow_state);
}
}
}
| |
/*
* 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.Linq;
using System.Text;
using OpenSim.Framework;
using System.IO;
using OpenMetaverse;
using InWorldz.Phlox.VM;
using log4net;
using System.Reflection;
using System.Diagnostics;
using InWorldz.Phlox.Serialization;
using OpenSim.Region.ScriptEngine.Shared.Api;
namespace InWorldz.Phlox.Engine
{
/// <summary>
/// Loads a script. Searches for it from the most efficient source (bytecode already in memory)
/// to the least efficient source (asset request and compilation)
/// </summary>
internal class ScriptLoader
{
private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IAssetCache _assetCache;
private ExecutionScheduler _exeScheduler;
private StateManager _stateManager;
public StateManager StateManager
{
get
{
return _stateManager;
}
set
{
_stateManager = value;
}
}
/// <summary>
/// A script that is loaded into memory with a reference count
/// </summary>
private class LoadedScript
{
public CompiledScript Script;
public int RefCount;
}
/// <summary>
/// Scripts loaded with the script asset UUID as the key
/// </summary>
private Dictionary<UUID, LoadedScript> _loadedScripts = new Dictionary<UUID, LoadedScript>();
/// <summary>
/// Scripts waiting to be loaded or unloaded, accessing this list must be done with a lock as requests
/// come from outside of the engine thread
/// </summary>
private LinkedList<LoadUnloadRequest> _outstandingLoadUnloadRequests = new LinkedList<LoadUnloadRequest>();
/// <summary>
/// Locks the _waitingForAssetServer list and the _waitingForCompilation queue
/// </summary>
private object _assetAndCompileLock = new object();
/// <summary>
/// Load requests waiting on the asset server for the script
/// </summary>
private Dictionary<UUID, List<LoadUnloadRequest>> _waitingForAssetServer = new Dictionary<UUID, List<LoadUnloadRequest>>();
/// <summary>
/// Called after an asset has been retrieved from the asset server to wake up the master scheduler
/// </summary>
private WorkArrivedDelegate _workArrived;
private class LoadedAsset
{
public uint LocalId;
public UUID ItemId;
public UUID AssetId;
public string ScriptText;
public List<LoadUnloadRequest> Requests;
}
/// <summary>
/// List of assets waiting for compilation
/// </summary>
private Queue<LoadedAsset> _waitingForCompilation = new Queue<LoadedAsset>();
/// <summary>
/// Used to measure compilation time
/// </summary>
private Stopwatch _stopwatch = new Stopwatch();
/// <summary>
/// The parent engine interface
/// </summary>
private EngineInterface _engineInterface;
/// <summary>
/// Requests for loaded script bytecode get queued here. This list must use locking because
/// the requests come from outside of the engine thread
/// </summary>
private Queue<RetrieveBytecodeRequest> _outstandingBytecodeRequests = new Queue<RetrieveBytecodeRequest>();
/// <summary>
/// The number of scripts that have been unloaded that we keep in the cache
/// </summary>
private const int MAX_CACHED_UNLOADED_SCRIPTS = 128;
/// <summary>
/// Cache that is utilized for scripts that have been unloaded to limit the
/// amount of disk thrasing that can happen when scripted objects are repeatedly
/// added and deleted from the scene
/// </summary>
private LRUCache<UUID, CompiledScript> _unloadedScriptCache = new LRUCache<UUID, CompiledScript>(MAX_CACHED_UNLOADED_SCRIPTS);
public ScriptLoader(IAssetCache assetCache, ExecutionScheduler exeScheduler,
WorkArrivedDelegate workArrived, EngineInterface engineInterface)
{
_assetCache = assetCache;
_exeScheduler = exeScheduler;
_workArrived = workArrived;
_engineInterface = engineInterface;
this.CreateDirectoryStructure();
}
private void CreateDirectoryStructure()
{
Directory.CreateDirectory(PhloxConstants.COMPILE_CACHE_DIR);
}
public void PostLoadUnloadRequest(LoadUnloadRequest req)
{
lock (_outstandingLoadUnloadRequests)
{
_outstandingLoadUnloadRequests.AddFirst(req);
}
_workArrived();
}
public WorkStatus DoWork()
{
//do we have outstanding unload requests?
bool lrqStatus = CheckAndPerformLoadUnloadRequest();
//do we have outstanding asset responses?
bool compStatus = CheckAndCompileScript();
//how about requests for compiled script assets?
bool byteCodeReqStatus = CheckAndRetrieveBytecodes();
return new WorkStatus
{
WorkWasDone = lrqStatus || compStatus || byteCodeReqStatus,
WorkIsPending = this.WorkIsPending(),
NextWakeUpTime = UInt64.MaxValue
};
}
// Returns true if it found the script loaded and decremented the refcount.
private bool PerformUnloadRequest(LoadUnloadRequest unloadReq)
{
bool rc = false;
// Find based on the item ID
VM.Interpreter loadedScript = _exeScheduler.FindScript(unloadReq.ItemId);
if (loadedScript != null)
{
LoadedScript reffedScript;
//tell the scheduler the script needs to be pulled
_exeScheduler.DoUnload(unloadReq.ItemId, unloadReq);
//tell the async command manager that it needs to remove this script
AsyncCommandManager.RemoveScript(_engineInterface, unloadReq.LocalId, unloadReq.ItemId);
//tell the state manager to remove this script
_stateManager.ScriptUnloaded(unloadReq.ItemId);
//decref and unload if refcount is 0 based on the Asset ID
if (_loadedScripts.TryGetValue(loadedScript.Script.AssetId, out reffedScript))
{
if (--reffedScript.RefCount == 0)
{
_loadedScripts.Remove(loadedScript.Script.AssetId);
_unloadedScriptCache.Add(loadedScript.Script.AssetId, loadedScript.Script);
}
rc = true;
}
}
// Callback here because if the Item ID was not found, the callback would be meaningless
if (unloadReq.PostUnloadCallback != null)
{
// Now call the completion callback (e.g. now that it is safe for the script to be removed in the delete case).
unloadReq.PostUnloadCallback(unloadReq.Prim, unloadReq.ItemId, unloadReq.CallbackParams.AllowedDrop, unloadReq.CallbackParams.FireEvents, unloadReq.CallbackParams.ReplaceArgs);
}
return rc;
}
private bool CheckAndCompileScript()
{
LoadedAsset loadedScript;
lock (_assetAndCompileLock)
{
if (_waitingForCompilation.Count == 0)
{
return false;
}
loadedScript = _waitingForCompilation.Dequeue();
}
List<Types.ILSLListener> subListeners = new List<Types.ILSLListener>();
foreach (LoadUnloadRequest request in loadedScript.Requests)
{
if (request.Listener != null)
{
subListeners.Add(new CompilationListenerAdaptor(request.Listener));
}
}
//perform compilation
Glue.CompilerFrontend frontend;
if (subListeners.Count == 0)
{
frontend = new Glue.CompilerFrontend(new LogOutputListener(loadedScript.Requests), ".");
}
else
{
frontend = new Glue.CompilerFrontend(new MulticastCompilerListener(subListeners), ".");
}
try
{
_stopwatch.Start();
CompiledScript comp = frontend.Compile(loadedScript.ScriptText);
_stopwatch.Stop();
if (comp != null)
{
comp.AssetId = loadedScript.AssetId;
//save the script
this.CacheCompiledScript(comp);
_log.InfoFormat("[Phlox]: Compiled script {0} ({1}ms) in {2}", loadedScript.AssetId, _stopwatch.ElapsedMilliseconds, loadedScript.LocalId);
foreach (LoadUnloadRequest request in loadedScript.Requests)
{
this.BeginScriptRun(request, comp);
}
_loadedScripts[comp.AssetId] = new LoadedScript { Script = comp, RefCount = loadedScript.Requests.Count };
}
else
{
_log.ErrorFormat("[Phlox]: Compilation failed for {0} item {1} in {2}", loadedScript.AssetId, loadedScript.ItemId, loadedScript.LocalId);
}
return true;
}
catch (Exception e)
{
_log.ErrorFormat("[Phlox]: Exception while compiling {0} item {1} in {2}: {3}", loadedScript.AssetId, loadedScript.ItemId, loadedScript.LocalId, e);
}
finally
{
frontend.Listener.CompilationFinished();
_stopwatch.Reset();
}
return false;
}
private void CacheCompiledScript(CompiledScript comp)
{
string scriptCacheDir = this.LookupDirectoryFromId(PhloxConstants.COMPILE_CACHE_DIR, comp.AssetId);
Directory.CreateDirectory(scriptCacheDir);
string scriptPath = Path.Combine(scriptCacheDir, comp.AssetId.ToString() + PhloxConstants.COMPILED_SCRIPT_EXTENSION);
SerializedScript script = SerializedScript.FromCompiledScript(comp);
using (FileStream f = File.Open(scriptPath, FileMode.Create))
{
ProtoBuf.Serializer.Serialize(f, script);
f.Close();
}
}
private bool CheckAndPerformLoadUnloadRequest()
{
LinkedListNode<LoadUnloadRequest> lrq;
lock (_outstandingLoadUnloadRequests)
{
if (_outstandingLoadUnloadRequests.Count > 0)
{
lrq = _outstandingLoadUnloadRequests.First;
_outstandingLoadUnloadRequests.RemoveFirst();
}
else
{
return false;
}
}
switch (lrq.Value.RequestType)
{
case LoadUnloadRequest.LUType.Load:
return this.PerformLoadRequest(lrq.Value);
case LoadUnloadRequest.LUType.Unload:
return this.PerformUnloadRequest(lrq.Value);
case LoadUnloadRequest.LUType.Reload:
return this.PerformReloadRequest(lrq.Value);
}
return false;
}
private bool PerformReloadRequest(LoadUnloadRequest loadUnloadRequest)
{
return this.PerformLoadRequest(loadUnloadRequest);
}
private bool PerformLoadRequest(LoadUnloadRequest lrq)
{
//look up the asset id
UUID scriptAssetId = this.FindAssetId(lrq);
if (scriptAssetId != UUID.Zero)
{
try
{
//we try to load a script the most efficient way possible.
//these if statements are ordered from most efficient to least
if (TryStartSharedScript(scriptAssetId, lrq))
{
return true;
}
else if (TryStartScriptFromUnloadedCache(scriptAssetId, lrq))
{
return true;
}
else if (TryStartScriptFromSerializedData(scriptAssetId, lrq))
{
return true;
}
else if (TryStartCachedScript(scriptAssetId, lrq))
{
return true;
}
else
{
SubmitAssetLoadRequest(lrq);
return true;
}
}
catch (LoaderException e)
{
_log.ErrorFormat("[Phlox]: Could not load script: " + e.Message);
}
}
return false;
}
/// <summary>
/// This function attempts to load a script from the unloaded script cache
/// </summary>
/// <param name="scriptAssetId">The asset ID for the script to be loaded</param>
/// <param name="lrq">The request that is causing the load</param>
/// <returns></returns>
private bool TryStartScriptFromUnloadedCache(UUID scriptAssetId, LoadUnloadRequest lrq)
{
CompiledScript compiledScript;
if (_unloadedScriptCache.TryGetValue(scriptAssetId, out compiledScript))
{
_log.InfoFormat("[Phlox]: Starting recovered script {0} in item {1} group {2} part {3}", scriptAssetId, lrq.ItemId, lrq.Prim.ParentGroup.LocalId, lrq.Prim.LocalId);
//remove the script from the unloaded cache for good measure since it is now loaded again
_unloadedScriptCache.Remove(scriptAssetId);
//check the part in the load request for this script.
//even though we're not using the passed in script asset,
//we should still do cleanup
ClearSerializedScriptData(lrq, scriptAssetId);
BeginScriptRun(lrq, compiledScript);
_loadedScripts[scriptAssetId] = new LoadedScript { Script = compiledScript, RefCount = 1 };
return true;
}
return false;
}
private bool TryStartScriptFromSerializedData(UUID scriptAssetId, LoadUnloadRequest lrq)
{
if (lrq.Prim.SerializedScriptByteCode == null) return false;
byte[] serializedCompiledScript;
if (lrq.Prim.SerializedScriptByteCode.TryGetValue(scriptAssetId, out serializedCompiledScript))
{
//deserialize and load
using (MemoryStream ms = new MemoryStream(serializedCompiledScript))
{
Serialization.SerializedScript script = ProtoBuf.Serializer.Deserialize<Serialization.SerializedScript>(ms);
if (script == null)
{
_log.ErrorFormat("[Phlox]: LOADER: Script data contained in prim failed to deserialize");
ClearSerializedScriptData(lrq, scriptAssetId);
return false;
}
else
{
CompiledScript compiledScript = script.ToCompiledScript();
_log.InfoFormat("[Phlox]: Starting contained script {0} in item {1} group {2} part {3}", scriptAssetId, lrq.ItemId, lrq.Prim.ParentGroup.LocalId, lrq.Prim.LocalId);
BeginScriptRun(lrq, compiledScript);
_loadedScripts[scriptAssetId] = new LoadedScript { Script = compiledScript, RefCount = 1 };
return true;
}
}
}
return false;
}
private bool SubmitAssetLoadRequest(LoadUnloadRequest lrq)
{
UUID scriptAssetId = this.FindAssetId(lrq);
if (scriptAssetId != UUID.Zero)
{
if (AddAssetWait(scriptAssetId, lrq))
{
_assetCache.GetAsset(scriptAssetId, delegate(UUID i, AssetBase a) { this.AssetReceived(lrq.Prim.LocalId, lrq.ItemId, i, a); }, AssetRequestInfo.InternalRequest());
}
return true;
}
return false;
}
/// <summary>
/// Tracks a wait on the asset server
/// </summary>
/// <param name="scriptAssetId"></param>
/// <param name="lrq"></param>
/// <returns>True if a request should be sent, false if not (already in progress)</returns>
private bool AddAssetWait(UUID scriptAssetId, LoadUnloadRequest lrq)
{
lock (_assetAndCompileLock)
{
List<LoadUnloadRequest> waitingRequests;
if (_waitingForAssetServer.TryGetValue(scriptAssetId, out waitingRequests))
{
//we already have another script waiting for load with the same UUID,
//add this one to the waiting list
waitingRequests.Add(lrq);
return false;
}
else
{
//no one waiting for this asset yet, create a new entry
_waitingForAssetServer.Add(scriptAssetId, new List<LoadUnloadRequest>() { lrq });
return true;
}
}
}
private void AssetReceived(uint localId, UUID itemId, UUID assetId, AssetBase asset)
{
lock (_assetAndCompileLock)
{
List<LoadUnloadRequest> waitingRequests;
if (_waitingForAssetServer.TryGetValue(assetId, out waitingRequests))
{
_waitingForAssetServer.Remove(assetId);
if (asset == null)
{
_log.ErrorFormat("[Phlox]: Asset not found for script {0}", assetId);
return;
}
//we have the asset, verify it, and signal that work has arrived
if (asset.Type != (sbyte)AssetType.LSLText)
{
_log.ErrorFormat("[Phlox]: Invalid asset type received from asset server. " +
"Expected LSLText, got {0}", asset.Type);
return;
}
string scriptText = OpenMetaverse.Utils.BytesToString(asset.Data);
_waitingForCompilation.Enqueue(new LoadedAsset { LocalId = localId, ItemId = itemId, AssetId = assetId, Requests = waitingRequests, ScriptText = scriptText });
_workArrived();
}
else
{
_log.ErrorFormat("[Phlox]: Received an asset for a script im not waiting for {0}", assetId);
}
}
}
/// <summary>
/// Try to load a script from disk and start it up
/// </summary>
/// <param name="scriptAssetId"></param>
/// <param name="lrq"></param>
/// <returns></returns>
private bool TryStartCachedScript(UUID scriptAssetId, LoadUnloadRequest lrq)
{
//check in the cache directory for compiled scripts
if (ScriptIsCached(scriptAssetId))
{
CompiledScript script = LoadScriptFromDisk(scriptAssetId);
_log.InfoFormat("[Phlox]: Starting cached script {0} in item {1} owner {2} part {3}", scriptAssetId, lrq.ItemId, lrq.Prim.ParentGroup.OwnerID, lrq.Prim.LocalId);
BeginScriptRun(lrq, script);
_loadedScripts[scriptAssetId] = new LoadedScript { Script = script, RefCount = 1 };
return true;
}
return false;
}
private void BeginScriptRun(LoadUnloadRequest lrq, CompiledScript script)
{
RuntimeState state = this.TryLoadState(lrq);
//if this is a reload, we unload first
if (lrq.RequestType == LoadUnloadRequest.LUType.Reload)
{
this.PerformUnloadRequest(lrq);
}
try
{
_exeScheduler.FinishedLoading(lrq, script, state);
}
catch (Exception e)
{
_log.ErrorFormat("[Phlox]: Error when informing scheduler of script load. Script: {0} Item: {1} Group: {2} Part: {3}. {4}", script.AssetId, lrq.ItemId, lrq.Prim.ParentGroup.LocalId, lrq.Prim.LocalId, e);
throw;
}
}
private CompiledScript LoadScriptFromDisk(UUID scriptAssetId)
{
string cacheDir = this.LookupDirectoryFromId(PhloxConstants.COMPILE_CACHE_DIR, scriptAssetId);
string scriptPath = Path.Combine(cacheDir, scriptAssetId.ToString() + PhloxConstants.COMPILED_SCRIPT_EXTENSION);
if (File.Exists(scriptPath))
{
SerializedScript serScript;
using (var file = File.OpenRead(scriptPath))
{
serScript = ProtoBuf.Serializer.Deserialize<SerializedScript>(file);
if (serScript == null)
{
throw new LoaderException(String.Format("Script {0} failed to deserialize from source at {1}", scriptAssetId,
scriptPath));
}
}
return serScript.ToCompiledScript();
}
else
{
throw new LoaderException(String.Format("Script {0} could not be found at {1}", scriptAssetId, scriptPath));
}
}
private string LookupDirectoryFromId(string baseDir, UUID id)
{
return Path.Combine(baseDir, id.ToString().Substring(0, PhloxConstants.CACHE_PREFIX_LEN));
}
private bool ScriptIsCached(UUID scriptAssetId)
{
string cacheDir = this.LookupDirectoryFromId(PhloxConstants.COMPILE_CACHE_DIR, scriptAssetId);
string scriptPath = Path.Combine(cacheDir, scriptAssetId.ToString() + PhloxConstants.COMPILED_SCRIPT_EXTENSION);
if (File.Exists(scriptPath))
{
return true;
}
return false;
}
/// <summary>
/// If the script asset is found cached, we start a new instance of it
/// </summary>
/// <param name="scriptAssetId"></param>
/// <returns></returns>
private bool TryStartSharedScript(UUID scriptAssetId, LoadUnloadRequest loadRequest)
{
LoadedScript script;
if (_loadedScripts.TryGetValue(scriptAssetId, out script))
{
//only adjust ref counts if this is not a reload
if (loadRequest.RequestType != LoadUnloadRequest.LUType.Reload)
{
script.RefCount++;
}
//check the part in the load request for this script.
//even though we're not using the passed in script asset,
//we should still do cleanup
ClearSerializedScriptData(loadRequest, scriptAssetId);
_log.InfoFormat("[Phlox]: Starting shared script {0} in item {1} owner {2} part {3}", scriptAssetId, loadRequest.ItemId, loadRequest.Prim.ParentGroup.OwnerID, loadRequest.Prim.LocalId);
BeginScriptRun(loadRequest, script.Script);
return true;
}
return false;
}
private void ClearSerializedScriptData(LoadUnloadRequest loadRequest, UUID scriptAssetId)
{
Dictionary<UUID, byte[]> dictionary = loadRequest.Prim.SerializedScriptByteCode;
if (dictionary == null) return;
if (dictionary.ContainsKey(scriptAssetId))
{
dictionary.Remove(scriptAssetId);
}
if (dictionary.Count == 0)
{
loadRequest.Prim.SerializedScriptByteCode = null;
}
}
/// <summary>
/// Attempt to load state from the correct source
/// </summary>
/// <param name="loadRequest">The request that sparked the script load</param>
/// <returns>The runtime state or null</returns>
private RuntimeState TryLoadState(LoadUnloadRequest loadRequest)
{
try
{
switch (loadRequest.StateSource)
{
case OpenSim.Region.Framework.ScriptStateSource.RegionLocalDisk:
return _stateManager.LoadStateFromDisk(loadRequest.ItemId);
case OpenSim.Region.Framework.ScriptStateSource.PrimData:
return _stateManager.LoadStateFromPrim(loadRequest.ItemId, loadRequest.OldItemId, loadRequest.Prim);
}
return null;
}
catch (Exception e)
{
_log.ErrorFormat("[Phlox]: Loading script state failed for {0}, {1}",
loadRequest.ItemId, e);
}
return null;
}
private bool WorkIsPending()
{
lock (_outstandingLoadUnloadRequests)
{
if (_outstandingLoadUnloadRequests.Count > 0 || _waitingForCompilation.Count > 0)
{
return true;
}
}
lock (_outstandingBytecodeRequests)
{
if (_outstandingBytecodeRequests.Count > 0)
{
return true;
}
}
return false;
}
private UUID FindAssetId(LoadUnloadRequest lrq)
{
TaskInventoryItem item = lrq.Prim.Inventory.GetInventoryItem(lrq.ItemId);
if (item == null)
{
_log.ErrorFormat("[Phlox]: Could not find inventory item {0} in primitive {1} ({2}) to start script",
lrq.ItemId, lrq.Prim.Name, lrq.Prim.UUID);
return UUID.Zero;
}
else
{
return item.AssetID;
}
}
internal void Stop()
{
}
internal void PostRetrieveByteCodeRequest(RetrieveBytecodeRequest rbRequest)
{
lock (_outstandingBytecodeRequests)
{
_outstandingBytecodeRequests.Enqueue(rbRequest);
}
_workArrived();
}
private bool CheckAndRetrieveBytecodes()
{
List<RetrieveBytecodeRequest> reqs;
lock (_outstandingBytecodeRequests)
{
if (_outstandingBytecodeRequests.Count == 0) return false;
reqs = new List<RetrieveBytecodeRequest>(_outstandingBytecodeRequests);
_outstandingBytecodeRequests.Clear();
}
foreach (var req in reqs)
{
Dictionary<UUID, byte[]> bytecodes = new Dictionary<UUID, byte[]>();
foreach (UUID id in req.ScriptIds)
{
if (!bytecodes.ContainsKey(id))
{
LoadedScript script;
if (_loadedScripts.TryGetValue(id, out script))
{
byte[] serializedScript = ReserializeScript(script.Script);
bytecodes.Add(id, serializedScript);
}
}
}
req.Bytecodes = bytecodes;
req.SignalDataReady();
}
return true;
}
/// <summary>
/// Reserializes a compiled script into a form again usable to pass over the wire or write to disk
/// </summary>
/// <param name="compiledScript"></param>
/// <returns></returns>
private byte[] ReserializeScript(CompiledScript compiledScript)
{
SerializedScript script = SerializedScript.FromCompiledScript(compiledScript);
using (MemoryStream memStream = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(memStream, script);
return memStream.ToArray();
}
}
}
}
| |
//
// System.ComponentModel.TypeDescriptorTests test cases
//
// Authors:
// Lluis Sanchez Gual (lluis@ximian.com)
//
// (c) 2004 Novell, Inc. (http://www.ximian.com)
//
using NUnit.Framework;
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Globalization;
namespace MonoTests.System.ComponentModel
{
class MyDesigner: IDesigner
{
public MyDesigner()
{
}
public IComponent Component {get{return null; }}
public DesignerVerbCollection Verbs {get{return null; }}
public void DoDefaultAction () { }
public void Initialize (IComponent component) { }
public void Dispose () { }
}
class MySite: ISite
{
public IComponent Component { get { return null; } }
public IContainer Container { get { return null; } }
public bool DesignMode { get { return true; } }
public string Name { get { return "TestName"; } set { } }
public object GetService (Type t)
{
if (t == typeof(ITypeDescriptorFilterService)) return new MyFilter ();
return null;
}
}
class MyFilter: ITypeDescriptorFilterService
{
public bool FilterAttributes (IComponent component,IDictionary attributes)
{
Attribute ea = new DefaultEventAttribute ("AnEvent");
attributes [ea.TypeId] = ea;
ea = new DefaultPropertyAttribute ("TestProperty");
attributes [ea.TypeId] = ea;
ea = new EditorAttribute ();
attributes [ea.TypeId] = ea;
return true;
}
public bool FilterEvents (IComponent component, IDictionary events)
{
events.Remove ("AnEvent");
return true;
}
public bool FilterProperties (IComponent component, IDictionary properties)
{
properties.Remove ("TestProperty");
return true;
}
}
class AnotherSite: ISite
{
public IComponent Component { get { return null; } }
public IContainer Container { get { return null; } }
public bool DesignMode { get { return true; } }
public string Name { get { return "TestName"; } set { } }
public object GetService (Type t)
{
if (t == typeof(ITypeDescriptorFilterService)) {
return new AnotherFilter ();
}
return null;
}
}
class AnotherFilter: ITypeDescriptorFilterService
{
public bool FilterAttributes (IComponent component,IDictionary attributes) {
Attribute ea = new DefaultEventAttribute ("AnEvent");
attributes [ea.TypeId] = ea;
ea = new DefaultPropertyAttribute ("TestProperty");
attributes [ea.TypeId] = ea;
ea = new EditorAttribute ();
attributes [ea.TypeId] = ea;
return true;
}
public bool FilterEvents (IComponent component, IDictionary events) {
return true;
}
public bool FilterProperties (IComponent component, IDictionary properties) {
return true;
}
}
[DescriptionAttribute ("my test component")]
[DesignerAttribute (typeof(MyDesigner), typeof(int))]
public class MyComponent: Component
{
string prop;
[DescriptionAttribute ("test")]
public event EventHandler AnEvent;
public event EventHandler AnotherEvent;
public MyComponent ()
{
}
public MyComponent (ISite site)
{
Site = site;
}
[DescriptionAttribute ("test")]
public string TestProperty
{
get { return prop; }
set { prop = value; }
}
public string AnotherProperty
{
get { return prop; }
set { prop = value; }
}
}
[DefaultProperty("AnotherProperty")]
[DefaultEvent("AnotherEvent")]
[DescriptionAttribute ("my test component")]
[DesignerAttribute (typeof(MyDesigner), typeof(int))]
public class AnotherComponent: Component {
string prop;
[DescriptionAttribute ("test")]
public event EventHandler AnEvent;
public event EventHandler AnotherEvent;
public AnotherComponent () {
}
public AnotherComponent (ISite site) {
Site = site;
}
[DescriptionAttribute ("test")]
public string TestProperty {
get { return prop; }
set { prop = value; }
}
public string AnotherProperty {
get { return prop; }
set { prop = value; }
}
}
public interface ITestInterface
{
void TestFunction ();
}
public class TestClass
{
public TestClass()
{}
void TestFunction ()
{}
}
public struct TestStruct
{
public int TestVal;
}
[TestFixture]
public class TypeDescriptorTests: Assertion
{
MyComponent com = new MyComponent ();
MyComponent sitedcom = new MyComponent (new MySite ());
AnotherComponent anothercom = new AnotherComponent ();
[Test]
public void TestCreateDesigner ()
{
IDesigner des = TypeDescriptor.CreateDesigner (com, typeof(int));
Assert ("t1", des is MyDesigner);
des = TypeDescriptor.CreateDesigner (com, typeof(string));
AssertNull ("t2", des);
}
[Test]
public void TestCreateEvent ()
{
EventDescriptor ed = TypeDescriptor.CreateEvent (typeof(MyComponent), "AnEvent", typeof(EventHandler), null);
AssertEquals ("t1", typeof(MyComponent), ed.ComponentType);
AssertEquals ("t2", typeof(EventHandler), ed.EventType);
AssertEquals ("t3", true, ed.IsMulticast);
AssertEquals ("t4", "AnEvent", ed.Name);
}
[Test]
public void TestCreateProperty ()
{
PropertyDescriptor pd = TypeDescriptor.CreateProperty (typeof(MyComponent), "TestProperty", typeof(string), null);
AssertEquals ("t1", typeof(MyComponent), pd.ComponentType);
AssertEquals ("t2", "TestProperty", pd.Name);
AssertEquals ("t3", typeof(string), pd.PropertyType);
AssertEquals ("t4", false, pd.IsReadOnly);
pd.SetValue (com, "hi");
AssertEquals ("t5", "hi", pd.GetValue(com));
}
[Test]
public void TestGetAttributes ()
{
AttributeCollection col = TypeDescriptor.GetAttributes (typeof(MyComponent));
Assert ("t2", col[typeof(DescriptionAttribute)] != null);
Assert ("t3", col[typeof(DesignerAttribute)] != null);
Assert ("t4", col[typeof(EditorAttribute)] == null);
col = TypeDescriptor.GetAttributes (com);
Assert ("t6", col[typeof(DescriptionAttribute)] != null);
Assert ("t7", col[typeof(DesignerAttribute)] != null);
Assert ("t8", col[typeof(EditorAttribute)] == null);
col = TypeDescriptor.GetAttributes (sitedcom);
Assert ("t10", col[typeof(DescriptionAttribute)] != null);
Assert ("t11", col[typeof(DesignerAttribute)] != null);
Assert ("t12", col[typeof(EditorAttribute)] != null);
}
[Test]
public void TestGetClassName ()
{
AssertEquals ("t1", typeof(MyComponent).FullName, TypeDescriptor.GetClassName (com));
}
[Test]
public void TestGetComponentName ()
{
#if !NET_2_0
AssertEquals ("t1", "MyComponent", TypeDescriptor.GetComponentName (com));
AssertEquals ("t2", "MyComponent", TypeDescriptor.GetComponentName (com, false));
AssertEquals ("t3", "Exception", TypeDescriptor.GetComponentName (new Exception ()));
AssertEquals ("t4", "Exception", TypeDescriptor.GetComponentName (new Exception (), false));
AssertNotNull ("t5", TypeDescriptor.GetComponentName (typeof (Exception)));
AssertNotNull ("t6", TypeDescriptor.GetComponentName (typeof (Exception), false));
#else
// in MS.NET 2.0, GetComponentName no longer returns
// the type name if there's no custom typedescriptor
// and no site
AssertNull ("t1", TypeDescriptor.GetComponentName (com));
AssertNull ("t2", TypeDescriptor.GetComponentName (com, false));
AssertNull ("t3", TypeDescriptor.GetComponentName (new Exception ()));
AssertNull ("t4", TypeDescriptor.GetComponentName (new Exception (), false));
AssertNull ("t5", TypeDescriptor.GetComponentName (typeof (Exception)));
AssertNull ("t6", TypeDescriptor.GetComponentName (typeof (Exception), false));
#endif
AssertEquals ("t7", "TestName", TypeDescriptor.GetComponentName (sitedcom));
AssertEquals ("t8", "TestName", TypeDescriptor.GetComponentName (sitedcom));
}
[Test]
public void TestGetConverter ()
{
AssertEquals (typeof(BooleanConverter), TypeDescriptor.GetConverter (typeof (bool)).GetType());
AssertEquals (typeof(ByteConverter), TypeDescriptor.GetConverter (typeof (byte)).GetType());
AssertEquals (typeof(SByteConverter), TypeDescriptor.GetConverter (typeof (sbyte)).GetType());
AssertEquals (typeof(StringConverter), TypeDescriptor.GetConverter (typeof (string)).GetType());
AssertEquals (typeof(CharConverter), TypeDescriptor.GetConverter (typeof (char)).GetType());
AssertEquals (typeof(Int16Converter), TypeDescriptor.GetConverter (typeof (short)).GetType());
AssertEquals (typeof(Int32Converter), TypeDescriptor.GetConverter (typeof (int)).GetType());
AssertEquals (typeof(Int64Converter), TypeDescriptor.GetConverter (typeof (long)).GetType());
AssertEquals (typeof(UInt16Converter), TypeDescriptor.GetConverter (typeof (ushort)).GetType());
AssertEquals (typeof(UInt32Converter), TypeDescriptor.GetConverter (typeof (uint)).GetType());
AssertEquals (typeof(UInt64Converter), TypeDescriptor.GetConverter (typeof (ulong)).GetType());
AssertEquals (typeof(SingleConverter), TypeDescriptor.GetConverter (typeof (float)).GetType());
AssertEquals (typeof(DoubleConverter), TypeDescriptor.GetConverter (typeof (double)).GetType());
AssertEquals (typeof(DecimalConverter), TypeDescriptor.GetConverter (typeof (decimal)).GetType());
AssertEquals (typeof(ArrayConverter), TypeDescriptor.GetConverter (typeof (Array)).GetType());
AssertEquals (typeof(CultureInfoConverter), TypeDescriptor.GetConverter (typeof (CultureInfo)).GetType());
AssertEquals (typeof(DateTimeConverter), TypeDescriptor.GetConverter (typeof (DateTime)).GetType());
AssertEquals (typeof(GuidConverter), TypeDescriptor.GetConverter (typeof (Guid)).GetType());
AssertEquals (typeof(TimeSpanConverter), TypeDescriptor.GetConverter (typeof (TimeSpan)).GetType());
AssertEquals (typeof(CollectionConverter), TypeDescriptor.GetConverter (typeof (ICollection)).GetType());
// Tests from bug #71444
AssertEquals (typeof(CollectionConverter), TypeDescriptor.GetConverter (typeof (IDictionary)).GetType());
AssertEquals (typeof(ReferenceConverter), TypeDescriptor.GetConverter (typeof (ITestInterface)).GetType());
AssertEquals (typeof(TypeConverter), TypeDescriptor.GetConverter (typeof (TestClass)).GetType());
AssertEquals (typeof(TypeConverter), TypeDescriptor.GetConverter (typeof (TestStruct)).GetType());
AssertEquals (typeof(TypeConverter), TypeDescriptor.GetConverter (new TestClass ()).GetType());
AssertEquals (typeof(TypeConverter), TypeDescriptor.GetConverter (new TestStruct ()).GetType());
AssertEquals (typeof(CollectionConverter), TypeDescriptor.GetConverter (new Hashtable ()).GetType());
}
[Test]
public void TestGetDefaultEvent ()
{
EventDescriptor des = TypeDescriptor.GetDefaultEvent (typeof(MyComponent));
AssertNull ("t1", des);
des = TypeDescriptor.GetDefaultEvent (com);
AssertNull ("t2", des);
des = TypeDescriptor.GetDefaultEvent (typeof(AnotherComponent));
AssertNotNull ("t3", des);
AssertEquals ("t4", "AnotherEvent", des.Name);
des = TypeDescriptor.GetDefaultEvent (anothercom);
AssertNotNull ("t5", des);
AssertEquals ("t6", "AnotherEvent", des.Name);
des = TypeDescriptor.GetDefaultEvent (sitedcom);
#if NET_2_0
AssertNull ("t7", des);
#else
AssertNotNull ("t7/1", des);
AssertEquals ("t7/2", "AnotherEvent", des.Name);
#endif
des = TypeDescriptor.GetDefaultEvent (new MyComponent(new AnotherSite ()));
AssertNotNull ("t8", des);
AssertEquals ("t9", "AnEvent", des.Name);
des = TypeDescriptor.GetDefaultEvent (new AnotherComponent(new AnotherSite ()));
AssertNotNull ("t10", des);
AssertEquals ("t11", "AnEvent", des.Name);
}
[Test]
public void TestGetDefaultProperty ()
{
PropertyDescriptor des = TypeDescriptor.GetDefaultProperty (typeof(MyComponent));
AssertNull ("t1", des);
des = TypeDescriptor.GetDefaultProperty (com);
AssertNull ("t2", des);
des = TypeDescriptor.GetDefaultProperty (typeof(AnotherComponent));
AssertNotNull ("t1", des);
AssertEquals ("t2", "AnotherProperty", des.Name);
des = TypeDescriptor.GetDefaultProperty (anothercom);
AssertNotNull ("t1", des);
AssertEquals ("t2", "AnotherProperty", des.Name);
}
[Test]
#if !NET_2_0
// throws NullReferenceException on MS.NET 1.x due to bug
// which is fixed in MS.NET 2.0
[NUnit.Framework.Category("NotDotNet")]
#endif
public void TestGetDefaultProperty2 ()
{
PropertyDescriptor des = TypeDescriptor.GetDefaultProperty (sitedcom);
AssertNull ("t1", des);
des = TypeDescriptor.GetDefaultProperty (new MyComponent (new AnotherSite ()));
AssertNotNull ("t2", des);
AssertEquals ("t3", "TestProperty", des.Name);
des = TypeDescriptor.GetDefaultProperty (new AnotherComponent (new AnotherSite ()));
AssertNotNull ("t4", des);
AssertEquals ("t5", "TestProperty", des.Name);
des = TypeDescriptor.GetDefaultProperty (new AnotherComponent (new MySite ()));
AssertNull ("t6", des);
}
[Test]
public void TestGetEvents ()
{
EventDescriptorCollection col = TypeDescriptor.GetEvents (typeof(MyComponent));
AssertEquals ("t1.1", 3, col.Count);
Assert ("t1.2", col.Find ("AnEvent", true) != null);
Assert ("t1.3", col.Find ("AnotherEvent", true) != null);
Assert ("t1.4", col.Find ("Disposed", true) != null);
col = TypeDescriptor.GetEvents (com);
AssertEquals ("t2.1", 3, col.Count);
Assert ("t2.2", col.Find ("AnEvent", true) != null);
Assert ("t2.3", col.Find ("AnotherEvent", true) != null);
Assert ("t2.4", col.Find ("Disposed", true) != null);
col = TypeDescriptor.GetEvents (sitedcom);
AssertEquals ("t3.1", 2, col.Count);
Assert ("t3.2", col.Find ("AnotherEvent", true) != null);
Assert ("t3.3", col.Find ("Disposed", true) != null);
Attribute[] filter = new Attribute[] { new DescriptionAttribute ("test") };
col = TypeDescriptor.GetEvents (typeof(MyComponent), filter);
AssertEquals ("t4.1", 1, col.Count);
Assert ("t4.2", col.Find ("AnEvent", true) != null);
col = TypeDescriptor.GetEvents (com, filter);
AssertEquals ("t5.1", 1, col.Count);
Assert ("t5.2", col.Find ("AnEvent", true) != null);
col = TypeDescriptor.GetEvents (sitedcom, filter);
AssertEquals ("t6", 0, col.Count);
}
[Test]
public void TestGetProperties ()
{
PropertyDescriptorCollection col = TypeDescriptor.GetProperties (typeof(MyComponent));
Assert ("t1.1", col.Find ("TestProperty", true) != null);
Assert ("t1.2", col.Find ("AnotherProperty", true) != null);
col = TypeDescriptor.GetProperties (com);
Assert ("t2.1", col.Find ("TestProperty", true) != null);
Assert ("t2.2", col.Find ("AnotherProperty", true) != null);
Attribute[] filter = new Attribute[] { new DescriptionAttribute ("test") };
col = TypeDescriptor.GetProperties (typeof(MyComponent), filter);
Assert ("t4.1", col.Find ("TestProperty", true) != null);
Assert ("t4.2", col.Find ("AnotherProperty", true) == null);
col = TypeDescriptor.GetProperties (com, filter);
Assert ("t5.1", col.Find ("TestProperty", true) != null);
Assert ("t5.2", col.Find ("AnotherProperty", true) == null);
}
[Test]
#if !NET_2_0
// throws NullReferenceException on MS.NET 1.x due to bug
// which is fixed in MS.NET 2.0
[NUnit.Framework.Category("NotDotNet")]
#endif
public void TestGetProperties2 ()
{
PropertyDescriptorCollection col = TypeDescriptor.GetProperties (sitedcom);
Assert ("t3.1", col.Find ("TestProperty", true) == null);
Assert ("t3.2", col.Find ("AnotherProperty", true) != null);
Attribute[] filter = new Attribute[] { new DescriptionAttribute ("test") };
col = TypeDescriptor.GetProperties (sitedcom, filter);
Assert ("t6.1", col.Find ("TestProperty", true) == null);
Assert ("t6.2", col.Find ("AnotherProperty", true) == null);
}
[TypeConverter (typeof (TestConverter))]
class TestConverterClass {
}
class TestConverter : TypeConverter {
public Type Type;
public TestConverter (Type type)
{
this.Type = type;
}
}
[Test]
public void TestConverterCtorWithArgument ()
{
TypeConverter t = TypeDescriptor.GetConverter (typeof (TestConverterClass));
Assert ("#01", null != t.GetType ());
AssertEquals ("#02", typeof (TestConverter), t.GetType ());
TestConverter converter = (TestConverter) t;
AssertEquals ("#03", typeof (TestConverterClass), converter.Type);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Umbraco.ModelsBuilder.Building
{
/// <summary>
/// Contains the result of a code parsing.
/// </summary>
internal class ParseResult
{
// "alias" is the umbraco alias
// content "name" is the complete name eg Foo.Bar.Name
// property "name" is just the local name
// see notes in IgnoreContentTypeAttribute
private readonly HashSet<string> _ignoredContent
= new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
//private readonly HashSet<string> _ignoredMixin
// = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
//private readonly HashSet<string> _ignoredMixinProperties
// = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
private readonly Dictionary<string, string> _renamedContent
= new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
private readonly HashSet<string> _withImplementContent
= new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
private readonly Dictionary<string, HashSet<string>> _ignoredProperty
= new Dictionary<string, HashSet<string>>();
private readonly Dictionary<string, Dictionary<string, string>> _renamedProperty
= new Dictionary<string, Dictionary<string, string>>();
private readonly Dictionary<string, string> _contentBase
= new Dictionary<string, string>();
private readonly Dictionary<string, string[]> _contentInterfaces
= new Dictionary<string, string[]>();
private readonly List<string> _usingNamespaces
= new List<string>();
private readonly Dictionary<string, List<StaticMixinMethodInfo>> _staticMixins
= new Dictionary<string, List<StaticMixinMethodInfo>>();
private readonly HashSet<string> _withCtor
= new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
public static readonly ParseResult Empty = new ParseResult();
private class StaticMixinMethodInfo
{
public StaticMixinMethodInfo(string contentName, string methodName, string returnType, string paramType)
{
ContentName = contentName;
MethodName = methodName;
//ReturnType = returnType;
//ParamType = paramType;
}
// short name eg Type1
public string ContentName { get; private set; }
// short name eg GetProp1
public string MethodName { get; private set; }
// those types cannot be FQ because when parsing, some of them
// might not exist since we're generating them... and so prob.
// that info is worthless - not using it anyway at the moment...
//public string ReturnType { get; private set; }
//public string ParamType { get; private set; }
}
#region Declare
// content with that alias should not be generated
// alias can end with a * (wildcard)
public void SetIgnoredContent(string contentAlias /*, bool ignoreContent, bool ignoreMixin, bool ignoreMixinProperties*/)
{
//if (ignoreContent)
_ignoredContent.Add(contentAlias);
//if (ignoreMixin)
// _ignoredMixin.Add(contentAlias);
//if (ignoreMixinProperties)
// _ignoredMixinProperties.Add(contentAlias);
}
// content with that alias should be generated with a different name
public void SetRenamedContent(string contentAlias, string contentName, bool withImplement)
{
_renamedContent[contentAlias] = contentName;
if (withImplement)
_withImplementContent.Add(contentAlias);
}
// property with that alias should not be generated
// applies to content name and any content that implements it
// here, contentName may be an interface
// alias can end with a * (wildcard)
public void SetIgnoredProperty(string contentName, string propertyAlias)
{
HashSet<string> ignores;
if (!_ignoredProperty.TryGetValue(contentName, out ignores))
ignores = _ignoredProperty[contentName] = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
ignores.Add(propertyAlias);
}
// property with that alias should be generated with a different name
// applies to content name and any content that implements it
// here, contentName may be an interface
public void SetRenamedProperty(string contentName, string propertyAlias, string propertyName)
{
Dictionary<string, string> renames;
if (!_renamedProperty.TryGetValue(contentName, out renames))
renames = _renamedProperty[contentName] = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
renames[propertyAlias] = propertyName;
}
// content with that name has a base class so no need to generate one
public void SetContentBaseClass(string contentName, string baseName)
{
if (baseName.ToLowerInvariant() != "object")
_contentBase[contentName] = baseName;
}
// content with that name implements the interfaces
public void SetContentInterfaces(string contentName, IEnumerable<string> interfaceNames)
{
_contentInterfaces[contentName] = interfaceNames.ToArray();
}
public void SetModelsBaseClassName(string modelsBaseClassName)
{
ModelsBaseClassName = modelsBaseClassName;
}
public void SetModelsNamespace(string modelsNamespace)
{
ModelsNamespace = modelsNamespace;
}
public void SetUsingNamespace(string usingNamespace)
{
_usingNamespaces.Add(usingNamespace);
}
public void SetStaticMixinMethod(string contentName, string methodName, string returnType, string paramType)
{
if (!_staticMixins.ContainsKey(contentName))
_staticMixins[contentName] = new List<StaticMixinMethodInfo>();
_staticMixins[contentName].Add(new StaticMixinMethodInfo(contentName, methodName, returnType, paramType));
}
public void SetHasCtor(string contentName)
{
_withCtor.Add(contentName);
}
#endregion
#region Query
public bool IsIgnored(string contentAlias)
{
return IsContentOrMixinIgnored(contentAlias, _ignoredContent);
}
//public bool IsMixinIgnored(string contentAlias)
//{
// return IsContentOrMixinIgnored(contentAlias, _ignoredMixin);
//}
//public bool IsMixinPropertiesIgnored(string contentAlias)
//{
// return IsContentOrMixinIgnored(contentAlias, _ignoredMixinProperties);
//}
private static bool IsContentOrMixinIgnored(string contentAlias, HashSet<string> ignored)
{
if (ignored.Contains(contentAlias)) return true;
return ignored
.Where(x => x.EndsWith("*"))
.Select(x => x.Substring(0, x.Length - 1))
.Any(x => contentAlias.StartsWith(x, StringComparison.InvariantCultureIgnoreCase));
}
public bool HasContentBase(string contentName)
{
return _contentBase.ContainsKey(contentName);
}
public bool IsContentRenamed(string contentAlias)
{
return _renamedContent.ContainsKey(contentAlias);
}
public bool HasContentImplement(string contentAlias)
{
return _withImplementContent.Contains(contentAlias);
}
public string ContentClrName(string contentAlias)
{
string name;
return (_renamedContent.TryGetValue(contentAlias, out name)) ? name : null;
}
public bool IsPropertyIgnored(string contentName, string propertyAlias)
{
HashSet<string> ignores;
if (_ignoredProperty.TryGetValue(contentName, out ignores))
{
if (ignores.Contains(propertyAlias)) return true;
if (ignores
.Where(x => x.EndsWith("*"))
.Select(x => x.Substring(0, x.Length - 1))
.Any(x => propertyAlias.StartsWith(x, StringComparison.InvariantCultureIgnoreCase)))
return true;
}
string baseName;
if (_contentBase.TryGetValue(contentName, out baseName)
&& IsPropertyIgnored(baseName, propertyAlias)) return true;
string[] interfaceNames;
if (_contentInterfaces.TryGetValue(contentName, out interfaceNames)
&& interfaceNames.Any(interfaceName => IsPropertyIgnored(interfaceName, propertyAlias))) return true;
return false;
}
public string PropertyClrName(string contentName, string propertyAlias)
{
Dictionary<string, string> renames;
string name;
if (_renamedProperty.TryGetValue(contentName, out renames)
&& renames.TryGetValue(propertyAlias, out name)) return name;
string baseName;
if (_contentBase.TryGetValue(contentName, out baseName)
&& null != (name = PropertyClrName(baseName, propertyAlias))) return name;
string[] interfaceNames;
if (_contentInterfaces.TryGetValue(contentName, out interfaceNames)
&& null != (name = interfaceNames
.Select(interfaceName => PropertyClrName(interfaceName, propertyAlias))
.FirstOrDefault(x => x != null))) return name;
return null;
}
public bool HasModelsBaseClassName
{
get { return !string.IsNullOrWhiteSpace(ModelsBaseClassName); }
}
public string ModelsBaseClassName { get; private set; }
public bool HasModelsNamespace
{
get { return !string.IsNullOrWhiteSpace(ModelsNamespace); }
}
public string ModelsNamespace { get; private set; }
public IEnumerable<string> UsingNamespaces
{
get { return _usingNamespaces; }
}
public IEnumerable<string> StaticMixinMethods(string contentName)
{
return _staticMixins.ContainsKey(contentName)
? _staticMixins[contentName].Select(x => x.MethodName)
: Enumerable.Empty<string>() ;
}
public bool HasCtor(string contentName)
{
return _withCtor.Contains(contentName);
}
#endregion
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using NUnit.Core;
using NUnit.Util;
namespace NUnit.UiKit
{
public delegate void SelectedTestsChangedEventHandler(object sender, SelectedTestsChangedEventArgs e);
/// <summary>
/// Summary description for TestTree.
/// </summary>
public class TestTree : System.Windows.Forms.UserControl
{
#region Instance Variables
// Contains all available categories, whether
// selected or not. Unselected members of this
// list are displayed in selectedList
private IList availableCategories = new List<string>();
// Our test loader
private TestLoader loader;
private System.Windows.Forms.TabControl tabs;
private System.Windows.Forms.TabPage testPage;
private System.Windows.Forms.TabPage categoryPage;
private System.Windows.Forms.Panel testPanel;
private System.Windows.Forms.Panel categoryPanel;
private System.Windows.Forms.Panel treePanel;
private System.Windows.Forms.Panel buttonPanel;
private NUnit.UiKit.TestSuiteTreeView tests;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.ListBox availableList;
private System.Windows.Forms.GroupBox selectedCategories;
private System.Windows.Forms.ListBox selectedList;
private System.Windows.Forms.Panel categoryButtonPanel;
private System.Windows.Forms.Button addCategory;
private System.Windows.Forms.Button removeCategory;
private System.Windows.Forms.Button clearAllButton;
private System.Windows.Forms.Button checkFailedButton;
private System.Windows.Forms.MenuItem treeMenu;
private System.Windows.Forms.MenuItem checkBoxesMenuItem;
private System.Windows.Forms.MenuItem treeMenuSeparatorItem1;
private System.Windows.Forms.MenuItem expandMenuItem;
private System.Windows.Forms.MenuItem collapseMenuItem;
private System.Windows.Forms.MenuItem treeMenuSeparatorItem2;
private System.Windows.Forms.MenuItem expandAllMenuItem;
private System.Windows.Forms.MenuItem collapseAllMenuItem;
private System.Windows.Forms.MenuItem hideTestsMenuItem;
private System.Windows.Forms.MenuItem treeMenuSeparatorItem3;
private System.Windows.Forms.MenuItem propertiesMenuItem;
private System.Windows.Forms.CheckBox excludeCheckbox;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
#endregion
#region Properties
public MenuItem TreeMenu
{
get { return treeMenu; }
}
public string[] SelectedCategories
{
get
{
int n = this.selectedList.Items.Count;
string[] categories = new string[n];
for( int i = 0; i < n; i++ )
categories[i] = this.selectedList.Items[i].ToString();
return categories;
}
}
[Browsable(false)]
public bool ShowCheckBoxes
{
get { return tests.CheckBoxes; }
set
{
tests.CheckBoxes = value;
buttonPanel.Visible = value;
clearAllButton.Visible = value;
checkFailedButton.Visible = value;
checkBoxesMenuItem.Checked = value;
}
}
#endregion
#region Construction and Initialization
public TestTree()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
treeMenu = new MenuItem();
this.checkBoxesMenuItem = new System.Windows.Forms.MenuItem();
this.treeMenuSeparatorItem1 = new System.Windows.Forms.MenuItem();
this.expandMenuItem = new System.Windows.Forms.MenuItem();
this.collapseMenuItem = new System.Windows.Forms.MenuItem();
this.treeMenuSeparatorItem2 = new System.Windows.Forms.MenuItem();
this.expandAllMenuItem = new System.Windows.Forms.MenuItem();
this.collapseAllMenuItem = new System.Windows.Forms.MenuItem();
this.hideTestsMenuItem = new System.Windows.Forms.MenuItem();
this.treeMenuSeparatorItem3 = new System.Windows.Forms.MenuItem();
this.propertiesMenuItem = new System.Windows.Forms.MenuItem();
//
// treeMenu
//
this.treeMenu.MergeType = MenuMerge.Add;
this.treeMenu.MergeOrder = 1;
this.treeMenu.MenuItems.AddRange(
new System.Windows.Forms.MenuItem[]
{
this.checkBoxesMenuItem,
this.treeMenuSeparatorItem1,
this.expandMenuItem,
this.collapseMenuItem,
this.treeMenuSeparatorItem2,
this.expandAllMenuItem,
this.collapseAllMenuItem,
this.hideTestsMenuItem,
this.treeMenuSeparatorItem3,
this.propertiesMenuItem
} );
this.treeMenu.Text = "&Tree";
this.treeMenu.Visible = false;
this.treeMenu.Popup += new System.EventHandler(this.treeMenu_Popup);
//
// checkBoxesMenuItem
//
this.checkBoxesMenuItem.Index = 0;
this.checkBoxesMenuItem.Text = "Show Check&Boxes";
this.checkBoxesMenuItem.Click += new System.EventHandler(this.checkBoxesMenuItem_Click);
//
// treeMenuSeparatorItem1
//
this.treeMenuSeparatorItem1.Index = 1;
this.treeMenuSeparatorItem1.Text = "-";
//
// expandMenuItem
//
this.expandMenuItem.Index = 2;
this.expandMenuItem.Text = "&Expand";
this.expandMenuItem.Click += new System.EventHandler(this.expandMenuItem_Click);
//
// collapseMenuItem
//
this.collapseMenuItem.Index = 3;
this.collapseMenuItem.Text = "&Collapse";
this.collapseMenuItem.Click += new System.EventHandler(this.collapseMenuItem_Click);
//
// treeMenuSeparatorItem2
//
this.treeMenuSeparatorItem2.Index = 4;
this.treeMenuSeparatorItem2.Text = "-";
//
// expandAllMenuItem
//
this.expandAllMenuItem.Index = 5;
this.expandAllMenuItem.Text = "Expand All";
this.expandAllMenuItem.Click += new System.EventHandler(this.expandAllMenuItem_Click);
//
// collapseAllMenuItem
//
this.collapseAllMenuItem.Index = 6;
this.collapseAllMenuItem.Text = "Collapse All";
this.collapseAllMenuItem.Click += new System.EventHandler(this.collapseAllMenuItem_Click);
//
// hideTestsMenuItem
//
this.hideTestsMenuItem.Index = 7;
this.hideTestsMenuItem.Text = "Hide Tests";
this.hideTestsMenuItem.Click += new System.EventHandler(this.hideTestsMenuItem_Click);
//
// treeMenuSeparatorItem3
//
this.treeMenuSeparatorItem3.Index = 8;
this.treeMenuSeparatorItem3.Text = "-";
//
// propertiesMenuItem
//
this.propertiesMenuItem.Index = 9;
this.propertiesMenuItem.Text = "&Properties";
this.propertiesMenuItem.Click += new System.EventHandler(this.propertiesMenuItem_Click);
tests.SelectedTestChanged += new SelectedTestChangedHandler(tests_SelectedTestChanged);
tests.CheckedTestChanged += new CheckedTestChangedHandler(tests_CheckedTestChanged);
this.excludeCheckbox.Enabled = false;
}
protected override void OnLoad(EventArgs e)
{
if ( !this.DesignMode )
{
this.ShowCheckBoxes =
Services.UserSettings.GetSetting( "Options.ShowCheckBoxes", false );
Initialize( Services.TestLoader );
Services.UserSettings.Changed += new SettingsEventHandler(UserSettings_Changed);
}
base.OnLoad (e);
}
public void Initialize(TestLoader loader)
{
this.tests.Initialize(loader, loader.Events);
this.loader = loader;
loader.Events.TestLoaded += new NUnit.Util.TestEventHandler(events_TestLoaded);
loader.Events.TestReloaded += new NUnit.Util.TestEventHandler(events_TestReloaded);
loader.Events.TestUnloaded += new NUnit.Util.TestEventHandler(events_TestUnloaded);
}
public void SelectCategories( string[] categories, bool exclude )
{
foreach( string category in categories )
{
if ( availableCategories.Contains( category ) )
{
if (!selectedList.Items.Contains(category))
{
selectedList.Items.Add(category);
}
availableList.Items.Remove( category );
this.excludeCheckbox.Checked = exclude;
}
}
UpdateCategoryFilter();
if (this.SelectedCategories.Length > 0)
this.excludeCheckbox.Enabled = true;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
#region View Menu Handlers
private void treeMenu_Popup(object sender, System.EventArgs e)
{
TreeNode selectedNode = tests.SelectedNode;
if ( selectedNode != null && selectedNode.Nodes.Count > 0 )
{
bool isExpanded = selectedNode.IsExpanded;
collapseMenuItem.Enabled = isExpanded;
expandMenuItem.Enabled = !isExpanded;
}
else
{
collapseMenuItem.Enabled = expandMenuItem.Enabled = false;
}
}
private void collapseMenuItem_Click(object sender, System.EventArgs e)
{
tests.SelectedNode.Collapse();
}
private void expandMenuItem_Click(object sender, System.EventArgs e)
{
tests.SelectedNode.Expand();
}
private void collapseAllMenuItem_Click(object sender, System.EventArgs e)
{
tests.BeginUpdate();
tests.CollapseAll();
tests.EndUpdate();
// Compensate for a bug in the underlying control
if ( tests.Nodes.Count > 0 )
tests.SelectedNode = tests.Nodes[0];
}
private void hideTestsMenuItem_Click(object sender, System.EventArgs e)
{
tests.HideTests();
}
private void expandAllMenuItem_Click(object sender, System.EventArgs e)
{
tests.BeginUpdate();
tests.ExpandAll();
tests.EndUpdate();
}
private void propertiesMenuItem_Click(object sender, System.EventArgs e)
{
if ( tests.SelectedTest != null )
tests.ShowPropertiesDialog( tests.SelectedTest );
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tabs = new System.Windows.Forms.TabControl();
this.testPage = new System.Windows.Forms.TabPage();
this.testPanel = new System.Windows.Forms.Panel();
this.treePanel = new System.Windows.Forms.Panel();
this.tests = new NUnit.UiKit.TestSuiteTreeView();
this.buttonPanel = new System.Windows.Forms.Panel();
this.checkFailedButton = new System.Windows.Forms.Button();
this.clearAllButton = new System.Windows.Forms.Button();
this.categoryPage = new System.Windows.Forms.TabPage();
this.categoryPanel = new System.Windows.Forms.Panel();
this.categoryButtonPanel = new System.Windows.Forms.Panel();
this.removeCategory = new System.Windows.Forms.Button();
this.addCategory = new System.Windows.Forms.Button();
this.selectedCategories = new System.Windows.Forms.GroupBox();
this.selectedList = new System.Windows.Forms.ListBox();
this.excludeCheckbox = new System.Windows.Forms.CheckBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.availableList = new System.Windows.Forms.ListBox();
this.tabs.SuspendLayout();
this.testPage.SuspendLayout();
this.testPanel.SuspendLayout();
this.treePanel.SuspendLayout();
this.buttonPanel.SuspendLayout();
this.categoryPage.SuspendLayout();
this.categoryPanel.SuspendLayout();
this.categoryButtonPanel.SuspendLayout();
this.selectedCategories.SuspendLayout();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// tabs
//
this.tabs.Alignment = System.Windows.Forms.TabAlignment.Left;
this.tabs.Controls.Add(this.testPage);
this.tabs.Controls.Add(this.categoryPage);
this.tabs.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabs.Location = new System.Drawing.Point(0, 0);
this.tabs.Multiline = true;
this.tabs.Name = "tabs";
this.tabs.SelectedIndex = 0;
this.tabs.Size = new System.Drawing.Size(248, 496);
this.tabs.TabIndex = 0;
//
// testPage
//
this.testPage.Controls.Add(this.testPanel);
this.testPage.Location = new System.Drawing.Point(25, 4);
this.testPage.Name = "testPage";
this.testPage.Size = new System.Drawing.Size(219, 488);
this.testPage.TabIndex = 0;
this.testPage.Text = "Tests";
//
// testPanel
//
this.testPanel.Controls.Add(this.treePanel);
this.testPanel.Controls.Add(this.buttonPanel);
this.testPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.testPanel.Location = new System.Drawing.Point(0, 0);
this.testPanel.Name = "testPanel";
this.testPanel.Size = new System.Drawing.Size(219, 488);
this.testPanel.TabIndex = 0;
//
// treePanel
//
this.treePanel.Controls.Add(this.tests);
this.treePanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.treePanel.Location = new System.Drawing.Point(0, 0);
this.treePanel.Name = "treePanel";
this.treePanel.Size = new System.Drawing.Size(219, 448);
this.treePanel.TabIndex = 0;
//
// tests
//
this.tests.AllowDrop = true;
this.tests.Dock = System.Windows.Forms.DockStyle.Fill;
this.tests.HideSelection = false;
this.tests.Location = new System.Drawing.Point(0, 0);
this.tests.Name = "tests";
this.tests.Size = new System.Drawing.Size(219, 448);
this.tests.TabIndex = 0;
this.tests.CheckBoxesChanged += new System.EventHandler(this.tests_CheckBoxesChanged);
//
// buttonPanel
//
this.buttonPanel.Controls.Add(this.checkFailedButton);
this.buttonPanel.Controls.Add(this.clearAllButton);
this.buttonPanel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.buttonPanel.Location = new System.Drawing.Point(0, 448);
this.buttonPanel.Name = "buttonPanel";
this.buttonPanel.Size = new System.Drawing.Size(219, 40);
this.buttonPanel.TabIndex = 1;
//
// checkFailedButton
//
this.checkFailedButton.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.checkFailedButton.Location = new System.Drawing.Point(117, 8);
this.checkFailedButton.Name = "checkFailedButton";
this.checkFailedButton.Size = new System.Drawing.Size(96, 23);
this.checkFailedButton.TabIndex = 1;
this.checkFailedButton.Text = "Check Failed";
this.checkFailedButton.Click += new System.EventHandler(this.checkFailedButton_Click);
//
// clearAllButton
//
this.clearAllButton.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.clearAllButton.Location = new System.Drawing.Point(13, 8);
this.clearAllButton.Name = "clearAllButton";
this.clearAllButton.Size = new System.Drawing.Size(96, 23);
this.clearAllButton.TabIndex = 0;
this.clearAllButton.Text = "Clear All";
this.clearAllButton.Click += new System.EventHandler(this.clearAllButton_Click);
//
// categoryPage
//
this.categoryPage.Controls.Add(this.categoryPanel);
this.categoryPage.Location = new System.Drawing.Point(25, 4);
this.categoryPage.Name = "categoryPage";
this.categoryPage.Size = new System.Drawing.Size(219, 488);
this.categoryPage.TabIndex = 1;
this.categoryPage.Text = "Categories";
//
// categoryPanel
//
this.categoryPanel.Controls.Add(this.categoryButtonPanel);
this.categoryPanel.Controls.Add(this.selectedCategories);
this.categoryPanel.Controls.Add(this.groupBox1);
this.categoryPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.categoryPanel.Location = new System.Drawing.Point(0, 0);
this.categoryPanel.Name = "categoryPanel";
this.categoryPanel.Size = new System.Drawing.Size(219, 488);
this.categoryPanel.TabIndex = 0;
//
// categoryButtonPanel
//
this.categoryButtonPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.categoryButtonPanel.Controls.Add(this.removeCategory);
this.categoryButtonPanel.Controls.Add(this.addCategory);
this.categoryButtonPanel.Location = new System.Drawing.Point(8, 280);
this.categoryButtonPanel.Name = "categoryButtonPanel";
this.categoryButtonPanel.Size = new System.Drawing.Size(203, 40);
this.categoryButtonPanel.TabIndex = 1;
//
// removeCategory
//
this.removeCategory.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.removeCategory.Location = new System.Drawing.Point(109, 8);
this.removeCategory.Name = "removeCategory";
this.removeCategory.TabIndex = 1;
this.removeCategory.Text = "Remove";
this.removeCategory.Click += new System.EventHandler(this.removeCategory_Click);
//
// addCategory
//
this.addCategory.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.addCategory.Location = new System.Drawing.Point(21, 8);
this.addCategory.Name = "addCategory";
this.addCategory.TabIndex = 0;
this.addCategory.Text = "Add";
this.addCategory.Click += new System.EventHandler(this.addCategory_Click);
//
// selectedCategories
//
this.selectedCategories.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.selectedCategories.Controls.Add(this.selectedList);
this.selectedCategories.Controls.Add(this.excludeCheckbox);
this.selectedCategories.Location = new System.Drawing.Point(8, 328);
this.selectedCategories.Name = "selectedCategories";
this.selectedCategories.Size = new System.Drawing.Size(203, 144);
this.selectedCategories.TabIndex = 2;
this.selectedCategories.TabStop = false;
this.selectedCategories.Text = "Selected Categories";
//
// selectedList
//
this.selectedList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.selectedList.ItemHeight = 16;
this.selectedList.Location = new System.Drawing.Point(8, 16);
this.selectedList.Name = "selectedList";
this.selectedList.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.selectedList.Size = new System.Drawing.Size(187, 84);
this.selectedList.TabIndex = 0;
this.selectedList.DoubleClick += new System.EventHandler(this.removeCategory_Click);
//
// excludeCheckbox
//
this.excludeCheckbox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.excludeCheckbox.Location = new System.Drawing.Point(8, 120);
this.excludeCheckbox.Name = "excludeCheckbox";
this.excludeCheckbox.Size = new System.Drawing.Size(179, 16);
this.excludeCheckbox.TabIndex = 1;
this.excludeCheckbox.Text = "Exclude these categories";
this.excludeCheckbox.CheckedChanged += new System.EventHandler(this.excludeCheckbox_CheckedChanged);
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.availableList);
this.groupBox1.Location = new System.Drawing.Point(8, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(203, 272);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Available Categories";
//
// availableList
//
this.availableList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.availableList.ItemHeight = 16;
this.availableList.Location = new System.Drawing.Point(8, 24);
this.availableList.Name = "availableList";
this.availableList.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.availableList.Size = new System.Drawing.Size(187, 244);
this.availableList.TabIndex = 0;
this.availableList.DoubleClick += new System.EventHandler(this.addCategory_Click);
//
// TestTree
//
this.Controls.Add(this.tabs);
this.Name = "TestTree";
this.Size = new System.Drawing.Size(248, 496);
this.tabs.ResumeLayout(false);
this.testPage.ResumeLayout(false);
this.testPanel.ResumeLayout(false);
this.treePanel.ResumeLayout(false);
this.buttonPanel.ResumeLayout(false);
this.categoryPage.ResumeLayout(false);
this.categoryPanel.ResumeLayout(false);
this.categoryButtonPanel.ResumeLayout(false);
this.selectedCategories.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region SelectedTestsChanged Event
public event SelectedTestsChangedEventHandler SelectedTestsChanged;
#endregion
public void RunAllTests()
{
RunAllTests(true);
}
public void RunAllTests(bool ignoreTests)
{
tests.RunAllTests(ignoreTests);
}
public void RunSelectedTests()
{
tests.RunSelectedTests();
}
public void RunFailedTests()
{
tests.RunFailedTests();
}
private void addCategory_Click(object sender, System.EventArgs e)
{
if (availableList.SelectedItems.Count > 0)
{
// Create a separate list to avoid exception
// when using the list box directly.
List<string> categories = new List<string>();
foreach ( string category in availableList.SelectedItems )
categories.Add(category);
foreach ( string category in categories)
{
selectedList.Items.Add(category);
availableList.Items.Remove(category);
}
UpdateCategoryFilter();
if (this.SelectedCategories.Length > 0)
this.excludeCheckbox.Enabled = true;
}
}
private void removeCategory_Click(object sender, System.EventArgs e)
{
if (selectedList.SelectedItems.Count > 0)
{
// Create a separate list to avoid exception
// when using the list box directly.
List<string> categories = new List<string>();
foreach (string category in selectedList.SelectedItems)
categories.Add(category);
foreach ( string category in categories )
{
selectedList.Items.Remove(category);
availableList.Items.Add(category);
}
UpdateCategoryFilter();
if (this.SelectedCategories.Length == 0)
{
this.excludeCheckbox.Checked = false;
this.excludeCheckbox.Enabled = false;
}
}
}
private void clearAllButton_Click(object sender, System.EventArgs e)
{
tests.ClearCheckedNodes();
}
private void checkFailedButton_Click(object sender, System.EventArgs e)
{
tests.CheckFailedNodes();
}
private void tests_SelectedTestChanged(ITest test)
{
if (SelectedTestsChanged != null)
{
SelectedTestsChangedEventArgs args = new SelectedTestsChangedEventArgs(test.TestName.Name, test.TestCount);
SelectedTestsChanged(tests, args);
}
}
private void events_TestLoaded(object sender, NUnit.Util.TestEventArgs args)
{
treeMenu.Visible = true;
availableCategories = this.loader.GetCategories();
availableList.Items.Clear();
selectedList.Items.Clear();
availableList.SuspendLayout();
foreach (string category in availableCategories)
availableList.Items.Add(category);
// tree may have restored visual state
if( !tests.CategoryFilter.IsEmpty )
{
ITestFilter filter = tests.CategoryFilter;
if ( filter is NUnit.Core.Filters.NotFilter )
{
filter = ((NUnit.Core.Filters.NotFilter)filter).BaseFilter;
this.excludeCheckbox.Checked = true;
}
foreach( string cat in ((NUnit.Core.Filters.CategoryFilter)filter).Categories )
if ( this.availableCategories.Contains( cat ) )
{
this.availableList.Items.Remove( cat );
this.selectedList.Items.Add( cat );
this.excludeCheckbox.Enabled = true;
}
UpdateCategoryFilter();
}
availableList.ResumeLayout();
}
private void events_TestReloaded(object sender, NUnit.Util.TestEventArgs args)
{
// Get new list of available categories
availableCategories = this.loader.GetCategories();
// Remove any selected items that are no longer available
int index = selectedList.Items.Count;
selectedList.SuspendLayout();
while( --index >= 0 )
{
string category = selectedList.Items[index].ToString();
if ( !availableCategories.Contains( category ) )
selectedList.Items.RemoveAt( index );
}
selectedList.ResumeLayout();
// Put any unselected available items availableList
availableList.Items.Clear();
availableList.SuspendLayout();
foreach( string category in availableCategories )
if( selectedList.FindStringExact( category ) < 0 )
availableList.Items.Add( category );
availableList.ResumeLayout();
// Tell the tree what is selected
UpdateCategoryFilter();
}
private void excludeCheckbox_CheckedChanged(object sender, System.EventArgs e)
{
UpdateCategoryFilter();
}
private void events_TestUnloaded(object sender, NUnit.Util.TestEventArgs args)
{
availableCategories.Clear();
availableList.Items.Clear();
selectedList.Items.Clear();
excludeCheckbox.Checked = false;
excludeCheckbox.Enabled = false;
treeMenu.Visible = false;
}
private void tests_CheckedTestChanged(ITest[] tests)
{
if (SelectedTestsChanged != null)
{
SelectedTestsChangedEventArgs args = new SelectedTestsChangedEventArgs("", tests.Length);
SelectedTestsChanged(tests, args);
}
if (tests.Length > 0)
{
}
}
private void checkBoxesMenuItem_Click(object sender, System.EventArgs e)
{
Services.UserSettings.SaveSetting( "Options.ShowCheckBoxes",
ShowCheckBoxes = !checkBoxesMenuItem.Checked );
// Temporary till we can save tree state and restore
//this.SetInitialExpansion();
}
private void UpdateCategoryFilter()
{
TestFilter catFilter;
if ( SelectedCategories == null || SelectedCategories.Length == 0 )
catFilter = TestFilter.Empty;
else
catFilter = new NUnit.Core.Filters.CategoryFilter( SelectedCategories );
if ( excludeCheckbox.Checked )
catFilter = new NUnit.Core.Filters.NotFilter( catFilter );
tests.CategoryFilter = catFilter;
}
private void tests_CheckBoxesChanged(object sender, System.EventArgs e)
{
ShowCheckBoxes = tests.CheckBoxes;
}
private void UserSettings_Changed(object sender, SettingsEventArgs args)
{
if ( args.SettingName == "Options.ShowCheckBoxes" )
this.ShowCheckBoxes = Services.UserSettings.GetSetting( args.SettingName, false );
}
}
public class SelectedTestsChangedEventArgs : EventArgs
{
private string testName;
private int count;
public SelectedTestsChangedEventArgs(string testName, int count)
{
this.testName = testName;
this.count = count;
}
public string TestName
{
get { return testName; }
}
public int TestCount
{
get { return count; }
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A shoe store.
/// </summary>
public class ShoeStore_Core : TypeCore, IStore
{
public ShoeStore_Core()
{
this._TypeId = 239;
this._Id = "ShoeStore";
this._Schema_Org_Url = "http://schema.org/ShoeStore";
string label = "";
GetLabel(out label, "ShoeStore", typeof(ShoeStore_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,252};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{252};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// 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.Runtime.InteropServices;
namespace System.Management
{
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
/// <summary>
/// <para> Contains information about a WMI method.</para>
/// </summary>
/// <example>
/// <code lang='C#'>using System;
/// using System.Management;
///
/// // This example shows how to obtain meta data
/// // about a WMI method with a given name in a given WMI class
///
/// class Sample_MethodData
/// {
/// public static int Main(string[] args) {
///
/// // Get the "SetPowerState" method in the Win32_LogicalDisk class
/// ManagementClass diskClass = new ManagementClass("win32_logicaldisk");
/// MethodData m = diskClass.Methods["SetPowerState"];
///
/// // Get method name (albeit we already know it)
/// Console.WriteLine("Name: " + m.Name);
///
/// // Get the name of the top-most class where this specific method was defined
/// Console.WriteLine("Origin: " + m.Origin);
///
/// // List names and types of input parameters
/// ManagementBaseObject inParams = m.InParameters;
/// foreach (PropertyData pdata in inParams.Properties) {
/// Console.WriteLine();
/// Console.WriteLine("InParam_Name: " + pdata.Name);
/// Console.WriteLine("InParam_Type: " + pdata.Type);
/// }
///
/// // List names and types of output parameters
/// ManagementBaseObject outParams = m.OutParameters;
/// foreach (PropertyData pdata in outParams.Properties) {
/// Console.WriteLine();
/// Console.WriteLine("OutParam_Name: " + pdata.Name);
/// Console.WriteLine("OutParam_Type: " + pdata.Type);
/// }
///
/// return 0;
/// }
/// }
/// </code>
/// <code lang='VB'>Imports System
/// Imports System.Management
///
/// ' This example shows how to obtain meta data
/// ' about a WMI method with a given name in a given WMI class
///
/// Class Sample_ManagementClass
/// Overloads Public Shared Function Main(args() As String) As Integer
///
/// ' Get the "SetPowerState" method in the Win32_LogicalDisk class
/// Dim diskClass As New ManagementClass("Win32_LogicalDisk")
/// Dim m As MethodData = diskClass.Methods("SetPowerState")
///
/// ' Get method name (albeit we already know it)
/// Console.WriteLine("Name: " & m.Name)
///
/// ' Get the name of the top-most class where
/// ' this specific method was defined
/// Console.WriteLine("Origin: " & m.Origin)
///
/// ' List names and types of input parameters
/// Dim inParams As ManagementBaseObject
/// inParams = m.InParameters
/// Dim pdata As PropertyData
/// For Each pdata In inParams.Properties
/// Console.WriteLine()
/// Console.WriteLine("InParam_Name: " & pdata.Name)
/// Console.WriteLine("InParam_Type: " & pdata.Type)
/// Next pdata
///
/// ' List names and types of output parameters
/// Dim outParams As ManagementBaseObject
/// outParams = m.OutParameters
/// For Each pdata in outParams.Properties
/// Console.WriteLine()
/// Console.WriteLine("OutParam_Name: " & pdata.Name)
/// Console.WriteLine("OutParam_Type: " & pdata.Type)
/// Next pdata
///
/// Return 0
/// End Function
/// End Class
/// </code>
/// </example>
//CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC//
public class MethodData
{
private readonly ManagementObject parent; //needed to be able to get method qualifiers
private readonly string methodName;
private IWbemClassObjectFreeThreaded wmiInParams;
private IWbemClassObjectFreeThreaded wmiOutParams;
private QualifierDataCollection qualifiers;
internal MethodData(ManagementObject parent, string methodName)
{
this.parent = parent;
this.methodName = methodName;
RefreshMethodInfo();
qualifiers = null;
}
//This private function is used to refresh the information from the Wmi object before returning the requested data
private void RefreshMethodInfo()
{
int status = (int)ManagementStatus.Failed;
try
{
status = parent.wbemObject.GetMethod_(methodName, 0, out wmiInParams, out wmiOutParams);
}
catch (COMException e)
{
ManagementException.ThrowWithExtendedInfo(e);
}
if ((status & 0xfffff000) == 0x80041000)
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
}
else if ((status & 0x80000000) != 0)
{
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
}
/// <summary>
/// <para>Gets or sets the name of the method.</para>
/// </summary>
/// <value>
/// <para>The name of the method.</para>
/// </value>
public string Name
{
get { return methodName != null ? methodName : ""; }
}
/// <summary>
/// <para> Gets or sets the input parameters to the method. Each
/// parameter is described as a property in the object. If a parameter is both in
/// and out, it appears in both the <see cref='System.Management.MethodData.InParameters'/> and <see cref='System.Management.MethodData.OutParameters'/>
/// properties.</para>
/// </summary>
/// <value>
/// <para>
/// A <see cref='System.Management.ManagementBaseObject'/>
/// containing all the input parameters to the
/// method.</para>
/// </value>
/// <remarks>
/// <para>Each parameter in the object should have an
/// <see langword='ID'/>
/// qualifier, identifying the order of the parameters in the method call.</para>
/// </remarks>
public ManagementBaseObject InParameters
{
get
{
RefreshMethodInfo();
return (null == wmiInParams) ? null : new ManagementBaseObject(wmiInParams);
}
}
/// <summary>
/// <para> Gets or sets the output parameters to the method. Each
/// parameter is described as a property in the object. If a parameter is both in
/// and out, it will appear in both the <see cref='System.Management.MethodData.InParameters'/> and <see cref='System.Management.MethodData.OutParameters'/>
/// properties.</para>
/// </summary>
/// <value>
/// <para>A <see cref='System.Management.ManagementBaseObject'/> containing all the output parameters to the method. </para>
/// </value>
/// <remarks>
/// <para>Each parameter in this object should have an
/// <see langword='ID'/> qualifier to identify the
/// order of the parameters in the method call.</para>
/// <para>The ReturnValue property is a special property of
/// the <see cref='System.Management.MethodData.OutParameters'/>
/// object and
/// holds the return value of the method.</para>
/// </remarks>
public ManagementBaseObject OutParameters
{
get
{
RefreshMethodInfo();
return (null == wmiOutParams) ? null : new ManagementBaseObject(wmiOutParams);
}
}
/// <summary>
/// <para>Gets the name of the management class in which the method was first
/// introduced in the class inheritance hierarchy.</para>
/// </summary>
/// <value>
/// A string representing the originating
/// management class name.
/// </value>
public string Origin
{
get
{
string className = null;
int status = parent.wbemObject.GetMethodOrigin_(methodName, out className);
if (status < 0)
{
if (status == (int)tag_WBEMSTATUS.WBEM_E_INVALID_OBJECT)
className = string.Empty; // Interpret as an unspecified property - return ""
else if ((status & 0xfffff000) == 0x80041000)
ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
else
Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
}
return className;
}
}
/// <summary>
/// <para>Gets a collection of qualifiers defined in the
/// method. Each element is of type <see cref='System.Management.QualifierData'/>
/// and contains information such as the qualifier name, value, and
/// flavor.</para>
/// </summary>
/// <value>
/// A <see cref='System.Management.QualifierDataCollection'/> containing the
/// qualifiers for this method.
/// </value>
/// <seealso cref='System.Management.QualifierData'/>
public QualifierDataCollection Qualifiers
{
get
{
if (qualifiers == null)
qualifiers = new QualifierDataCollection(parent, methodName, QualifierType.MethodQualifier);
return qualifiers;
}
}
}//MethodData
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using CodeElementWeakComAggregateHandle =
Microsoft.VisualStudio.LanguageServices.Implementation.Interop.WeakComHandle<EnvDTE.CodeElement, EnvDTE.CodeElement>;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
public sealed partial class FileCodeModel
{
/// <summary>
/// A wrapper around a collection containing weak references that can clean
/// itself out of dead weak references in a timesliced way.
/// The class holds an enumerator over inner collection and a queue of dead elements.
/// On every 25 element added the cleanup is initiated, which is performed when
/// CleanupWeakComHandles() method is called (FCM calls it on idle).
/// The cleanup works in timesliced way.
/// The cleanup first scans the inner collection adding each element with dead weak
/// ref to the dead queue. When scan is finished (or new element is added/removed,
/// which invalidates the enumerator), cleanup processes the dead queue removing
/// elements from the inner collection.
/// We keep dead queue alive even when the enumerator got invalidated, removing elements
/// from the dead queue when they are removed from the collection via external call.
/// </summary>
private class CleanableWeakComHandleTable
{
// TODO: Move these to options
private static readonly TimeSpan s_timeSliceForFileCodeModelCleanup = TimeSpan.FromMilliseconds(15);
private const int ElementsAddedBeforeFileCodeModelCleanup = 25;
private readonly Dictionary<SyntaxNodeKey, CodeElementWeakComAggregateHandle> _elements;
private bool _needCleanup;
private int _elementsAddedSinceLastCleanup;
// Dead queue is a hash set so we could effectively remove element from
// the dead queue when it's being removed externally
private readonly HashSet<SyntaxNodeKey> _deadQueue;
private IEnumerator<KeyValuePair<SyntaxNodeKey, CodeElementWeakComAggregateHandle>> _cleanupEnumerator;
private enum State
{
Initial,
Checking,
ProcessingDeadQueue
}
private State _state;
public CleanableWeakComHandleTable()
{
_elements = new Dictionary<SyntaxNodeKey, CodeElementWeakComAggregateHandle>();
_deadQueue = new HashSet<SyntaxNodeKey>();
_state = State.Initial;
}
private void InvalidateEnumerator()
{
if (_cleanupEnumerator != null)
{
_cleanupEnumerator.Dispose();
_cleanupEnumerator = null;
}
}
public bool NeedCleanup
{
get { return _needCleanup; }
}
public void Add(SyntaxNodeKey key, CodeElementWeakComAggregateHandle value)
{
TriggerCleanup();
InvalidateEnumerator();
_elements.Add(key, value);
}
public void Remove(SyntaxNodeKey key)
{
InvalidateEnumerator();
if (_deadQueue.Contains(key))
{
_deadQueue.Remove(key);
}
_elements.Remove(key);
}
public bool TryGetValue(SyntaxNodeKey key, out CodeElementWeakComAggregateHandle value)
{
return _elements.TryGetValue(key, out value);
}
public bool ContainsKey(SyntaxNodeKey key)
{
return _elements.ContainsKey(key);
}
public IEnumerable<CodeElementWeakComAggregateHandle> Values
{
get { return _elements.Values; }
}
private void TriggerCleanup()
{
_elementsAddedSinceLastCleanup++;
if (_elementsAddedSinceLastCleanup >= ElementsAddedBeforeFileCodeModelCleanup)
{
_needCleanup = true;
_elementsAddedSinceLastCleanup = 0;
}
}
private bool CheckWeakComHandles(TimeSlice timeSlice)
{
Debug.Assert(_cleanupEnumerator != null);
Debug.Assert(_state == State.Checking);
while (_cleanupEnumerator.MoveNext())
{
if (!_cleanupEnumerator.Current.Value.IsAlive())
{
_deadQueue.Add(_cleanupEnumerator.Current.Key);
}
if (timeSlice.IsOver)
{
return false;
}
}
return true;
}
private bool ProcessDeadQueue(TimeSlice timeSlice)
{
Debug.Assert(_cleanupEnumerator == null, "We should never process dead queue when enumerator is alive.");
while (_deadQueue.Count > 0)
{
var key = _deadQueue.First();
_deadQueue.Remove(key);
Debug.Assert(_elements.ContainsKey(key), "How come the key is in the dead queue, but not in the dictionary?");
_elements.Remove(key);
if (timeSlice.IsOver)
{
return false;
}
}
return true;
}
public void CleanupWeakComHandles()
{
if (!_needCleanup)
{
return;
}
var timeSlice = new TimeSlice(s_timeSliceForFileCodeModelCleanup);
if (_state == State.Initial)
{
_cleanupEnumerator = _elements.GetEnumerator();
_state = State.Checking;
}
if (_state == State.Checking)
{
if (_cleanupEnumerator == null)
{
// The enumerator got reset while we were checking, need to process dead queue
// before starting checking over again
if (!ProcessDeadQueue(timeSlice))
{
// Need more time to finish processing dead queue, continue next time
return;
}
_cleanupEnumerator = _elements.GetEnumerator();
}
if (!CheckWeakComHandles(timeSlice))
{
// Need more time to check for dead elements, continue next time
return;
}
// Done with checking, now process dead queue
InvalidateEnumerator();
_state = State.ProcessingDeadQueue;
}
if (_state == State.ProcessingDeadQueue)
{
if (!ProcessDeadQueue(timeSlice))
{
// Need more time to finish processing dead queue, continue next time
return;
}
// Done with cleanup
_state = State.Initial;
_needCleanup = false;
}
}
}
}
}
| |
namespace StockSharp.Algo.Import
{
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using Ecng.ComponentModel;
using Ecng.Serialization;
/// <summary>
/// Importing field description.
/// </summary>
public abstract class FieldMapping : NotifiableObject, IPersistable, ICloneable
{
private FastDateTimeParser _dateParser;
private FastTimeSpanParser _timeParser;
private readonly HashSet<string> _enumNames = new(StringComparer.InvariantCultureIgnoreCase);
/// <summary>
/// Initializes a new instance of the <see cref="FieldMapping"/>.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="displayName">Display name.</param>
/// <param name="description">Description.</param>
/// <param name="type">Field type.</param>
protected FieldMapping(string name, string displayName, string description, Type type)
{
//if (settings == null)
// throw new ArgumentNullException(nameof(settings));
if (name.IsEmpty())
throw new ArgumentNullException(nameof(name));
if (displayName.IsEmpty())
throw new ArgumentNullException(nameof(displayName));
if (description.IsEmpty())
description = displayName;
Type = type ?? throw new ArgumentNullException(nameof(type));
Name = name;
DisplayName = displayName;
Description = description;
IsEnabled = true;
//Number = -1;
if (Type.IsDateTime())
Format = "yyyyMMdd";
else if (Type == typeof(TimeSpan))
Format = "hh:mm:ss";
if (Type.IsEnum)
_enumNames.AddRange(Type.GetNames());
}
/// <summary>
/// Name.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Is field extended.
/// </summary>
public bool IsExtended { get; set; }
/// <summary>
/// Display name.
/// </summary>
public string DisplayName { get; }
/// <summary>
/// Description.
/// </summary>
public string Description { get; }
/// <summary>
/// Date format.
/// </summary>
public string Format { get; set; }
/// <summary>
/// Field type.
/// </summary>
public Type Type { get; }
/// <summary>
/// Is field required.
/// </summary>
public bool IsRequired { get; set; }
/// <summary>
/// Is field enabled.
/// </summary>
public bool IsEnabled
{
get => Order != null;
set
{
if (IsEnabled == value)
return;
if (value)
{
if (Order == null)
Order = 0;
}
else
Order = null;
NotifyChanged(nameof(IsEnabled));
NotifyChanged(nameof(Order));
}
}
private int? _order;
/// <summary>
/// Field order.
/// </summary>
public int? Order
{
get => _order;
set
{
if (Order == value)
return;
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
_order = value;
IsEnabled = value != null;
NotifyChanged(nameof(IsEnabled));
NotifyChanged(nameof(Order));
}
}
private IEnumerable<FieldMappingValue> _values = Enumerable.Empty<FieldMappingValue>();
/// <summary>
/// Mapping values.
/// </summary>
public IEnumerable<FieldMappingValue> Values
{
get => _values;
set => _values = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Default value.
/// </summary>
public string DefaultValue { get; set; }
/// <summary>
/// Zero as <see langword="null"/>.
/// </summary>
public bool ZeroAsNull { get; set; }
/// <summary>
/// Multiple field's instancies allowed.
/// </summary>
public bool IsMultiple => IsAdapter;
/// <summary>
/// <see cref="AdapterType"/> required.
/// </summary>
public bool IsAdapter { get; set; }
/// <summary>
/// Adapter.
/// </summary>
public Type AdapterType { get; set; }
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public void Load(SettingsStorage storage)
{
Name = storage.GetValue<string>(nameof(Name));
IsExtended = storage.GetValue<bool>(nameof(IsExtended));
Values = storage.GetValue<SettingsStorage[]>(nameof(Values)).Select(s => s.Load<FieldMappingValue>()).ToArray();
DefaultValue = storage.GetValue<string>(nameof(DefaultValue));
Format = storage.GetValue<string>(nameof(Format));
ZeroAsNull = storage.GetValue<bool>(nameof(ZeroAsNull));
//IsEnabled = storage.GetValue(nameof(IsEnabled), IsEnabled);
if (storage.ContainsKey(nameof(IsEnabled)))
IsEnabled = storage.GetValue<bool>(nameof(IsEnabled));
else
Order = storage.GetValue<int?>(nameof(Order));
IsAdapter = storage.GetValue(nameof(IsAdapter), IsAdapter);
AdapterType = storage.GetValue<string>(nameof(AdapterType)).To<Type>();
}
void IPersistable.Save(SettingsStorage storage)
{
storage.SetValue(nameof(Name), Name);
storage.SetValue(nameof(IsExtended), IsExtended);
storage.SetValue(nameof(Values), Values.Select(v => v.Save()).ToArray());
storage.SetValue(nameof(DefaultValue), DefaultValue);
storage.SetValue(nameof(Format), Format);
//storage.SetValue(nameof(IsEnabled), IsEnabled);
storage.SetValue(nameof(Order), Order);
storage.SetValue(nameof(ZeroAsNull), ZeroAsNull);
storage.SetValue(nameof(IsAdapter), IsAdapter);
storage.SetValue(nameof(AdapterType), AdapterType.To<string>());
}
/// <summary>
/// Apply value.
/// </summary>
/// <param name="instance">Instance.</param>
/// <param name="value">Field value.</param>
public void ApplyFileValue(object instance, string value)
{
if (value.IsEmpty())
{
ApplyDefaultValue(instance);
return;
}
if (Values.Any())
{
var v = Values.FirstOrDefault(vl => vl.ValueFile.EqualsIgnoreCase(value));
if (v != null)
{
ApplyValue(instance, v.ValueStockSharp);
return;
}
}
if (_enumNames.Contains(value))
{
ApplyValue(instance, value.To(Type));
return;
}
ApplyValue(instance, value);
}
/// <summary>
/// Apply default value.
/// </summary>
/// <param name="instance">Instance.</param>
public void ApplyDefaultValue(object instance)
{
ApplyValue(instance, DefaultValue);
}
private void ApplyValue(object instance, object value)
{
if (Type == typeof(decimal))
{
if (value is string str)
{
if (str.ContainsIgnoreCase("e")) // exponential notation
value = str.To<double>();
else
{
str = str.Replace(',', '.').RemoveSpaces().ReplaceWhiteSpaces().Trim();
if (str.IsEmpty())
return;
value = str;
}
}
}
else if (Type.IsDateTime())
{
if (value is string str)
{
if (_dateParser == null)
_dateParser = new FastDateTimeParser(Format);
if (Type == typeof(DateTimeOffset))
{
var dto = _dateParser.ParseDto(str);
if (dto.Offset.IsDefault())
{
var tz = Scope<TimeZoneInfo>.Current?.Value;
if (tz != null)
dto = dto.UtcDateTime.ApplyTimeZone(tz);
}
value = dto;
}
else
{
value = _dateParser.Parse(str);
}
}
}
else if (Type == typeof(TimeSpan))
{
if (value is string str)
{
if (_timeParser == null)
_timeParser = new FastTimeSpanParser(Format);
value = _timeParser.Parse(str);
}
}
if (value != null)
{
value = value.To(Type);
if (ZeroAsNull && Type.IsNumeric() && value.To<decimal>() == 0)
return;
OnApply(instance, value);
}
}
/// <summary>
/// Apply value.
/// </summary>
/// <param name="instance">Instance.</param>
/// <param name="value">Field value.</param>
protected abstract void OnApply(object instance, object value);
/// <inheritdoc />
public override string ToString() => Name;
/// <inheritdoc />
public abstract object Clone();
/// <summary>
/// Reset state.
/// </summary>
public void Reset()
{
_dateParser = null;
_timeParser = null;
}
/// <summary>
/// Get <see cref="FieldMapping"/> instance or clone dependent on <see cref="IsMultiple"/>.
/// </summary>
/// <returns>Field.</returns>
public FieldMapping GetOrClone()
{
return IsMultiple ? (FieldMapping)Clone() : this;
}
}
/// <summary>
/// Importing field description.
/// </summary>
/// <typeparam name="TInstance">Type, containing the field.</typeparam>
/// <typeparam name="TValue">Field value type.</typeparam>
public class FieldMapping<TInstance, TValue> : FieldMapping
{
private readonly Action<TInstance, TValue> _apply;
/// <summary>
/// Initializes a new instance of the <see cref="FieldMapping{TInstance,TValue}"/>.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="displayName">Display name.</param>
/// <param name="description">Description.</param>
/// <param name="apply">Apply field value action.</param>
public FieldMapping(string name, string displayName, string description, Action<TInstance, TValue> apply)
: this(name, displayName, description, typeof(TValue), apply)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FieldMapping{TInstance,TValue}"/>.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="displayName">Display name.</param>
/// <param name="description">Description.</param>
/// <param name="type">Field type.</param>
/// <param name="apply">Apply field value action.</param>
public FieldMapping(string name, string displayName, string description, Type type, Action<TInstance, TValue> apply)
: base(name, displayName, description, type)
{
_apply = apply ?? throw new ArgumentNullException(nameof(apply));
}
/// <inheritdoc />
protected override void OnApply(object instance, object value)
{
_apply((TInstance)instance, (TValue)value);
}
/// <inheritdoc />
public override object Clone()
{
var clone = new FieldMapping<TInstance, TValue>(Name, DisplayName, Description, _apply);
clone.Load(this.Save());
return clone;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Xml
{
using System.IO;
using System.Runtime;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Threading;
abstract class XmlStreamNodeWriter : XmlNodeWriter
{
Stream stream;
byte[] buffer;
int offset;
bool ownsStream;
const int bufferLength = 512;
const int maxEntityLength = 32;
const int maxBytesPerChar = 3;
Encoding encoding;
int hasPendingWrite;
AsyncEventArgs<object> flushBufferState;
static UTF8Encoding UTF8Encoding = new UTF8Encoding(false, true);
static AsyncCallback onFlushBufferComplete;
static AsyncEventArgsCallback onGetFlushComplete;
protected XmlStreamNodeWriter()
{
this.buffer = new byte[bufferLength];
encoding = XmlStreamNodeWriter.UTF8Encoding;
}
protected void SetOutput(Stream stream, bool ownsStream, Encoding encoding)
{
this.stream = stream;
this.ownsStream = ownsStream;
this.offset = 0;
if (encoding != null)
{
this.encoding = encoding;
}
}
// Getting/Setting the Stream exists for fragmenting
public Stream Stream
{
get
{
return stream;
}
set
{
stream = value;
}
}
// StreamBuffer/BufferOffset exists only for the BinaryWriter to fix up nodes
public byte[] StreamBuffer
{
get
{
return buffer;
}
}
public int BufferOffset
{
get
{
return offset;
}
}
public int Position
{
get
{
return (int)stream.Position + offset;
}
}
protected byte[] GetBuffer(int count, out int offset)
{
Fx.Assert(count >= 0 && count <= bufferLength, "");
int bufferOffset = this.offset;
if (bufferOffset + count <= bufferLength)
{
offset = bufferOffset;
}
else
{
FlushBuffer();
offset = 0;
}
#if DEBUG
Fx.Assert(offset + count <= bufferLength, "");
for (int i = 0; i < count; i++)
{
buffer[offset + i] = (byte)'<';
}
#endif
return buffer;
}
internal AsyncCompletionResult GetBufferAsync(GetBufferAsyncEventArgs getBufferState)
{
Fx.Assert(getBufferState != null, "GetBufferAsyncEventArgs cannot be null.");
int count = getBufferState.Arguments.Count;
Fx.Assert(count >= 0 && count <= bufferLength, String.Empty);
int finalOffset = 0;
int bufferOffset = this.offset;
if (bufferOffset + count <= bufferLength)
{
finalOffset = bufferOffset;
}
else
{
if (onGetFlushComplete == null)
{
onGetFlushComplete = new AsyncEventArgsCallback(GetBufferFlushComplete);
}
if (flushBufferState == null)
{
this.flushBufferState = new AsyncEventArgs<object>();
}
this.flushBufferState.Set(onGetFlushComplete, getBufferState, this);
if (FlushBufferAsync(this.flushBufferState) == AsyncCompletionResult.Completed)
{
finalOffset = 0;
this.flushBufferState.Complete(true);
}
else
{
return AsyncCompletionResult.Queued;
}
}
#if DEBUG
Fx.Assert(finalOffset + count <= bufferLength, "");
for (int i = 0; i < count; i++)
{
buffer[finalOffset + i] = (byte)'<';
}
#endif
//return the buffer and finalOffset;
getBufferState.Result = getBufferState.Result ?? new GetBufferEventResult();
getBufferState.Result.Buffer = this.buffer;
getBufferState.Result.Offset = finalOffset;
return AsyncCompletionResult.Completed;
}
static void GetBufferFlushComplete(IAsyncEventArgs completionState)
{
XmlStreamNodeWriter thisPtr = (XmlStreamNodeWriter)completionState.AsyncState;
GetBufferAsyncEventArgs getBufferState = (GetBufferAsyncEventArgs)thisPtr.flushBufferState.Arguments;
getBufferState.Result = getBufferState.Result ?? new GetBufferEventResult();
getBufferState.Result.Buffer = thisPtr.buffer;
getBufferState.Result.Offset = 0;
getBufferState.Complete(false, completionState.Exception);
}
AsyncCompletionResult FlushBufferAsync(AsyncEventArgs<object> state)
{
if (Interlocked.CompareExchange(ref this.hasPendingWrite, 1, 0) != 0)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.FlushBufferAlreadyInUse)));
}
if (this.offset != 0)
{
if (onFlushBufferComplete == null)
{
onFlushBufferComplete = new AsyncCallback(OnFlushBufferCompete);
}
IAsyncResult result = stream.BeginWrite(buffer, 0, this.offset, onFlushBufferComplete, this);
if (!result.CompletedSynchronously)
{
return AsyncCompletionResult.Queued;
}
stream.EndWrite(result);
this.offset = 0;
}
if (Interlocked.CompareExchange(ref this.hasPendingWrite, 0, 1) != 1)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.NoAsyncWritePending)));
}
return AsyncCompletionResult.Completed;
}
static void OnFlushBufferCompete(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
XmlStreamNodeWriter thisPtr = (XmlStreamNodeWriter)result.AsyncState;
Exception completionException = null;
try
{
thisPtr.stream.EndWrite(result);
thisPtr.offset = 0;
if (Interlocked.CompareExchange(ref thisPtr.hasPendingWrite, 0, 1) != 1)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.NoAsyncWritePending)));
}
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
completionException = ex;
}
thisPtr.flushBufferState.Complete(false, completionException);
}
protected IAsyncResult BeginGetBuffer(int count, AsyncCallback callback, object state)
{
Fx.Assert(count >= 0 && count <= bufferLength, "");
return new GetBufferAsyncResult(count, this, callback, state);
}
protected byte[] EndGetBuffer(IAsyncResult result, out int offset)
{
return GetBufferAsyncResult.End(result, out offset);
}
class GetBufferAsyncResult : AsyncResult
{
XmlStreamNodeWriter writer;
int offset;
int count;
static AsyncCompletion onComplete = new AsyncCompletion(OnComplete);
public GetBufferAsyncResult(int count, XmlStreamNodeWriter writer, AsyncCallback callback, object state)
: base(callback, state)
{
this.count = count;
this.writer = writer;
int bufferOffset = writer.offset;
bool completeSelf = false;
if (bufferOffset + count <= bufferLength)
{
this.offset = bufferOffset;
completeSelf = true;
}
else
{
IAsyncResult result = writer.BeginFlushBuffer(PrepareAsyncCompletion(onComplete), this);
completeSelf = SyncContinue(result);
}
if (completeSelf)
{
this.Complete(true);
}
}
static bool OnComplete(IAsyncResult result)
{
GetBufferAsyncResult thisPtr = (GetBufferAsyncResult)result.AsyncState;
return thisPtr.HandleFlushBuffer(result);
}
bool HandleFlushBuffer(IAsyncResult result)
{
writer.EndFlushBuffer(result);
this.offset = 0;
#if DEBUG
Fx.Assert(this.offset + this.count <= bufferLength, "");
for (int i = 0; i < this.count; i++)
{
writer.buffer[this.offset + i] = (byte)'<';
}
#endif
return true;
}
public static byte[] End(IAsyncResult result, out int offset)
{
GetBufferAsyncResult thisPtr = AsyncResult.End<GetBufferAsyncResult>(result);
offset = thisPtr.offset;
return thisPtr.writer.buffer;
}
}
protected void Advance(int count)
{
Fx.Assert(offset + count <= bufferLength, "");
offset += count;
}
void EnsureByte()
{
if (offset >= bufferLength)
{
FlushBuffer();
}
}
protected void WriteByte(byte b)
{
EnsureByte();
buffer[offset++] = b;
}
protected void WriteByte(char ch)
{
Fx.Assert(ch < 0x80, "");
WriteByte((byte)ch);
}
protected void WriteBytes(byte b1, byte b2)
{
byte[] buffer = this.buffer;
int offset = this.offset;
if (offset + 1 >= bufferLength)
{
FlushBuffer();
offset = 0;
}
buffer[offset + 0] = b1;
buffer[offset + 1] = b2;
this.offset += 2;
}
protected void WriteBytes(char ch1, char ch2)
{
Fx.Assert(ch1 < 0x80 && ch2 < 0x80, "");
WriteBytes((byte)ch1, (byte)ch2);
}
public void WriteBytes(byte[] byteBuffer, int byteOffset, int byteCount)
{
if (byteCount < bufferLength)
{
int offset;
byte[] buffer = GetBuffer(byteCount, out offset);
Buffer.BlockCopy(byteBuffer, byteOffset, buffer, offset, byteCount);
Advance(byteCount);
}
else
{
FlushBuffer();
stream.Write(byteBuffer, byteOffset, byteCount);
}
}
public IAsyncResult BeginWriteBytes(byte[] byteBuffer, int byteOffset, int byteCount, AsyncCallback callback, object state)
{
return new WriteBytesAsyncResult(byteBuffer, byteOffset, byteCount, this, callback, state);
}
public void EndWriteBytes(IAsyncResult result)
{
WriteBytesAsyncResult.End(result);
}
class WriteBytesAsyncResult : AsyncResult
{
static AsyncCompletion onHandleGetBufferComplete = new AsyncCompletion(OnHandleGetBufferComplete);
static AsyncCompletion onHandleFlushBufferComplete = new AsyncCompletion(OnHandleFlushBufferComplete);
static AsyncCompletion onHandleWrite = new AsyncCompletion(OnHandleWrite);
byte[] byteBuffer;
int byteOffset;
int byteCount;
XmlStreamNodeWriter writer;
public WriteBytesAsyncResult(byte[] byteBuffer, int byteOffset, int byteCount, XmlStreamNodeWriter writer, AsyncCallback callback, object state)
: base(callback, state)
{
this.byteBuffer = byteBuffer;
this.byteOffset = byteOffset;
this.byteCount = byteCount;
this.writer = writer;
bool completeSelf = false;
if (byteCount < bufferLength)
{
completeSelf = HandleGetBuffer(null);
}
else
{
completeSelf = HandleFlushBuffer(null);
}
if (completeSelf)
{
this.Complete(true);
}
}
static bool OnHandleGetBufferComplete(IAsyncResult result)
{
WriteBytesAsyncResult thisPtr = (WriteBytesAsyncResult)result.AsyncState;
return thisPtr.HandleGetBuffer(result);
}
static bool OnHandleFlushBufferComplete(IAsyncResult result)
{
WriteBytesAsyncResult thisPtr = (WriteBytesAsyncResult)result.AsyncState;
return thisPtr.HandleFlushBuffer(result);
}
static bool OnHandleWrite(IAsyncResult result)
{
WriteBytesAsyncResult thisPtr = (WriteBytesAsyncResult)result.AsyncState;
return thisPtr.HandleWrite(result);
}
bool HandleGetBuffer(IAsyncResult result)
{
if (result == null)
{
result = writer.BeginGetBuffer(this.byteCount, PrepareAsyncCompletion(onHandleGetBufferComplete), this);
if (!result.CompletedSynchronously)
{
return false;
}
}
int offset;
byte[] buffer = writer.EndGetBuffer(result, out offset);
Buffer.BlockCopy(this.byteBuffer, this.byteOffset, buffer, offset, this.byteCount);
writer.Advance(this.byteCount);
return true;
}
bool HandleFlushBuffer(IAsyncResult result)
{
if (result == null)
{
result = writer.BeginFlushBuffer(PrepareAsyncCompletion(onHandleFlushBufferComplete), this);
if (!result.CompletedSynchronously)
{
return false;
}
}
writer.EndFlushBuffer(result);
return HandleWrite(null);
}
bool HandleWrite(IAsyncResult result)
{
if (result == null)
{
result = writer.stream.BeginWrite(this.byteBuffer, this.byteOffset, this.byteCount, PrepareAsyncCompletion(onHandleWrite), this);
if (!result.CompletedSynchronously)
{
return false;
}
}
writer.stream.EndWrite(result);
return true;
}
public static void End(IAsyncResult result)
{
AsyncResult.End<WriteBytesAsyncResult>(result);
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe protected void UnsafeWriteBytes(byte* bytes, int byteCount)
{
FlushBuffer();
byte[] buffer = this.buffer;
while (byteCount > bufferLength)
{
for (int i = 0; i < bufferLength; i++)
buffer[i] = bytes[i];
stream.Write(buffer, 0, bufferLength);
bytes += bufferLength;
byteCount -= bufferLength;
}
if (byteCount > 0)
{
for (int i = 0; i < byteCount; i++)
buffer[i] = bytes[i];
stream.Write(buffer, 0, byteCount);
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code.",
Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")]
[SecuritySafeCritical]
unsafe protected void WriteUTF8Char(int ch)
{
if (ch < 0x80)
{
WriteByte((byte)ch);
}
else if (ch <= char.MaxValue)
{
char* chars = stackalloc char[1];
chars[0] = (char)ch;
UnsafeWriteUTF8Chars(chars, 1);
}
else
{
SurrogateChar surrogateChar = new SurrogateChar(ch);
char* chars = stackalloc char[2];
chars[0] = surrogateChar.HighChar;
chars[1] = surrogateChar.LowChar;
UnsafeWriteUTF8Chars(chars, 2);
}
}
protected void WriteUTF8Chars(byte[] chars, int charOffset, int charCount)
{
if (charCount < bufferLength)
{
int offset;
byte[] buffer = GetBuffer(charCount, out offset);
Buffer.BlockCopy(chars, charOffset, buffer, offset, charCount);
Advance(charCount);
}
else
{
FlushBuffer();
stream.Write(chars, charOffset, charCount);
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code.",
Safe = "Unsafe code is effectively encapsulated, all inputs are validated.")]
[SecuritySafeCritical]
unsafe protected void WriteUTF8Chars(string value)
{
int count = value.Length;
if (count > 0)
{
fixed (char* chars = value)
{
UnsafeWriteUTF8Chars(chars, count);
}
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe protected void UnsafeWriteUTF8Chars(char* chars, int charCount)
{
const int charChunkSize = bufferLength / maxBytesPerChar;
while (charCount > charChunkSize)
{
int offset;
int chunkSize = charChunkSize;
if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate
chunkSize--;
byte[] buffer = GetBuffer(chunkSize * maxBytesPerChar, out offset);
Advance(UnsafeGetUTF8Chars(chars, chunkSize, buffer, offset));
charCount -= chunkSize;
chars += chunkSize;
}
if (charCount > 0)
{
int offset;
byte[] buffer = GetBuffer(charCount * maxBytesPerChar, out offset);
Advance(UnsafeGetUTF8Chars(chars, charCount, buffer, offset));
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe protected void UnsafeWriteUnicodeChars(char* chars, int charCount)
{
const int charChunkSize = bufferLength / 2;
while (charCount > charChunkSize)
{
int offset;
int chunkSize = charChunkSize;
if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate
chunkSize--;
byte[] buffer = GetBuffer(chunkSize * 2, out offset);
Advance(UnsafeGetUnicodeChars(chars, chunkSize, buffer, offset));
charCount -= chunkSize;
chars += chunkSize;
}
if (charCount > 0)
{
int offset;
byte[] buffer = GetBuffer(charCount * 2, out offset);
Advance(UnsafeGetUnicodeChars(chars, charCount, buffer, offset));
}
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe protected int UnsafeGetUnicodeChars(char* chars, int charCount, byte[] buffer, int offset)
{
char* charsMax = chars + charCount;
while (chars < charsMax)
{
char value = *chars++;
buffer[offset++] = (byte)value;
value >>= 8;
buffer[offset++] = (byte)value;
}
return charCount * 2;
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe protected int UnsafeGetUTF8Length(char* chars, int charCount)
{
char* charsMax = chars + charCount;
while (chars < charsMax)
{
if (*chars >= 0x80)
break;
chars++;
}
if (chars == charsMax)
return charCount;
return (int)(chars - (charsMax - charCount)) + encoding.GetByteCount(chars, (int)(charsMax - chars));
}
[Fx.Tag.SecurityNote(Critical = "Contains unsafe code. Caller needs to validate arguments.")]
[SecurityCritical]
unsafe protected int UnsafeGetUTF8Chars(char* chars, int charCount, byte[] buffer, int offset)
{
if (charCount > 0)
{
fixed (byte* _bytes = &buffer[offset])
{
byte* bytes = _bytes;
byte* bytesMax = &bytes[buffer.Length - offset];
char* charsMax = &chars[charCount];
while (true)
{
while (chars < charsMax && *chars < 0x80)
{
*bytes = (byte)(*chars);
bytes++;
chars++;
}
if (chars >= charsMax)
break;
char* charsStart = chars;
while (chars < charsMax && *chars >= 0x80)
{
chars++;
}
bytes += encoding.GetBytes(charsStart, (int)(chars - charsStart), bytes, (int)(bytesMax - bytes));
if (chars >= charsMax)
break;
}
return (int)(bytes - _bytes);
}
}
return 0;
}
protected virtual void FlushBuffer()
{
if (offset != 0)
{
stream.Write(buffer, 0, offset);
offset = 0;
}
}
protected virtual IAsyncResult BeginFlushBuffer(AsyncCallback callback, object state)
{
return new FlushBufferAsyncResult(this, callback, state);
}
protected virtual void EndFlushBuffer(IAsyncResult result)
{
FlushBufferAsyncResult.End(result);
}
class FlushBufferAsyncResult : AsyncResult
{
static AsyncCompletion onComplete = new AsyncCompletion(OnComplete);
XmlStreamNodeWriter writer;
public FlushBufferAsyncResult(XmlStreamNodeWriter writer, AsyncCallback callback, object state)
: base(callback, state)
{
this.writer = writer;
bool completeSelf = true;
if (writer.offset != 0)
{
completeSelf = HandleFlushBuffer(null);
}
if (completeSelf)
{
this.Complete(true);
}
}
static bool OnComplete(IAsyncResult result)
{
FlushBufferAsyncResult thisPtr = (FlushBufferAsyncResult)result.AsyncState;
return thisPtr.HandleFlushBuffer(result);
}
bool HandleFlushBuffer(IAsyncResult result)
{
if (result == null)
{
result = this.writer.stream.BeginWrite(writer.buffer, 0, writer.offset, PrepareAsyncCompletion(onComplete), this);
if (!result.CompletedSynchronously)
{
return false;
}
}
this.writer.stream.EndWrite(result);
this.writer.offset = 0;
return true;
}
public static void End(IAsyncResult result)
{
AsyncResult.End<FlushBufferAsyncResult>(result);
}
}
public override void Flush()
{
FlushBuffer();
stream.Flush();
}
public override void Close()
{
if (stream != null)
{
if (ownsStream)
{
stream.Close();
}
stream = null;
}
}
internal class GetBufferArgs
{
public int Count { get; set; }
}
internal class GetBufferEventResult
{
internal byte[] Buffer { get; set; }
internal int Offset { get; set; }
}
internal class GetBufferAsyncEventArgs : AsyncEventArgs<GetBufferArgs, GetBufferEventResult>
{
}
}
}
| |
// 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Osu.Objects;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Editor
{
[TestFixture]
public class TestSceneEditorSeekSnapping : EditorClockTestScene
{
public TestSceneEditorSeekSnapping()
{
BeatDivisor.Value = 4;
}
[BackgroundDependencyLoader]
private void load()
{
var testBeatmap = new Beatmap
{
ControlPointInfo = new ControlPointInfo(),
HitObjects =
{
new HitCircle { StartTime = 0 },
new HitCircle { StartTime = 5000 }
}
};
testBeatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = 200 });
testBeatmap.ControlPointInfo.Add(100, new TimingControlPoint { BeatLength = 400 });
testBeatmap.ControlPointInfo.Add(175, new TimingControlPoint { BeatLength = 800 });
testBeatmap.ControlPointInfo.Add(350, new TimingControlPoint { BeatLength = 200 });
testBeatmap.ControlPointInfo.Add(450, new TimingControlPoint { BeatLength = 100 });
testBeatmap.ControlPointInfo.Add(500, new TimingControlPoint { BeatLength = 307.69230769230802 });
Beatmap.Value = CreateWorkingBeatmap(testBeatmap);
Child = new TimingPointVisualiser(testBeatmap, 5000) { Clock = Clock };
}
/// <summary>
/// Tests whether time is correctly seeked without snapping.
/// </summary>
[Test]
public void TestSeekNoSnapping()
{
reset();
// Forwards
AddStep("Seek(0)", () => Clock.Seek(0));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
AddStep("Seek(33)", () => Clock.Seek(33));
AddAssert("Time = 33", () => Clock.CurrentTime == 33);
AddStep("Seek(89)", () => Clock.Seek(89));
AddAssert("Time = 89", () => Clock.CurrentTime == 89);
// Backwards
AddStep("Seek(25)", () => Clock.Seek(25));
AddAssert("Time = 25", () => Clock.CurrentTime == 25);
AddStep("Seek(0)", () => Clock.Seek(0));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
/// <summary>
/// Tests whether seeking to exact beat times puts us on the beat time.
/// These are the white/yellow ticks on the graph.
/// </summary>
[Test]
public void TestSeekSnappingOnBeat()
{
reset();
AddStep("Seek(0), Snap", () => Clock.SeekSnapped(0));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
AddStep("Seek(50), Snap", () => Clock.SeekSnapped(50));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("Seek(100), Snap", () => Clock.SeekSnapped(100));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(175), Snap", () => Clock.SeekSnapped(175));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(350), Snap", () => Clock.SeekSnapped(350));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("Seek(400), Snap", () => Clock.SeekSnapped(400));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("Seek(450), Snap", () => Clock.SeekSnapped(450));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests whether seeking to somewhere in the middle between beats puts us on the expected beats.
/// For example, snapping between a white/yellow beat should put us on either the yellow or white, depending on which one we're closer too.
/// </summary>
[Test]
public void TestSeekSnappingInBetweenBeat()
{
reset();
AddStep("Seek(24), Snap", () => Clock.SeekSnapped(24));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
AddStep("Seek(26), Snap", () => Clock.SeekSnapped(26));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("Seek(150), Snap", () => Clock.SeekSnapped(150));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(170), Snap", () => Clock.SeekSnapped(170));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(274), Snap", () => Clock.SeekSnapped(274));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(276), Snap", () => Clock.SeekSnapped(276));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
}
/// <summary>
/// Tests that when seeking forward with no beat snapping, beats are never explicitly snapped to, nor the next timing point (if we've skipped it).
/// </summary>
[Test]
public void TestSeekForwardNoSnapping()
{
reset();
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 200", () => Clock.CurrentTime == 200);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests that when seeking forward with beat snapping, all beats are snapped to and timing points are never skipped.
/// </summary>
[Test]
public void TestSeekForwardSnappingOnBeat()
{
reset();
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests that when seeking forward from in-between two beats, the next beat or timing point is snapped to, and no beats are skipped.
/// This will also test being extremely close to the next beat/timing point, to ensure rounding is not an issue.
/// </summary>
[Test]
public void TestSeekForwardSnappingFromInBetweenBeat()
{
reset();
AddStep("Seek(49)", () => Clock.Seek(49));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("Seek(49.999)", () => Clock.Seek(49.999));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("Seek(99)", () => Clock.Seek(99));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(99.999)", () => Clock.Seek(99.999));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(174)", () => Clock.Seek(174));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(349)", () => Clock.Seek(349));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("Seek(399)", () => Clock.Seek(399));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("Seek(449)", () => Clock.Seek(449));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests that when seeking backward with no beat snapping, beats are never explicitly snapped to, nor the next timing point (if we've skipped it).
/// </summary>
[Test]
public void TestSeekBackwardNoSnapping()
{
reset();
AddStep("Seek(450)", () => Clock.Seek(450));
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 150", () => Clock.CurrentTime == 150);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
/// <summary>
/// Tests that when seeking backward with beat snapping, all beats are snapped to and timing points are never skipped.
/// </summary>
[Test]
public void TestSeekBackwardSnappingOnBeat()
{
reset();
AddStep("Seek(450)", () => Clock.Seek(450));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
/// <summary>
/// Tests that when seeking backward from in-between two beats, the previous beat or timing point is snapped to, and no beats are skipped.
/// This will also test being extremely close to the previous beat/timing point, to ensure rounding is not an issue.
/// </summary>
[Test]
public void TestSeekBackwardSnappingFromInBetweenBeat()
{
reset();
AddStep("Seek(451)", () => Clock.Seek(451));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
AddStep("Seek(450.999)", () => Clock.Seek(450.999));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
AddStep("Seek(401)", () => Clock.Seek(401));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("Seek(401.999)", () => Clock.Seek(401.999));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
}
/// <summary>
/// Tests that there are no rounding issues when snapping to beats within a timing point with a floating-point beatlength.
/// </summary>
[Test]
public void TestSeekingWithFloatingPointBeatLength()
{
reset();
double lastTime = 0;
AddStep("Seek(0)", () => Clock.Seek(0));
for (int i = 0; i < 9; i++)
{
AddStep("SeekForward, Snap", () =>
{
lastTime = Clock.CurrentTime;
Clock.SeekForward(true);
});
AddAssert("Time > lastTime", () => Clock.CurrentTime > lastTime);
}
for (int i = 0; i < 9; i++)
{
AddStep("SeekBackward, Snap", () =>
{
lastTime = Clock.CurrentTime;
Clock.SeekBackward(true);
});
AddAssert("Time < lastTime", () => Clock.CurrentTime < lastTime);
}
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
private void reset()
{
AddStep("Reset", () => Clock.Seek(0));
}
private class TimingPointVisualiser : CompositeDrawable
{
private readonly double length;
private readonly Drawable tracker;
public TimingPointVisualiser(IBeatmap beatmap, double length)
{
this.length = length;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Width = 0.75f;
FillFlowContainer timelineContainer;
InternalChildren = new Drawable[]
{
new Box
{
Name = "Background",
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(85f)
},
new Container
{
Name = "Tracks",
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding(15),
Children = new[]
{
tracker = new Box
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Y,
RelativePositionAxes = Axes.X,
Width = 2,
Colour = Color4.Red,
},
timelineContainer = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Spacing = new Vector2(0, 5)
},
}
}
};
var timingPoints = beatmap.ControlPointInfo.TimingPoints;
for (int i = 0; i < timingPoints.Count; i++)
{
TimingControlPoint next = i == timingPoints.Count - 1 ? null : timingPoints[i + 1];
timelineContainer.Add(new TimingPointTimeline(timingPoints[i], next?.Time ?? length, length));
}
}
protected override void Update()
{
base.Update();
tracker.X = (float)(Time.Current / length);
}
private class TimingPointTimeline : CompositeDrawable
{
public TimingPointTimeline(TimingControlPoint timingPoint, double endTime, double fullDuration)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Box createMainTick(double time) => new Box
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomCentre,
RelativePositionAxes = Axes.X,
X = (float)(time / fullDuration),
Height = 10,
Width = 2
};
Box createBeatTick(double time) => new Box
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomCentre,
RelativePositionAxes = Axes.X,
X = (float)(time / fullDuration),
Height = 5,
Width = 2,
Colour = time > endTime ? Color4.Gray : Color4.Yellow
};
AddInternal(createMainTick(timingPoint.Time));
AddInternal(createMainTick(endTime));
for (double t = timingPoint.Time + timingPoint.BeatLength / 4; t < fullDuration; t += timingPoint.BeatLength / 4)
AddInternal(createBeatTick(t));
}
}
}
}
}
| |
// 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.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using osu.Framework.Bindables;
using osu.Framework.Input.Events;
using osuTK;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A list container that enables its children to be rearranged via dragging.
/// </summary>
/// <remarks>
/// Adding duplicate items is not currently supported.
/// </remarks>
/// <typeparam name="TModel">The type of rearrangeable item.</typeparam>
public abstract class RearrangeableListContainer<TModel> : CompositeDrawable
{
private const float exp_base = 1.05f;
/// <summary>
/// The items contained by this <see cref="RearrangeableListContainer{TModel}"/>, in the order they are arranged.
/// </summary>
public readonly BindableList<TModel> Items = new BindableList<TModel>();
/// <summary>
/// The maximum exponent of the automatic scroll speed at the boundaries of this <see cref="RearrangeableListContainer{TModel}"/>.
/// </summary>
protected float MaxExponent = 50;
/// <summary>
/// The <see cref="ScrollContainer"/> containing the flow of items.
/// </summary>
protected readonly ScrollContainer<Drawable> ScrollContainer;
/// <summary>
/// The <see cref="FillFlowContainer"/> containing of all the <see cref="RearrangeableListItem{TModel}"/>s.
/// </summary>
protected readonly FillFlowContainer<RearrangeableListItem<TModel>> ListContainer;
/// <summary>
/// The mapping of <typeparamref name="TModel"/> to <see cref="RearrangeableListItem{TModel}"/>.
/// </summary>
protected IReadOnlyDictionary<TModel, RearrangeableListItem<TModel>> ItemMap => itemMap;
private readonly Dictionary<TModel, RearrangeableListItem<TModel>> itemMap = new Dictionary<TModel, RearrangeableListItem<TModel>>();
private RearrangeableListItem<TModel> currentlyDraggedItem;
private Vector2 screenSpaceDragPosition;
/// <summary>
/// Creates a new <see cref="RearrangeableListContainer{TModel}"/>.
/// </summary>
protected RearrangeableListContainer()
{
ListContainer = CreateListFillFlowContainer().With(d =>
{
d.RelativeSizeAxes = Axes.X;
d.AutoSizeAxes = Axes.Y;
d.Direction = FillDirection.Vertical;
});
InternalChild = ScrollContainer = CreateScrollContainer().With(d =>
{
d.RelativeSizeAxes = Axes.Both;
d.Child = ListContainer;
});
Items.CollectionChanged += collectionChanged;
}
private void collectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
addItems(e.NewItems);
break;
case NotifyCollectionChangedAction.Remove:
removeItems(e.OldItems);
// Explicitly reset scroll position here so that ScrollContainer doesn't retain our
// scroll position if we quickly add new items after calling a Clear().
if (Items.Count == 0)
ScrollContainer.ScrollToStart();
break;
case NotifyCollectionChangedAction.Reset:
currentlyDraggedItem = null;
ListContainer.Clear();
itemMap.Clear();
break;
case NotifyCollectionChangedAction.Replace:
removeItems(e.OldItems);
addItems(e.NewItems);
break;
}
}
private void removeItems(IList items)
{
foreach (var item in items.Cast<TModel>())
{
if (currentlyDraggedItem != null && EqualityComparer<TModel>.Default.Equals(currentlyDraggedItem.Model, item))
currentlyDraggedItem = null;
ListContainer.Remove(itemMap[item]);
itemMap.Remove(item);
}
reSort();
}
private void addItems(IList items)
{
var drawablesToAdd = new List<Drawable>();
foreach (var item in items.Cast<TModel>())
{
if (itemMap.ContainsKey(item))
{
throw new InvalidOperationException(
$"Duplicate items cannot be added to a {nameof(BindableList<TModel>)} that is currently bound with a {nameof(RearrangeableListContainer<TModel>)}.");
}
var drawable = CreateDrawable(item).With(d =>
{
d.StartArrangement += startArrangement;
d.Arrange += arrange;
d.EndArrangement += endArrangement;
});
drawablesToAdd.Add(drawable);
itemMap[item] = drawable;
}
if (!IsLoaded)
addToHierarchy(drawablesToAdd);
else
LoadComponentsAsync(drawablesToAdd, addToHierarchy);
void addToHierarchy(IEnumerable<Drawable> drawables)
{
foreach (var d in drawables.Cast<RearrangeableListItem<TModel>>())
{
// Don't add drawables whose models were removed during the async load, or drawables that are no longer attached to the contained model.
if (itemMap.TryGetValue(d.Model, out var modelDrawable) && modelDrawable == d)
ListContainer.Add(d);
}
reSort();
}
}
private void reSort()
{
for (int i = 0; i < Items.Count; i++)
{
var drawable = itemMap[Items[i]];
// If the async load didn't complete, the item wouldn't exist in the container and an exception would be thrown
if (drawable.Parent == ListContainer)
ListContainer.SetLayoutPosition(drawable, i);
}
}
private void startArrangement(RearrangeableListItem<TModel> item, DragStartEvent e)
{
currentlyDraggedItem = item;
screenSpaceDragPosition = e.ScreenSpaceMousePosition;
}
private void arrange(RearrangeableListItem<TModel> item, DragEvent e) => screenSpaceDragPosition = e.ScreenSpaceMousePosition;
private void endArrangement(RearrangeableListItem<TModel> item, DragEndEvent e) => currentlyDraggedItem = null;
protected override void Update()
{
base.Update();
if (currentlyDraggedItem != null)
updateScrollPosition();
}
protected override void UpdateAfterChildren()
{
base.UpdateAfterChildren();
if (currentlyDraggedItem != null)
updateArrangement();
}
private void updateScrollPosition()
{
Vector2 localPos = ScrollContainer.ToLocalSpace(screenSpaceDragPosition);
float scrollSpeed = 0;
if (localPos.Y < 0)
{
var power = Math.Min(MaxExponent, Math.Abs(localPos.Y));
scrollSpeed = (float)(-MathF.Pow(exp_base, power) * Clock.ElapsedFrameTime * 0.1);
}
else if (localPos.Y > ScrollContainer.DrawHeight)
{
var power = Math.Min(MaxExponent, Math.Abs(ScrollContainer.DrawHeight - localPos.Y));
scrollSpeed = (float)(MathF.Pow(exp_base, power) * Clock.ElapsedFrameTime * 0.1);
}
if ((scrollSpeed < 0 && ScrollContainer.Current > 0) || (scrollSpeed > 0 && !ScrollContainer.IsScrolledToEnd()))
ScrollContainer.ScrollBy(scrollSpeed);
}
private void updateArrangement()
{
var localPos = ListContainer.ToLocalSpace(screenSpaceDragPosition);
int srcIndex = Items.IndexOf(currentlyDraggedItem.Model);
// Find the last item with position < mouse position. Note we can't directly use
// the item positions as they are being transformed
float heightAccumulator = 0;
int dstIndex = 0;
for (; dstIndex < Items.Count; dstIndex++)
{
var drawable = itemMap[Items[dstIndex]];
if (!drawable.IsLoaded)
continue;
// Using BoundingBox here takes care of scale, paddings, etc...
float height = drawable.BoundingBox.Height;
// Rearrangement should occur only after the mid-point of items is crossed
heightAccumulator += height / 2;
// Check if the midpoint has been crossed (i.e. cursor is located above the midpoint)
if (heightAccumulator > localPos.Y)
{
if (dstIndex > srcIndex)
{
// Suppose an item is dragged just slightly below its own midpoint. The rearrangement condition (accumulator > pos) will be satisfied for the next immediate item
// but not the currently-dragged item, which will invoke a rearrangement. This is an off-by-one condition.
// Rearrangement should not occur until the midpoint of the next item is crossed, and so to fix this the next item's index is discarded.
dstIndex--;
}
break;
}
// Add the remainder of the height of the current item
heightAccumulator += height / 2 + ListContainer.Spacing.Y;
}
dstIndex = Math.Clamp(dstIndex, 0, Items.Count - 1);
if (srcIndex == dstIndex)
return;
Items.Move(srcIndex, dstIndex);
// Todo: this could be optimised, but it's a very simple iteration over all the items
reSort();
}
/// <summary>
/// Creates the <see cref="FillFlowContainer{DrawableRearrangeableListItem}"/> for the items.
/// </summary>
protected virtual FillFlowContainer<RearrangeableListItem<TModel>> CreateListFillFlowContainer() => new FillFlowContainer<RearrangeableListItem<TModel>>();
/// <summary>
/// Creates the <see cref="ScrollContainer"/> for the list of items.
/// </summary>
protected abstract ScrollContainer<Drawable> CreateScrollContainer();
/// <summary>
/// Creates the <see cref="Drawable"/> representation of an item.
/// </summary>
/// <param name="item">The item to create the <see cref="Drawable"/> representation of.</param>
/// <returns>The <see cref="RearrangeableListItem{TModel}"/>.</returns>
protected abstract RearrangeableListItem<TModel> CreateDrawable(TModel item);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
using System.Collections;
using System.Windows.Forms;
using DowUtils;
namespace Factotum{
public class ERadialLocation : IEntity
{
public static event EventHandler<EntityChangedEventArgs> Changed;
protected virtual void OnChanged(Guid? ID)
{
// Copy to a temporary variable to be thread-safe.
EventHandler<EntityChangedEventArgs> temp = Changed;
if (temp != null)
temp(this, new EntityChangedEventArgs(ID));
}
// Mapped database columns
// Use Guid?s for Primary Keys and foreign keys (whether they're nullable or not).
// Use int?, decimal?, etc for numbers (whether they're nullable or not).
// Strings, images, etc, are reference types already
private Guid? RdlDBid;
private string RdlName;
private bool RdlIsLclChg;
private bool RdlUsedInOutage;
private bool RdlIsActive;
// Textbox limits
public static int RdlNameCharLimit = 50;
// Field-specific error message strings (normally just needed for textbox data)
private string RdlNameErrMsg;
// Form level validation message
private string RdlErrMsg;
//--------------------------------------------------------
// Field Properties
//--------------------------------------------------------
// Primary key accessor
public Guid? ID
{
get { return RdlDBid; }
}
public string RadialLocationName
{
get { return RdlName; }
set { RdlName = Util.NullifyEmpty(value); }
}
public bool RadialLocationIsLclChg
{
get { return RdlIsLclChg; }
set { RdlIsLclChg = value; }
}
public bool RadialLocationUsedInOutage
{
get { return RdlUsedInOutage; }
set { RdlUsedInOutage = value; }
}
public bool RadialLocationIsActive
{
get { return RdlIsActive; }
set { RdlIsActive = value; }
}
//-----------------------------------------------------------------
// Field Level Error Messages.
// Include one for every text column
// In cases where we need to ensure data consistency, we may need
// them for other types.
//-----------------------------------------------------------------
public string RadialLocationNameErrMsg
{
get { return RdlNameErrMsg; }
}
//--------------------------------------
// Form level Error Message
//--------------------------------------
public string RadialLocationErrMsg
{
get { return RdlErrMsg; }
set { RdlErrMsg = Util.NullifyEmpty(value); }
}
//--------------------------------------
// Textbox Name Length Validation
//--------------------------------------
public bool RadialLocationNameLengthOk(string s)
{
if (s == null) return true;
if (s.Length > RdlNameCharLimit)
{
RdlNameErrMsg = string.Format("Radial Location Names cannot exceed {0} characters", RdlNameCharLimit);
return false;
}
else
{
RdlNameErrMsg = null;
return true;
}
}
//--------------------------------------
// Field-Specific Validation
// sets and clears error messages
//--------------------------------------
public bool RadialLocationNameValid(string name)
{
bool existingIsInactive;
if (!RadialLocationNameLengthOk(name)) return false;
// KEEP, MODIFY OR REMOVE THIS AS REQUIRED
// YOU MAY NEED THE NAME TO BE UNIQUE FOR A SPECIFIC PARENT, ETC..
if (NameExists(name, RdlDBid, out existingIsInactive))
{
RdlNameErrMsg = existingIsInactive ?
"That Radial Location Name exists but its status has been set to inactive." :
"That Radial Location Name is already in use.";
return false;
}
RdlNameErrMsg = null;
return true;
}
//--------------------------------------
// Constructors
//--------------------------------------
// Default constructor. Field defaults must be set here.
// Any defaults set by the database will be overridden.
public ERadialLocation()
{
this.RdlIsLclChg = false;
this.RdlUsedInOutage = false;
this.RdlIsActive = true;
}
// Constructor which loads itself from the supplied id.
// If the id is null, this gives the same result as using the default constructor.
public ERadialLocation(Guid? id) : this()
{
Load(id);
}
//--------------------------------------
// Public Methods
//--------------------------------------
//----------------------------------------------------
// Load the object from the database given a Guid?
//----------------------------------------------------
public void Load(Guid? id)
{
if (id == null) return;
SqlCeCommand cmd = Globals.cnn.CreateCommand();
SqlCeDataReader dr;
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"Select
RdlDBid,
RdlName,
RdlIsLclChg,
RdlUsedInOutage,
RdlIsActive
from RadialLocations
where RdlDBid = @p0";
cmd.Parameters.Add(new SqlCeParameter("@p0", id));
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
dr = cmd.ExecuteReader();
// The query should return one record.
// If it doesn't return anything (no match) the object is not affected
if (dr.Read())
{
// For all nullable values, replace dbNull with null
RdlDBid = (Guid?)dr[0];
RdlName = (string)dr[1];
RdlIsLclChg = (bool)dr[2];
RdlUsedInOutage = (bool)dr[3];
RdlIsActive = (bool)dr[4];
}
dr.Close();
}
//--------------------------------------
// Save the current record if it's valid
//--------------------------------------
public Guid? Save()
{
if (!Valid())
{
// Note: We're returning null if we fail,
// so don't just assume you're going to get your id back
// and set your id to the result of this function call.
return null;
}
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
if (ID == null)
{
// we are inserting a new record
// If this is not a master db, set the local change flag to true.
if (!Globals.IsMasterDB) RdlIsLclChg = true;
// first ask the database for a new Guid
cmd.CommandText = "Select Newid()";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
RdlDBid = (Guid?)(cmd.ExecuteScalar());
// Replace any nulls with dbnull
cmd.Parameters.AddRange(new SqlCeParameter[] {
new SqlCeParameter("@p0", RdlDBid),
new SqlCeParameter("@p1", RdlName),
new SqlCeParameter("@p2", RdlIsLclChg),
new SqlCeParameter("@p3", RdlUsedInOutage),
new SqlCeParameter("@p4", RdlIsActive)
});
cmd.CommandText = @"Insert Into RadialLocations (
RdlDBid,
RdlName,
RdlIsLclChg,
RdlUsedInOutage,
RdlIsActive
) values (@p0,@p1,@p2,@p3,@p4)";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Unable to insert RadialLocations row");
}
}
else
{
// we are updating an existing record
// Replace any nulls with dbnull
cmd.Parameters.AddRange(new SqlCeParameter[] {
new SqlCeParameter("@p0", RdlDBid),
new SqlCeParameter("@p1", RdlName),
new SqlCeParameter("@p2", RdlIsLclChg),
new SqlCeParameter("@p3", RdlUsedInOutage),
new SqlCeParameter("@p4", RdlIsActive)});
cmd.CommandText =
@"Update RadialLocations
set
RdlName = @p1,
RdlIsLclChg = @p2,
RdlUsedInOutage = @p3,
RdlIsActive = @p4
Where RdlDBid = @p0";
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("Unable to update radiallocations row");
}
}
OnChanged(ID);
return ID;
}
//--------------------------------------
// Validate the current record
//--------------------------------------
// Make this public so that the UI can check validation itself
// if it chooses to do so. This is also called by the Save function.
public bool Valid()
{
// First check each field to see if it's valid from the UI perspective
if (!RadialLocationNameValid(RadialLocationName)) return false;
// Check form to make sure all required fields have been filled in
if (!RequiredFieldsFilled()) return false;
// Check for incorrect field interactions...
return true;
}
//--------------------------------------
// Delete the current record
//--------------------------------------
public bool Delete(bool promptUser)
{
// If the current object doesn't reference a database record, there's nothing to do.
if (RdlDBid == null)
{
RadialLocationErrMsg = "Unable to delete. Record not found.";
return false;
}
if (RdlUsedInOutage)
{
RadialLocationErrMsg = "Unable to delete this Radial Location because it has been used in past outages.\r\nYou may wish to inactivate it instead.";
return false;
}
if (!RdlIsLclChg && !Globals.IsMasterDB)
{
RadialLocationErrMsg = "Unable to delete because this Radial Location was not added during this outage.\r\nYou may wish to inactivate instead.";
return false;
}
if (HasChildren())
{
RadialLocationErrMsg = "Unable to delete because this Radial Location is referenced by one or more grids.";
return false;
}
DialogResult rslt = DialogResult.None;
if (promptUser)
{
rslt = MessageBox.Show("Are you sure?", "Factotum: Deleting...",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
}
if (!promptUser || rslt == DialogResult.OK)
{
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
@"Delete from RadialLocations
where RdlDBid = @p0";
cmd.Parameters.Add("@p0", RdlDBid);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
int rowsAffected = cmd.ExecuteNonQuery();
// Todo: figure out how I really want to do this.
// Is there a problem with letting the database try to do cascading deletes?
// How should the user be notified of the problem??
if (rowsAffected < 1)
{
RadialLocationErrMsg = "Unable to delete. Please try again later.";
return false;
}
else
{
RadialLocationErrMsg = null;
OnChanged(ID);
return true;
}
}
else
{
return false;
}
}
private bool HasChildren()
{
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandText =
@"Select GrdDBid from Grids
where GrdRdlID = @p0";
cmd.Parameters.Add("@p0", RdlDBid);
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
object result = cmd.ExecuteScalar();
return result != null;
}
//--------------------------------------------------------------------
// Static listing methods which return collections of radiallocations
//--------------------------------------------------------------------
// This helper function builds the collection for you based on the flags you send it
// I originally had a flag that would let you indicate inactive items by appending '(inactive)'
// to the name. This was a bad idea, because sometimes the objects in this collection
// will get modified and saved back to the database -- with the extra text appended to the name.
public static ERadialLocationCollection ListByName(bool showinactive, bool addNoSelection)
{
ERadialLocation radiallocation;
ERadialLocationCollection radiallocations = new ERadialLocationCollection();
if (addNoSelection)
{
// Insert a default item with name "<No Selection>"
radiallocation = new ERadialLocation();
radiallocation.RdlName = "<No Selection>";
radiallocations.Add(radiallocation);
}
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
string qry = @"Select
RdlDBid,
RdlName,
RdlIsLclChg,
RdlUsedInOutage,
RdlIsActive
from RadialLocations";
if (!showinactive)
qry += " where RdlIsActive = 1";
qry += " order by RdlName";
cmd.CommandText = qry;
SqlCeDataReader dr;
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
dr = cmd.ExecuteReader();
// Build new objects and add them to the collection
while (dr.Read())
{
radiallocation = new ERadialLocation((Guid?)dr[0]);
radiallocation.RdlName = (string)(dr[1]);
radiallocation.RdlIsLclChg = (bool)(dr[2]);
radiallocation.RdlUsedInOutage = (bool)(dr[3]);
radiallocation.RdlIsActive = (bool)(dr[4]);
radiallocations.Add(radiallocation);
}
// Finish up
dr.Close();
return radiallocations;
}
// Get a Default data view with all columns that a user would likely want to see.
// You can bind this view to a DataGridView, hide the columns you don't need, filter, etc.
// I decided not to indicate inactive in the names of inactive items. The 'user'
// can always show the inactive column if they wish.
public static DataView GetDefaultDataView()
{
DataSet ds = new DataSet();
DataView dv;
SqlCeDataAdapter da = new SqlCeDataAdapter();
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
// Changing the booleans to 'Yes' and 'No' eliminates the silly checkboxes and
// makes the column sortable.
// You'll likely want to modify this query further, joining in other tables, etc.
string qry = @"Select
RdlDBid as ID,
RdlName as RadialLocationName,
CASE
WHEN RdlIsLclChg = 0 THEN 'No'
ELSE 'Yes'
END as RadialLocationIsLclChg,
CASE
WHEN RdlUsedInOutage = 0 THEN 'No'
ELSE 'Yes'
END as RadialLocationUsedInOutage,
CASE
WHEN RdlIsActive = 0 THEN 'No'
ELSE 'Yes'
END as RadialLocationIsActive
from RadialLocations";
cmd.CommandText = qry;
da.SelectCommand = cmd;
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
da.Fill(ds);
dv = new DataView(ds.Tables[0]);
return dv;
}
//--------------------------------------
// Private utilities
//--------------------------------------
// Check if the name exists for any records besides the current one
// This is used to show an error when the user tabs away from the field.
// We don't want to show an error if the user has left the field blank.
// If it's a required field, we'll catch it when the user hits save.
private bool NameExists(string name, Guid? id, out bool existingIsInactive)
{
existingIsInactive = false;
if (Util.IsNullOrEmpty(name)) return false;
SqlCeCommand cmd = Globals.cnn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new SqlCeParameter("@p1", name));
if (id == null)
{
cmd.CommandText = "Select RdlIsActive from RadialLocations where RdlName = @p1";
}
else
{
cmd.CommandText = "Select RdlIsActive from RadialLocations where RdlName = @p1 and RdlDBid != @p0";
cmd.Parameters.Add(new SqlCeParameter("@p0", id));
}
if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open();
object val = cmd.ExecuteScalar();
bool exists = (val != null);
if (exists) existingIsInactive = !(bool)val;
return exists;
}
// Check for required fields, setting the individual error messages
private bool RequiredFieldsFilled()
{
bool allFilled = true;
if (RadialLocationName == null)
{
RdlNameErrMsg = "A unique RadialLocation Name is required";
allFilled = false;
}
else
{
RdlNameErrMsg = null;
}
return allFilled;
}
}
//--------------------------------------
// RadialLocation Collection class
//--------------------------------------
public class ERadialLocationCollection : CollectionBase
{
//this event is fired when the collection's items have changed
public event EventHandler Changed;
//this is the constructor of the collection.
public ERadialLocationCollection()
{ }
//the indexer of the collection
public ERadialLocation this[int index]
{
get
{
return (ERadialLocation)this.List[index];
}
}
//this method fires the Changed event.
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
{
Changed(this, e);
}
}
public bool ContainsID(Guid? ID)
{
if (ID == null) return false;
foreach (ERadialLocation radiallocation in InnerList)
{
if (radiallocation.ID == ID)
return true;
}
return false;
}
//returns the index of an item in the collection
public int IndexOf(ERadialLocation item)
{
return InnerList.IndexOf(item);
}
//adds an item to the collection
public void Add(ERadialLocation item)
{
this.List.Add(item);
OnChanged(EventArgs.Empty);
}
//inserts an item in the collection at a specified index
public void Insert(int index, ERadialLocation item)
{
this.List.Insert(index, item);
OnChanged(EventArgs.Empty);
}
//removes an item from the collection.
public void Remove(ERadialLocation item)
{
this.List.Remove(item);
OnChanged(EventArgs.Empty);
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
namespace IronPython.Compiler.Ast {
/// <summary>
/// PythonWalker class - The Python AST Walker (default result is true)
/// </summary>
public class PythonWalker {
// This is generated by the scripts\generate_walker.py script.
// That will scan all types that derive from the IronPython AST nodes and inject into here.
#region Generated Python AST Walker
// *** BEGIN GENERATED CODE ***
// generated by function: gen_python_walker from: generate_walker.py
// AndExpression
public virtual bool Walk(AndExpression node) { return true; }
public virtual void PostWalk(AndExpression node) { }
// BackQuoteExpression
public virtual bool Walk(BackQuoteExpression node) { return true; }
public virtual void PostWalk(BackQuoteExpression node) { }
// BinaryExpression
public virtual bool Walk(BinaryExpression node) { return true; }
public virtual void PostWalk(BinaryExpression node) { }
// CallExpression
public virtual bool Walk(CallExpression node) { return true; }
public virtual void PostWalk(CallExpression node) { }
// ConditionalExpression
public virtual bool Walk(ConditionalExpression node) { return true; }
public virtual void PostWalk(ConditionalExpression node) { }
// ConstantExpression
public virtual bool Walk(ConstantExpression node) { return true; }
public virtual void PostWalk(ConstantExpression node) { }
// DictionaryComprehension
public virtual bool Walk(DictionaryComprehension node) { return true; }
public virtual void PostWalk(DictionaryComprehension node) { }
// DictionaryExpression
public virtual bool Walk(DictionaryExpression node) { return true; }
public virtual void PostWalk(DictionaryExpression node) { }
// ErrorExpression
public virtual bool Walk(ErrorExpression node) { return true; }
public virtual void PostWalk(ErrorExpression node) { }
// GeneratorExpression
public virtual bool Walk(GeneratorExpression node) { return true; }
public virtual void PostWalk(GeneratorExpression node) { }
// IndexExpression
public virtual bool Walk(IndexExpression node) { return true; }
public virtual void PostWalk(IndexExpression node) { }
// LambdaExpression
public virtual bool Walk(LambdaExpression node) { return true; }
public virtual void PostWalk(LambdaExpression node) { }
// ListComprehension
public virtual bool Walk(ListComprehension node) { return true; }
public virtual void PostWalk(ListComprehension node) { }
// ListExpression
public virtual bool Walk(ListExpression node) { return true; }
public virtual void PostWalk(ListExpression node) { }
// MemberExpression
public virtual bool Walk(MemberExpression node) { return true; }
public virtual void PostWalk(MemberExpression node) { }
// NameExpression
public virtual bool Walk(NameExpression node) { return true; }
public virtual void PostWalk(NameExpression node) { }
// OrExpression
public virtual bool Walk(OrExpression node) { return true; }
public virtual void PostWalk(OrExpression node) { }
// ParenthesisExpression
public virtual bool Walk(ParenthesisExpression node) { return true; }
public virtual void PostWalk(ParenthesisExpression node) { }
// SetComprehension
public virtual bool Walk(SetComprehension node) { return true; }
public virtual void PostWalk(SetComprehension node) { }
// SetExpression
public virtual bool Walk(SetExpression node) { return true; }
public virtual void PostWalk(SetExpression node) { }
// SliceExpression
public virtual bool Walk(SliceExpression node) { return true; }
public virtual void PostWalk(SliceExpression node) { }
// TupleExpression
public virtual bool Walk(TupleExpression node) { return true; }
public virtual void PostWalk(TupleExpression node) { }
// UnaryExpression
public virtual bool Walk(UnaryExpression node) { return true; }
public virtual void PostWalk(UnaryExpression node) { }
// YieldExpression
public virtual bool Walk(YieldExpression node) { return true; }
public virtual void PostWalk(YieldExpression node) { }
// AssertStatement
public virtual bool Walk(AssertStatement node) { return true; }
public virtual void PostWalk(AssertStatement node) { }
// AssignmentStatement
public virtual bool Walk(AssignmentStatement node) { return true; }
public virtual void PostWalk(AssignmentStatement node) { }
// AugmentedAssignStatement
public virtual bool Walk(AugmentedAssignStatement node) { return true; }
public virtual void PostWalk(AugmentedAssignStatement node) { }
// BreakStatement
public virtual bool Walk(BreakStatement node) { return true; }
public virtual void PostWalk(BreakStatement node) { }
// ClassDefinition
public virtual bool Walk(ClassDefinition node) { return true; }
public virtual void PostWalk(ClassDefinition node) { }
// ContinueStatement
public virtual bool Walk(ContinueStatement node) { return true; }
public virtual void PostWalk(ContinueStatement node) { }
// DelStatement
public virtual bool Walk(DelStatement node) { return true; }
public virtual void PostWalk(DelStatement node) { }
// EmptyStatement
public virtual bool Walk(EmptyStatement node) { return true; }
public virtual void PostWalk(EmptyStatement node) { }
// ExecStatement
public virtual bool Walk(ExecStatement node) { return true; }
public virtual void PostWalk(ExecStatement node) { }
// ExpressionStatement
public virtual bool Walk(ExpressionStatement node) { return true; }
public virtual void PostWalk(ExpressionStatement node) { }
// ForStatement
public virtual bool Walk(ForStatement node) { return true; }
public virtual void PostWalk(ForStatement node) { }
// FromImportStatement
public virtual bool Walk(FromImportStatement node) { return true; }
public virtual void PostWalk(FromImportStatement node) { }
// FunctionDefinition
public virtual bool Walk(FunctionDefinition node) { return true; }
public virtual void PostWalk(FunctionDefinition node) { }
// GlobalStatement
public virtual bool Walk(GlobalStatement node) { return true; }
public virtual void PostWalk(GlobalStatement node) { }
// IfStatement
public virtual bool Walk(IfStatement node) { return true; }
public virtual void PostWalk(IfStatement node) { }
// ImportStatement
public virtual bool Walk(ImportStatement node) { return true; }
public virtual void PostWalk(ImportStatement node) { }
// PythonAst
public virtual bool Walk(PythonAst node) { return true; }
public virtual void PostWalk(PythonAst node) { }
// RaiseStatement
public virtual bool Walk(RaiseStatement node) { return true; }
public virtual void PostWalk(RaiseStatement node) { }
// ReturnStatement
public virtual bool Walk(ReturnStatement node) { return true; }
public virtual void PostWalk(ReturnStatement node) { }
// SuiteStatement
public virtual bool Walk(SuiteStatement node) { return true; }
public virtual void PostWalk(SuiteStatement node) { }
// TryStatement
public virtual bool Walk(TryStatement node) { return true; }
public virtual void PostWalk(TryStatement node) { }
// WhileStatement
public virtual bool Walk(WhileStatement node) { return true; }
public virtual void PostWalk(WhileStatement node) { }
// WithStatement
public virtual bool Walk(WithStatement node) { return true; }
public virtual void PostWalk(WithStatement node) { }
// Arg
public virtual bool Walk(Arg node) { return true; }
public virtual void PostWalk(Arg node) { }
// ComprehensionFor
public virtual bool Walk(ComprehensionFor node) { return true; }
public virtual void PostWalk(ComprehensionFor node) { }
// ComprehensionIf
public virtual bool Walk(ComprehensionIf node) { return true; }
public virtual void PostWalk(ComprehensionIf node) { }
// DottedName
public virtual bool Walk(DottedName node) { return true; }
public virtual void PostWalk(DottedName node) { }
// IfStatementTest
public virtual bool Walk(IfStatementTest node) { return true; }
public virtual void PostWalk(IfStatementTest node) { }
// ModuleName
public virtual bool Walk(ModuleName node) { return true; }
public virtual void PostWalk(ModuleName node) { }
// Parameter
public virtual bool Walk(Parameter node) { return true; }
public virtual void PostWalk(Parameter node) { }
// RelativeModuleName
public virtual bool Walk(RelativeModuleName node) { return true; }
public virtual void PostWalk(RelativeModuleName node) { }
// SublistParameter
public virtual bool Walk(SublistParameter node) { return true; }
public virtual void PostWalk(SublistParameter node) { }
// TryStatementHandler
public virtual bool Walk(TryStatementHandler node) { return true; }
public virtual void PostWalk(TryStatementHandler node) { }
// *** END GENERATED CODE ***
#endregion
}
/// <summary>
/// PythonWalkerNonRecursive class - The Python AST Walker (default result is false)
/// </summary>
public class PythonWalkerNonRecursive : PythonWalker {
#region Generated Python AST Walker Nonrecursive
// *** BEGIN GENERATED CODE ***
// generated by function: gen_python_walker_nr from: generate_walker.py
// AndExpression
public override bool Walk(AndExpression node) { return false; }
public override void PostWalk(AndExpression node) { }
// BackQuoteExpression
public override bool Walk(BackQuoteExpression node) { return false; }
public override void PostWalk(BackQuoteExpression node) { }
// BinaryExpression
public override bool Walk(BinaryExpression node) { return false; }
public override void PostWalk(BinaryExpression node) { }
// CallExpression
public override bool Walk(CallExpression node) { return false; }
public override void PostWalk(CallExpression node) { }
// ConditionalExpression
public override bool Walk(ConditionalExpression node) { return false; }
public override void PostWalk(ConditionalExpression node) { }
// ConstantExpression
public override bool Walk(ConstantExpression node) { return false; }
public override void PostWalk(ConstantExpression node) { }
// DictionaryComprehension
public override bool Walk(DictionaryComprehension node) { return false; }
public override void PostWalk(DictionaryComprehension node) { }
// DictionaryExpression
public override bool Walk(DictionaryExpression node) { return false; }
public override void PostWalk(DictionaryExpression node) { }
// ErrorExpression
public override bool Walk(ErrorExpression node) { return false; }
public override void PostWalk(ErrorExpression node) { }
// GeneratorExpression
public override bool Walk(GeneratorExpression node) { return false; }
public override void PostWalk(GeneratorExpression node) { }
// IndexExpression
public override bool Walk(IndexExpression node) { return false; }
public override void PostWalk(IndexExpression node) { }
// LambdaExpression
public override bool Walk(LambdaExpression node) { return false; }
public override void PostWalk(LambdaExpression node) { }
// ListComprehension
public override bool Walk(ListComprehension node) { return false; }
public override void PostWalk(ListComprehension node) { }
// ListExpression
public override bool Walk(ListExpression node) { return false; }
public override void PostWalk(ListExpression node) { }
// MemberExpression
public override bool Walk(MemberExpression node) { return false; }
public override void PostWalk(MemberExpression node) { }
// NameExpression
public override bool Walk(NameExpression node) { return false; }
public override void PostWalk(NameExpression node) { }
// OrExpression
public override bool Walk(OrExpression node) { return false; }
public override void PostWalk(OrExpression node) { }
// ParenthesisExpression
public override bool Walk(ParenthesisExpression node) { return false; }
public override void PostWalk(ParenthesisExpression node) { }
// SetComprehension
public override bool Walk(SetComprehension node) { return false; }
public override void PostWalk(SetComprehension node) { }
// SetExpression
public override bool Walk(SetExpression node) { return false; }
public override void PostWalk(SetExpression node) { }
// SliceExpression
public override bool Walk(SliceExpression node) { return false; }
public override void PostWalk(SliceExpression node) { }
// TupleExpression
public override bool Walk(TupleExpression node) { return false; }
public override void PostWalk(TupleExpression node) { }
// UnaryExpression
public override bool Walk(UnaryExpression node) { return false; }
public override void PostWalk(UnaryExpression node) { }
// YieldExpression
public override bool Walk(YieldExpression node) { return false; }
public override void PostWalk(YieldExpression node) { }
// AssertStatement
public override bool Walk(AssertStatement node) { return false; }
public override void PostWalk(AssertStatement node) { }
// AssignmentStatement
public override bool Walk(AssignmentStatement node) { return false; }
public override void PostWalk(AssignmentStatement node) { }
// AugmentedAssignStatement
public override bool Walk(AugmentedAssignStatement node) { return false; }
public override void PostWalk(AugmentedAssignStatement node) { }
// BreakStatement
public override bool Walk(BreakStatement node) { return false; }
public override void PostWalk(BreakStatement node) { }
// ClassDefinition
public override bool Walk(ClassDefinition node) { return false; }
public override void PostWalk(ClassDefinition node) { }
// ContinueStatement
public override bool Walk(ContinueStatement node) { return false; }
public override void PostWalk(ContinueStatement node) { }
// DelStatement
public override bool Walk(DelStatement node) { return false; }
public override void PostWalk(DelStatement node) { }
// EmptyStatement
public override bool Walk(EmptyStatement node) { return false; }
public override void PostWalk(EmptyStatement node) { }
// ExecStatement
public override bool Walk(ExecStatement node) { return false; }
public override void PostWalk(ExecStatement node) { }
// ExpressionStatement
public override bool Walk(ExpressionStatement node) { return false; }
public override void PostWalk(ExpressionStatement node) { }
// ForStatement
public override bool Walk(ForStatement node) { return false; }
public override void PostWalk(ForStatement node) { }
// FromImportStatement
public override bool Walk(FromImportStatement node) { return false; }
public override void PostWalk(FromImportStatement node) { }
// FunctionDefinition
public override bool Walk(FunctionDefinition node) { return false; }
public override void PostWalk(FunctionDefinition node) { }
// GlobalStatement
public override bool Walk(GlobalStatement node) { return false; }
public override void PostWalk(GlobalStatement node) { }
// IfStatement
public override bool Walk(IfStatement node) { return false; }
public override void PostWalk(IfStatement node) { }
// ImportStatement
public override bool Walk(ImportStatement node) { return false; }
public override void PostWalk(ImportStatement node) { }
// PythonAst
public override bool Walk(PythonAst node) { return false; }
public override void PostWalk(PythonAst node) { }
// RaiseStatement
public override bool Walk(RaiseStatement node) { return false; }
public override void PostWalk(RaiseStatement node) { }
// ReturnStatement
public override bool Walk(ReturnStatement node) { return false; }
public override void PostWalk(ReturnStatement node) { }
// SuiteStatement
public override bool Walk(SuiteStatement node) { return false; }
public override void PostWalk(SuiteStatement node) { }
// TryStatement
public override bool Walk(TryStatement node) { return false; }
public override void PostWalk(TryStatement node) { }
// WhileStatement
public override bool Walk(WhileStatement node) { return false; }
public override void PostWalk(WhileStatement node) { }
// WithStatement
public override bool Walk(WithStatement node) { return false; }
public override void PostWalk(WithStatement node) { }
// Arg
public override bool Walk(Arg node) { return false; }
public override void PostWalk(Arg node) { }
// ComprehensionFor
public override bool Walk(ComprehensionFor node) { return false; }
public override void PostWalk(ComprehensionFor node) { }
// ComprehensionIf
public override bool Walk(ComprehensionIf node) { return false; }
public override void PostWalk(ComprehensionIf node) { }
// DottedName
public override bool Walk(DottedName node) { return false; }
public override void PostWalk(DottedName node) { }
// IfStatementTest
public override bool Walk(IfStatementTest node) { return false; }
public override void PostWalk(IfStatementTest node) { }
// ModuleName
public override bool Walk(ModuleName node) { return false; }
public override void PostWalk(ModuleName node) { }
// Parameter
public override bool Walk(Parameter node) { return false; }
public override void PostWalk(Parameter node) { }
// RelativeModuleName
public override bool Walk(RelativeModuleName node) { return false; }
public override void PostWalk(RelativeModuleName node) { }
// SublistParameter
public override bool Walk(SublistParameter node) { return false; }
public override void PostWalk(SublistParameter node) { }
// TryStatementHandler
public override bool Walk(TryStatementHandler node) { return false; }
public override void PostWalk(TryStatementHandler node) { }
// *** END GENERATED CODE ***
#endregion
}
}
| |
using UnityEngine;
using System.IO;
using System.Collections.Generic;
#if UNITY_ANDROID || UNITY_IOS
using NativeShareNamespace;
#endif
#pragma warning disable 0414
public class NativeShare
{
public enum ShareResult { Unknown = 0, Shared = 1, NotShared = 2 };
public delegate void ShareResultCallback( ShareResult result, string shareTarget );
#if !UNITY_EDITOR && UNITY_ANDROID
private static AndroidJavaClass m_ajc = null;
private static AndroidJavaClass AJC
{
get
{
if( m_ajc == null )
m_ajc = new AndroidJavaClass( "com.yasirkula.unity.NativeShare" );
return m_ajc;
}
}
private static AndroidJavaObject m_context = null;
private static AndroidJavaObject Context
{
get
{
if( m_context == null )
{
using( AndroidJavaObject unityClass = new AndroidJavaClass( "com.unity3d.player.UnityPlayer" ) )
{
m_context = unityClass.GetStatic<AndroidJavaObject>( "currentActivity" );
}
}
return m_context;
}
}
#elif !UNITY_EDITOR && UNITY_IOS
[System.Runtime.InteropServices.DllImport( "__Internal" )]
private static extern void _NativeShare_Share( string[] files, int filesCount, string subject, string text, string link );
#endif
private string subject = string.Empty;
private string text = string.Empty;
private string title = string.Empty;
private string url = string.Empty;
#if UNITY_EDITOR || UNITY_ANDROID
private readonly List<string> targetPackages = new List<string>( 0 );
private readonly List<string> targetClasses = new List<string>( 0 );
#endif
private readonly List<string> files = new List<string>( 0 );
private readonly List<string> mimes = new List<string>( 0 );
private ShareResultCallback callback;
public NativeShare SetSubject( string subject )
{
this.subject = subject ?? string.Empty;
return this;
}
public NativeShare SetText( string text )
{
this.text = text ?? string.Empty;
return this;
}
public NativeShare SetUrl( string url )
{
this.url = url ?? string.Empty;
return this;
}
public NativeShare SetTitle( string title )
{
this.title = title ?? string.Empty;
return this;
}
public NativeShare SetCallback( ShareResultCallback callback )
{
this.callback = callback;
return this;
}
public NativeShare AddTarget( string androidPackageName, string androidClassName = null )
{
#if UNITY_EDITOR || UNITY_ANDROID
if( !string.IsNullOrEmpty( androidPackageName ) )
{
if( androidClassName == null )
androidClassName = string.Empty;
bool isUnique = true;
for( int i = 0; i < targetPackages.Count; i++ )
{
if( targetPackages[i] == androidPackageName && targetClasses[i] == androidClassName )
{
isUnique = false;
break;
}
}
if( isUnique )
{
targetPackages.Add( androidPackageName );
targetClasses.Add( androidClassName );
}
}
#endif
return this;
}
public NativeShare AddFile( string filePath, string mime = null )
{
if( !string.IsNullOrEmpty( filePath ) && File.Exists( filePath ) )
{
files.Add( filePath );
mimes.Add( mime ?? string.Empty );
}
else
Debug.LogError( "Share Error: file does not exist at path or permission denied: " + filePath );
return this;
}
public NativeShare AddFile( Texture2D texture, string createdFileName = "Image.png" )
{
if( !texture )
Debug.LogError( "Share Error: Texture does not exist!" );
else
{
if( string.IsNullOrEmpty( createdFileName ) )
createdFileName = "Image.png";
bool saveAsJpeg;
if( createdFileName.EndsWith( ".jpeg", System.StringComparison.OrdinalIgnoreCase ) || createdFileName.EndsWith( ".jpg", System.StringComparison.OrdinalIgnoreCase ) )
saveAsJpeg = true;
else
{
if( !createdFileName.EndsWith( ".png", System.StringComparison.OrdinalIgnoreCase ) )
createdFileName += ".png";
saveAsJpeg = false;
}
string filePath = Path.Combine( Application.temporaryCachePath, createdFileName );
File.WriteAllBytes( filePath, GetTextureBytes( texture, saveAsJpeg ) );
AddFile( filePath, saveAsJpeg ? "image/jpeg" : "image/png" );
}
return this;
}
public void Share()
{
if( files.Count == 0 && subject.Length == 0 && text.Length == 0 && url.Length == 0 )
{
Debug.LogWarning( "Share Error: attempting to share nothing!" );
return;
}
#if UNITY_EDITOR
Debug.Log( "Shared!" );
if( callback != null )
callback( ShareResult.Shared, null );
#elif UNITY_ANDROID
AJC.CallStatic( "Share", Context, new NSShareResultCallbackAndroid( callback ), targetPackages.ToArray(), targetClasses.ToArray(), files.ToArray(), mimes.ToArray(), subject, CombineURLWithText(), title );
#elif UNITY_IOS
NSShareResultCallbackiOS.Initialize( callback );
if( files.Count == 0 )
_NativeShare_Share( new string[0], 0, subject, text, GetURLWithScheme() );
else
{
// While sharing both a URL and a file, some apps either don't show up in share sheet or omit the file
// If we append URL to text, the issue is resolved for at least some of these apps
_NativeShare_Share( files.ToArray(), files.Count, subject, CombineURLWithText(), "" );
}
#else
Debug.LogWarning( "NativeShare is not supported on this platform!" );
#endif
}
#region Utility Functions
public static bool TargetExists( string androidPackageName, string androidClassName = null )
{
#if !UNITY_EDITOR && UNITY_ANDROID
if( string.IsNullOrEmpty( androidPackageName ) )
return false;
if( androidClassName == null )
androidClassName = string.Empty;
return AJC.CallStatic<bool>( "TargetExists", Context, androidPackageName, androidClassName );
#else
return true;
#endif
}
public static bool FindTarget( out string androidPackageName, out string androidClassName, string packageNameRegex, string classNameRegex = null )
{
androidPackageName = null;
androidClassName = null;
#if !UNITY_EDITOR && UNITY_ANDROID
if( string.IsNullOrEmpty( packageNameRegex ) )
return false;
if( classNameRegex == null )
classNameRegex = string.Empty;
string result = AJC.CallStatic<string>( "FindMatchingTarget", Context, packageNameRegex, classNameRegex );
if( string.IsNullOrEmpty( result ) )
return false;
int splitIndex = result.IndexOf( '>' );
if( splitIndex <= 0 || splitIndex >= result.Length - 1 )
return false;
androidPackageName = result.Substring( 0, splitIndex );
androidClassName = result.Substring( splitIndex + 1 );
return true;
#else
return false;
#endif
}
#endregion
#region Internal Functions
private string GetURLWithScheme()
{
return ( url.Length == 0 || url.Contains( "://" ) ) ? url : ( "https://" + url );
}
private string CombineURLWithText()
{
if( url.Length == 0 || text.IndexOf( url, System.StringComparison.OrdinalIgnoreCase ) >= 0 )
return text;
else if( text.Length == 0 )
return GetURLWithScheme();
else
return string.Concat( text, " ", GetURLWithScheme() );
}
private byte[] GetTextureBytes( Texture2D texture, bool isJpeg )
{
try
{
return isJpeg ? texture.EncodeToJPG( 100 ) : texture.EncodeToPNG();
}
catch( UnityException )
{
return GetTextureBytesFromCopy( texture, isJpeg );
}
catch( System.ArgumentException )
{
return GetTextureBytesFromCopy( texture, isJpeg );
}
#pragma warning disable 0162
return null;
#pragma warning restore 0162
}
private byte[] GetTextureBytesFromCopy( Texture2D texture, bool isJpeg )
{
// Texture is marked as non-readable, create a readable copy and share it instead
Debug.LogWarning( "Sharing non-readable textures is slower than sharing readable textures" );
Texture2D sourceTexReadable = null;
RenderTexture rt = RenderTexture.GetTemporary( texture.width, texture.height );
RenderTexture activeRT = RenderTexture.active;
try
{
Graphics.Blit( texture, rt );
RenderTexture.active = rt;
sourceTexReadable = new Texture2D( texture.width, texture.height, isJpeg ? TextureFormat.RGB24 : TextureFormat.RGBA32, false );
sourceTexReadable.ReadPixels( new Rect( 0, 0, texture.width, texture.height ), 0, 0, false );
sourceTexReadable.Apply( false, false );
}
catch( System.Exception e )
{
Debug.LogException( e );
Object.DestroyImmediate( sourceTexReadable );
return null;
}
finally
{
RenderTexture.active = activeRT;
RenderTexture.ReleaseTemporary( rt );
}
try
{
return isJpeg ? sourceTexReadable.EncodeToJPG( 100 ) : sourceTexReadable.EncodeToPNG();
}
catch( System.Exception e )
{
Debug.LogException( e );
return null;
}
finally
{
Object.DestroyImmediate( sourceTexReadable );
}
}
#endregion
}
#pragma warning restore 0414
| |
// Copyright (c) 2016-2022 James Skimming. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace Castle.DynamicProxy;
using Castle.DynamicProxy.InterfaceProxies;
using Xunit;
using Xunit.Abstractions;
public static class ProxyGen
{
public static readonly IProxyGenerator Generator = new ProxyGenerator();
public static IInterfaceToProxy CreateProxy(ListLogger log, IAsyncInterceptor interceptor)
{
return CreateProxy(log, interceptor, out _);
}
public static IInterfaceToProxy CreateProxy(
ListLogger log,
IAsyncInterceptor interceptor,
out ClassWithInterfaceToProxy target)
{
var localTarget = new ClassWithInterfaceToProxy(log);
target = localTarget;
return CreateProxy(() => localTarget, interceptor);
}
public static IInterfaceToProxy CreateProxy(Func<IInterfaceToProxy> factory, IAsyncInterceptor interceptor)
{
IInterfaceToProxy implementation = factory();
IInterfaceToProxy proxy = Generator.CreateInterfaceProxyWithTargetInterface(implementation, interceptor);
return proxy;
}
}
public class AsyncDeterminationInterceptorShould
{
private readonly ITestOutputHelper _output;
public AsyncDeterminationInterceptorShould(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void Implement_IInterceptor()
{
var sut = new AsyncDeterminationInterceptor(new TestAsyncInterceptor(new ListLogger(_output)));
Assert.IsAssignableFrom<IInterceptor>(sut);
}
}
public class WhenInterceptingSynchronousVoidMethods
{
private const string MethodName = nameof(IInterfaceToProxy.SynchronousVoidMethod);
private readonly ListLogger _log;
private readonly IInterfaceToProxy _proxy;
public WhenInterceptingSynchronousVoidMethods(ITestOutputHelper output)
{
_log = new ListLogger(output);
_proxy = ProxyGen.CreateProxy(_log, new TestAsyncInterceptor(_log));
}
[Fact]
public void ShouldLog4Entries()
{
// Act
_proxy.SynchronousVoidMethod();
// Assert
Assert.Equal(4, _log.Count);
}
[Fact]
public void ShouldAllowInterceptionPriorToInvocation()
{
// Act
_proxy.SynchronousVoidMethod();
// Assert
Assert.Equal($"{MethodName}:InterceptStart", _log[0]);
}
[Fact]
public void ShouldAllowInterceptionAfterInvocation()
{
// Act
_proxy.SynchronousVoidMethod();
// Assert
Assert.Equal($"{MethodName}:InterceptEnd", _log[3]);
}
}
public class WhenInterceptingSynchronousResultMethods
{
private const string MethodName = nameof(IInterfaceToProxy.SynchronousResultMethod);
private readonly ListLogger _log;
private readonly IInterfaceToProxy _proxy;
public WhenInterceptingSynchronousResultMethods(ITestOutputHelper output)
{
_log = new ListLogger(output);
_proxy = ProxyGen.CreateProxy(_log, new TestAsyncInterceptor(_log));
}
[Fact]
public void ShouldLog4Entries()
{
// Act
Guid result = _proxy.SynchronousResultMethod();
// Assert
Assert.NotEqual(Guid.Empty, result);
Assert.Equal(4, _log.Count);
}
[Fact]
public void ShouldAllowInterceptionPriorToInvocation()
{
// Act
_proxy.SynchronousResultMethod();
// Assert
Assert.Equal($"{MethodName}:InterceptStart", _log[0]);
}
[Fact]
public void ShouldAllowInterceptionAfterInvocation()
{
// Act
_proxy.SynchronousResultMethod();
// Assert
Assert.Equal($"{MethodName}:InterceptEnd", _log[3]);
}
}
public class WhenInterceptingAsynchronousVoidMethods
{
private const string MethodName = nameof(IInterfaceToProxy.AsynchronousVoidMethod);
private readonly ListLogger _log;
private readonly IInterfaceToProxy _proxy;
public WhenInterceptingAsynchronousVoidMethods(ITestOutputHelper output)
{
_log = new ListLogger(output);
_proxy = ProxyGen.CreateProxy(_log, new TestAsyncInterceptor(_log));
}
[Fact]
public async Task ShouldLog4Entries()
{
// Act
await _proxy.AsynchronousVoidMethod().ConfigureAwait(false);
// Assert
Assert.Equal(4, _log.Count);
}
[Fact]
public async Task ShouldAllowInterceptionPriorToInvocation()
{
// Act
await _proxy.AsynchronousVoidMethod().ConfigureAwait(false);
// Assert
Assert.Equal($"{MethodName}:InterceptStart", _log[0]);
}
[Fact]
public async Task ShouldAllowInterceptionAfterInvocation()
{
// Act
await _proxy.AsynchronousVoidMethod().ConfigureAwait(false);
// Assert
Assert.Equal($"{MethodName}:InterceptEnd", _log[3]);
}
}
public class WhenInterceptingAsynchronousResultMethods
{
private const string MethodName = nameof(IInterfaceToProxy.AsynchronousResultMethod);
private readonly ListLogger _log;
private readonly IInterfaceToProxy _proxy;
public WhenInterceptingAsynchronousResultMethods(ITestOutputHelper output)
{
_log = new ListLogger(output);
_proxy = ProxyGen.CreateProxy(_log, new TestAsyncInterceptor(_log));
}
[Fact]
public async Task ShouldLog4Entries()
{
// Act
Guid result = await _proxy.AsynchronousResultMethod().ConfigureAwait(false);
// Assert
Assert.NotEqual(Guid.Empty, result);
Assert.Equal(4, _log.Count);
}
[Fact]
public async Task ShouldAllowInterceptionPriorToInvocation()
{
// Act
await _proxy.AsynchronousResultMethod().ConfigureAwait(false);
// Assert
Assert.Equal($"{MethodName}:InterceptStart", _log[0]);
}
[Fact]
public async Task ShouldAllowInterceptionAfterInvocation()
{
// Act
await _proxy.AsynchronousResultMethod().ConfigureAwait(false);
// Assert
Assert.Equal($"{MethodName}:InterceptEnd", _log[3]);
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2014 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
#if PARALLEL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace NUnit.Framework.Internal.Execution
{
/// <summary>
/// ParallelWorkItemDispatcher handles execution of work items by
/// queuing them for worker threads to process.
/// </summary>
public class ParallelWorkItemDispatcher : IWorkItemDispatcher
{
private static readonly Logger log = InternalTrace.GetLogger("Dispatcher");
private WorkItem _topLevelWorkItem;
private readonly Stack<WorkItem> _savedWorkItems = new Stack<WorkItem>();
#region Events
/// <summary>
/// Event raised whenever a shift is starting.
/// </summary>
public event ShiftChangeEventHandler ShiftStarting;
/// <summary>
/// Event raised whenever a shift has ended.
/// </summary>
public event ShiftChangeEventHandler ShiftFinished;
#endregion
#region Constructor
/// <summary>
/// Construct a ParallelWorkItemDispatcher
/// </summary>
/// <param name="levelOfParallelism">Number of workers to use</param>
public ParallelWorkItemDispatcher(int levelOfParallelism)
{
log.Info("Initializing with {0} workers", levelOfParallelism);
LevelOfParallelism = levelOfParallelism;
InitializeShifts();
}
private void InitializeShifts()
{
foreach (var shift in Shifts)
shift.EndOfShift += OnEndOfShift;
// Assign queues to shifts
ParallelShift.AddQueue(ParallelQueue);
#if APARTMENT_STATE
ParallelShift.AddQueue(ParallelSTAQueue);
#endif
NonParallelShift.AddQueue(NonParallelQueue);
#if APARTMENT_STATE
NonParallelSTAShift.AddQueue(NonParallelSTAQueue);
#endif
// Create workers and assign to shifts and queues
// TODO: Avoid creating all the workers till needed
for (int i = 1; i <= LevelOfParallelism; i++)
{
string name = string.Format("ParallelWorker#" + i.ToString());
ParallelShift.Assign(new TestWorker(ParallelQueue, name));
}
#if APARTMENT_STATE
ParallelShift.Assign(new TestWorker(ParallelSTAQueue, "ParallelSTAWorker"));
#endif
var worker = new TestWorker(NonParallelQueue, "NonParallelWorker");
worker.Busy += OnStartNonParallelWorkItem;
NonParallelShift.Assign(worker);
#if APARTMENT_STATE
worker = new TestWorker(NonParallelSTAQueue, "NonParallelSTAWorker");
worker.Busy += OnStartNonParallelWorkItem;
NonParallelSTAShift.Assign(worker);
#endif
}
private void OnStartNonParallelWorkItem(TestWorker worker, WorkItem work)
{
// This captures the startup of TestFixtures and SetUpFixtures,
// but not their teardown items, which are not composite items
if (work.IsolateChildTests)
IsolateQueues(work);
}
#endregion
#region Properties
/// <summary>
/// Number of parallel worker threads
/// </summary>
public int LevelOfParallelism { get; }
/// <summary>
/// Enumerates all the shifts supported by the dispatcher
/// </summary>
public IEnumerable<WorkShift> Shifts
{
get
{
yield return ParallelShift;
yield return NonParallelShift;
#if APARTMENT_STATE
yield return NonParallelSTAShift;
#endif
}
}
/// <summary>
/// Enumerates all the Queues supported by the dispatcher
/// </summary>
public IEnumerable<WorkItemQueue> Queues
{
get
{
yield return ParallelQueue;
#if APARTMENT_STATE
yield return ParallelSTAQueue;
#endif
yield return NonParallelQueue;
#if APARTMENT_STATE
yield return NonParallelSTAQueue;
#endif
}
}
// WorkShifts - Dispatcher processes tests in three non-overlapping shifts.
// See comment in Workshift.cs for a more detailed explanation.
private WorkShift ParallelShift { get; } = new WorkShift("Parallel");
private WorkShift NonParallelShift { get; } = new WorkShift("NonParallel");
#if APARTMENT_STATE
private WorkShift NonParallelSTAShift { get; } = new WorkShift("NonParallelSTA");
// WorkItemQueues
private WorkItemQueue ParallelQueue { get; } = new WorkItemQueue("ParallelQueue", true, ApartmentState.MTA);
private WorkItemQueue ParallelSTAQueue { get; } = new WorkItemQueue("ParallelSTAQueue", true, ApartmentState.STA);
private WorkItemQueue NonParallelQueue { get; } = new WorkItemQueue("NonParallelQueue", false, ApartmentState.MTA);
private WorkItemQueue NonParallelSTAQueue { get; } = new WorkItemQueue("NonParallelSTAQueue", false, ApartmentState.STA);
#else
// WorkItemQueues
private WorkItemQueue ParallelQueue { get; } = new WorkItemQueue("ParallelQueue", true);
private WorkItemQueue NonParallelQueue { get; } = new WorkItemQueue("NonParallelQueue", false);
#endif
#endregion
#region IWorkItemDispatcher Members
/// <summary>
/// Start execution, setting the top level work,
/// enqueuing it and starting a shift to execute it.
/// </summary>
public void Start(WorkItem topLevelWorkItem)
{
_topLevelWorkItem = topLevelWorkItem;
Dispatch(topLevelWorkItem, InitialExecutionStrategy(topLevelWorkItem));
var shift = SelectNextShift();
ShiftStarting?.Invoke(shift);
shift.Start();
}
// Initial strategy for the top level item is solely determined
// by the ParallelScope of that item. While other approaches are
// possible, this one gives the user a predictable result.
private static ParallelExecutionStrategy InitialExecutionStrategy(WorkItem workItem)
{
return workItem.ParallelScope == ParallelScope.Default || workItem.ParallelScope == ParallelScope.None
? ParallelExecutionStrategy.NonParallel
: ParallelExecutionStrategy.Parallel;
}
/// <summary>
/// Dispatch a single work item for execution. The first
/// work item dispatched is saved as the top-level
/// work item and used when stopping the run.
/// </summary>
/// <param name="work">The item to dispatch</param>
public void Dispatch(WorkItem work)
{
Dispatch(work, work.ExecutionStrategy);
}
// Separate method so it can be used by Start
private void Dispatch(WorkItem work, ParallelExecutionStrategy strategy)
{
log.Debug("Using {0} strategy for {1}", strategy, work.Name);
switch (strategy)
{
default:
case ParallelExecutionStrategy.Direct:
work.Execute();
break;
case ParallelExecutionStrategy.Parallel:
#if APARTMENT_STATE
if (work.TargetApartment == ApartmentState.STA)
ParallelSTAQueue.Enqueue(work);
else
#endif
ParallelQueue.Enqueue(work);
break;
case ParallelExecutionStrategy.NonParallel:
#if APARTMENT_STATE
if (work.TargetApartment == ApartmentState.STA)
NonParallelSTAQueue.Enqueue(work);
else
#endif
NonParallelQueue.Enqueue(work);
break;
}
}
/// <summary>
/// Cancel the ongoing run completely.
/// If no run is in process, the call has no effect.
/// </summary>
public void CancelRun(bool force)
{
foreach (var shift in Shifts)
shift.Cancel(force);
}
private readonly object _queueLock = new object();
private int _isolationLevel = 0;
/// <summary>
/// Save the state of the queues and create a new isolated set
/// </summary>
internal void IsolateQueues(WorkItem work)
{
log.Info("Saving Queue State for {0}", work.Name);
lock (_queueLock)
{
foreach (WorkItemQueue queue in Queues)
queue.Save();
_savedWorkItems.Push(_topLevelWorkItem);
_topLevelWorkItem = work;
_isolationLevel++;
}
}
/// <summary>
/// Try to remove isolated queues and restore old ones
/// </summary>
private void TryRestoreQueues()
{
// Keep lock until we can remove for both methods
lock (_queueLock)
{
if (_isolationLevel <= 0)
{
log.Debug("Ignoring call to restore Queue State");
return;
}
log.Info("Restoring Queue State");
foreach (WorkItemQueue queue in Queues)
queue.Restore();
_topLevelWorkItem = _savedWorkItems.Pop();
_isolationLevel--;
}
}
#endregion
#region Helper Methods
private void OnEndOfShift(WorkShift endingShift)
{
ShiftFinished?.Invoke(endingShift);
WorkShift nextShift = null;
while (true)
{
// Shift has ended but all work may not yet be done
while (_topLevelWorkItem.State != WorkItemState.Complete)
{
// This will return null if all queues are empty.
nextShift = SelectNextShift();
if (nextShift != null)
{
ShiftStarting?.Invoke(nextShift);
nextShift.Start();
return;
}
}
// If the shift has ended for an isolated queue, restore
// the queues and keep trying. Otherwise, we are done.
if (_isolationLevel > 0)
TryRestoreQueues();
else
break;
}
// All done - shutdown all shifts
foreach (var shift in Shifts)
shift.ShutDown();
}
private WorkShift SelectNextShift()
{
foreach (var shift in Shifts)
if (shift.HasWork)
return shift;
return null;
}
#endregion
}
#region ParallelScopeHelper Class
#if NET35
static class ParallelScopeHelper
{
public static bool HasFlag(this ParallelScope scope, ParallelScope value)
{
return (scope & value) != 0;
}
}
#endif
#endregion
}
#endif
| |
namespace AutoMapper
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Impl;
using Internal;
using Mappers;
using QueryableExtensions;
using QueryableExtensions.Impl;
public class MappingEngine : IMappingEngine, IMappingEngineRunner
{
private static readonly IDictionaryFactory DictionaryFactory = PlatformAdapter.Resolve<IDictionaryFactory>();
private static readonly IProxyGeneratorFactory ProxyGeneratorFactory = PlatformAdapter.Resolve<IProxyGeneratorFactory>();
private static readonly IExpressionResultConverter[] ExpressionResultConverters =
{
new MemberGetterExpressionResultConverter(),
new MemberResolverExpressionResultConverter(),
new NullSubstitutionExpressionResultConverter()
};
private static readonly IExpressionBinder[] Binders =
{
new NullableExpressionBinder(),
new AssignableExpressionBinder(),
new EnumerableExpressionBinder(),
new MappedTypeExpressionBinder(),
new CustomProjectionExpressionBinder(),
new StringExpressionBinder()
};
private bool _disposed;
private readonly IObjectMapper[] _mappers;
private readonly Internal.IDictionary<TypePair, IObjectMapper> _objectMapperCache;
private readonly Internal.IDictionary<ExpressionRequest, LambdaExpression> _expressionCache;
private readonly Func<Type, object> _serviceCtor;
public MappingEngine(IConfigurationProvider configurationProvider)
: this(
configurationProvider,
DictionaryFactory.CreateDictionary<TypePair, IObjectMapper>(),
DictionaryFactory.CreateDictionary<ExpressionRequest, LambdaExpression>(),
configurationProvider.ServiceCtor)
{
}
public MappingEngine(IConfigurationProvider configurationProvider, Internal.IDictionary<TypePair, IObjectMapper> objectMapperCache, Internal.IDictionary<ExpressionRequest, LambdaExpression> expressionCache,
Func<Type, object> serviceCtor)
{
ConfigurationProvider = configurationProvider;
_objectMapperCache = objectMapperCache;
_expressionCache = expressionCache;
_serviceCtor = serviceCtor;
_mappers = configurationProvider.GetMappers();
ConfigurationProvider.TypeMapCreated += ClearTypeMap;
}
public IConfigurationProvider ConfigurationProvider { get; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (ConfigurationProvider != null)
ConfigurationProvider.TypeMapCreated -= ClearTypeMap;
}
_disposed = true;
}
}
public TDestination Map<TDestination>(object source)
{
return Map<TDestination>(source, DefaultMappingOptions);
}
public TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
{
var mappedObject = default(TDestination);
if (source != null)
{
var sourceType = source.GetType();
var destinationType = typeof (TDestination);
mappedObject = (TDestination) Map(source, sourceType, destinationType, opts);
}
return mappedObject;
}
public TDestination Map<TSource, TDestination>(TSource source)
{
Type modelType = typeof (TSource);
Type destinationType = typeof (TDestination);
return (TDestination) Map(source, modelType, destinationType, DefaultMappingOptions);
}
public TDestination Map<TSource, TDestination>(TSource source,
Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
Type modelType = typeof (TSource);
Type destinationType = typeof (TDestination);
var options = new MappingOperationOptions<TSource, TDestination>();
opts(options);
return (TDestination) MapCore(source, modelType, destinationType, options);
}
public TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
{
return Map(source, destination, DefaultMappingOptions);
}
public TDestination Map<TSource, TDestination>(TSource source, TDestination destination,
Action<IMappingOperationOptions<TSource, TDestination>> opts)
{
Type modelType = typeof (TSource);
Type destinationType = typeof (TDestination);
var options = new MappingOperationOptions<TSource, TDestination>();
opts(options);
return (TDestination) MapCore(source, destination, modelType, destinationType, options);
}
public object Map(object source, Type sourceType, Type destinationType)
{
return Map(source, sourceType, destinationType, DefaultMappingOptions);
}
public object Map(object source, Type sourceType, Type destinationType, Action<IMappingOperationOptions> opts)
{
var options = new MappingOperationOptions();
opts(options);
return MapCore(source, sourceType, destinationType, options);
}
private object MapCore(object source, Type sourceType, Type destinationType, MappingOperationOptions options)
{
TypeMap typeMap = ConfigurationProvider.ResolveTypeMap(source, null, sourceType, destinationType);
var context = new ResolutionContext(typeMap, source, sourceType, destinationType, options, this);
return ((IMappingEngineRunner) this).Map(context);
}
public object Map(object source, object destination, Type sourceType, Type destinationType)
{
return Map(source, destination, sourceType, destinationType, DefaultMappingOptions);
}
public object Map(object source, object destination, Type sourceType, Type destinationType,
Action<IMappingOperationOptions> opts)
{
var options = new MappingOperationOptions();
opts(options);
return MapCore(source, destination, sourceType, destinationType, options);
}
private object MapCore(object source, object destination, Type sourceType, Type destinationType,
MappingOperationOptions options)
{
TypeMap typeMap = ConfigurationProvider.ResolveTypeMap(source, destination, sourceType, destinationType);
var context = new ResolutionContext(typeMap, source, destination, sourceType, destinationType, options, this);
return ((IMappingEngineRunner) this).Map(context);
}
public TDestination DynamicMap<TSource, TDestination>(TSource source)
{
Type modelType = typeof (TSource);
Type destinationType = typeof (TDestination);
return (TDestination) DynamicMap(source, modelType, destinationType);
}
public void DynamicMap<TSource, TDestination>(TSource source, TDestination destination)
{
Type modelType = typeof (TSource);
Type destinationType = typeof (TDestination);
DynamicMap(source, destination, modelType, destinationType);
}
public TDestination DynamicMap<TDestination>(object source)
{
Type modelType = source?.GetType() ?? typeof (object);
Type destinationType = typeof (TDestination);
return (TDestination) DynamicMap(source, modelType, destinationType);
}
public object DynamicMap(object source, Type sourceType, Type destinationType)
{
var typeMap = ConfigurationProvider.ResolveTypeMap(source, null, sourceType, destinationType);
var context = new ResolutionContext(typeMap, source, sourceType, destinationType,
new MappingOperationOptions
{
CreateMissingTypeMaps = true
}, this);
return ((IMappingEngineRunner) this).Map(context);
}
public void DynamicMap(object source, object destination, Type sourceType, Type destinationType)
{
var typeMap = ConfigurationProvider.ResolveTypeMap(source, destination, sourceType, destinationType);
var context = new ResolutionContext(typeMap, source, destination, sourceType, destinationType,
new MappingOperationOptions
{
CreateMissingTypeMaps = true
}, this);
((IMappingEngineRunner) this).Map(context);
}
public TDestination Map<TSource, TDestination>(ResolutionContext parentContext, TSource source)
{
Type destinationType = typeof (TDestination);
Type sourceType = typeof (TSource);
TypeMap typeMap = ConfigurationProvider.ResolveTypeMap(source, null, sourceType, destinationType);
var context = parentContext.CreateTypeContext(typeMap, source, null, sourceType, destinationType);
return (TDestination) ((IMappingEngineRunner) this).Map(context);
}
public Expression CreateMapExpression(Type sourceType, Type destinationType, System.Collections.Generic.IDictionary<string, object> parameters = null, params string[] membersToExpand)
{
parameters = parameters ?? new Dictionary<string, object>();
var cachedExpression =
_expressionCache.GetOrAdd(new ExpressionRequest(sourceType, destinationType, membersToExpand),
tp => CreateMapExpression(tp, DictionaryFactory.CreateDictionary<ExpressionRequest, int>()));
if (!parameters.Any())
return cachedExpression;
var visitor = new ConstantExpressionReplacementVisitor(parameters);
return visitor.Visit(cachedExpression);
}
public LambdaExpression CreateMapExpression(ExpressionRequest request, Internal.IDictionary<ExpressionRequest, int> typePairCount)
{
// this is the input parameter of this expression with name <variableName>
ParameterExpression instanceParameter = Expression.Parameter(request.SourceType, "dto");
var total = CreateMapExpression(request, instanceParameter, typePairCount);
return Expression.Lambda(total, instanceParameter);
}
public Expression CreateMapExpression(ExpressionRequest request,
Expression instanceParameter, Internal.IDictionary<ExpressionRequest, int> typePairCount)
{
var typeMap = ConfigurationProvider.ResolveTypeMap(request.SourceType,
request.DestinationType);
if (typeMap == null)
{
const string MessageFormat = "Missing map from {0} to {1}. Create using Mapper.CreateMap<{0}, {1}>.";
var message = string.Format(MessageFormat, request.SourceType.Name, request.DestinationType.Name);
throw new InvalidOperationException(message);
}
var bindings = CreateMemberBindings(request, typeMap, instanceParameter, typePairCount);
var parameterReplacer = new ParameterReplacementVisitor(instanceParameter);
var visitor = new NewFinderVisitor();
var constructorExpression = typeMap.DestinationConstructorExpression(instanceParameter);
visitor.Visit(parameterReplacer.Visit(constructorExpression));
var expression = Expression.MemberInit(
visitor.NewExpression,
bindings.ToArray()
);
return expression;
}
private class NewFinderVisitor : ExpressionVisitor
{
public NewExpression NewExpression { get; private set; }
protected override Expression VisitNew(NewExpression node)
{
NewExpression = node;
return base.VisitNew(node);
}
}
private List<MemberBinding> CreateMemberBindings(ExpressionRequest request,
TypeMap typeMap,
Expression instanceParameter, Internal.IDictionary<ExpressionRequest, int> typePairCount)
{
var bindings = new List<MemberBinding>();
var visitCount = typePairCount.AddOrUpdate(request, 0, (tp, i) => i + 1);
if (visitCount >= typeMap.MaxDepth)
return bindings;
foreach (var propertyMap in typeMap.GetPropertyMaps().Where(pm => pm.CanResolveValue()))
{
var result = ResolveExpression(propertyMap, request.SourceType, instanceParameter);
if (propertyMap.ExplicitExpansion &&
!request.IncludedMembers.Contains(propertyMap.DestinationProperty.Name))
continue;
var propertyTypeMap = ConfigurationProvider.ResolveTypeMap(result.Type,
propertyMap.DestinationPropertyType);
var propertyRequest = new ExpressionRequest(result.Type, propertyMap.DestinationPropertyType,
request.IncludedMembers);
var binder = Binders.FirstOrDefault(b => b.IsMatch(propertyMap, propertyTypeMap, result));
if (binder == null)
{
var message =
$"Unable to create a map expression from {propertyMap.SourceMember?.DeclaringType?.Name}.{propertyMap.SourceMember?.Name} ({result.Type}) to {propertyMap.DestinationProperty.MemberInfo.DeclaringType?.Name}.{propertyMap.DestinationProperty.Name} ({propertyMap.DestinationPropertyType})";
throw new AutoMapperMappingException(message);
}
var bindExpression = binder.Build(this, propertyMap, propertyTypeMap, propertyRequest, result, typePairCount);
bindings.Add(bindExpression);
}
return bindings;
}
private static ExpressionResolutionResult ResolveExpression(PropertyMap propertyMap, Type currentType,
Expression instanceParameter)
{
var result = new ExpressionResolutionResult(instanceParameter, currentType);
foreach (var resolver in propertyMap.GetSourceValueResolvers())
{
var matchingExpressionConverter =
ExpressionResultConverters.FirstOrDefault(c => c.CanGetExpressionResolutionResult(result, resolver));
if (matchingExpressionConverter == null)
throw new Exception("Can't resolve this to Queryable Expression");
result = matchingExpressionConverter.GetExpressionResolutionResult(result, propertyMap, resolver);
}
return result;
}
private class ConstantExpressionReplacementVisitor : ExpressionVisitor
{
private readonly System.Collections.Generic.IDictionary<string, object> _paramValues;
public ConstantExpressionReplacementVisitor(
System.Collections.Generic.IDictionary<string, object> paramValues)
{
_paramValues = paramValues;
}
protected override Expression VisitMember(MemberExpression node)
{
if (!node.Member.DeclaringType.Name.Contains("<>"))
return base.VisitMember(node);
if (!_paramValues.ContainsKey(node.Member.Name))
return base.VisitMember(node);
return Expression.Convert(
Expression.Constant(_paramValues[node.Member.Name]),
node.Member.GetMemberType());
}
}
object IMappingEngineRunner.Map(ResolutionContext context)
{
try
{
var contextTypePair = new TypePair(context.SourceType, context.DestinationType);
Func<TypePair, IObjectMapper> missFunc =
tp => _mappers.FirstOrDefault(mapper => mapper.IsMatch(context));
IObjectMapper mapperToUse = _objectMapperCache.GetOrAdd(contextTypePair, missFunc);
if (mapperToUse == null || (context.Options.CreateMissingTypeMaps && !mapperToUse.IsMatch(context)))
{
if (context.Options.CreateMissingTypeMaps)
{
var typeMap = ConfigurationProvider.CreateTypeMap(context.SourceType, context.DestinationType);
context = context.CreateTypeContext(typeMap, context.SourceValue, context.DestinationValue, context.SourceType, context.DestinationType);
mapperToUse = missFunc(contextTypePair);
if(mapperToUse == null)
{
throw new AutoMapperMappingException(context, "Unsupported mapping.");
}
_objectMapperCache.AddOrUpdate(contextTypePair, mapperToUse, (tp, mapper) => mapperToUse);
}
else
{
if(context.SourceValue != null)
{
throw new AutoMapperMappingException(context, "Missing type map configuration or unsupported mapping.");
}
return ObjectCreator.CreateDefaultValue(context.DestinationType);
}
}
return mapperToUse.Map(context, this);
}
catch (AutoMapperMappingException)
{
throw;
}
catch (Exception ex)
{
throw new AutoMapperMappingException(context, ex);
}
}
object IMappingEngineRunner.CreateObject(ResolutionContext context)
{
var typeMap = context.TypeMap;
var destinationType = context.DestinationType;
if (typeMap != null)
if (typeMap.DestinationCtor != null)
return typeMap.DestinationCtor(context);
else if (typeMap.ConstructDestinationUsingServiceLocator)
return context.Options.ServiceCtor(destinationType);
else if (typeMap.ConstructorMap != null)
return typeMap.ConstructorMap.ResolveValue(context, this);
if (context.DestinationValue != null)
return context.DestinationValue;
if (destinationType.IsInterface())
destinationType = ProxyGeneratorFactory.Create().GetProxyType(destinationType);
return !ConfigurationProvider.MapNullSourceValuesAsNull
? ObjectCreator.CreateNonNullValue(destinationType)
: ObjectCreator.CreateObject(destinationType);
}
bool IMappingEngineRunner.ShouldMapSourceValueAsNull(ResolutionContext context)
{
if (context.DestinationType.IsValueType() && !context.DestinationType.IsNullableType())
return false;
var typeMap = context.GetContextTypeMap();
if (typeMap != null)
return ConfigurationProvider.GetProfileConfiguration(typeMap.Profile).MapNullSourceValuesAsNull;
return ConfigurationProvider.MapNullSourceValuesAsNull;
}
bool IMappingEngineRunner.ShouldMapSourceCollectionAsNull(ResolutionContext context)
{
var typeMap = context.GetContextTypeMap();
if (typeMap != null)
return ConfigurationProvider.GetProfileConfiguration(typeMap.Profile).MapNullSourceCollectionsAsNull;
return ConfigurationProvider.MapNullSourceCollectionsAsNull;
}
private void ClearTypeMap(object sender, TypeMapCreatedEventArgs e)
{
IObjectMapper existing;
_objectMapperCache.TryRemove(new TypePair(e.TypeMap.SourceType, e.TypeMap.DestinationType), out existing);
}
private void DefaultMappingOptions(IMappingOperationOptions opts)
{
opts.ConstructServicesUsing(_serviceCtor);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.DocumentationComments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.DocumentationComments
{
[ExportCommandHandler(PredefinedCommandHandlerNames.DocumentationComments, ContentTypeNames.CSharpContentType)]
[Order(After = PredefinedCommandHandlerNames.Rename)]
internal class DocumentationCommentCommandHandler
: AbstractDocumentationCommentCommandHandler<DocumentationCommentTriviaSyntax, MemberDeclarationSyntax>
{
[ImportingConstructor]
public DocumentationCommentCommandHandler(
IWaitIndicator waitIndicator,
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService,
IAsyncCompletionService completionService) :
base(waitIndicator, undoHistoryRegistry, editorOperationsFactoryService, completionService)
{
}
protected override string ExteriorTriviaText
{
get { return "///"; }
}
protected override MemberDeclarationSyntax GetContainingMember(
SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
return syntaxTree.GetRoot(cancellationToken).FindToken(position).GetAncestor<MemberDeclarationSyntax>();
}
protected override bool SupportsDocumentationComments(MemberDeclarationSyntax member)
{
if (member == null)
{
return false;
}
switch (member.Kind())
{
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMemberDeclaration:
case SyntaxKind.FieldDeclaration:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.EventFieldDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
return true;
default:
return false;
}
}
protected override bool HasDocumentationComment(MemberDeclarationSyntax member)
{
return member.GetFirstToken().LeadingTrivia.Any(SyntaxKind.SingleLineDocumentationCommentTrivia, SyntaxKind.MultiLineDocumentationCommentTrivia);
}
protected override int GetPrecedingDocumentationCommentCount(MemberDeclarationSyntax member)
{
var firstToken = member.GetFirstToken();
var count = firstToken.LeadingTrivia.Count(t => t.IsDocComment());
var previousToken = firstToken.GetPreviousToken();
if (previousToken.Kind() != SyntaxKind.None)
{
count += previousToken.TrailingTrivia.Count(t => t.IsDocComment());
}
return count;
}
protected override bool IsMemberDeclaration(MemberDeclarationSyntax member)
{
return true;
}
protected override List<string> GetDocumentationCommentStubLines(MemberDeclarationSyntax member)
{
var list = new List<string>();
list.Add("/// <summary>");
list.Add("/// ");
list.Add("/// </summary>");
var typeParameterList = member.GetTypeParameterList();
if (typeParameterList != null)
{
foreach (var typeParam in typeParameterList.Parameters)
{
list.Add("/// <typeparam name=\"" + typeParam.Identifier.ValueText + "\"></typeparam>");
}
}
var parameterList = member.GetParameterList();
if (parameterList != null)
{
foreach (var param in parameterList.Parameters)
{
list.Add("/// <param name=\"" + param.Identifier.ValueText + "\"></param>");
}
}
if (member.IsKind(SyntaxKind.MethodDeclaration) ||
member.IsKind(SyntaxKind.IndexerDeclaration) ||
member.IsKind(SyntaxKind.DelegateDeclaration) ||
member.IsKind(SyntaxKind.OperatorDeclaration))
{
var returnType = member.GetMemberType();
if (returnType != null &&
!(returnType.IsKind(SyntaxKind.PredefinedType) && ((PredefinedTypeSyntax)returnType).Keyword.IsKindOrHasMatchingText(SyntaxKind.VoidKeyword)))
{
list.Add("/// <returns></returns>");
}
}
return list;
}
protected override SyntaxToken GetTokenToRight(
SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
if (position >= syntaxTree.GetText(cancellationToken).Length)
{
return default(SyntaxToken);
}
return syntaxTree.GetRoot(cancellationToken).FindTokenOnRightOfPosition(
position, includeDirectives: true, includeDocumentationComments: true);
}
protected override SyntaxToken GetTokenToLeft(
SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
if (position < 1)
{
return default(SyntaxToken);
}
return syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition(
position - 1, includeDirectives: true, includeDocumentationComments: true);
}
protected override bool IsDocCommentNewLine(SyntaxToken token)
{
return token.RawKind == (int)SyntaxKind.XmlTextLiteralNewLineToken;
}
protected override bool IsEndOfLineTrivia(SyntaxTrivia trivia)
{
return trivia.RawKind == (int)SyntaxKind.EndOfLineTrivia;
}
protected override bool IsSingleExteriorTrivia(DocumentationCommentTriviaSyntax documentationComment, bool allowWhitespace = false)
{
if (documentationComment == null)
{
return false;
}
if (IsMultilineDocComment(documentationComment))
{
return false;
}
if (documentationComment.Content.Count != 1)
{
return false;
}
var xmlText = documentationComment.Content[0] as XmlTextSyntax;
if (xmlText == null)
{
return false;
}
var textTokens = xmlText.TextTokens;
if (!textTokens.Any())
{
return false;
}
if (!allowWhitespace && textTokens.Count != 1)
{
return false;
}
if (textTokens.Any(t => !string.IsNullOrWhiteSpace(t.ToString())))
{
return false;
}
var lastTextToken = textTokens.Last();
var firstTextToken = textTokens.First();
return lastTextToken.Kind() == SyntaxKind.XmlTextLiteralNewLineToken
&& firstTextToken.LeadingTrivia.Count == 1
&& firstTextToken.LeadingTrivia.ElementAt(0).Kind() == SyntaxKind.DocumentationCommentExteriorTrivia
&& firstTextToken.LeadingTrivia.ElementAt(0).ToString() == ExteriorTriviaText
&& lastTextToken.TrailingTrivia.Count == 0;
}
private IList<SyntaxToken> GetTextTokensFollowingExteriorTrivia(XmlTextSyntax xmlText)
{
var result = new List<SyntaxToken>();
var tokenList = xmlText.TextTokens;
foreach (var token in tokenList.Reverse())
{
result.Add(token);
if (token.LeadingTrivia.Any(SyntaxKind.DocumentationCommentExteriorTrivia))
{
break;
}
}
result.Reverse();
return result;
}
protected override bool EndsWithSingleExteriorTrivia(DocumentationCommentTriviaSyntax documentationComment)
{
if (documentationComment == null)
{
return false;
}
if (IsMultilineDocComment(documentationComment))
{
return false;
}
var xmlText = documentationComment.Content.LastOrDefault() as XmlTextSyntax;
if (xmlText == null)
{
return false;
}
var textTokens = GetTextTokensFollowingExteriorTrivia(xmlText);
if (textTokens.Any(t => !string.IsNullOrWhiteSpace(t.ToString())))
{
return false;
}
var lastTextToken = textTokens.LastOrDefault();
var firstTextToken = textTokens.FirstOrDefault();
return lastTextToken.Kind() == SyntaxKind.XmlTextLiteralNewLineToken
&& firstTextToken.LeadingTrivia.Count == 1
&& firstTextToken.LeadingTrivia.ElementAt(0).Kind() == SyntaxKind.DocumentationCommentExteriorTrivia
&& firstTextToken.LeadingTrivia.ElementAt(0).ToString() == ExteriorTriviaText
&& lastTextToken.TrailingTrivia.Count == 0;
}
protected override bool IsMultilineDocComment(DocumentationCommentTriviaSyntax documentationComment)
{
return documentationComment.IsMultilineDocComment();
}
protected override bool AddIndent
{
get { return true; }
}
}
}
| |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
// @Generated by gentest/gentest.rb from gentest/fixtures/YGPercentageTest.html
using System;
using NUnit.Framework;
namespace Facebook.Yoga
{
[TestFixture]
public class YGPercentageTest
{
[Test]
public void Test_percentage_width_height()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 30.Percent();
root_child0.Height = 30.Percent();
root.Insert(0, root_child0);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(60f, root_child0.LayoutWidth);
Assert.AreEqual(60f, root_child0.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(140f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(60f, root_child0.LayoutWidth);
Assert.AreEqual(60f, root_child0.LayoutHeight);
}
[Test]
public void Test_percentage_position_left_top()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 400;
root.Height = 400;
YogaNode root_child0 = new YogaNode(config);
root_child0.Left = 10.Percent();
root_child0.Top = 20.Percent();
root_child0.Width = 45.Percent();
root_child0.Height = 55.Percent();
root.Insert(0, root_child0);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(400f, root.LayoutWidth);
Assert.AreEqual(400f, root.LayoutHeight);
Assert.AreEqual(40f, root_child0.LayoutX);
Assert.AreEqual(80f, root_child0.LayoutY);
Assert.AreEqual(180f, root_child0.LayoutWidth);
Assert.AreEqual(220f, root_child0.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(400f, root.LayoutWidth);
Assert.AreEqual(400f, root.LayoutHeight);
Assert.AreEqual(260f, root_child0.LayoutX);
Assert.AreEqual(80f, root_child0.LayoutY);
Assert.AreEqual(180f, root_child0.LayoutWidth);
Assert.AreEqual(220f, root_child0.LayoutHeight);
}
[Test]
public void Test_percentage_position_bottom_right()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 500;
root.Height = 500;
YogaNode root_child0 = new YogaNode(config);
root_child0.Right = 20.Percent();
root_child0.Bottom = 10.Percent();
root_child0.Width = 55.Percent();
root_child0.Height = 15.Percent();
root.Insert(0, root_child0);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(500f, root.LayoutWidth);
Assert.AreEqual(500f, root.LayoutHeight);
Assert.AreEqual(-100f, root_child0.LayoutX);
Assert.AreEqual(-50f, root_child0.LayoutY);
Assert.AreEqual(275f, root_child0.LayoutWidth);
Assert.AreEqual(75f, root_child0.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(500f, root.LayoutWidth);
Assert.AreEqual(500f, root.LayoutHeight);
Assert.AreEqual(125f, root_child0.LayoutX);
Assert.AreEqual(-50f, root_child0.LayoutY);
Assert.AreEqual(275f, root_child0.LayoutWidth);
Assert.AreEqual(75f, root_child0.LayoutHeight);
}
[Test]
public void Test_percentage_flex_basis()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.FlexBasis = 50.Percent();
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 1;
root_child1.FlexBasis = 25.Percent();
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(125f, root_child0.LayoutWidth);
Assert.AreEqual(200f, root_child0.LayoutHeight);
Assert.AreEqual(125f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(75f, root_child1.LayoutWidth);
Assert.AreEqual(200f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(75f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(125f, root_child0.LayoutWidth);
Assert.AreEqual(200f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(75f, root_child1.LayoutWidth);
Assert.AreEqual(200f, root_child1.LayoutHeight);
}
[Test]
public void Test_percentage_flex_basis_cross()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.FlexBasis = 50.Percent();
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 1;
root_child1.FlexBasis = 25.Percent();
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(200f, root_child0.LayoutWidth);
Assert.AreEqual(125f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(125f, root_child1.LayoutY);
Assert.AreEqual(200f, root_child1.LayoutWidth);
Assert.AreEqual(75f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(200f, root_child0.LayoutWidth);
Assert.AreEqual(125f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(125f, root_child1.LayoutY);
Assert.AreEqual(200f, root_child1.LayoutWidth);
Assert.AreEqual(75f, root_child1.LayoutHeight);
}
[Test]
public void Test_percentage_flex_basis_cross_min_height()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.MinHeight = 60.Percent();
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 2;
root_child1.MinHeight = 10.Percent();
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(200f, root_child0.LayoutWidth);
Assert.AreEqual(140f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(140f, root_child1.LayoutY);
Assert.AreEqual(200f, root_child1.LayoutWidth);
Assert.AreEqual(60f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(200f, root_child0.LayoutWidth);
Assert.AreEqual(140f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(140f, root_child1.LayoutY);
Assert.AreEqual(200f, root_child1.LayoutWidth);
Assert.AreEqual(60f, root_child1.LayoutHeight);
}
[Test]
public void Test_percentage_flex_basis_main_max_height()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.FlexBasis = 10.Percent();
root_child0.MaxHeight = 60.Percent();
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 4;
root_child1.FlexBasis = 10.Percent();
root_child1.MaxHeight = 20.Percent();
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(52f, root_child0.LayoutWidth);
Assert.AreEqual(120f, root_child0.LayoutHeight);
Assert.AreEqual(52f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(148f, root_child1.LayoutWidth);
Assert.AreEqual(40f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(148f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(52f, root_child0.LayoutWidth);
Assert.AreEqual(120f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(148f, root_child1.LayoutWidth);
Assert.AreEqual(40f, root_child1.LayoutHeight);
}
[Test]
public void Test_percentage_flex_basis_cross_max_height()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.FlexBasis = 10.Percent();
root_child0.MaxHeight = 60.Percent();
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 4;
root_child1.FlexBasis = 10.Percent();
root_child1.MaxHeight = 20.Percent();
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(200f, root_child0.LayoutWidth);
Assert.AreEqual(120f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(120f, root_child1.LayoutY);
Assert.AreEqual(200f, root_child1.LayoutWidth);
Assert.AreEqual(40f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(200f, root_child0.LayoutWidth);
Assert.AreEqual(120f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(120f, root_child1.LayoutY);
Assert.AreEqual(200f, root_child1.LayoutWidth);
Assert.AreEqual(40f, root_child1.LayoutHeight);
}
[Test]
public void Test_percentage_flex_basis_main_max_width()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.FlexBasis = 15.Percent();
root_child0.MaxWidth = 60.Percent();
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 4;
root_child1.FlexBasis = 10.Percent();
root_child1.MaxWidth = 20.Percent();
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(120f, root_child0.LayoutWidth);
Assert.AreEqual(200f, root_child0.LayoutHeight);
Assert.AreEqual(120f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(40f, root_child1.LayoutWidth);
Assert.AreEqual(200f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(80f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(120f, root_child0.LayoutWidth);
Assert.AreEqual(200f, root_child0.LayoutHeight);
Assert.AreEqual(40f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(40f, root_child1.LayoutWidth);
Assert.AreEqual(200f, root_child1.LayoutHeight);
}
[Test]
public void Test_percentage_flex_basis_cross_max_width()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.FlexBasis = 10.Percent();
root_child0.MaxWidth = 60.Percent();
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 4;
root_child1.FlexBasis = 15.Percent();
root_child1.MaxWidth = 20.Percent();
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(120f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(50f, root_child1.LayoutY);
Assert.AreEqual(40f, root_child1.LayoutWidth);
Assert.AreEqual(150f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(80f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(120f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(160f, root_child1.LayoutX);
Assert.AreEqual(50f, root_child1.LayoutY);
Assert.AreEqual(40f, root_child1.LayoutWidth);
Assert.AreEqual(150f, root_child1.LayoutHeight);
}
[Test]
public void Test_percentage_flex_basis_main_min_width()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.FlexBasis = 15.Percent();
root_child0.MinWidth = 60.Percent();
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 4;
root_child1.FlexBasis = 10.Percent();
root_child1.MinWidth = 20.Percent();
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(120f, root_child0.LayoutWidth);
Assert.AreEqual(200f, root_child0.LayoutHeight);
Assert.AreEqual(120f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(80f, root_child1.LayoutWidth);
Assert.AreEqual(200f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(80f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(120f, root_child0.LayoutWidth);
Assert.AreEqual(200f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(80f, root_child1.LayoutWidth);
Assert.AreEqual(200f, root_child1.LayoutHeight);
}
[Test]
public void Test_percentage_flex_basis_cross_min_width()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.FlexBasis = 10.Percent();
root_child0.MinWidth = 60.Percent();
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 4;
root_child1.FlexBasis = 15.Percent();
root_child1.MinWidth = 20.Percent();
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(200f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(50f, root_child1.LayoutY);
Assert.AreEqual(200f, root_child1.LayoutWidth);
Assert.AreEqual(150f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(200f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(50f, root_child1.LayoutY);
Assert.AreEqual(200f, root_child1.LayoutWidth);
Assert.AreEqual(150f, root_child1.LayoutHeight);
}
[Test]
public void Test_percentage_multiple_nested_with_padding_margin_and_percentage_values()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.FlexBasis = 10.Percent();
root_child0.MarginLeft = 5;
root_child0.MarginTop = 5;
root_child0.MarginRight = 5;
root_child0.MarginBottom = 5;
root_child0.PaddingLeft = 3;
root_child0.PaddingTop = 3;
root_child0.PaddingRight = 3;
root_child0.PaddingBottom = 3;
root_child0.MinWidth = 60.Percent();
root.Insert(0, root_child0);
YogaNode root_child0_child0 = new YogaNode(config);
root_child0_child0.MarginLeft = 5;
root_child0_child0.MarginTop = 5;
root_child0_child0.MarginRight = 5;
root_child0_child0.MarginBottom = 5;
root_child0_child0.PaddingLeft = 3.Percent();
root_child0_child0.PaddingTop = 3.Percent();
root_child0_child0.PaddingRight = 3.Percent();
root_child0_child0.PaddingBottom = 3.Percent();
root_child0_child0.Width = 50.Percent();
root_child0.Insert(0, root_child0_child0);
YogaNode root_child0_child0_child0 = new YogaNode(config);
root_child0_child0_child0.MarginLeft = 5.Percent();
root_child0_child0_child0.MarginTop = 5.Percent();
root_child0_child0_child0.MarginRight = 5.Percent();
root_child0_child0_child0.MarginBottom = 5.Percent();
root_child0_child0_child0.PaddingLeft = 3;
root_child0_child0_child0.PaddingTop = 3;
root_child0_child0_child0.PaddingRight = 3;
root_child0_child0_child0.PaddingBottom = 3;
root_child0_child0_child0.Width = 45.Percent();
root_child0_child0.Insert(0, root_child0_child0_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 4;
root_child1.FlexBasis = 15.Percent();
root_child1.MinWidth = 20.Percent();
root.Insert(1, root_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(5f, root_child0.LayoutX);
Assert.AreEqual(5f, root_child0.LayoutY);
Assert.AreEqual(190f, root_child0.LayoutWidth);
Assert.AreEqual(48f, root_child0.LayoutHeight);
Assert.AreEqual(8f, root_child0_child0.LayoutX);
Assert.AreEqual(8f, root_child0_child0.LayoutY);
Assert.AreEqual(92f, root_child0_child0.LayoutWidth);
Assert.AreEqual(25f, root_child0_child0.LayoutHeight);
Assert.AreEqual(10f, root_child0_child0_child0.LayoutX);
Assert.AreEqual(10f, root_child0_child0_child0.LayoutY);
Assert.AreEqual(36f, root_child0_child0_child0.LayoutWidth);
Assert.AreEqual(6f, root_child0_child0_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(58f, root_child1.LayoutY);
Assert.AreEqual(200f, root_child1.LayoutWidth);
Assert.AreEqual(142f, root_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(5f, root_child0.LayoutX);
Assert.AreEqual(5f, root_child0.LayoutY);
Assert.AreEqual(190f, root_child0.LayoutWidth);
Assert.AreEqual(48f, root_child0.LayoutHeight);
Assert.AreEqual(90f, root_child0_child0.LayoutX);
Assert.AreEqual(8f, root_child0_child0.LayoutY);
Assert.AreEqual(92f, root_child0_child0.LayoutWidth);
Assert.AreEqual(25f, root_child0_child0.LayoutHeight);
Assert.AreEqual(46f, root_child0_child0_child0.LayoutX);
Assert.AreEqual(10f, root_child0_child0_child0.LayoutY);
Assert.AreEqual(36f, root_child0_child0_child0.LayoutWidth);
Assert.AreEqual(6f, root_child0_child0_child0.LayoutHeight);
Assert.AreEqual(0f, root_child1.LayoutX);
Assert.AreEqual(58f, root_child1.LayoutY);
Assert.AreEqual(200f, root_child1.LayoutWidth);
Assert.AreEqual(142f, root_child1.LayoutHeight);
}
[Test]
public void Test_percentage_margin_should_calculate_based_only_on_width()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Width = 200;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.MarginLeft = 10.Percent();
root_child0.MarginTop = 10.Percent();
root_child0.MarginRight = 10.Percent();
root_child0.MarginBottom = 10.Percent();
root.Insert(0, root_child0);
YogaNode root_child0_child0 = new YogaNode(config);
root_child0_child0.Width = 10;
root_child0_child0.Height = 10;
root_child0.Insert(0, root_child0_child0);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(20f, root_child0.LayoutX);
Assert.AreEqual(20f, root_child0.LayoutY);
Assert.AreEqual(160f, root_child0.LayoutWidth);
Assert.AreEqual(60f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0.LayoutY);
Assert.AreEqual(10f, root_child0_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0_child0.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(20f, root_child0.LayoutX);
Assert.AreEqual(20f, root_child0.LayoutY);
Assert.AreEqual(160f, root_child0.LayoutWidth);
Assert.AreEqual(60f, root_child0.LayoutHeight);
Assert.AreEqual(150f, root_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0.LayoutY);
Assert.AreEqual(10f, root_child0_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0_child0.LayoutHeight);
}
[Test]
public void Test_percentage_padding_should_calculate_based_only_on_width()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Width = 200;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexGrow = 1;
root_child0.PaddingLeft = 10.Percent();
root_child0.PaddingTop = 10.Percent();
root_child0.PaddingRight = 10.Percent();
root_child0.PaddingBottom = 10.Percent();
root.Insert(0, root_child0);
YogaNode root_child0_child0 = new YogaNode(config);
root_child0_child0.Width = 10;
root_child0_child0.Height = 10;
root_child0.Insert(0, root_child0_child0);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(200f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(20f, root_child0_child0.LayoutX);
Assert.AreEqual(20f, root_child0_child0.LayoutY);
Assert.AreEqual(10f, root_child0_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0_child0.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(200f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(170f, root_child0_child0.LayoutX);
Assert.AreEqual(20f, root_child0_child0.LayoutY);
Assert.AreEqual(10f, root_child0_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0_child0.LayoutHeight);
}
[Test]
public void Test_percentage_absolute_position()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Width = 200;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.PositionType = YogaPositionType.Absolute;
root_child0.Left = 30.Percent();
root_child0.Top = 10.Percent();
root_child0.Width = 10;
root_child0.Height = 10;
root.Insert(0, root_child0);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(60f, root_child0.LayoutX);
Assert.AreEqual(10f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(60f, root_child0.LayoutX);
Assert.AreEqual(10f, root_child0.LayoutY);
Assert.AreEqual(10f, root_child0.LayoutWidth);
Assert.AreEqual(10f, root_child0.LayoutHeight);
}
[Test]
public void Test_percentage_width_height_undefined_parent_size()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 50.Percent();
root_child0.Height = 50.Percent();
root.Insert(0, root_child0);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(0f, root.LayoutWidth);
Assert.AreEqual(0f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(0f, root_child0.LayoutWidth);
Assert.AreEqual(0f, root_child0.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(0f, root.LayoutWidth);
Assert.AreEqual(0f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(0f, root_child0.LayoutWidth);
Assert.AreEqual(0f, root_child0.LayoutHeight);
}
[Test]
public void Test_percent_within_flex_grow()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.FlexDirection = YogaFlexDirection.Row;
root.Width = 350;
root.Height = 100;
YogaNode root_child0 = new YogaNode(config);
root_child0.Width = 100;
root.Insert(0, root_child0);
YogaNode root_child1 = new YogaNode(config);
root_child1.FlexGrow = 1;
root.Insert(1, root_child1);
YogaNode root_child1_child0 = new YogaNode(config);
root_child1_child0.Width = 100.Percent();
root_child1.Insert(0, root_child1_child0);
YogaNode root_child2 = new YogaNode(config);
root_child2.Width = 100;
root.Insert(2, root_child2);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(350f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(0f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(100f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(150f, root_child1.LayoutWidth);
Assert.AreEqual(100f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child1_child0.LayoutX);
Assert.AreEqual(0f, root_child1_child0.LayoutY);
Assert.AreEqual(150f, root_child1_child0.LayoutWidth);
Assert.AreEqual(0f, root_child1_child0.LayoutHeight);
Assert.AreEqual(250f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(100f, root_child2.LayoutWidth);
Assert.AreEqual(100f, root_child2.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(350f, root.LayoutWidth);
Assert.AreEqual(100f, root.LayoutHeight);
Assert.AreEqual(250f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(100f, root_child0.LayoutHeight);
Assert.AreEqual(100f, root_child1.LayoutX);
Assert.AreEqual(0f, root_child1.LayoutY);
Assert.AreEqual(150f, root_child1.LayoutWidth);
Assert.AreEqual(100f, root_child1.LayoutHeight);
Assert.AreEqual(0f, root_child1_child0.LayoutX);
Assert.AreEqual(0f, root_child1_child0.LayoutY);
Assert.AreEqual(150f, root_child1_child0.LayoutWidth);
Assert.AreEqual(0f, root_child1_child0.LayoutHeight);
Assert.AreEqual(0f, root_child2.LayoutX);
Assert.AreEqual(0f, root_child2.LayoutY);
Assert.AreEqual(100f, root_child2.LayoutWidth);
Assert.AreEqual(100f, root_child2.LayoutHeight);
}
[Test]
public void Test_percentage_container_in_wrapping_container()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.JustifyContent = YogaJustify.Center;
root.AlignItems = YogaAlign.Center;
root.Width = 200;
root.Height = 200;
YogaNode root_child0 = new YogaNode(config);
root.Insert(0, root_child0);
YogaNode root_child0_child0 = new YogaNode(config);
root_child0_child0.FlexDirection = YogaFlexDirection.Row;
root_child0_child0.JustifyContent = YogaJustify.Center;
root_child0_child0.Width = 100.Percent();
root_child0.Insert(0, root_child0_child0);
YogaNode root_child0_child0_child0 = new YogaNode(config);
root_child0_child0_child0.Width = 50;
root_child0_child0_child0.Height = 50;
root_child0_child0.Insert(0, root_child0_child0_child0);
YogaNode root_child0_child0_child1 = new YogaNode(config);
root_child0_child0_child1.Width = 50;
root_child0_child0_child1.Height = 50;
root_child0_child0.Insert(1, root_child0_child0_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(50f, root_child0.LayoutX);
Assert.AreEqual(75f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0.LayoutY);
Assert.AreEqual(100f, root_child0_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0_child0.LayoutY);
Assert.AreEqual(50f, root_child0_child0_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0_child0.LayoutHeight);
Assert.AreEqual(50f, root_child0_child0_child1.LayoutX);
Assert.AreEqual(0f, root_child0_child0_child1.LayoutY);
Assert.AreEqual(50f, root_child0_child0_child1.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(200f, root.LayoutWidth);
Assert.AreEqual(200f, root.LayoutHeight);
Assert.AreEqual(50f, root_child0.LayoutX);
Assert.AreEqual(75f, root_child0.LayoutY);
Assert.AreEqual(100f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0.LayoutY);
Assert.AreEqual(100f, root_child0_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0.LayoutHeight);
Assert.AreEqual(50f, root_child0_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0_child0.LayoutY);
Assert.AreEqual(50f, root_child0_child0_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0_child1.LayoutX);
Assert.AreEqual(0f, root_child0_child0_child1.LayoutY);
Assert.AreEqual(50f, root_child0_child0_child1.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0_child1.LayoutHeight);
}
[Test]
public void Test_percent_absolute_position()
{
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
root.Width = 60;
root.Height = 50;
YogaNode root_child0 = new YogaNode(config);
root_child0.FlexDirection = YogaFlexDirection.Row;
root_child0.PositionType = YogaPositionType.Absolute;
root_child0.Left = 50.Percent();
root_child0.Width = 100.Percent();
root_child0.Height = 50;
root.Insert(0, root_child0);
YogaNode root_child0_child0 = new YogaNode(config);
root_child0_child0.Width = 100.Percent();
root_child0.Insert(0, root_child0_child0);
YogaNode root_child0_child1 = new YogaNode(config);
root_child0_child1.Width = 100.Percent();
root_child0.Insert(1, root_child0_child1);
root.StyleDirection = YogaDirection.LTR;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(60f, root.LayoutWidth);
Assert.AreEqual(50f, root.LayoutHeight);
Assert.AreEqual(30f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(60f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0.LayoutY);
Assert.AreEqual(60f, root_child0_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0.LayoutHeight);
Assert.AreEqual(60f, root_child0_child1.LayoutX);
Assert.AreEqual(0f, root_child0_child1.LayoutY);
Assert.AreEqual(60f, root_child0_child1.LayoutWidth);
Assert.AreEqual(50f, root_child0_child1.LayoutHeight);
root.StyleDirection = YogaDirection.RTL;
root.CalculateLayout();
Assert.AreEqual(0f, root.LayoutX);
Assert.AreEqual(0f, root.LayoutY);
Assert.AreEqual(60f, root.LayoutWidth);
Assert.AreEqual(50f, root.LayoutHeight);
Assert.AreEqual(30f, root_child0.LayoutX);
Assert.AreEqual(0f, root_child0.LayoutY);
Assert.AreEqual(60f, root_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0.LayoutHeight);
Assert.AreEqual(0f, root_child0_child0.LayoutX);
Assert.AreEqual(0f, root_child0_child0.LayoutY);
Assert.AreEqual(60f, root_child0_child0.LayoutWidth);
Assert.AreEqual(50f, root_child0_child0.LayoutHeight);
Assert.AreEqual(-60f, root_child0_child1.LayoutX);
Assert.AreEqual(0f, root_child0_child1.LayoutY);
Assert.AreEqual(60f, root_child0_child1.LayoutWidth);
Assert.AreEqual(50f, root_child0_child1.LayoutHeight);
}
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
[System.Serializable]
[NodeAttributes( "Vector2", "Constants", "Vector2 property", null, KeyCode.Alpha2 )]
public sealed class Vector2Node : PropertyNode
{
[SerializeField]
private Vector2 m_defaultValue = Vector2.zero;
[SerializeField]
private Vector2 m_materialValue = Vector2.zero;
private const float LabelWidth = 8;
private int m_cachedPropertyId = -1;
public Vector2Node() : base() { }
public Vector2Node( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { }
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_insideSize.Set(50,20);
m_selectedLocation = PreviewLocation.BottomCenter;
AddOutputVectorPorts( WirePortDataType.FLOAT2, "XY" );
m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType );
m_previewShaderGUID = "88b4191eb06084d4da85d1dd2f984085";
}
public override void CopyDefaultsToMaterial()
{
m_materialValue = m_defaultValue;
}
public override void DrawSubProperties()
{
m_defaultValue = EditorGUILayoutVector2Field( Constants.DefaultValueLabel, m_defaultValue );
}
public override void DrawMaterialProperties()
{
if ( m_materialMode )
EditorGUI.BeginChangeCheck();
m_materialValue = EditorGUILayoutVector2Field( Constants.MaterialValueLabel, m_materialValue );
if ( m_materialMode && EditorGUI.EndChangeCheck() )
m_requireMaterialUpdate = true;
}
public override void SetPreviewInputs()
{
base.SetPreviewInputs();
if ( m_cachedPropertyId == -1 )
m_cachedPropertyId = Shader.PropertyToID( "_InputVector" );
if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
PreviewMaterial.SetVector( m_cachedPropertyId, new Vector4( m_materialValue[ 0 ], m_materialValue[ 1 ], 0, 0 ) );
else
PreviewMaterial.SetVector( m_cachedPropertyId, new Vector4( m_defaultValue[ 0 ], m_defaultValue[ 1 ], 0, 0 ) );
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( m_isVisible )
{
m_propertyDrawPos = m_remainingBox;
m_propertyDrawPos.x = m_remainingBox.x - LabelWidth * drawInfo.InvertedZoom;
m_propertyDrawPos.width = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_WIDTH_FIELD_SIZE;
m_propertyDrawPos.height = drawInfo.InvertedZoom * Constants.FLOAT_DRAW_HEIGHT_FIELD_SIZE;
EditorGUI.BeginChangeCheck();
for ( int i = 0; i < 2; i++ )
{
m_propertyDrawPos.y = m_outputPorts[ i + 1 ].Position.y - 2 * drawInfo.InvertedZoom;
if ( m_materialMode && m_currentParameterType != PropertyType.Constant )
{
float val = m_materialValue[ i ];
UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref val, LabelWidth * drawInfo.InvertedZoom );
m_materialValue[ i ] = val;
}
else
{
float val = m_defaultValue[ i ];
UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref val, LabelWidth * drawInfo.InvertedZoom );
m_defaultValue[ i ] = val;
}
}
if ( EditorGUI.EndChangeCheck() )
{
m_requireMaterialUpdate = m_materialMode;
//MarkForPreviewUpdate();
BeginDelayedDirtyProperty();
}
}
}
public override void ConfigureLocalVariable( ref MasterNodeDataCollector dataCollector )
{
Vector2 value = m_defaultValue;
dataCollector.AddLocalVariable( UniqueId, CreateLocalVarDec( value.x + "," + value.y ) );
m_outputPorts[ 0 ].SetLocalValue( m_propertyName );
m_outputPorts[ 1 ].SetLocalValue( m_propertyName + ".x" );
m_outputPorts[ 2 ].SetLocalValue( m_propertyName + ".y" );
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
base.GenerateShaderForOutput( outputId,ref dataCollector, ignoreLocalvar );
m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType );
if ( m_currentParameterType != PropertyType.Constant )
return GetOutputVectorItem( 0, outputId, PropertyData );
if ( m_outputPorts[ outputId ].IsLocalValue )
{
return m_outputPorts[ outputId ].LocalValue;
}
if ( CheckLocalVariable( ref dataCollector ) )
{
return m_outputPorts[ outputId ].LocalValue;
}
Vector2 value = m_defaultValue;
string result = string.Empty;
switch ( outputId )
{
case 0:
{
result = m_precisionString+"( " + value.x + "," + value.y + " )";
}
break;
case 1:
{
result = value.x.ToString();
}
break;
case 2:
{
result = value.y.ToString();
}
break;
}
if ( result.Equals( string.Empty ) )
{
UIUtils.ShowMessage( "Vector2Node generating empty code", MessageSeverity.Warning );
}
return result;
}
public override string GetPropertyValue()
{
return PropertyAttributes + m_propertyName + "(\"" + m_propertyInspectorName + "\", Vector) = (" + m_defaultValue.x + "," + m_defaultValue.y + ",0,0)";
}
public override void UpdateMaterial( Material mat )
{
base.UpdateMaterial( mat );
if ( UIUtils.IsProperty( m_currentParameterType ) )
{
mat.SetVector( m_propertyName, m_materialValue );
}
}
public override void SetMaterialMode( Material mat , bool fetchMaterialValues )
{
base.SetMaterialMode( mat , fetchMaterialValues );
if ( fetchMaterialValues && m_materialMode && UIUtils.IsProperty( m_currentParameterType ) && mat.HasProperty( m_propertyName ) )
{
m_materialValue = mat.GetVector( m_propertyName );
}
}
public override void ForceUpdateFromMaterial( Material material )
{
if ( UIUtils.IsProperty( m_currentParameterType ) && material.HasProperty( m_propertyName ) )
m_materialValue = material.GetVector( m_propertyName );
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
string[] components = GetCurrentParam( ref nodeParams ).Split( IOUtils.VECTOR_SEPARATOR );
if ( components.Length == 2 )
{
m_defaultValue.x = Convert.ToSingle( components[ 0 ] );
m_defaultValue.y = Convert.ToSingle( components[ 1 ] );
}
else
{
UIUtils.ShowMessage( "Incorrect number of float2 values", MessageSeverity.Error );
}
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_defaultValue.x.ToString() + IOUtils.VECTOR_SEPARATOR +
m_defaultValue.y.ToString() );
}
public override void ReadAdditionalClipboardData( ref string[] nodeParams )
{
base.ReadAdditionalClipboardData( ref nodeParams );
m_materialValue = IOUtils.StringToVector2( GetCurrentParam( ref nodeParams ) );
}
public override void WriteAdditionalClipboardData( ref string nodeInfo )
{
base.WriteAdditionalClipboardData( ref nodeInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, IOUtils.Vector2ToString( m_materialValue ) );
}
public override string GetPropertyValStr()
{
return ( m_materialMode && m_currentParameterType != PropertyType.Constant ) ? m_materialValue.x.ToString( Mathf.Abs( m_materialValue.x ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_materialValue.y.ToString( Mathf.Abs( m_materialValue.y ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel ) :
m_defaultValue.x.ToString( Mathf.Abs( m_defaultValue.x ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel ) + IOUtils.VECTOR_SEPARATOR +
m_defaultValue.y.ToString( Mathf.Abs( m_defaultValue.y ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel );
}
public Vector2 Value
{
get { return m_defaultValue; }
set { m_defaultValue = value; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using ITN.Felicity.Api.Areas.HelpPage.ModelDescriptions;
using ITN.Felicity.Api.Areas.HelpPage.Models;
namespace ITN.Felicity.Api.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using Internal.Runtime.CompilerServices;
namespace System
{
// The String class represents a static string of characters. Many of
// the string methods perform some type of transformation on the current
// instance and return the result as a new string. As with arrays, character
// positions (indices) are zero-based.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed partial class String : IComparable, IEnumerable, IConvertible, IEnumerable<char>, IComparable<string>, IEquatable<string>, ICloneable
{
// String constructors
// These are special. The implementation methods for these have a different signature from the
// declared constructors.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char[] value);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private string Ctor(char[] value)
{
if (value == null || value.Length == 0)
return Empty;
string result = FastAllocateString(value.Length);
unsafe
{
fixed (char* dest = &result._firstChar, source = value)
wstrcpy(dest, source, value.Length);
}
return result;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char[] value, int startIndex, int length);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private string Ctor(char[] value, int startIndex, int length)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (startIndex > value.Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (length == 0)
return Empty;
string result = FastAllocateString(length);
unsafe
{
fixed (char* dest = &result._firstChar, source = value)
wstrcpy(dest, source + startIndex, length);
}
return result;
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern unsafe String(char* value);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(char* ptr)
{
if (ptr == null)
return Empty;
int count = wcslen(ptr);
if (count == 0)
return Empty;
string result = FastAllocateString(count);
fixed (char* dest = &result._firstChar)
wstrcpy(dest, ptr, count);
return result;
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern unsafe String(char* value, int startIndex, int length);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(char* ptr, int startIndex, int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
char* pStart = ptr + startIndex;
// overflow check
if (pStart < ptr)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
if (length == 0)
return Empty;
if (ptr == null)
throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR);
string result = FastAllocateString(length);
fixed (char* dest = &result._firstChar)
wstrcpy(dest, pStart, length);
return result;
}
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
public extern unsafe String(sbyte* value);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(sbyte* value)
{
byte* pb = (byte*)value;
if (pb == null)
return Empty;
int numBytes = strlen((byte*)value);
return CreateStringForSByteConstructor(pb, numBytes);
}
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
public extern unsafe String(sbyte* value, int startIndex, int length);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(sbyte* value, int startIndex, int length)
{
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (value == null)
{
if (length == 0)
return Empty;
throw new ArgumentNullException(nameof(value));
}
byte* pStart = (byte*)(value + startIndex);
// overflow check
if (pStart < value)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_PartialWCHAR);
return CreateStringForSByteConstructor(pStart, length);
}
// Encoder for String..ctor(sbyte*) and String..ctor(sbyte*, int, int)
private static unsafe string CreateStringForSByteConstructor(byte *pb, int numBytes)
{
Debug.Assert(numBytes >= 0);
Debug.Assert(pb <= (pb + numBytes));
if (numBytes == 0)
return Empty;
#if PLATFORM_WINDOWS
int numCharsRequired = Interop.Kernel32.MultiByteToWideChar(Interop.Kernel32.CP_ACP, Interop.Kernel32.MB_PRECOMPOSED, pb, numBytes, (char*)null, 0);
if (numCharsRequired == 0)
throw new ArgumentException(SR.Arg_InvalidANSIString);
string newString = FastAllocateString(numCharsRequired);
fixed (char *pFirstChar = &newString._firstChar)
{
numCharsRequired = Interop.Kernel32.MultiByteToWideChar(Interop.Kernel32.CP_ACP, Interop.Kernel32.MB_PRECOMPOSED, pb, numBytes, pFirstChar, numCharsRequired);
}
if (numCharsRequired == 0)
throw new ArgumentException(SR.Arg_InvalidANSIString);
return newString;
#else
return Encoding.UTF8.GetString(pb, numBytes);
#endif
}
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.InternalCall)]
public extern unsafe String(sbyte* value, int startIndex, int length, Encoding enc);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(sbyte* value, int startIndex, int length, Encoding enc)
{
if (enc == null)
return new string(value, startIndex, length);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (value == null)
{
if (length == 0)
return Empty;
throw new ArgumentNullException(nameof(value));
}
byte* pStart = (byte*)(value + startIndex);
// overflow check
if (pStart < value)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
return enc.GetString(new ReadOnlySpan<byte>(pStart, length));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char c, int count);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private string Ctor(char c, int count)
{
if (count <= 0)
{
if (count == 0)
return Empty;
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount);
}
string result = FastAllocateString(count);
if (c != '\0') // Fast path null char string
{
unsafe
{
fixed (char* dest = &result._firstChar)
{
uint cc = (uint)((c << 16) | c);
uint* dmem = (uint*)dest;
if (count >= 4)
{
count -= 4;
do
{
dmem[0] = cc;
dmem[1] = cc;
dmem += 2;
count -= 4;
} while (count >= 0);
}
if ((count & 2) != 0)
{
*dmem = cc;
dmem++;
}
if ((count & 1) != 0)
((char*)dmem)[0] = c;
}
}
}
return result;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(ReadOnlySpan<char> value);
#if PROJECTN
[DependencyReductionRoot]
#endif
#if !CORECLR
static
#endif
private unsafe string Ctor(ReadOnlySpan<char> value)
{
if (value.Length == 0)
return Empty;
string result = FastAllocateString(value.Length);
fixed (char* dest = &result._firstChar, src = &MemoryMarshal.GetReference(value))
wstrcpy(dest, src, value.Length);
return result;
}
public static string Create<TState>(int length, TState state, SpanAction<char, TState> action)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
if (length <= 0)
{
if (length == 0)
return Empty;
throw new ArgumentOutOfRangeException(nameof(length));
}
string result = FastAllocateString(length);
action(new Span<char>(ref result.GetRawStringData(), length), state);
return result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator ReadOnlySpan<char>(string value) =>
value != null ? new ReadOnlySpan<char>(ref value.GetRawStringData(), value.Length) : default;
public object Clone()
{
return this;
}
public static unsafe string Copy(string str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
string result = FastAllocateString(str.Length);
fixed (char* dest = &result._firstChar, src = &str._firstChar)
wstrcpy(dest, src, str.Length);
return result;
}
// Converts a substring of this string to an array of characters. Copies the
// characters of this string beginning at position sourceIndex and ending at
// sourceIndex + count - 1 to the character array buffer, beginning
// at destinationIndex.
//
public unsafe void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
{
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount);
if (sourceIndex < 0)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index);
if (count > Length - sourceIndex)
throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexCount);
if (destinationIndex > destination.Length - count || destinationIndex < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_IndexCount);
fixed (char* src = &_firstChar, dest = destination)
wstrcpy(dest + destinationIndex, src + sourceIndex, count);
}
// Returns the entire string as an array of characters.
public unsafe char[] ToCharArray()
{
if (Length == 0)
return Array.Empty<char>();
char[] chars = new char[Length];
fixed (char* src = &_firstChar, dest = &chars[0])
wstrcpy(dest, src, Length);
return chars;
}
// Returns a substring of this string as an array of characters.
//
public unsafe char[] ToCharArray(int startIndex, int length)
{
// Range check everything.
if (startIndex < 0 || startIndex > Length || startIndex > Length - length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (length <= 0)
{
if (length == 0)
return Array.Empty<char>();
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
}
char[] chars = new char[length];
fixed (char* src = &_firstChar, dest = &chars[0])
wstrcpy(dest, src + startIndex, length);
return chars;
}
[NonVersionable]
public static bool IsNullOrEmpty(string value)
{
// Using 0u >= (uint)value.Length rather than
// value.Length == 0 as it will elide the bounds check to
// the first char: value[0] if that is performed following the test
// for the same test cost.
// Ternary operator returning true/false prevents redundant asm generation:
// https://github.com/dotnet/coreclr/issues/914
return (value == null || 0u >= (uint)value.Length) ? true : false;
}
[System.Runtime.CompilerServices.IndexerName("Chars")]
public char this[Index index]
{
get
{
int actualIndex = index.GetOffset(Length);
return this[actualIndex];
}
}
[System.Runtime.CompilerServices.IndexerName("Chars")]
public string this[Range range] => Substring(range);
public static bool IsNullOrWhiteSpace(string value)
{
if (value == null) return true;
for (int i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i])) return false;
}
return true;
}
internal ref char GetRawStringData() => ref _firstChar;
// Helper for encodings so they can talk to our buffer directly
// stringLength must be the exact size we'll expect
internal static unsafe string CreateStringFromEncoding(
byte* bytes, int byteLength, Encoding encoding)
{
Debug.Assert(bytes != null);
Debug.Assert(byteLength >= 0);
// Get our string length
int stringLength = encoding.GetCharCount(bytes, byteLength, null);
Debug.Assert(stringLength >= 0, "stringLength >= 0");
// They gave us an empty string if they needed one
// 0 bytelength might be possible if there's something in an encoder
if (stringLength == 0)
return Empty;
string s = FastAllocateString(stringLength);
fixed (char* pTempChars = &s._firstChar)
{
int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null);
Debug.Assert(stringLength == doubleCheck,
"Expected encoding.GetChars to return same length as encoding.GetCharCount");
}
return s;
}
// This is only intended to be used by char.ToString.
// It is necessary to put the code in this class instead of Char, since _firstChar is a private member.
// Making _firstChar internal would be dangerous since it would make it much easier to break String's immutability.
internal static string CreateFromChar(char c)
{
string result = FastAllocateString(1);
result._firstChar = c;
return result;
}
internal static string CreateFromChar(char c1, char c2)
{
string result = FastAllocateString(2);
result._firstChar = c1;
Unsafe.Add(ref result._firstChar, 1) = c2;
return result;
}
internal static unsafe void wstrcpy(char* dmem, char* smem, int charCount)
{
Buffer.Memmove((byte*)dmem, (byte*)smem, ((uint)charCount) * 2);
}
// Returns this string.
public override string ToString()
{
return this;
}
// Returns this string.
public string ToString(IFormatProvider provider)
{
return this;
}
public CharEnumerator GetEnumerator()
{
return new CharEnumerator(this);
}
IEnumerator<char> IEnumerable<char>.GetEnumerator()
{
return new CharEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new CharEnumerator(this);
}
/// <summary>
/// Returns an enumeration of <see cref="Rune"/> from this string.
/// </summary>
/// <remarks>
/// Invalid sequences will be represented in the enumeration by <see cref="Rune.ReplacementChar"/>.
/// </remarks>
public StringRuneEnumerator EnumerateRunes()
{
return new StringRuneEnumerator(this);
}
internal static unsafe int wcslen(char* ptr)
{
char* end = ptr;
// First make sure our pointer is aligned on a word boundary
int alignment = IntPtr.Size - 1;
// If ptr is at an odd address (e.g. 0x5), this loop will simply iterate all the way
while (((uint)end & (uint)alignment) != 0)
{
if (*end == 0) goto FoundZero;
end++;
}
#if !BIT64
// The following code is (somewhat surprisingly!) significantly faster than a naive loop,
// at least on x86 and the current jit.
// The loop condition below works because if "end[0] & end[1]" is non-zero, that means
// neither operand can have been zero. If is zero, we have to look at the operands individually,
// but we hope this going to fairly rare.
// In general, it would be incorrect to access end[1] if we haven't made sure
// end[0] is non-zero. However, we know the ptr has been aligned by the loop above
// so end[0] and end[1] must be in the same word (and therefore page), so they're either both accessible, or both not.
while ((end[0] & end[1]) != 0 || (end[0] != 0 && end[1] != 0))
{
end += 2;
}
Debug.Assert(end[0] == 0 || end[1] == 0);
if (end[0] != 0) end++;
#else // !BIT64
// Based on https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
// 64-bit implementation: process 1 ulong (word) at a time
// What we do here is add 0x7fff from each of the
// 4 individual chars within the ulong, using MagicMask.
// If the char > 0 and < 0x8001, it will have its high bit set.
// We then OR with MagicMask, to set all the other bits.
// This will result in all bits set (ulong.MaxValue) for any
// char that fits the above criteria, and something else otherwise.
// Note that for any char > 0x8000, this will be a false
// positive and we will fallback to the slow path and
// check each char individually. This is OK though, since
// we optimize for the common case (ASCII chars, which are < 0x80).
// NOTE: We can access a ulong a time since the ptr is aligned,
// and therefore we're only accessing the same word/page. (See notes
// for the 32-bit version above.)
const ulong MagicMask = 0x7fff7fff7fff7fff;
while (true)
{
ulong word = *(ulong*)end;
word += MagicMask; // cause high bit to be set if not zero, and <= 0x8000
word |= MagicMask; // set everything besides the high bits
if (word == ulong.MaxValue) // 0xffff...
{
// all of the chars have their bits set (and therefore none can be 0)
end += 4;
continue;
}
// at least one of them didn't have their high bit set!
// go through each char and check for 0.
if (end[0] == 0) goto EndAt0;
if (end[1] == 0) goto EndAt1;
if (end[2] == 0) goto EndAt2;
if (end[3] == 0) goto EndAt3;
// if we reached here, it was a false positive-- just continue
end += 4;
}
EndAt3: end++;
EndAt2: end++;
EndAt1: end++;
EndAt0:
#endif // !BIT64
FoundZero:
Debug.Assert(*end == 0);
int count = (int)(end - ptr);
#if BIT64
// Check for overflow
if (ptr + count != end)
throw new ArgumentException(SR.Arg_MustBeNullTerminatedString);
#else
Debug.Assert(ptr + count == end);
#endif
return count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe int strlen(byte* ptr)
{
// IndexOf processes memory in aligned chunks, and thus it won't crash even if it accesses memory beyond the null terminator.
int length = SpanHelpers.IndexOf(ref *ptr, (byte)'\0', int.MaxValue);
if (length < 0)
{
ThrowMustBeNullTerminatedString();
}
return length;
}
private static void ThrowMustBeNullTerminatedString()
{
throw new ArgumentException(SR.Arg_MustBeNullTerminatedString);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.String;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(this, provider);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(this, provider);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(this, provider);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(this, provider);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(this, provider);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(this, provider);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(this, provider);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(this, provider);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(this, provider);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(this, provider);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(this, provider);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(this, provider);
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(this, provider);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return Convert.ToDateTime(this, provider);
}
object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
// Normalization Methods
// These just wrap calls to Normalization class
public bool IsNormalized()
{
return IsNormalized(NormalizationForm.FormC);
}
public bool IsNormalized(NormalizationForm normalizationForm)
{
#if CORECLR
if (this.IsFastSort())
{
// If its FastSort && one of the 4 main forms, then its already normalized
if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD)
return true;
}
#endif
return Normalization.IsNormalized(this, normalizationForm);
}
public string Normalize()
{
return Normalize(NormalizationForm.FormC);
}
public string Normalize(NormalizationForm normalizationForm)
{
#if CORECLR
if (this.IsAscii())
{
// If its FastSort && one of the 4 main forms, then its already normalized
if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
normalizationForm == NormalizationForm.FormKD)
return this;
}
#endif
return Normalization.Normalize(this, normalizationForm);
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Registrasi_FISAddRJ : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["RegistrasiFIS"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
btnSave.Text = "<center><img alt=\"" + Resources.GetString("", "Save") + "\" src=\"" + Request.ApplicationPath + "/images/save_f2.gif\" align=\"middle\" border=\"0\" name=\"save\" value=\"save\"><center>";
btnCancel.Text = "<center><img alt=\"" + Resources.GetString("", "Cancel") + "\" src=\"" + Request.ApplicationPath + "/images/cancel_f2.gif\" align=\"middle\" border=\"0\" name=\"cancel\" value=\"cancel\"><center>";
GetListJenisPenjamin();
GetListHubungan();
GetListStatus();
GetListPangkat();
GetListAgama();
GetListPendidikan();
txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy");
GetNomorRegistrasi();
GetNomorTunggu();
GetListKelompokPemeriksaan();
GetListSatuanKerjaPenjamin();
}
}
//=========
public void GetListStatus()
{
string StatusId = "";
SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status();
DataTable dt = myObj.GetList();
cmbStatusPenjamin.Items.Clear();
int i = 0;
cmbStatusPenjamin.Items.Add("");
cmbStatusPenjamin.Items[i].Text = "";
cmbStatusPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbStatusPenjamin.Items.Add("");
cmbStatusPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbStatusPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == StatusId)
{
cmbStatusPenjamin.SelectedIndex = i;
}
i++;
}
}
public void GetListPangkat()
{
string PangkatId = "";
SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat();
DataTable dt = myObj.GetList();
cmbPangkatPenjamin.Items.Clear();
int i = 0;
cmbPangkatPenjamin.Items.Add("");
cmbPangkatPenjamin.Items[i].Text = "";
cmbPangkatPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPangkatPenjamin.Items.Add("");
cmbPangkatPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbPangkatPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PangkatId)
{
cmbPangkatPenjamin.SelectedIndex = i;
}
i++;
}
}
public void GetListAgama()
{
string AgamaId = "";
BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama();
DataTable dt = myObj.GetList();
cmbAgamaPenjamin.Items.Clear();
int i = 0;
cmbAgamaPenjamin.Items.Add("");
cmbAgamaPenjamin.Items[i].Text = "";
cmbAgamaPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbAgamaPenjamin.Items.Add("");
cmbAgamaPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbAgamaPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == AgamaId)
cmbAgamaPenjamin.SelectedIndex = i;
i++;
}
}
public void GetListPendidikan()
{
string PendidikanId = "";
BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan();
DataTable dt = myObj.GetList();
cmbPendidikanPenjamin.Items.Clear();
int i = 0;
cmbPendidikanPenjamin.Items.Add("");
cmbPendidikanPenjamin.Items[i].Text = "";
cmbPendidikanPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbPendidikanPenjamin.Items.Add("");
cmbPendidikanPenjamin.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString();
cmbPendidikanPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == PendidikanId)
cmbPendidikanPenjamin.SelectedIndex = i;
i++;
}
}
//==========
public void GetNomorTunggu()
{
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.PoliklinikId = 34;//FIS
myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
txtNomorTunggu.Text = myObj.GetNomorTunggu().ToString();
}
public void GetListJenisPenjamin()
{
string JenisPenjaminId = "";
SIMRS.DataAccess.RS_JenisPenjamin myObj = new SIMRS.DataAccess.RS_JenisPenjamin();
DataTable dt = myObj.GetList();
cmbJenisPenjamin.Items.Clear();
int i = 0;
foreach (DataRow dr in dt.Rows)
{
cmbJenisPenjamin.Items.Add("");
cmbJenisPenjamin.Items[i].Text = dr["Nama"].ToString();
cmbJenisPenjamin.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == JenisPenjaminId)
cmbJenisPenjamin.SelectedIndex = i;
i++;
}
}
public void GetListHubungan()
{
string HubunganId = "";
SIMRS.DataAccess.RS_Hubungan myObj = new SIMRS.DataAccess.RS_Hubungan();
DataTable dt = myObj.GetList();
cmbHubungan.Items.Clear();
int i = 0;
cmbHubungan.Items.Add("");
cmbHubungan.Items[i].Text = "";
cmbHubungan.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbHubungan.Items.Add("");
cmbHubungan.Items[i].Text = dr["Nama"].ToString();
cmbHubungan.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == HubunganId)
cmbHubungan.SelectedIndex = i;
i++;
}
}
public void GetNomorRegistrasi()
{
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.PoliklinikId = 34;//FIS
myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
txtNoRegistrasi.Text = myObj.GetNomorRegistrasi();
lblNoRegistrasi.Text = txtNoRegistrasi.Text;
}
public void GetListKelompokPemeriksaan()
{
SIMRS.DataAccess.RS_KelompokPemeriksaan myObj = new SIMRS.DataAccess.RS_KelompokPemeriksaan();
myObj.JenisPemeriksaanId = 4;//FIS
DataTable dt = myObj.GetListByJenisPemeriksaanId();
cmbKelompokPemeriksaan.Items.Clear();
int i = 0;
foreach (DataRow dr in dt.Rows)
{
cmbKelompokPemeriksaan.Items.Add("");
cmbKelompokPemeriksaan.Items[i].Text = dr["Nama"].ToString();
cmbKelompokPemeriksaan.Items[i].Value = dr["Id"].ToString();
i++;
}
cmbKelompokPemeriksaan.SelectedIndex = 0;
GetListPemeriksaan();
}
public DataSet GetDataPemeriksaan()
{
DataSet ds = new DataSet();
if (Session["dsLayananFIS"] != null)
ds = (DataSet)Session["dsLayananFIS"];
else
{
SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan();
myObj.PoliklinikId = 34;// FIS
DataTable myData = myObj.SelectAllWPoliklinikIdLogic();
ds.Tables.Add(myData);
Session.Add("dsLayananFIS", ds);
}
return ds;
}
public void GetListPemeriksaan()
{
DataSet ds = new DataSet();
ds = GetDataPemeriksaan();
lstRefPemeriksaan.DataTextField = "Nama";
lstRefPemeriksaan.DataValueField = "Id";
DataView dv = ds.Tables[0].DefaultView;
dv.RowFilter = " KelompokPemeriksaanId = " + cmbKelompokPemeriksaan.SelectedItem.Value;
lstRefPemeriksaan.DataSource = dv;
lstRefPemeriksaan.DataBind();
}
public void OnSave(Object sender, EventArgs e)
{
lblError.Text = "";
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (!Page.IsValid)
{
return;
}
if (txtPasienId.Text == "")
{
lblError.Text = "Data Pasien Belum dipilih !";
return;
}
int PenjaminId = 0;
if (cmbJenisPenjamin.SelectedIndex > 0)
{
//Input Data Penjamin
SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin();
myPenj.PenjaminId = 0;
if (cmbJenisPenjamin.SelectedIndex == 1)
{
myPenj.Nama = txtNamaPenjamin.Text;
if (cmbHubungan.SelectedIndex > 0)
myPenj.HubunganId = int.Parse(cmbHubungan.SelectedItem.Value);
myPenj.Umur = txtUmurPenjamin.Text;
myPenj.Alamat = txtAlamatPenjamin.Text;
myPenj.Telepon = txtTeleponPenjamin.Text;
if (cmbAgamaPenjamin.SelectedIndex > 0)
myPenj.AgamaId = int.Parse(cmbAgamaPenjamin.SelectedItem.Value);
if (cmbPendidikanPenjamin.SelectedIndex > 0)
myPenj.PendidikanId = int.Parse(cmbPendidikanPenjamin.SelectedItem.Value);
if (cmbPangkatPenjamin.SelectedIndex > 0)
myPenj.PangkatId = int.Parse(cmbPangkatPenjamin.SelectedItem.Value);
myPenj.NoKTP = txtNoKTPPenjamin.Text;
myPenj.GolDarah = txtGolDarahPenjamin.Text;
myPenj.NRP = txtNRPPenjamin.Text;
//myPenj.Kesatuan = txtKesatuanPenjamin.Text;
myPenj.Kesatuan = cmbSatuanKerjaPenjamin.SelectedItem.ToString();
myPenj.AlamatKesatuan = txtAlamatKesatuanPenjamin.Text;
myPenj.Keterangan = txtKeteranganPenjamin.Text;
}
else
{
myPenj.Nama = txtNamaPerusahaan.Text;
myPenj.NamaKontak = txtNamaKontak.Text;
myPenj.Alamat = txtAlamatPerusahaan.Text;
myPenj.Telepon = txtTeleponPerusahaan.Text;
myPenj.Fax = txtFAXPerusahaan.Text;
}
myPenj.CreatedBy = UserId;
myPenj.CreatedDate = DateTime.Now;
myPenj.Insert();
PenjaminId = (int)myPenj.PenjaminId;
}
//Input Data Registrasi
SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi();
myReg.RegistrasiId = 0;
myReg.PasienId = Int64.Parse(txtPasienId.Text);
GetNomorRegistrasi();
myReg.NoRegistrasi = txtNoRegistrasi.Text;
//myReg.NoUrut = txtNoUrut.Text;
myReg.JenisRegistrasiId = 1;
myReg.TanggalRegistrasi = DateTime.Parse(txtTanggalRegistrasi.Text);
myReg.JenisPenjaminId = int.Parse(cmbJenisPenjamin.SelectedItem.Value);
if (PenjaminId != 0)
myReg.PenjaminId = PenjaminId;
myReg.CreatedBy = UserId;
myReg.CreatedDate = DateTime.Now;
myReg.Insert();
//Input Data Rawat Jalan
SIMRS.DataAccess.RS_RawatJalan myRJ = new SIMRS.DataAccess.RS_RawatJalan();
myRJ.RawatJalanId = 0;
myRJ.RegistrasiId = myReg.RegistrasiId;
myRJ.AsalPasienId = Int64.Parse(txtRegistrasiId.Text);
myRJ.PoliklinikId = 34;//FIS
myRJ.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
GetNomorTunggu();
if (txtNomorTunggu.Text != "")
myRJ.NomorTunggu = int.Parse(txtNomorTunggu.Text);
myRJ.Keterangan = txtKeterangan.Text;
myRJ.Status = 0;//Baru daftar
myRJ.CreatedBy = UserId;
myRJ.CreatedDate = DateTime.Now;
myRJ.Insert();
////Input Data Layanan
SIMRS.DataAccess.RS_RJLayanan myLayanan = new SIMRS.DataAccess.RS_RJLayanan();
SIMRS.DataAccess.RS_Layanan myTarif = new SIMRS.DataAccess.RS_Layanan();
if (lstPemeriksaan.Items.Count > 0)
{
string[] kellay;
string[] Namakellay;
DataTable dt;
for (int i = 0; i < lstPemeriksaan.Items.Count; i++)
{
myLayanan.RJLayananId = 0;
myLayanan.RawatJalanId = myRJ.RawatJalanId;
myLayanan.JenisLayananId = 3;
kellay = lstPemeriksaan.Items[i].Value.Split('|');
Namakellay = lstPemeriksaan.Items[i].Text.Split(':');
myLayanan.KelompokLayananId = 2;
myLayanan.LayananId = int.Parse(kellay[1]);
myLayanan.NamaLayanan = Namakellay[1];
myTarif.Id = int.Parse(kellay[1]);
dt = myTarif.GetTarifRIByLayananId(0);
if (dt.Rows.Count > 0)
myLayanan.Tarif = dt.Rows[0]["Tarif"].ToString() != "" ? (Decimal)dt.Rows[0]["Tarif"] : 0;
else
myLayanan.Tarif = 0;
myLayanan.JumlahSatuan = double.Parse("1");
myLayanan.Discount = 0;
myLayanan.BiayaTambahan = 0;
myLayanan.JumlahTagihan = myLayanan.Tarif;
myLayanan.Keterangan = "";
myLayanan.CreatedBy = UserId;
myLayanan.CreatedDate = DateTime.Now;
myLayanan.Insert();
}
}
//=================
string CurrentPage = "";
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
CurrentPage = Request.QueryString["CurrentPage"].ToString();
Response.Redirect("FISView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + myRJ.RawatJalanId);
}
public void OnCancel(Object sender, EventArgs e)
{
string CurrentPage = "";
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
CurrentPage = Request.QueryString["CurrentPage"].ToString();
Response.Redirect("FISList.aspx?CurrentPage=" + CurrentPage);
}
protected void cmbJenisPenjamin_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbJenisPenjamin.SelectedIndex == 1)
{
tblPenjaminKeluarga.Visible = true;
tblPenjaminPerusahaan.Visible = false;
if (txtPenjaminId.Text != "")
{
SIMRS.DataAccess.RS_Penjamin myRJ = new SIMRS.DataAccess.RS_Penjamin();
myRJ.PenjaminId = Int64.Parse(txtPenjaminId.Text);
DataTable dt = myRJ.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
txtNamaPenjamin.Text = row["Nama"].ToString();
cmbHubungan.SelectedValue = row["HubunganId"].ToString();
txtUmurPenjamin.Text = row["Umur"].ToString();
txtAlamatPenjamin.Text = row["Alamat"].ToString();
txtTeleponPenjamin.Text = row["Telepon"].ToString();
cmbAgamaPenjamin.SelectedValue = row["AgamaId"].ToString();
cmbPendidikanPenjamin.SelectedValue = row["PendidikanId"].ToString();
cmbStatusPenjamin.SelectedValue = row["StatusId"].ToString();
cmbPangkatPenjamin.SelectedValue = row["PangkatId"].ToString();
txtNoKTPPenjamin.Text = row["NoKTP"].ToString();
txtGolDarahPenjamin.Text = row["GolDarah"].ToString();
txtNRPPenjamin.Text = row["NRP"].ToString();
//cmbSatuanKerjaPenjamin.Text = row["Kesatuan"].ToString();
txtAlamatKesatuanPenjamin.Text = row["AlamatKesatuan"].ToString();
txtKeteranganPenjamin.Text = row["Keterangan"].ToString();
}
else
{
EmptyFormPejamin();
}
}
}
else if (cmbJenisPenjamin.SelectedIndex == 2 || cmbJenisPenjamin.SelectedIndex == 3)
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = true;
if (txtPenjaminId.Text != "")
{
SIMRS.DataAccess.RS_Penjamin myRJ = new SIMRS.DataAccess.RS_Penjamin();
myRJ.PenjaminId = Int64.Parse(txtPenjaminId.Text);
DataTable dt = myRJ.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
txtNamaPerusahaan.Text = row["Nama"].ToString();
txtNamaKontak.Text = row["NamaKontak"].ToString();
txtAlamatPerusahaan.Text = row["Alamat"].ToString();
txtTeleponPerusahaan.Text = row["Telepon"].ToString();
txtFAXPerusahaan.Text = row["Fax"].ToString();
txtKeteranganPerusahaan.Text = row["Keterangan"].ToString();
}
else
{
EmptyFormPejamin();
}
}
}
else
{
tblPenjaminKeluarga.Visible = false;
tblPenjaminPerusahaan.Visible = false;
}
}
protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e)
{
GetNomorTunggu();
GetNomorRegistrasi();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
GetListPasien();
EmptyFormPasien();
}
public DataView GetResultSearch()
{
DataSet ds = new DataSet();
DataTable myData = new DataTable();
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.JenisPoliklinikId = 1; // RawatJalan
if (txtNoRMSearch.Text != "")
myObj.NoRM = txtNoRMSearch.Text;
if (txtNamaSearch.Text != "")
myObj.Nama = txtNamaSearch.Text;
if (txtNRPSearch.Text != "")
myObj.NRP = txtNRPSearch.Text;
myData = myObj.SelectAllFilter();
DataView dv = myData.DefaultView;
return dv;
}
public void GetListPasien()
{
GridViewPasien.SelectedIndex = -1;
// Re-binds the grid
GridViewPasien.DataSource = GetResultSearch();
GridViewPasien.DataBind();
}
protected void GridViewPasien_SelectedIndexChanged(object sender, EventArgs e)
{
Int64 RawatJalanId = (Int64)GridViewPasien.SelectedValue;
UpdateFormPasien(RawatJalanId);
EmptyFormPejamin();
}
public void UpdateFormPasien(Int64 RawatJalanId)
{
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.RawatJalanId = RawatJalanId;
DataTable dt = myObj.SelectOne();
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
txtPasienId.Text = row["PasienId"].ToString();
txtRawatJalanId.Text = row["RawatJalanId"].ToString();
txtRegistrasiId.Text = row["RegistrasiId"].ToString();
lblNoRMHeader.Text = row["NoRM"].ToString();
lblNoRM.Text = row["NoRM"].ToString();
lblNamaPasienHeader.Text = row["Nama"].ToString();
lblNamaPasien.Text = row["Nama"].ToString();
lblStatus.Text = row["StatusNama"].ToString();
lblPangkat.Text = row["PangkatNama"].ToString();
lblNoAskes.Text = row["NoAskes"].ToString();
lblNoKTP.Text = row["NoKTP"].ToString();
lblGolDarah.Text = row["GolDarah"].ToString();
lblNRP.Text = row["NRP"].ToString();
lblKesatuan.Text = row["Kesatuan"].ToString();
lblTempatLahir.Text = row["TempatLahir"].ToString() == "" ? " " : row["TempatLahir"].ToString();
lblTanggalLahir.Text = row["TanggalLahir"].ToString() != "" ? ((DateTime)row["TanggalLahir"]).ToString("dd MMMM yyyy"):"";
lblAlamat.Text = row["Alamat"].ToString();
lblTelepon.Text = row["Telepon"].ToString();
lblJenisKelamin.Text = row["JenisKelamin"].ToString();
lblStatusPerkawinan.Text = row["StatusPerkawinanNama"].ToString();
lblAgama.Text = row["AgamaNama"].ToString();
lblPendidikan.Text = row["PendidikanNama"].ToString();
lblPekerjaan.Text = row["Pekerjaan"].ToString();
lblAlamatKantor.Text = row["AlamatKantor"].ToString();
lblTeleponKantor.Text = row["TeleponKantor"].ToString();
lblKeterangan.Text = row["Keterangan"].ToString();
if (row["PoliklinikNama"].ToString() != "")
txtKeterangan.Text = "Pasien Rawa Jalan: Dari " + row["PoliklinikNama"].ToString();
if (row["DokterNama"].ToString() != "")
txtKeterangan.Text += " Dokter " + row["DokterNama"].ToString();
}
else
{
EmptyFormPasien();
}
SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi();
myReg.PasienId = Int64.Parse(txtPasienId.Text);
DataTable dTbl = myReg.SelectOne_ByPasienId();
if (dTbl.Rows.Count > 0)
{
DataRow rs = dTbl.Rows[0];
txtPenjaminId.Text = rs["PenjaminId"].ToString();
}
}
public void EmptyFormPasien()
{
txtPasienId.Text = "";
txtRawatJalanId.Text = "";
txtRegistrasiId.Text = "";
lblNoRMHeader.Text = "";
lblNoRM.Text = "";
lblNamaPasien.Text = "";
lblNamaPasienHeader.Text = "";
lblStatus.Text = "";
lblPangkat.Text = "";
lblNoAskes.Text = "";
lblNoKTP.Text = "";
lblGolDarah.Text = "";
lblNRP.Text = "";
lblKesatuan.Text = "";
lblTempatLahir.Text = "";
lblTanggalLahir.Text = "";
lblAlamat.Text = "";
lblTelepon.Text = "";
lblJenisKelamin.Text = "";
lblStatusPerkawinan.Text = "";
lblAgama.Text = "";
lblPendidikan.Text = "";
lblPekerjaan.Text = "";
lblAlamatKantor.Text = "";
lblTeleponKantor.Text = "";
lblKeterangan.Text = "";
txtKeterangan.Text = "";
}
protected void GridViewPasien_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewPasien.SelectedIndex = -1;
GridViewPasien.PageIndex = e.NewPageIndex;
GridViewPasien.DataSource = GetResultSearch();
GridViewPasien.DataBind();
EmptyFormPasien();
}
protected void cmbKelompokPemeriksaan_SelectedIndexChanged(object sender, EventArgs e)
{
GetListPemeriksaan();
}
protected void btnAddPemeriksaan_Click(object sender, EventArgs e)
{
if (lstRefPemeriksaan.SelectedIndex != -1)
{
int i = lstPemeriksaan.Items.Count;
bool exist = false;
string selectValue = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value;
for (int j = 0; j < i; j++)
{
if (lstPemeriksaan.Items[j].Value == selectValue)
{
exist = true;
break;
}
}
if (!exist)
{
ListItem newItem = new ListItem();
newItem.Text = cmbKelompokPemeriksaan.SelectedItem.Text + ": " + lstRefPemeriksaan.SelectedItem.Text;
newItem.Value = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value;
lstPemeriksaan.Items.Add(newItem);
}
}
}
protected void btnRemovePemeriksaan_Click(object sender, EventArgs e)
{
if (lstPemeriksaan.SelectedIndex != -1)
{
lstPemeriksaan.Items.RemoveAt(lstPemeriksaan.SelectedIndex);
}
}
public void GetListSatuanKerjaPenjamin()
{
string SatuanKerjaId = "";
SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja();
DataTable dt = myObj.GetList();
cmbSatuanKerjaPenjamin.Items.Clear();
int i = 0;
cmbSatuanKerjaPenjamin.Items.Add("");
cmbSatuanKerjaPenjamin.Items[i].Text = "";
cmbSatuanKerjaPenjamin.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbSatuanKerjaPenjamin.Items.Add("");
cmbSatuanKerjaPenjamin.Items[i].Text = dr["NamaSatker"].ToString();
cmbSatuanKerjaPenjamin.Items[i].Value = dr["IdSatuanKerja"].ToString();
if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId)
{
cmbSatuanKerjaPenjamin.SelectedIndex = i;
}
i++;
}
}
public void EmptyFormPejamin()
{
txtNamaPenjamin.Text = "";
cmbHubungan.SelectedValue = "";
txtUmurPenjamin.Text = "";
txtAlamatPenjamin.Text = "";
txtTeleponPenjamin.Text = "";
cmbAgamaPenjamin.SelectedIndex = 0;
cmbPendidikanPenjamin.SelectedIndex = 0;
cmbStatusPenjamin.SelectedIndex = 0;
//cmbPangkatPenjamin.SelectedIndex = 0;
txtNoKTPPenjamin.Text = "";
txtGolDarahPenjamin.Text = "";
txtNRPPenjamin.Text = "";
cmbSatuanKerjaPenjamin.SelectedIndex = 0;
txtAlamatKesatuanPenjamin.Text = "";
txtKeteranganPenjamin.Text = "";
txtNamaPerusahaan.Text = "";
txtNamaKontak.Text = "";
txtAlamatPerusahaan.Text = "";
txtTeleponPerusahaan.Text = "";
txtFAXPerusahaan.Text = "";
txtKeteranganPerusahaan.Text = "";
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using CondenserDotNet.Configuration;
using CondenserDotNet.Configuration.Consul;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Xunit;
namespace Condenser.Tests.Integration
{
public class ConfigFacts
{
const string _value1 = "testValue1";
const string _value2 = "testValue2";
const string _value3 = "testValue3";
const string _value4 = "testValue4";
[Fact]
public async Task TestRegister()
{
var keyname = Guid.NewGuid().ToString();
using (var configRegistry = new ConsulRegistry())
{
await configRegistry.SetKeyAsync($"org/{keyname}/test1", _value1);
await configRegistry.SetKeyAsync($"org/{keyname}/test2", _value2);
var result = await configRegistry.AddStaticKeyPathAsync($"org/{keyname}");
Assert.True(result);
var firstValue = configRegistry["test1"];
var secondValue = configRegistry["test2"];
Assert.Equal(_value1, firstValue);
Assert.Equal(_value2, secondValue);
}
}
[Fact]
public async Task TestSingleKey()
{
var keyname = Guid.NewGuid().ToString();
using(var configRegistry = new ConsulRegistry())
{
await configRegistry.SetKeyAsync($"org/{keyname}/test1", _value1);
var result = await configRegistry.AddStaticKeyPathAsync($"org/{keyname}/test1", true);
Assert.True(result);
var value = configRegistry["test1"];
Assert.Equal(_value1, value);
}
}
[Fact]
public async Task TestKeyHandlesFrontSlash()
{
using (var registry = CondenserConfigBuilder.FromConsul().Build())
{
var keyname = Guid.NewGuid().ToString();
await registry.SetKeyAsync($"org/{keyname}/test1", _value1);
var result = await registry.AddStaticKeyPathAsync($"/org/{keyname}");
Assert.True(result);
var firstValue = registry["test1"];
Assert.Equal(_value1, firstValue);
}
}
[Fact]
public async Task DontPickUpChangesFact()
{
var keyname = Guid.NewGuid().ToString();
using (var configRegistry = new ConsulRegistry())
{
await configRegistry.SetKeyAsync($"org/{keyname}/test1", _value1);
var result = await configRegistry.AddStaticKeyPathAsync($"org/{keyname}");
await configRegistry.SetKeyAsync($"org/{keyname}/test1", _value2);
await Task.Delay(500); //give some time to sync
var firstValue = configRegistry["test1"];
Assert.Equal(_value1, firstValue);
}
}
[Fact]
public async Task PickUpChangesFact()
{
var keyid = Guid.NewGuid().ToString();
using (var configRegistry = new ConsulRegistry())
{
await configRegistry.SetKeyAsync($"org/{keyid}/test2", _value1);
await configRegistry.AddUpdatingPathAsync($"org/{keyid}/");
await Task.Delay(500);
Assert.Equal(_value1, configRegistry["test2"]);
await configRegistry.SetKeyAsync($"org/{keyid}/test2", _value2);
await Task.Delay(500); //give some time to sync
Assert.Equal(_value2, configRegistry["test2"]);
}
}
[Fact]
public async Task GetCallbackForSpecificKey()
{
Console.WriteLine(nameof(GetCallbackForSpecificKey));
var keyid = Guid.NewGuid().ToString();
using (var configRegistry = new ConsulRegistry())
{
var e = new ManualResetEvent(false);
configRegistry.AddWatchOnSingleKey("test1", keyValue => e.Set());
await configRegistry.SetKeyAsync($"org/{keyid}/test1", _value1);
await configRegistry.AddUpdatingPathAsync($"org/{keyid}/");
await Task.Delay(1000);
await configRegistry.SetKeyAsync($"org/{keyid}/test1", _value2);
//Wait for a max of 1 second for the change to notify us
Assert.True(e.WaitOne(2000));
}
}
[Fact]
public async Task GetCallbackForKeyThatIsAdded()
{
var keyid = Guid.NewGuid().ToString();
using (var configRegistry = new ConsulRegistry())
{
var e = new ManualResetEvent(false);
configRegistry.AddWatchOnSingleKey("test1", keyValue => e.Set());
await configRegistry.AddUpdatingPathAsync($"org/{keyid}/");
//give it time to register
await Task.Delay(1000);
await configRegistry.SetKeyAsync($"org/{keyid}/test1", _value2);
//Wait for a max of 1 second for the change to notify us
Assert.True(e.WaitOne(2000));
}
}
[Fact]
public async Task GetCallbackForAnyKey()
{
Console.WriteLine(nameof(GetCallbackForAnyKey));
var keyid = Guid.NewGuid().ToString();
using (var configRegistry = new ConsulRegistry())
{
await configRegistry.SetKeyAsync($"org/{keyid}/test1", _value1);
await configRegistry.AddUpdatingPathAsync($"org/{keyid}");
var e = new ManualResetEvent(false);
configRegistry.AddWatchOnEntireConfig(() => e.Set());
//give the registration time to complete registration
await Task.Delay(1000);
await configRegistry.SetKeyAsync($"org/{keyid}/test1", _value2);
//Wait for a max of 1 second for the change to notify us
Assert.True(e.WaitOne(2000));
}
}
[Fact]
public async Task CanLoadUsingConsulConfigurationProvider()
{
var keyname = Guid.NewGuid().ToString();
using (var configRegistry = new ConsulRegistry())
{
await configRegistry.SetKeyAsync($"org/{keyname}/test1", _value1);
await configRegistry.SetKeyAsync($"org/{keyname}/test2", _value2);
await configRegistry.SetKeyAsync($"org/{keyname}/Nested/test3", _value3);
await configRegistry.SetKeyAsync($"org/{keyname}/Nested/test4", _value4);
await configRegistry.AddStaticKeyPathAsync($"org");
var config = new ConfigurationBuilder()
.AddConfigurationRegistry(configRegistry)
.Build();
var simpleSettings = new SimpleSettings();
var configSection = config.GetSection(keyname);
configSection.Bind(simpleSettings);
Assert.Equal(_value1, simpleSettings.Test1);
Assert.Equal(_value2, simpleSettings.Test2);
Assert.Equal(_value3, simpleSettings.Nested.Test3);
Assert.Equal(_value4, simpleSettings.Nested.Test4);
}
}
[Fact]
public async Task CanLoadUsingConsulJsonConfigurationProvider()
{
var keyname = Guid.NewGuid().ToString();
using (var configRegistry = new ConsulRegistry(Options.Create<ConsulRegistryConfig>(new ConsulRegistryConfig() { KeyParser = new JsonKeyValueParser() })))
{
var settings = new SimpleSettings
{
Test1 = _value1,
Test2 = _value2,
Nested = new SimpleNestedSettings
{
Test3 = _value3,
Test4 = _value4
}
};
await configRegistry.SetKeyJsonAsync($"org/{keyname}/Settings", settings);
var config = new ConfigurationBuilder()
.AddConfigurationRegistry(configRegistry)
.Build();
//TODO: At the moment require this line after builder as it sets parser. Probably need to rethink this.
await configRegistry.AddStaticKeyPathAsync($"org/{keyname}");
var simpleSettings = new SimpleSettings();
var configSection = config.GetSection("Settings");
configSection.Bind(simpleSettings);
Assert.Equal(_value1, simpleSettings.Test1);
Assert.Equal(_value2, simpleSettings.Test2);
Assert.Equal(_value3, simpleSettings.Nested.Test3);
Assert.Equal(_value4, simpleSettings.Nested.Test4);
}
}
private class SimpleSettings
{
public string Test1 { get; set; }
public string Test2 { get; set; }
public SimpleNestedSettings Nested { get; set; }
}
private class SimpleNestedSettings
{
public string Test3 { get; set; }
public string Test4 { get; set; }
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface ISalesPersonOriginalData : ISchemaBaseOriginalData
{
string SalesQuota { get; }
string Bonus { get; }
string CommissionPct { get; }
string SalesYTD { get; }
string SalesLastYear { get; }
string rowguid { get; }
SalesPersonQuotaHistory SalesPersonQuotaHistory { get; }
SalesTerritory SalesTerritory { get; }
Person Person { get; }
IEnumerable<Store> Stores { get; }
}
public partial class SalesPerson : OGM<SalesPerson, SalesPerson.SalesPersonData, System.String>, ISchemaBase, INeo4jBase, ISalesPersonOriginalData
{
#region Initialize
static SalesPerson()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, SalesPerson> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.SalesPersonAlias, IWhereQuery> query)
{
q.SalesPersonAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.SalesPerson.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"SalesPerson => SalesQuota : {this.SalesQuota?.ToString() ?? "null"}, Bonus : {this.Bonus}, CommissionPct : {this.CommissionPct}, SalesYTD : {this.SalesYTD}, SalesLastYear : {this.SalesLastYear}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new SalesPersonData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.Bonus == null)
throw new PersistenceException(string.Format("Cannot save SalesPerson with key '{0}' because the Bonus cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.CommissionPct == null)
throw new PersistenceException(string.Format("Cannot save SalesPerson with key '{0}' because the CommissionPct cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.SalesYTD == null)
throw new PersistenceException(string.Format("Cannot save SalesPerson with key '{0}' because the SalesYTD cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.SalesLastYear == null)
throw new PersistenceException(string.Format("Cannot save SalesPerson with key '{0}' because the SalesLastYear cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.rowguid == null)
throw new PersistenceException(string.Format("Cannot save SalesPerson with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save SalesPerson with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class SalesPersonData : Data<System.String>
{
public SalesPersonData()
{
}
public SalesPersonData(SalesPersonData data)
{
SalesQuota = data.SalesQuota;
Bonus = data.Bonus;
CommissionPct = data.CommissionPct;
SalesYTD = data.SalesYTD;
SalesLastYear = data.SalesLastYear;
rowguid = data.rowguid;
SalesPersonQuotaHistory = data.SalesPersonQuotaHistory;
SalesTerritory = data.SalesTerritory;
Person = data.Person;
Stores = data.Stores;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "SalesPerson";
SalesPersonQuotaHistory = new EntityCollection<SalesPersonQuotaHistory>(Wrapper, Members.SalesPersonQuotaHistory);
SalesTerritory = new EntityCollection<SalesTerritory>(Wrapper, Members.SalesTerritory);
Person = new EntityCollection<Person>(Wrapper, Members.Person, item => { if (Members.Person.Events.HasRegisteredChangeHandlers) { object loadHack = item.SalesPerson; } });
Stores = new EntityCollection<Store>(Wrapper, Members.Stores, item => { if (Members.Stores.Events.HasRegisteredChangeHandlers) { object loadHack = item.SalesPerson; } });
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("SalesQuota", SalesQuota);
dictionary.Add("Bonus", Bonus);
dictionary.Add("CommissionPct", CommissionPct);
dictionary.Add("SalesYTD", SalesYTD);
dictionary.Add("SalesLastYear", SalesLastYear);
dictionary.Add("rowguid", rowguid);
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("SalesQuota", out value))
SalesQuota = (string)value;
if (properties.TryGetValue("Bonus", out value))
Bonus = (string)value;
if (properties.TryGetValue("CommissionPct", out value))
CommissionPct = (string)value;
if (properties.TryGetValue("SalesYTD", out value))
SalesYTD = (string)value;
if (properties.TryGetValue("SalesLastYear", out value))
SalesLastYear = (string)value;
if (properties.TryGetValue("rowguid", out value))
rowguid = (string)value;
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface ISalesPerson
public string SalesQuota { get; set; }
public string Bonus { get; set; }
public string CommissionPct { get; set; }
public string SalesYTD { get; set; }
public string SalesLastYear { get; set; }
public string rowguid { get; set; }
public EntityCollection<SalesPersonQuotaHistory> SalesPersonQuotaHistory { get; private set; }
public EntityCollection<SalesTerritory> SalesTerritory { get; private set; }
public EntityCollection<Person> Person { get; private set; }
public EntityCollection<Store> Stores { get; private set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface ISalesPerson
public string SalesQuota { get { LazyGet(); return InnerData.SalesQuota; } set { if (LazySet(Members.SalesQuota, InnerData.SalesQuota, value)) InnerData.SalesQuota = value; } }
public string Bonus { get { LazyGet(); return InnerData.Bonus; } set { if (LazySet(Members.Bonus, InnerData.Bonus, value)) InnerData.Bonus = value; } }
public string CommissionPct { get { LazyGet(); return InnerData.CommissionPct; } set { if (LazySet(Members.CommissionPct, InnerData.CommissionPct, value)) InnerData.CommissionPct = value; } }
public string SalesYTD { get { LazyGet(); return InnerData.SalesYTD; } set { if (LazySet(Members.SalesYTD, InnerData.SalesYTD, value)) InnerData.SalesYTD = value; } }
public string SalesLastYear { get { LazyGet(); return InnerData.SalesLastYear; } set { if (LazySet(Members.SalesLastYear, InnerData.SalesLastYear, value)) InnerData.SalesLastYear = value; } }
public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } }
public SalesPersonQuotaHistory SalesPersonQuotaHistory
{
get { return ((ILookupHelper<SalesPersonQuotaHistory>)InnerData.SalesPersonQuotaHistory).GetItem(null); }
set
{
if (LazySet(Members.SalesPersonQuotaHistory, ((ILookupHelper<SalesPersonQuotaHistory>)InnerData.SalesPersonQuotaHistory).GetItem(null), value))
((ILookupHelper<SalesPersonQuotaHistory>)InnerData.SalesPersonQuotaHistory).SetItem(value, null);
}
}
public SalesTerritory SalesTerritory
{
get { return ((ILookupHelper<SalesTerritory>)InnerData.SalesTerritory).GetItem(null); }
set
{
if (LazySet(Members.SalesTerritory, ((ILookupHelper<SalesTerritory>)InnerData.SalesTerritory).GetItem(null), value))
((ILookupHelper<SalesTerritory>)InnerData.SalesTerritory).SetItem(value, null);
}
}
public Person Person
{
get { return ((ILookupHelper<Person>)InnerData.Person).GetItem(null); }
set
{
if (LazySet(Members.Person, ((ILookupHelper<Person>)InnerData.Person).GetItem(null), value))
((ILookupHelper<Person>)InnerData.Person).SetItem(value, null);
}
}
private void ClearPerson(DateTime? moment)
{
((ILookupHelper<Person>)InnerData.Person).ClearLookup(moment);
}
public EntityCollection<Store> Stores { get { return InnerData.Stores; } }
private void ClearStores(DateTime? moment)
{
((ILookupHelper<Store>)InnerData.Stores).ClearLookup(moment);
}
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static SalesPersonMembers members = null;
public static SalesPersonMembers Members
{
get
{
if (members == null)
{
lock (typeof(SalesPerson))
{
if (members == null)
members = new SalesPersonMembers();
}
}
return members;
}
}
public class SalesPersonMembers
{
internal SalesPersonMembers() { }
#region Members for interface ISalesPerson
public Property SalesQuota { get; } = Datastore.AdventureWorks.Model.Entities["SalesPerson"].Properties["SalesQuota"];
public Property Bonus { get; } = Datastore.AdventureWorks.Model.Entities["SalesPerson"].Properties["Bonus"];
public Property CommissionPct { get; } = Datastore.AdventureWorks.Model.Entities["SalesPerson"].Properties["CommissionPct"];
public Property SalesYTD { get; } = Datastore.AdventureWorks.Model.Entities["SalesPerson"].Properties["SalesYTD"];
public Property SalesLastYear { get; } = Datastore.AdventureWorks.Model.Entities["SalesPerson"].Properties["SalesLastYear"];
public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["SalesPerson"].Properties["rowguid"];
public Property SalesPersonQuotaHistory { get; } = Datastore.AdventureWorks.Model.Entities["SalesPerson"].Properties["SalesPersonQuotaHistory"];
public Property SalesTerritory { get; } = Datastore.AdventureWorks.Model.Entities["SalesPerson"].Properties["SalesTerritory"];
public Property Person { get; } = Datastore.AdventureWorks.Model.Entities["SalesPerson"].Properties["Person"];
public Property Stores { get; } = Datastore.AdventureWorks.Model.Entities["SalesPerson"].Properties["Stores"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static SalesPersonFullTextMembers fullTextMembers = null;
public static SalesPersonFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(SalesPerson))
{
if (fullTextMembers == null)
fullTextMembers = new SalesPersonFullTextMembers();
}
}
return fullTextMembers;
}
}
public class SalesPersonFullTextMembers
{
internal SalesPersonFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(SalesPerson))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["SalesPerson"];
}
}
return entity;
}
private static SalesPersonEvents events = null;
public static SalesPersonEvents Events
{
get
{
if (events == null)
{
lock (typeof(SalesPerson))
{
if (events == null)
events = new SalesPersonEvents();
}
}
return events;
}
}
public class SalesPersonEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<SalesPerson, EntityEventArgs> onNew;
public event EventHandler<SalesPerson, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<SalesPerson, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<SalesPerson, EntityEventArgs> onDelete;
public event EventHandler<SalesPerson, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<SalesPerson, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<SalesPerson, EntityEventArgs> onSave;
public event EventHandler<SalesPerson, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<SalesPerson, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnSalesQuota
private static bool onSalesQuotaIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onSalesQuota;
public static event EventHandler<SalesPerson, PropertyEventArgs> OnSalesQuota
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onSalesQuotaIsRegistered)
{
Members.SalesQuota.Events.OnChange -= onSalesQuotaProxy;
Members.SalesQuota.Events.OnChange += onSalesQuotaProxy;
onSalesQuotaIsRegistered = true;
}
onSalesQuota += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onSalesQuota -= value;
if (onSalesQuota == null && onSalesQuotaIsRegistered)
{
Members.SalesQuota.Events.OnChange -= onSalesQuotaProxy;
onSalesQuotaIsRegistered = false;
}
}
}
}
private static void onSalesQuotaProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onSalesQuota;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnBonus
private static bool onBonusIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onBonus;
public static event EventHandler<SalesPerson, PropertyEventArgs> OnBonus
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onBonusIsRegistered)
{
Members.Bonus.Events.OnChange -= onBonusProxy;
Members.Bonus.Events.OnChange += onBonusProxy;
onBonusIsRegistered = true;
}
onBonus += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onBonus -= value;
if (onBonus == null && onBonusIsRegistered)
{
Members.Bonus.Events.OnChange -= onBonusProxy;
onBonusIsRegistered = false;
}
}
}
}
private static void onBonusProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onBonus;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnCommissionPct
private static bool onCommissionPctIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onCommissionPct;
public static event EventHandler<SalesPerson, PropertyEventArgs> OnCommissionPct
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onCommissionPctIsRegistered)
{
Members.CommissionPct.Events.OnChange -= onCommissionPctProxy;
Members.CommissionPct.Events.OnChange += onCommissionPctProxy;
onCommissionPctIsRegistered = true;
}
onCommissionPct += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onCommissionPct -= value;
if (onCommissionPct == null && onCommissionPctIsRegistered)
{
Members.CommissionPct.Events.OnChange -= onCommissionPctProxy;
onCommissionPctIsRegistered = false;
}
}
}
}
private static void onCommissionPctProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onCommissionPct;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnSalesYTD
private static bool onSalesYTDIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onSalesYTD;
public static event EventHandler<SalesPerson, PropertyEventArgs> OnSalesYTD
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onSalesYTDIsRegistered)
{
Members.SalesYTD.Events.OnChange -= onSalesYTDProxy;
Members.SalesYTD.Events.OnChange += onSalesYTDProxy;
onSalesYTDIsRegistered = true;
}
onSalesYTD += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onSalesYTD -= value;
if (onSalesYTD == null && onSalesYTDIsRegistered)
{
Members.SalesYTD.Events.OnChange -= onSalesYTDProxy;
onSalesYTDIsRegistered = false;
}
}
}
}
private static void onSalesYTDProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onSalesYTD;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnSalesLastYear
private static bool onSalesLastYearIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onSalesLastYear;
public static event EventHandler<SalesPerson, PropertyEventArgs> OnSalesLastYear
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onSalesLastYearIsRegistered)
{
Members.SalesLastYear.Events.OnChange -= onSalesLastYearProxy;
Members.SalesLastYear.Events.OnChange += onSalesLastYearProxy;
onSalesLastYearIsRegistered = true;
}
onSalesLastYear += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onSalesLastYear -= value;
if (onSalesLastYear == null && onSalesLastYearIsRegistered)
{
Members.SalesLastYear.Events.OnChange -= onSalesLastYearProxy;
onSalesLastYearIsRegistered = false;
}
}
}
}
private static void onSalesLastYearProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onSalesLastYear;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region Onrowguid
private static bool onrowguidIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onrowguid;
public static event EventHandler<SalesPerson, PropertyEventArgs> Onrowguid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
Members.rowguid.Events.OnChange += onrowguidProxy;
onrowguidIsRegistered = true;
}
onrowguid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onrowguid -= value;
if (onrowguid == null && onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
onrowguidIsRegistered = false;
}
}
}
}
private static void onrowguidProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onrowguid;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnSalesPersonQuotaHistory
private static bool onSalesPersonQuotaHistoryIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onSalesPersonQuotaHistory;
public static event EventHandler<SalesPerson, PropertyEventArgs> OnSalesPersonQuotaHistory
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onSalesPersonQuotaHistoryIsRegistered)
{
Members.SalesPersonQuotaHistory.Events.OnChange -= onSalesPersonQuotaHistoryProxy;
Members.SalesPersonQuotaHistory.Events.OnChange += onSalesPersonQuotaHistoryProxy;
onSalesPersonQuotaHistoryIsRegistered = true;
}
onSalesPersonQuotaHistory += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onSalesPersonQuotaHistory -= value;
if (onSalesPersonQuotaHistory == null && onSalesPersonQuotaHistoryIsRegistered)
{
Members.SalesPersonQuotaHistory.Events.OnChange -= onSalesPersonQuotaHistoryProxy;
onSalesPersonQuotaHistoryIsRegistered = false;
}
}
}
}
private static void onSalesPersonQuotaHistoryProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onSalesPersonQuotaHistory;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnSalesTerritory
private static bool onSalesTerritoryIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onSalesTerritory;
public static event EventHandler<SalesPerson, PropertyEventArgs> OnSalesTerritory
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onSalesTerritoryIsRegistered)
{
Members.SalesTerritory.Events.OnChange -= onSalesTerritoryProxy;
Members.SalesTerritory.Events.OnChange += onSalesTerritoryProxy;
onSalesTerritoryIsRegistered = true;
}
onSalesTerritory += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onSalesTerritory -= value;
if (onSalesTerritory == null && onSalesTerritoryIsRegistered)
{
Members.SalesTerritory.Events.OnChange -= onSalesTerritoryProxy;
onSalesTerritoryIsRegistered = false;
}
}
}
}
private static void onSalesTerritoryProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onSalesTerritory;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnPerson
private static bool onPersonIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onPerson;
public static event EventHandler<SalesPerson, PropertyEventArgs> OnPerson
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onPersonIsRegistered)
{
Members.Person.Events.OnChange -= onPersonProxy;
Members.Person.Events.OnChange += onPersonProxy;
onPersonIsRegistered = true;
}
onPerson += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onPerson -= value;
if (onPerson == null && onPersonIsRegistered)
{
Members.Person.Events.OnChange -= onPersonProxy;
onPersonIsRegistered = false;
}
}
}
}
private static void onPersonProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onPerson;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnStores
private static bool onStoresIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onStores;
public static event EventHandler<SalesPerson, PropertyEventArgs> OnStores
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onStoresIsRegistered)
{
Members.Stores.Events.OnChange -= onStoresProxy;
Members.Stores.Events.OnChange += onStoresProxy;
onStoresIsRegistered = true;
}
onStores += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onStores -= value;
if (onStores == null && onStoresIsRegistered)
{
Members.Stores.Events.OnChange -= onStoresProxy;
onStoresIsRegistered = false;
}
}
}
}
private static void onStoresProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onStores;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onModifiedDate;
public static event EventHandler<SalesPerson, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<SalesPerson, PropertyEventArgs> onUid;
public static event EventHandler<SalesPerson, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<SalesPerson, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((SalesPerson)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region ISalesPersonOriginalData
public ISalesPersonOriginalData OriginalVersion { get { return this; } }
#region Members for interface ISalesPerson
string ISalesPersonOriginalData.SalesQuota { get { return OriginalData.SalesQuota; } }
string ISalesPersonOriginalData.Bonus { get { return OriginalData.Bonus; } }
string ISalesPersonOriginalData.CommissionPct { get { return OriginalData.CommissionPct; } }
string ISalesPersonOriginalData.SalesYTD { get { return OriginalData.SalesYTD; } }
string ISalesPersonOriginalData.SalesLastYear { get { return OriginalData.SalesLastYear; } }
string ISalesPersonOriginalData.rowguid { get { return OriginalData.rowguid; } }
SalesPersonQuotaHistory ISalesPersonOriginalData.SalesPersonQuotaHistory { get { return ((ILookupHelper<SalesPersonQuotaHistory>)OriginalData.SalesPersonQuotaHistory).GetOriginalItem(null); } }
SalesTerritory ISalesPersonOriginalData.SalesTerritory { get { return ((ILookupHelper<SalesTerritory>)OriginalData.SalesTerritory).GetOriginalItem(null); } }
Person ISalesPersonOriginalData.Person { get { return ((ILookupHelper<Person>)OriginalData.Person).GetOriginalItem(null); } }
IEnumerable<Store> ISalesPersonOriginalData.Stores { get { return OriginalData.Stores.OriginalData; } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace LibuvSharp
{
public enum UVFileAccess
{
Read = 0,
Write = 1,
ReadWrite = 3,
}
// TODO:
// 1. uv_fs_utime uv_fs_futime
public class UVFile
{
public UVFile(int fd)
: this(Loop.Constructor, fd)
{
}
public UVFile(Loop loop, int fd)
{
Loop = loop;
FileDescriptor = fd;
}
public Loop Loop { get; protected set; }
public int FileDescriptor { get; protected set; }
public Encoding Encoding { get; set; }
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_open(IntPtr loop, IntPtr req, string path, int flags, int mode, NativeMethods.uv_fs_cb callback);
public static void Open(Loop loop, string path, UVFileAccess access, Action<Exception, UVFile> callback)
{
var fsr = new FileSystemRequest(path);
fsr.Callback = (ex) => {
UVFile file = null;
if (fsr.Result != IntPtr.Zero) {
file = new UVFile(loop, fsr.Result.ToInt32());
}
Ensure.Success(ex, callback, file);
};
int r = uv_fs_open(loop.NativeHandle, fsr.Handle, path, (int)access, 0, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public static void Open(string path, UVFileAccess access, Action<Exception, UVFile> callback)
{
Open(Loop.Constructor, path, access, callback);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_close(IntPtr loop, IntPtr req, int fd, NativeMethods.uv_fs_cb callback);
public void Close(Loop loop, Action<Exception> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = callback;
int r = uv_fs_close(loop.NativeHandle, fsr.Handle, FileDescriptor, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public void Close(Loop loop)
{
Close(loop, null);
}
public void Close(Action<Exception> callback)
{
Close(Loop, callback);
}
public void Close()
{
Close(Loop);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_read(IntPtr loop, IntPtr req, int fd, UnixBufferStruct[] buf, int nbufs, long offset, NativeMethods.uv_fs_cb callback);
public void Read(Loop loop, int offset, ArraySegment<byte> segment, Action<Exception, int> callback)
{
var datagchandle = GCHandle.Alloc(segment.Array, GCHandleType.Pinned);
var fsr = new FileSystemRequest();
fsr.Callback = (ex) => {
Ensure.Success(ex, callback, fsr.Result.ToInt32());
datagchandle.Free();
};
UnixBufferStruct[] buf = new UnixBufferStruct[1];
buf[0] = new UnixBufferStruct(new IntPtr(datagchandle.AddrOfPinnedObject().ToInt64() + segment.Offset), segment.Count);
int r = uv_fs_read(loop.NativeHandle, fsr.Handle, FileDescriptor, buf, 1, offset, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public void Read(Loop loop, int offset, byte[] data, int index, int count, Action<Exception, int> callback)
{
Read(loop, offset, new ArraySegment<byte>(data, index, count), callback);
}
public void Read(Loop loop, byte[] data, int index, int count, Action<Exception, int> callback)
{
Read(loop, -1, data, index, count, callback);
}
public void Read(Loop loop, int offset, byte[] data, Action<Exception, int> callback)
{
Ensure.ArgumentNotNull(data, "data");
Read(loop, offset, data, 0, data.Length, callback);
}
public void Read(Loop loop, byte[] data, Action<Exception, int> callback)
{
Read(loop, -1, data, callback);
}
public void Read(Loop loop, int offset, byte[] data, int index, int count)
{
Read(loop, offset, data, index, count, null);
}
public void Read(Loop loop, byte[] data, int index, int count)
{
Read(loop, -1, data, index, count);
}
public void Read(Loop loop, byte[] data)
{
Ensure.ArgumentNotNull(data, "data");
Read(loop, data, 0, data.Length);
}
public void Read(int offset, byte[] data, int index, int count, Action<Exception, int> callback)
{
Read(this.Loop, offset, data, index, count, callback);
}
public void Read(byte[] data, int index, int count, Action<Exception, int> callback)
{
Read(this.Loop, data, index, count, callback);
}
public void Read(int offset, byte[] data, Action<Exception, int> callback)
{
Read(this.Loop, offset, data, callback);
}
public void Read(byte[] data, Action<Exception, int> callback)
{
Read(this.Loop, data, callback);
}
public void Read(int offset, byte[] data, int index, int count)
{
Read(this.Loop, offset, data, index, count);
}
public void Read(byte[] data, int index, int count)
{
Read(this.Loop, data, index, count);
}
public void Read(byte[] data)
{
Read(this.Loop, data);
}
public void Read(Loop loop, ArraySegment<byte> data, Action<Exception, int> callback)
{
Read(loop, -1, data, callback);
}
public void Read(Loop loop, int offset, ArraySegment<byte> data)
{
Read(loop, offset, data, null);
}
public void Read(Loop loop, ArraySegment<byte> data)
{
Read(loop, data, null);
}
public void Read(int offset, ArraySegment<byte> data, Action<Exception, int> callback)
{
Read(Loop, offset, data, callback);
}
public void Read(ArraySegment<byte> data, Action<Exception, int> callback)
{
Read(-1, data, callback);
}
public void Read(int offset, ArraySegment<byte> data)
{
Read(offset, data, null);
}
public void Read(ArraySegment<byte> data)
{
Read(data, null);
}
public int Read(Loop loop, int offset, Encoding encoding, string text, Action<Exception, int> callback)
{
var bytes = encoding.GetBytes(text);
Read(loop, offset, bytes, callback);
return bytes.Length;
}
public int Read(Loop loop, Encoding encoding, string text, Action<Exception, int> callback)
{
return Read(loop, -1, encoding, text, callback);
}
public int Read(Loop loop, int offset, Encoding encoding, string text)
{
return Read(loop, offset, encoding, text, null);
}
public int Read(Loop loop, Encoding encoding, string text)
{
return Read(loop, -1, encoding, text);
}
public int Read(Loop loop, int offset, string text, Action<Exception, int> callback)
{
return Read(loop, offset, Encoding ?? Encoding.Default, text, callback);
}
public int Read(Loop loop, string text, Action<Exception, int> callback)
{
return Read(loop, -1, text, callback);
}
public int Read(Loop loop, int offset, string text)
{
return Read(loop, offset, text, null);
}
public int Read(Loop loop, string text)
{
return Read(loop, -1, text);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_write(IntPtr loop, IntPtr req, int fd, UnixBufferStruct[] bufs, int nbufs, long offset, NativeMethods.uv_fs_cb fs_cb);
public void Write(Loop loop, int offset, ArraySegment<byte> segment, Action<Exception, int> callback)
{
var datagchandle = GCHandle.Alloc(segment.Array, GCHandleType.Pinned);
var fsr = new FileSystemRequest();
fsr.Callback = (ex) => {
Ensure.Success(ex, callback, fsr.Result.ToInt32());
datagchandle.Free();
};
UnixBufferStruct[] buf = new UnixBufferStruct[1];
buf[0] = new UnixBufferStruct(new IntPtr(datagchandle.AddrOfPinnedObject().ToInt64() + segment.Offset), segment.Count);
int r = uv_fs_write(loop.NativeHandle, fsr.Handle, FileDescriptor, buf, segment.Count, offset, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public void Write(Loop loop, int offset, byte[] data, int index, int count, Action<Exception, int> callback)
{
Write(loop, offset, new ArraySegment<byte>(data, index, count), callback);
}
public void Write(Loop loop, byte[] data, int index, int count, Action<Exception, int> callback)
{
Write(loop, -1, data, index, count, callback);
}
public void Write(Loop loop, int offset, byte[] data, Action<Exception, int> callback)
{
Write(loop, offset, data, 0, data.Length, callback);
}
public void Write(Loop loop, byte[] data, Action<Exception, int> callback)
{
Write(loop, -1, data, callback);
}
public void Write(Loop loop, int offset, byte[] data, int index, int count)
{
Write(loop, offset, data, index, count, null);
}
public void Write(Loop loop, byte[] data, int index, int count)
{
Write(loop, -1, data, index, count);
}
public void Write(Loop loop, byte[] data)
{
Ensure.ArgumentNotNull(data, "data");
Write(loop, data, 0, data.Length);
}
public void Write(int offset, byte[] data, int index, int count, Action<Exception, int> callback)
{
Write(this.Loop, offset, data, index, count, callback);
}
public void Write(byte[] data, int index, int count, Action<Exception, int> callback)
{
Write(-1, data, index, count, callback);
}
public void Write(int offset, byte[] data, Action<Exception, int> callback)
{
Write(this.Loop, offset, data, callback);
}
public void Write(byte[] data, Action<Exception, int> callback)
{
Write(this.Loop, data, callback);
}
public void Write(int offset, byte[] data, int index, int count)
{
Write(offset, data, index, count, null);
}
public void Write(byte[] data, int index, int count)
{
Write(-1, data, index, count);
}
public void Write(byte[] data)
{
Ensure.ArgumentNotNull(data, "data");
Write(data, 0, data.Length);
}
public void Write(Loop loop, ArraySegment<byte> data, Action<Exception, int> callback)
{
Write(loop, -1, data, callback);
}
public void Write(int offset, Loop loop, ArraySegment<byte> data)
{
Write(loop, offset, data, null);
}
public void Write(Loop loop, ArraySegment<byte> data)
{
Write(loop, data, null);
}
public void Write(int offset, ArraySegment<byte> data, Action<Exception, int> callback)
{
Write(Loop, offset, data, callback);
}
public void Write(ArraySegment<byte> data, Action<Exception, int> callback)
{
Write(-1, data, callback);
}
public void Write(int offset, ArraySegment<byte> data)
{
Write(offset, data, null);
}
public void Write(ArraySegment<byte> data)
{
Write(data, null);
}
public int Write(Loop loop, int offset, Encoding encoding, string text, Action<Exception, int> callback)
{
var bytes = encoding.GetBytes(text);
Write(loop, offset, bytes, callback);
return bytes.Length;
}
public int Write(Loop loop, Encoding encoding, string text, Action<Exception, int> callback)
{
return Write(loop, -1, encoding, text, callback);
}
public int Write(Loop loop, int offset, Encoding encoding, string text)
{
return Write(loop, offset, encoding, text, null);
}
public int Write(Loop loop, Encoding encoding, string text)
{
return Write(loop, -1, encoding, text);
}
public int Write(Loop loop, int offset, string text, Action<Exception, int> callback)
{
return Write(loop, offset, Encoding ?? Encoding.Default, text, callback);
}
public int Write(Loop loop, string text, Action<Exception, int> callback)
{
return Write(loop, -1, text, callback);
}
public int Write(Loop loop, int offset, string text)
{
return Write(loop, offset, text, null);
}
public int Write(Loop loop, string text)
{
return Write(loop, -1, text);
}
public int Write(int offset, Encoding encoding, string text, Action<Exception, int> callback)
{
return Write(this.Loop, offset, encoding, text, callback);
}
public int Write(Encoding encoding, string text, Action<Exception, int> callback)
{
return Write(this.Loop, encoding, text, callback);
}
public int Write(int offset, Encoding encoding, string text)
{
return Write(this.Loop, offset, encoding, text);
}
public int Write(Encoding encoding, string text)
{
return Write(this.Loop, encoding, text);
}
public int Write(int offset, string text, Action<Exception, int> callback)
{
return Write(this.Loop, offset, text, callback);
}
public int Write(string text, Action<Exception, int> callback)
{
return Write(this.Loop, text, callback);
}
public int Write(int offset, string text)
{
return Write(this.Loop, offset, text);
}
public int Write(string text)
{
return Write(this.Loop, text);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_stat(IntPtr loop, IntPtr req, string path, NativeMethods.uv_fs_cb callback);
public static void Stat(Loop loop, string path, Action<Exception, UVFileStat> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = (ex) => {
if (callback != null) {
Ensure.Success(ex, callback, new UVFileStat(fsr.stat));
}
};
int r = uv_fs_stat(loop.NativeHandle, fsr.Handle, path, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public static void Stat(string path, Action<Exception, UVFileStat> callback)
{
Stat(Loop.Constructor, path, callback);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_fstat(IntPtr loop, IntPtr req, int fd, NativeMethods.uv_fs_cb callback);
public void Stat(Loop loop, Action<Exception, UVFileStat> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = (ex) => {
if (callback != null) {
Ensure.Success(ex, callback, new UVFileStat(fsr.stat));
}
};
int r = uv_fs_fstat(loop.NativeHandle, fsr.Handle, FileDescriptor, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_fsync(IntPtr loop, IntPtr req, int fd, NativeMethods.uv_fs_cb callback);
public void Sync(Loop loop, Action<Exception> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = callback;
int r = uv_fs_fsync(loop.NativeHandle, fsr.Handle, FileDescriptor, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public void Sync(Loop loop)
{
Sync(loop, null);
}
public void Sync(Action<Exception> callback)
{
Sync(Loop.Constructor, callback);
}
public void Sync()
{
Sync((Action<Exception>)null);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_fdatasync(IntPtr loop, IntPtr req, int fd, NativeMethods.uv_fs_cb callback);
public void DataSync(Loop loop, Action<Exception> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = callback;
int r = uv_fs_fdatasync(loop.NativeHandle, fsr.Handle, FileDescriptor, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public void DataSync(Loop loop)
{
DataSync(loop, null);
}
public void DataSync(Action<Exception> callback)
{
DataSync(Loop.Constructor, callback);
}
public void DataSync()
{
DataSync((Action<Exception>)null);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_ftruncate(IntPtr loop, IntPtr req, int file, long offset, NativeMethods.uv_fs_cb callback);
public void Truncate(Loop loop, int offset, Action<Exception> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = callback;
int r = uv_fs_ftruncate(loop.NativeHandle, fsr.Handle, FileDescriptor, offset, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public void Truncate(Loop loop, int offset)
{
Truncate(loop, offset);
}
public void Truncate(int offset, Action<Exception> callback)
{
Truncate(Loop.Constructor, offset, callback);
}
public void Truncate(int offset)
{
Truncate(offset, null);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_fchmod(IntPtr loop, IntPtr req, int fd, int mode, NativeMethods.uv_fs_cb callback);
public void Chmod(Loop loop, int mode, Action<Exception> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = callback;
int r = uv_fs_fchmod(loop.NativeHandle, fsr.Handle, FileDescriptor, mode, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public void Chmod(Loop loop, int mode)
{
Chmod(loop, mode, null);
}
public void Chmod(int mode, Action<Exception> callback)
{
Chmod(Loop.Constructor, mode, callback);
}
public void Chmod(int mode)
{
Chmod(mode, null);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_chmod(IntPtr loop, IntPtr req, string path, int mode, NativeMethods.uv_fs_cb callback);
public static void Chmod(Loop loop, string path, int mode, Action<Exception> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = callback;
int r = uv_fs_chmod(loop.NativeHandle, fsr.Handle, path, mode, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public static void Chmod(Loop loop, string path, int mode)
{
Chmod(loop, path, mode, null);
}
public static void Chmod(string path, int mode, Action<Exception> callback)
{
Chmod(Loop.Constructor, path, mode, callback);
}
public static void Chmod(string path, int mode)
{
Chmod(path, mode, null);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_chown(IntPtr loop, IntPtr req, string path, int uid, int gid, NativeMethods.uv_fs_cb callback);
public static void Chown(Loop loop, string path, int uid, int gid, Action<Exception> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = callback;
int r = uv_fs_chown(loop.NativeHandle, fsr.Handle, path, uid, gid, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public static void Chown(Loop loop, string path, int uid, int gid)
{
Chown(loop, path, uid, gid, null);
}
public static void Chown(string path, int uid, int gid, Action<Exception> callback)
{
Chown(Loop.Constructor, path, uid, gid, callback);
}
public static void Chown(string path, int uid, int gid)
{
Chown(path, uid, gid, null);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_fchown(IntPtr loop, IntPtr req, int fd, int uid, int gid, NativeMethods.uv_fs_cb callback);
public void Chown(Loop loop, int uid, int gid, Action<Exception> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = callback;
int r = uv_fs_fchown(loop.NativeHandle, fsr.Handle, FileDescriptor, uid, gid, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public void Chown(Loop loop, int uid, int gid)
{
Chown(loop, uid, gid, null);
}
public void Chown(int uid, int gid, Action<Exception> callback)
{
Chown(Loop.Constructor, uid, gid, callback);
}
public void Chown(int uid, int gid)
{
Chown(uid, gid, null);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_unlink(IntPtr loop, IntPtr req, string path, NativeMethods.uv_fs_cb callback);
public static void Unlink(Loop loop, string path, Action<Exception> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = callback;
int r = uv_fs_unlink(loop.NativeHandle, fsr.Handle, path, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public static void Unlink(Loop loop, string path)
{
Unlink(loop, path, null);
}
public static void Unlink(string path, Action<Exception> callback)
{
Unlink(Loop.Constructor, path, callback);
}
public static void Unlink(string path)
{
Unlink(path, null);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_link(IntPtr loop, IntPtr req, string path, string newPath, NativeMethods.uv_fs_cb callback);
public static void Link(Loop loop, string path, string newPath, Action<Exception> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = callback;
int r = uv_fs_link(loop.NativeHandle, fsr.Handle, path, newPath, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public static void Link(Loop loop, string path, string newPath)
{
Link(loop, path, newPath, null);
}
public static void Link(string path, string newPath, Action<Exception> callback)
{
Link(Loop.Constructor, path, newPath, callback);
}
public static void Link(string path, string newPath)
{
Link(path, newPath, null);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_symlink(IntPtr loop, IntPtr req, string path, string newPath, int flags, NativeMethods.uv_fs_cb callback);
public static void Symlink(Loop loop, string path, string newPath, Action<Exception> callback)
{
var fsr = new FileSystemRequest();
fsr.Callback = callback;
int r = uv_fs_symlink(loop.NativeHandle, fsr.Handle, path, newPath, 0, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public static void Symlink(Loop loop, string path, string newPath)
{
Symlink(loop, path, newPath, null);
}
public static void Symlink(string path, string newPath, Action<Exception> callback)
{
Symlink(Loop.Constructor, path, newPath, callback);
}
public static void Symlink(string path, string newPath)
{
Symlink(path, newPath, null);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
private static extern int uv_fs_readlink(IntPtr loop, IntPtr req, string path, NativeMethods.uv_fs_cb callback);
public static void Readlink(Loop loop, string path, Action<Exception, string> callback)
{
var fsr = new FileSystemRequest(path);
fsr.Callback = (ex) => {
string res = null;
if (ex == null) {
res = Marshal.PtrToStringAuto(fsr.Pointer);
}
Ensure.Success(ex, callback, res);
};
int r = uv_fs_readlink(loop.NativeHandle, fsr.Handle, path, FileSystemRequest.CallbackDelegate);
Ensure.Success(r);
}
public static void Readlink(string path, Action<Exception, string> callback)
{
Readlink(Loop.Constructor, path, callback);
}
}
}
| |
using System;
using System.Collections;
using Mod;
using Mod.Managers;
using Mod.Modules;
using RC;
using UnityEngine;
using UnityEngine.UI;
using LogType = Mod.Logging.LogType;
using Object = UnityEngine.Object;
[DisallowMultipleComponent]
// ReSharper disable once CheckNamespace
public class Minimap : MonoBehaviour, IDisposable
{
private GameObject[] _interface;
private bool assetsInitialized = false;
private static Sprite borderSprite;
private RectTransform borderT;
private Canvas canvas;
private Vector2 cornerPosition;
private float cornerSizeRatio;
private Preset initialPreset;
public static Minimap instance;
private bool isEnabled;
private bool isEnabledTemp;
private Vector3 lastMinimapCenter;
private float lastMinimapOrthoSize;
private Camera lastUsedCamera;
private bool maximized = false;
private RectTransform minimap;
private float MINIMAP_CORNER_SIZE;
public float MINIMAP_CORNER_SIZE_SCALED;
private Vector2 MINIMAP_ICON_SIZE;
private float MINIMAP_POINTER_DIST;
private float MINIMAP_POINTER_SIZE;
private int MINIMAP_SIZE;
private Vector2 MINIMAP_SUPPLY_SIZE;
private MinimapIcon[] minimapIcons;
private bool minimapIsCreated = false;
private RectTransform minimapMaskT;
private Bounds minimapOrthographicBounds;
public RenderTexture minimapRT;
public Camera myCam;
private static Sprite pointerSprite;
private CanvasScaler scaler;
private static Sprite supplySprite;
private static Sprite whiteIconSprite;
private void AddBorderToTexture(ref Texture2D texture, Color borderColor, int borderPixelSize)
{
int num = texture.width * borderPixelSize;
Color[] colors = new Color[num];
for (int i = 0; i < num; i++)
{
colors[i] = borderColor;
}
texture.SetPixels(0, texture.height - borderPixelSize, texture.width - 1, borderPixelSize, colors);
texture.SetPixels(0, 0, texture.width, borderPixelSize, colors);
texture.SetPixels(0, 0, borderPixelSize, texture.height, colors);
texture.SetPixels(texture.width - borderPixelSize, 0, borderPixelSize, texture.height, colors);
texture.Apply();
}
private void AutomaticSetCameraProperties(Camera cam)
{
Renderer[] rendererArray = FindObjectsOfType<Renderer>();
if (rendererArray.Length > 0)
{
this.minimapOrthographicBounds = new Bounds(rendererArray[0].transform.position, Vector3.zero);
for (int i = 0; i < rendererArray.Length; i++)
{
if (rendererArray[i].gameObject.layer == 9)
{
this.minimapOrthographicBounds.Encapsulate(rendererArray[i].bounds);
}
}
}
Vector3 size = this.minimapOrthographicBounds.size;
float num2 = size.x > size.z ? size.x : size.z;
size.z = size.x = num2;
this.minimapOrthographicBounds.size = size;
cam.orthographic = true;
cam.orthographicSize = num2 * 0.5f;
Vector3 center = this.minimapOrthographicBounds.center;
center.y = cam.farClipPlane * 0.5f;
Transform transform = cam.transform;
transform.position = center;
transform.eulerAngles = new Vector3(90f, 0f, 0f);
cam.aspect = 1f;
this.lastMinimapCenter = center;
this.lastMinimapOrthoSize = cam.orthographicSize;
}
private void AutomaticSetOrthoBounds()
{
Renderer[] rendererArray = FindObjectsOfType<Renderer>();
if (rendererArray.Length > 0)
{
this.minimapOrthographicBounds = new Bounds(rendererArray[0].transform.position, Vector3.zero);
for (int i = 0; i < rendererArray.Length; i++)
{
this.minimapOrthographicBounds.Encapsulate(rendererArray[i].bounds);
}
}
Vector3 size = this.minimapOrthographicBounds.size;
float num2 = size.x > size.z ? size.x : size.z;
size.z = size.x = num2;
this.minimapOrthographicBounds.size = size;
this.lastMinimapCenter = this.minimapOrthographicBounds.center;
this.lastMinimapOrthoSize = num2 * 0.5f;
}
private void Awake()
{
instance = this;
}
private Texture2D CaptureMinimap(Camera cam)
{
RenderTexture active = RenderTexture.active;
RenderTexture.active = cam.targetTexture;
cam.Render();
Texture2D textured = new Texture2D(cam.targetTexture.width, cam.targetTexture.height, TextureFormat.RGB24, false)
{
filterMode = FilterMode.Bilinear
};
textured.ReadPixels(new Rect(0f, 0f, cam.targetTexture.width, cam.targetTexture.height), 0, 0);
textured.Apply();
RenderTexture.active = active;
return textured;
}
private void CaptureMinimapRT(Camera cam)
{
RenderTexture active = RenderTexture.active;
RenderTexture.active = this.minimapRT;
cam.targetTexture = this.minimapRT;
cam.Render();
RenderTexture.active = active;
}
private void CheckUserInput()
{
if (!ModuleManager.Enabled(nameof(ModuleShowMap)) || !GameManager.settings.IsMapAllowed)
Dispose();
}
public void CreateMinimap(Camera cam, int minimapResolution = 512, float cornerSize = 0.3f, Preset mapPreset = null)
{
this.isEnabled = true;
this.lastUsedCamera = cam;
if (!this.assetsInitialized)
{
this.Initialize();
}
GameObject obj2 = GameObject.Find("mainLight");
Light component = null;
Quaternion identity = Quaternion.identity;
LightShadows none = LightShadows.None;
Color clear = Color.clear;
float intensity = 0f;
float nearClipPlane = cam.nearClipPlane;
float farClipPlane = cam.farClipPlane;
int cullingMask = cam.cullingMask;
if (obj2 != null)
{
component = obj2.GetComponent<Light>();
identity = component.transform.rotation;
none = component.shadows;
intensity = component.intensity;
clear = component.color;
component.shadows = LightShadows.None;
component.color = Color.white;
component.intensity = 0.5f;
component.transform.eulerAngles = new Vector3(90f, 0f, 0f);
}
cam.nearClipPlane = 0.3f;
cam.farClipPlane = 1000f;
cam.cullingMask = 512;
cam.clearFlags = CameraClearFlags.Color;
this.MINIMAP_SIZE = minimapResolution;
this.MINIMAP_CORNER_SIZE = this.MINIMAP_SIZE * cornerSize;
this.cornerSizeRatio = cornerSize;
this.CreateMinimapRT(cam, minimapResolution);
if (mapPreset != null)
{
this.initialPreset = mapPreset;
this.ManualSetCameraProperties(cam, mapPreset.center, mapPreset.orthographicSize);
}
else
{
this.AutomaticSetCameraProperties(cam);
}
this.CaptureMinimapRT(cam);
if (obj2 != null)
{
component.shadows = none;
component.transform.rotation = identity;
component.color = clear;
component.intensity = intensity;
}
cam.nearClipPlane = nearClipPlane;
cam.farClipPlane = farClipPlane;
cam.cullingMask = cullingMask;
cam.orthographic = false;
cam.clearFlags = CameraClearFlags.Skybox;
this.CreateUnityUIRT(minimapResolution);
this.minimapIsCreated = true;
StartCoroutine(this.HackRoutine());
}
private void CreateMinimapRT(Camera cam, int pixelSize)
{
if (this.minimapRT == null)
{
bool flag2 = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RGB565);
RenderTextureFormat format = flag2 ? RenderTextureFormat.RGB565 : RenderTextureFormat.Default;
this.minimapRT = new RenderTexture(pixelSize, pixelSize, 16, format);
if (!flag2)
Shelter.LogBoth("{0} ({1}) does not support RGB565 format, the minimap will have transparency issues on certain maps", LogType.Error,
SystemInfo.graphicsDeviceName, SystemInfo.graphicsDeviceVendor);
}
cam.targetTexture = this.minimapRT;
}
private void CreateUnityUIRT(int minimapResolution)
{
_interface = new GameObject[4];
_interface[0] = new GameObject("Canvas");
_interface[0].AddComponent<RectTransform>();
this.canvas = _interface[0].AddComponent<Canvas>();
this.canvas.renderMode = RenderMode.ScreenSpaceOverlay;
this.scaler = _interface[0].AddComponent<CanvasScaler>();
this.scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
this.scaler.referenceResolution = new Vector2(800f, 600f);
this.scaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
this.scaler.matchWidthOrHeight = 1f;
_interface[1] = new GameObject("Mask");
_interface[1].transform.SetParent(_interface[0].transform, false);
this.minimapMaskT = _interface[1].AddComponent<RectTransform>();
_interface[1].AddComponent<CanvasRenderer>();
this.minimapMaskT.anchorMin = this.minimapMaskT.anchorMax = Vector2.one;
float num = this.MINIMAP_CORNER_SIZE * 0.5f;
this.cornerPosition = new Vector2(-(num + 5f), -(num + 70f));
this.minimapMaskT.anchoredPosition = this.cornerPosition;
this.minimapMaskT.sizeDelta = new Vector2(this.MINIMAP_CORNER_SIZE, this.MINIMAP_CORNER_SIZE);
_interface[2] = new GameObject("MapBorder");
_interface[2].transform.SetParent(this.minimapMaskT, false);
this.borderT = _interface[2].AddComponent<RectTransform>();
this.borderT.anchorMin = this.borderT.anchorMax = new Vector2(0.5f, 0.5f);
this.borderT.sizeDelta = this.minimapMaskT.sizeDelta;
_interface[2].AddComponent<CanvasRenderer>();
Image image = _interface[2].AddComponent<Image>();
image.sprite = borderSprite;
image.type = Image.Type.Sliced;
_interface[3] = new GameObject("Minimap");
_interface[3].transform.SetParent(this.minimapMaskT, false);
this.minimap = _interface[3].AddComponent<RectTransform>();
this.minimap.SetAsFirstSibling();
_interface[3].AddComponent<CanvasRenderer>();
this.minimap.anchorMin = this.minimap.anchorMax = new Vector2(0.5f, 0.5f);
this.minimap.anchoredPosition = Vector2.zero;
this.minimap.sizeDelta = this.minimapMaskT.sizeDelta;
RawImage image2 = _interface[3].AddComponent<RawImage>();
image2.texture = this.minimapRT;
image2.maskable = true;
_interface[3].AddComponent<Mask>().showMaskGraphic = true;
}
private Vector2 GetSizeForStyle(IconStyle style)
{
if (style == IconStyle.CIRCLE)
{
return this.MINIMAP_ICON_SIZE;
}
if (style == IconStyle.SUPPLY)
{
return this.MINIMAP_SUPPLY_SIZE;
}
return Vector2.zero;
}
private static Sprite GetSpriteForStyle(IconStyle style)
{
if (style == IconStyle.CIRCLE)
{
return whiteIconSprite;
}
if (style == IconStyle.SUPPLY)
{
return supplySprite;
}
return null;
}
private IEnumerator HackRoutine()
{
yield return new WaitForEndOfFrame();
this.RecaptureMinimap(this.lastUsedCamera, this.lastMinimapCenter, this.lastMinimapOrthoSize);
}
private void Initialize()
{
Vector3 pivot = new Vector3(0.5f, 0.5f);
Texture2D texture = (Texture2D)GameManager.RCassets.Load("icon");
Rect rect = new Rect(0f, 0f, texture.width, texture.height);
whiteIconSprite = Sprite.Create(texture, rect, pivot);
texture = (Texture2D)GameManager.RCassets.Load("iconpointer");
rect = new Rect(0f, 0f, texture.width, texture.height);
pointerSprite = Sprite.Create(texture, rect, pivot);
texture = (Texture2D)GameManager.RCassets.Load("supplyicon");
rect = new Rect(0f, 0f, texture.width, texture.height);
supplySprite = Sprite.Create(texture, rect, pivot);
texture = (Texture2D)GameManager.RCassets.Load("mapborder");
rect = new Rect(0f, 0f, texture.width, texture.height);
Vector4 border = new Vector4(5f, 5f, 5f, 5f);
borderSprite = Sprite.Create(texture, rect, pivot, 100f, 1, SpriteMeshType.FullRect, border);
this.MINIMAP_ICON_SIZE = new Vector2(whiteIconSprite.texture.width, whiteIconSprite.texture.height);
this.MINIMAP_POINTER_SIZE = (pointerSprite.texture.width + pointerSprite.texture.height) / 2f;
this.MINIMAP_POINTER_DIST = (this.MINIMAP_ICON_SIZE.x + this.MINIMAP_ICON_SIZE.y) * 0.25f;
this.MINIMAP_SUPPLY_SIZE = new Vector2(supplySprite.texture.width, supplySprite.texture.height);
this.assetsInitialized = true;
}
private void ManualSetCameraProperties(Camera cam, Vector3 centerPoint, float orthoSize)
{
Transform transform = cam.transform;
centerPoint.y = cam.farClipPlane * 0.5f;
transform.position = centerPoint;
transform.eulerAngles = new Vector3(90f, 0f, 0f);
cam.orthographic = true;
cam.orthographicSize = orthoSize;
float x = orthoSize * 2f;
this.minimapOrthographicBounds = new Bounds(centerPoint, new Vector3(x, 0f, x));
this.lastMinimapCenter = centerPoint;
this.lastMinimapOrthoSize = orthoSize;
}
private void ManualSetOrthoBounds(Vector3 centerPoint, float orthoSize)
{
float x = orthoSize * 2f;
this.minimapOrthographicBounds = new Bounds(centerPoint, new Vector3(x, 0f, x));
this.lastMinimapCenter = centerPoint;
this.lastMinimapOrthoSize = orthoSize;
}
public void Maximize()
{
this.isEnabledTemp = true;
if (!this.isEnabled)
{
this.SetEnabledTemp(true);
}
this.minimapMaskT.anchorMin = this.minimapMaskT.anchorMax = new Vector2(0.5f, 0.5f);
this.minimapMaskT.anchoredPosition = Vector2.zero;
this.minimapMaskT.sizeDelta = new Vector2(this.MINIMAP_SIZE, this.MINIMAP_SIZE);
this.minimap.sizeDelta = this.minimapMaskT.sizeDelta;
this.borderT.sizeDelta = this.minimapMaskT.sizeDelta;
if (this.minimapIcons != null)
{
foreach (MinimapIcon icon in minimapIcons)
{
if (icon != null)
{
icon.SetSize(GetSizeForStyle(icon.style));
if (icon.rotation)
{
icon.SetPointerSize(MINIMAP_POINTER_SIZE, MINIMAP_POINTER_DIST);
}
}
}
}
this.maximized = true;
}
public void Minimize()
{
this.isEnabledTemp = false;
if (!this.isEnabled)
{
this.SetEnabledTemp(false);
}
this.minimapMaskT.anchorMin = this.minimapMaskT.anchorMax = Vector2.one;
this.minimapMaskT.anchoredPosition = this.cornerPosition;
this.minimapMaskT.sizeDelta = new Vector2(this.MINIMAP_CORNER_SIZE, this.MINIMAP_CORNER_SIZE);
this.minimap.sizeDelta = this.minimapMaskT.sizeDelta;
this.borderT.sizeDelta = this.minimapMaskT.sizeDelta;
if (this.minimapIcons != null)
{
float num = 1f - (this.MINIMAP_SIZE - this.MINIMAP_CORNER_SIZE) / this.MINIMAP_SIZE;
float a = this.MINIMAP_POINTER_SIZE * num;
a = Mathf.Max(a, this.MINIMAP_POINTER_SIZE * 0.5f);
float originDistance = (this.MINIMAP_POINTER_SIZE - a) / this.MINIMAP_POINTER_SIZE;
originDistance = this.MINIMAP_POINTER_DIST * originDistance;
for (int i = 0; i < this.minimapIcons.Length; i++)
{
MinimapIcon icon = this.minimapIcons[i];
if (icon != null)
{
Vector2 sizeForStyle = this.GetSizeForStyle(icon.style);
sizeForStyle.x = Mathf.Max(sizeForStyle.x * num, sizeForStyle.x * 0.5f);
sizeForStyle.y = Mathf.Max(sizeForStyle.y * num, sizeForStyle.y * 0.5f);
icon.SetSize(sizeForStyle);
if (icon.rotation)
{
icon.SetPointerSize(a, originDistance);
}
}
}
}
this.maximized = false;
}
public static void OnScreenResolutionChanged()
{
if (instance != null)
instance.StartCoroutine(instance.ScreenResolutionChangedRoutine());
}
private void RecaptureMinimap()
{
if (this.lastUsedCamera != null)
{
this.RecaptureMinimap(this.lastUsedCamera, this.lastMinimapCenter, this.lastMinimapOrthoSize);
}
}
private void RecaptureMinimap(Camera cam, Vector3 centerPosition, float orthoSize)
{
if (this.minimap != null)
{
GameObject obj2 = GameObject.Find("mainLight");
Light component = null;
Quaternion identity = Quaternion.identity;
LightShadows none = LightShadows.None;
Color clear = Color.clear;
float intensity = 0f;
float nearClipPlane = cam.nearClipPlane;
float farClipPlane = cam.farClipPlane;
int cullingMask = cam.cullingMask;
if (obj2 != null)
{
component = obj2.GetComponent<Light>();
identity = component.transform.rotation;
none = component.shadows;
clear = component.color;
intensity = component.intensity;
component.shadows = LightShadows.None;
component.color = Color.white;
component.intensity = 0.5f;
component.transform.eulerAngles = new Vector3(90f, 0f, 0f);
}
cam.nearClipPlane = 0.3f;
cam.farClipPlane = 1000f;
cam.clearFlags = CameraClearFlags.Color;
cam.cullingMask = 512;
this.CreateMinimapRT(cam, this.MINIMAP_SIZE);
this.ManualSetCameraProperties(cam, centerPosition, orthoSize);
this.CaptureMinimapRT(cam);
if (obj2 != null)
{
component.shadows = none;
component.transform.rotation = identity;
component.color = clear;
component.intensity = intensity;
}
cam.nearClipPlane = nearClipPlane;
cam.farClipPlane = farClipPlane;
cam.cullingMask = cullingMask;
cam.orthographic = false;
cam.clearFlags = CameraClearFlags.Skybox;
}
}
private IEnumerator ScreenResolutionChangedRoutine()
{
yield return 0;
this.RecaptureMinimap();
}
public void SetEnabled(bool enabled)
{
this.isEnabled = enabled;
if (this.canvas != null)
{
this.canvas.gameObject.SetActive(enabled);
}
}
public void SetEnabledTemp(bool enabled)
{
if (this.canvas != null)
{
this.canvas.gameObject.SetActive(enabled);
}
}
public void TrackGameObjectOnMinimap(GameObject objToTrack, Color iconColor, bool trackOrientation, bool depthAboveAll = false, IconStyle iconStyle = 0)
{
if (this.minimap != null)
{
MinimapIcon icon;
if (trackOrientation)
{
icon = MinimapIcon.CreateWithRotation(this.minimap, objToTrack, iconStyle, this.MINIMAP_POINTER_DIST);
}
else
{
icon = MinimapIcon.Create(this.minimap, objToTrack, iconStyle);
}
icon.SetColor(iconColor);
icon.SetDepth(depthAboveAll);
Vector2 sizeForStyle = this.GetSizeForStyle(iconStyle);
if (this.maximized)
{
icon.SetSize(sizeForStyle);
if (icon.rotation)
{
icon.SetPointerSize(this.MINIMAP_POINTER_SIZE, this.MINIMAP_POINTER_DIST);
}
}
else
{
float num = 1f - (this.MINIMAP_SIZE - this.MINIMAP_CORNER_SIZE) / this.MINIMAP_SIZE;
sizeForStyle.x = Mathf.Max(sizeForStyle.x * num, sizeForStyle.x * 0.5f);
sizeForStyle.y = Mathf.Max(sizeForStyle.y * num, sizeForStyle.y * 0.5f);
icon.SetSize(sizeForStyle);
if (icon.rotation)
{
float a = this.MINIMAP_POINTER_SIZE * num;
a = Mathf.Max(a, this.MINIMAP_POINTER_SIZE * 0.5f);
float originDistance = (this.MINIMAP_POINTER_SIZE - a) / this.MINIMAP_POINTER_SIZE;
originDistance = this.MINIMAP_POINTER_DIST * originDistance;
icon.SetPointerSize(a, originDistance);
}
}
if (this.minimapIcons == null)
{
this.minimapIcons = new MinimapIcon[] { icon };
}
else
{
MinimapIcon[] iconArray2 = new MinimapIcon[this.minimapIcons.Length + 1];
for (int i = 0; i < this.minimapIcons.Length; i++)
{
iconArray2[i] = this.minimapIcons[i];
}
iconArray2[iconArray2.Length - 1] = icon;
this.minimapIcons = iconArray2;
}
}
}
public static void TryRecaptureInstance()
{
if (instance != null)
{
instance.RecaptureMinimap();
}
}
public IEnumerator TryRecaptureInstanceE(float time)
{
yield return new WaitForSeconds(time);
TryRecaptureInstance();
}
private void Update()
{
this.CheckUserInput();
if ((this.isEnabled || this.isEnabledTemp) && this.minimapIsCreated && this.minimapIcons != null)
{
for (int i = 0; i < this.minimapIcons.Length; i++)
{
MinimapIcon icon = this.minimapIcons[i];
if (icon == null)
{
RCextensions.RemoveAt<MinimapIcon>(ref this.minimapIcons, i);
}
else if (!icon.UpdateUI(this.minimapOrthographicBounds, this.maximized ? this.MINIMAP_SIZE : this.MINIMAP_CORNER_SIZE))
{
icon.Destroy();
RCextensions.RemoveAt<MinimapIcon>(ref this.minimapIcons, i);
}
}
}
}
public static void WaitAndTryRecaptureInstance(float time)
{
instance.StartCoroutine(instance.TryRecaptureInstanceE(time));
}
public enum IconStyle
{
CIRCLE,
SUPPLY
}
public class MinimapIcon
{
private Transform obj;
private RectTransform pointerRect;
public readonly bool rotation;
public readonly IconStyle style;
private RectTransform uiRect;
public MinimapIcon(GameObject trackedObject, GameObject uiElement, IconStyle style)
{
this.rotation = false;
this.style = style;
this.obj = trackedObject.transform;
this.uiRect = uiElement.GetComponent<RectTransform>();
CatchDestroy component = this.obj.GetComponent<CatchDestroy>();
if (component == null)
{
this.obj.gameObject.AddComponent<CatchDestroy>().target = uiElement;
}
else if (component.target != null && component.target != uiElement)
{
Object.Destroy(component.target);
}
else
{
component.target = uiElement;
}
}
public MinimapIcon(GameObject trackedObject, GameObject uiElement, GameObject uiPointer, IconStyle style)
{
this.rotation = true;
this.style = style;
this.obj = trackedObject.transform;
this.uiRect = uiElement.GetComponent<RectTransform>();
this.pointerRect = uiPointer.GetComponent<RectTransform>();
CatchDestroy component = this.obj.GetComponent<CatchDestroy>();
if (component == null)
{
this.obj.gameObject.AddComponent<CatchDestroy>().target = uiElement;
}
else if (component.target != null && component.target != uiElement)
{
Object.Destroy(component.target);
}
else
{
component.target = uiElement;
}
}
public static MinimapIcon Create(RectTransform parent, GameObject trackedObject, IconStyle style)
{
Sprite spriteForStyle = GetSpriteForStyle(style);
GameObject uiElement = new GameObject("MinimapIcon");
RectTransform transform = uiElement.AddComponent<RectTransform>();
transform.anchorMin = transform.anchorMax = new Vector3(0.5f, 0.5f);
transform.sizeDelta = new Vector2(spriteForStyle.texture.width, spriteForStyle.texture.height);
Image image = uiElement.AddComponent<Image>();
image.sprite = spriteForStyle;
image.type = Image.Type.Simple;
uiElement.transform.SetParent(parent, false);
return new MinimapIcon(trackedObject, uiElement, style);
}
public static MinimapIcon CreateWithRotation(RectTransform parent, GameObject trackedObject, IconStyle style, float pointerDist)
{
Sprite spriteForStyle = GetSpriteForStyle(style);
GameObject uiElement = new GameObject("MinimapIcon");
RectTransform transform = uiElement.AddComponent<RectTransform>();
transform.anchorMin = transform.anchorMax = new Vector3(0.5f, 0.5f);
transform.sizeDelta = new Vector2(spriteForStyle.texture.width, spriteForStyle.texture.height);
Image image = uiElement.AddComponent<Image>();
image.sprite = spriteForStyle;
image.type = Image.Type.Simple;
uiElement.transform.SetParent(parent, false);
GameObject uiPointer = new GameObject("IconPointer");
RectTransform transform2 = uiPointer.AddComponent<RectTransform>();
transform2.anchorMin = transform2.anchorMax = transform.anchorMin;
transform2.sizeDelta = new Vector2(pointerSprite.texture.width, pointerSprite.texture.height);
Image image2 = uiPointer.AddComponent<Image>();
image2.sprite = pointerSprite;
image2.type = Image.Type.Simple;
uiPointer.transform.SetParent(transform, false);
transform2.anchoredPosition = new Vector2(0f, pointerDist);
return new MinimapIcon(trackedObject, uiElement, uiPointer, style);
}
public void Destroy()
{
if (this.uiRect != null)
{
Object.Destroy(this.uiRect.gameObject);
}
}
public void SetColor(Color color)
{
if (this.uiRect != null)
{
this.uiRect.GetComponent<Image>().color = color;
}
}
public void SetDepth(bool aboveAll)
{
if (this.uiRect != null)
{
if (aboveAll)
{
this.uiRect.SetAsLastSibling();
}
else
{
this.uiRect.SetAsFirstSibling();
}
}
}
public void SetPointerSize(float size, float originDistance)
{
if (this.pointerRect != null)
{
this.pointerRect.sizeDelta = new Vector2(size, size);
this.pointerRect.anchoredPosition = new Vector2(0f, originDistance);
}
}
public void SetSize(Vector2 size)
{
if (this.uiRect != null)
{
this.uiRect.sizeDelta = size;
}
}
public bool UpdateUI(Bounds worldBounds, float minimapSize)
{
if (this.obj == null)
{
return false;
}
float x = worldBounds.size.x;
Vector3 vector = this.obj.position - worldBounds.center;
vector.y = vector.z;
vector.z = 0f;
float num2 = Mathf.Abs(vector.x) / x;
vector.x = vector.x < 0f ? -num2 : num2;
float num3 = Mathf.Abs(vector.y) / x;
vector.y = vector.y < 0f ? -num3 : num3;
Vector2 vector2 = vector * minimapSize;
this.uiRect.anchoredPosition = vector2;
if (this.rotation)
{
float z = Mathf.Atan2(this.obj.forward.z, this.obj.forward.x) * 57.29578f - 90f;
this.uiRect.eulerAngles = new Vector3(0f, 0f, z);
}
return true;
}
}
public class Preset
{
public readonly Vector3 center;
public readonly float orthographicSize;
public Preset(Vector3 center, float orthographicSize)
{
this.center = center;
this.orthographicSize = orthographicSize;
}
}
public void Dispose()
{
foreach (var obj in _interface)
Destroy(obj);
Destroy(this);
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Cms.Security
{
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Web;
using Adxstudio.Xrm.Blogs;
using Adxstudio.Xrm.Cases;
using Adxstudio.Xrm.Configuration;
using Adxstudio.Xrm.Events.Security;
using Adxstudio.Xrm.Forums.Security;
using Adxstudio.Xrm.Ideas;
using Adxstudio.Xrm.Issues;
using Adxstudio.Xrm.Security;
using Adxstudio.Xrm.Services;
using Adxstudio.Xrm.Services.Query;
using Adxstudio.Xrm.Diagnostics.Trace;
using Adxstudio.Xrm.Web;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
public class CmsCrmEntitySecurityProvider : CrmEntitySecurityProvider
{
private ICacheSupportingCrmEntitySecurityProvider _underlyingProvider;
public override void Initialize(string name, NameValueCollection config)
{
base.Initialize(name, config);
var portalName = config["portalName"];
var contentMapProvider = AdxstudioCrmConfigurationManager.CreateContentMapProvider(portalName);
_underlyingProvider = contentMapProvider != null
? new ContentMapUncachedProvider(contentMapProvider)
: new UncachedProvider(portalName);
var cacheInfoFactory = new CrmEntitySecurityCacheInfoFactory(GetType().FullName);
bool cachingEnabled;
if (!bool.TryParse(config["cachingEnabled"], out cachingEnabled)) { cachingEnabled = true; }
if (cachingEnabled)
{
_underlyingProvider = new ApplicationCachingCrmEntitySecurityProvider(_underlyingProvider, cacheInfoFactory);
}
bool requestCachingEnabled;
if (!bool.TryParse(config["requestCachingEnabled"], out requestCachingEnabled)) { requestCachingEnabled = true; }
if (requestCachingEnabled && HttpContext.Current != null)
{
_underlyingProvider = new RequestCachingCrmEntitySecurityProvider(_underlyingProvider, cacheInfoFactory);
}
}
public override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right)
{
return _underlyingProvider.TryAssert(context, entity, right);
}
internal class UncachedProvider : CacheSupportingCrmEntitySecurityProvider
{
private readonly WebPageAccessControlSecurityProvider _webPageAccessControlProvider;
private readonly PublishedDatesAccessProvider _publishedDatesAccessProvider;
private readonly PublishingStateAccessProvider _publishingStateAccessProvider;
private readonly EventAccessPermissionProvider _eventAccessPermissionProvider;
private readonly ForumAccessPermissionProvider _forumAccessPermissionProvider;
private readonly BlogSecurityProvider _blogSecurityProvider;
private readonly IdeaSecurityProvider _ideaSecurityProvider;
private readonly IssueSecurityProvider _issueSecurityProvider;
private readonly HttpContext current;
public UncachedProvider(string portalName = null)
: this(new WebPageAccessControlSecurityProvider(HttpContext.Current), new PublishedDatesAccessProvider(HttpContext.Current), new PublishingStateAccessProvider(HttpContext.Current), portalName)
{
this.current = HttpContext.Current;
}
protected UncachedProvider(
WebPageAccessControlSecurityProvider webPageAccessControlProvider,
PublishedDatesAccessProvider publishedDatesAccessProvider,
PublishingStateAccessProvider publishingStateAccessProvider, string portalName = null)
{
_webPageAccessControlProvider = webPageAccessControlProvider;
_publishedDatesAccessProvider = publishedDatesAccessProvider;
_publishingStateAccessProvider = publishingStateAccessProvider;
_eventAccessPermissionProvider = new EventAccessPermissionProvider();
_forumAccessPermissionProvider = new ForumAccessPermissionProvider(this.current);
_blogSecurityProvider = new BlogSecurityProvider(_webPageAccessControlProvider, this.current, portalName);
_ideaSecurityProvider = new IdeaSecurityProvider(this.current, portalName);
_issueSecurityProvider = new IssueSecurityProvider(portalName);
PortalName = portalName;
}
protected string PortalName { get; private set; }
public override bool TryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
if (entity != null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(
"right={0}, logicalName={1}, id={2}",
right, EntityNamePrivacy.GetEntityName(entity.LogicalName),
entity.Id));
}
else
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("right={0}", right));
}
var timer = Stopwatch.StartNew();
var result = InnerTryAssert(context, entity, right, dependencies);
timer.Stop();
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("result={0}, duration={1} ms", result, timer.ElapsedMilliseconds));
return result;
}
private bool InnerTryAssert(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
if (entity == null)
{
return false;
}
if (right == CrmEntityRight.Read && (!_publishedDatesAccessProvider.TryAssert(context, entity) || !_publishingStateAccessProvider.TryAssert(context, entity)))
{
// We let the date and state access providers handle their own caching logic, so we signal any
// caching providers above this one to not cache this result.
dependencies.IsCacheable = false;
return false;
}
dependencies.AddEntityDependency(entity);
var entityName = entity.LogicalName;
CrmEntityInactiveInfo inactiveInfo;
if (CrmEntityInactiveInfo.TryGetInfo(entityName, out inactiveInfo) && inactiveInfo.IsInactive(entity))
{
return false;
}
if (entityName == "adx_webpage")
{
return TestWebPage(context, entity, right, dependencies);
}
if (entityName == "feedback")
{
return TestFeedback(context, entity, right, dependencies);
}
if (entityName == "adx_event")
{
return TestEvent(context, entity, right, dependencies);
}
if (entityName == "adx_eventschedule")
{
return TestEventSchedule(context, entity, right, dependencies);
}
if ((entityName == "adx_eventspeaker" || entityName == "adx_eventsponsor") && right == CrmEntityRight.Read)
{
return true;
}
if (entityName == "adx_communityforum")
{
return TestForum(context, entity, right, dependencies);
}
if (entityName == "adx_communityforumthread")
{
return TestForumThread(context, entity, right, dependencies);
}
if (entityName == "adx_communityforumpost")
{
return TestForumPost(context, entity, right, dependencies);
}
if (entityName == "adx_communityforumannouncement")
{
return TestForumAnnouncement(context, entity, right, dependencies);
}
if (entityName == "adx_forumthreadtype")
{
return right == CrmEntityRight.Read;
}
if ((entityName == "adx_pagetemplate" || entityName == "adx_publishingstate" || "adx_websitelanguage" == entityName) && right == CrmEntityRight.Read)
{
return true;
}
if (entityName == "adx_webfile")
{
return TestWebFile(context, entity, right, dependencies);
}
if (entityName == "adx_contentsnippet" || entityName == "adx_weblinkset" || entityName == "adx_weblink" || entityName == "adx_sitemarker")
{
return TestWebsiteAccessPermission(context, entity, right, dependencies);
}
if (entityName == "adx_shortcut")
{
return TestShortcut(context, entity, right, dependencies);
}
if (entityName == "adx_blog")
{
return TestBlog(context, entity, right, dependencies);
}
if (entityName == "adx_blogpost")
{
return TestBlogPost(context, entity, right, dependencies);
}
if (entityName == "adx_ideaforum")
{
return TestIdeaForum(context, entity, right, dependencies);
}
if (entityName == "adx_idea")
{
return TestIdea(context, entity, right, dependencies);
}
if (entityName == "adx_ideacomment")
{
return TestIdeaComment(context, entity, right, dependencies);
}
if (entityName == "adx_ideavote")
{
return TestIdeaVote(context, entity, right, dependencies);
}
if (entityName == "adx_issueforum")
{
return TestIssueForum(context, entity, right, dependencies);
}
if (entityName == "adx_issue")
{
return TestIssue(context, entity, right, dependencies);
}
if (entityName == "adx_issuecomment")
{
return TestIssueComment(context, entity, right, dependencies);
}
if (entityName == "adx_adplacement" || entityName == "adx_ad")
{
return right == CrmEntityRight.Read;
}
if (entityName == "email")
{
return right == CrmEntityRight.Read;
}
if (entityName == "incident" && right == CrmEntityRight.Read)
{
return IsPublicCase(entity);
}
if (IsPortalKbArticle(entity))
{
return right == CrmEntityRight.Read;
}
if (IsPublicKnowledgeArticle(entity))
{
return right == CrmEntityRight.Read;
}
if (IsCategory(entity))
{
return right == CrmEntityRight.Read;
}
if (IsAnnotation(entity))
{
return right == CrmEntityRight.Read;
}
// To allow note attachments to be read by the customer to which the order or quote belongs.
if (entityName == "salesorder" || entityName == "quote")
{
var customerid = entity.GetAttributeValue<EntityReference>("customerid");
var portalContext = PortalCrmConfigurationManager.CreatePortalContext(PortalName);
return right == CrmEntityRight.Read
&& customerid != null
&& portalContext != null
&& portalContext.User != null
&& customerid.Equals(portalContext.User.ToEntityReference());
}
if (TestServiceRequest(context, entity))
{
return right == CrmEntityRight.Read;
}
Entity parentPermit;
if (TryGetParentPermit(context, entity, out parentPermit))
{
return TestParentPermit(context, parentPermit, right);
}
return false;
}
protected virtual bool TestBlog(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _blogSecurityProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestBlogPost(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _blogSecurityProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestBlogPost(OrganizationServiceContext context, EntityReference entityReference, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entityReference != null) && _blogSecurityProvider.TryAssert(context, entityReference, right, dependencies);
}
protected virtual bool TestEvent(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _eventAccessPermissionProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestEventSchedule(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null)
&& entity.GetAttributeValue<EntityReference>("adx_eventid") != null
&& TestEvent(context, entity.GetRelatedEntity(context, "adx_event_eventschedule"), right, dependencies);
}
protected virtual bool TestForum(OrganizationServiceContext context, EntityReference entityReference, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entityReference != null) && _forumAccessPermissionProvider.TryAssert(context, entityReference, right, dependencies);
}
protected virtual bool TestForum(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _forumAccessPermissionProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestForumAnnouncement(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
if (entity == null)
{
return false;
}
return this.TestForum(context, entity.GetAttributeValue<EntityReference>("adx_forumid"), right, dependencies);
}
protected virtual bool TestForumThread(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
if (entity == null)
{
return false;
}
return this.TestForum(context, entity.GetAttributeValue<EntityReference>("adx_forumid"), right, dependencies);
}
protected virtual bool TestForumPost(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
if (entity == null || entity.GetAttributeValue<EntityReference>("adx_forumthreadid") == null)
{
return false;
}
var threadRef = entity.GetAttributeValue<EntityReference>("adx_forumthreadid");
var fetch = new Fetch
{
Entity = new FetchEntity("adx_communityforumthread", new[] { "adx_forumid" })
{
Filters = new[]
{
new Filter
{
Conditions = new[] { new Condition("adx_communityforumthreadid", ConditionOperator.Equal, threadRef.Id) }
}
}
}
};
var thread = context.RetrieveSingle(fetch);
return this.TestForumThread(context, thread, right, dependencies);
}
protected virtual bool TestIdeaForum(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _ideaSecurityProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestIdea(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _ideaSecurityProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestIdeaComment(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _ideaSecurityProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestIdeaVote(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _ideaSecurityProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestIssueForum(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _issueSecurityProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestIssue(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _issueSecurityProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestIssueComment(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _issueSecurityProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestSurvey(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return true;
}
protected virtual bool TestShortcut(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
// For shortcut change permission, always test rights on shortcut parent.
if (right == CrmEntityRight.Change)
{
return TestShortcutParent(context, entity, right, dependencies);
}
return entity.GetAttributeValue<bool?>("adx_disabletargetvalidation").GetValueOrDefault(false)
? TestShortcutParent(context, entity, right, dependencies)
: TestShortcutTarget(context, entity, right, dependencies);
}
protected virtual bool TestShortcutTarget(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
if (entity == null)
{
return false;
}
if (!string.IsNullOrEmpty(entity.GetAttributeValue<string>("adx_externalurl")))
{
return true;
}
if (entity.GetAttributeValue<EntityReference>("adx_webpageid") != null)
{
return this.TestWebPage(context, entity.GetAttributeValue<EntityReference>("adx_webpageid"), right, dependencies);
}
if (entity.GetAttributeValue<EntityReference>("adx_webfileid") != null)
{
var reference = entity.GetAttributeValue<EntityReference>("adx_webfileid");
var webfile = context.RetrieveSingle(
"adx_webfile",
new[] { "adx_blogpostid", "adx_parentpageid" },
new Condition("adx_webfileid", ConditionOperator.Equal, reference.Id));
return this.TestWebFile(context, webfile, right, dependencies);
}
if (entity.GetAttributeValue<EntityReference>("adx_forumid") != null)
{
return this.TestForum(context, entity.GetAttributeValue<EntityReference>("adx_forumid"), right, dependencies);
}
// legacy entities
if (entity.GetAttributeValue<EntityReference>("adx_surveyid") != null)
{
return TestSurvey(context, entity.GetRelatedEntity(context, "adx_survey_shortcut"), right, dependencies);
}
if (entity.GetAttributeValue<EntityReference>("adx_eventid") != null)
{
return TestEvent(context, entity.GetRelatedEntity(context, "adx_event_shortcut"), right, dependencies);
}
return false;
}
protected virtual bool TestShortcutParent(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && TestWebPage(context, entity.GetAttributeValue<EntityReference>("adx_webpageid"), right, dependencies);
}
protected virtual bool TestParentWebPage(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && TestWebPage(context, entity.GetAttributeValue<EntityReference>("adx_parentpageid"), right, dependencies);
}
protected virtual bool TestWebFile(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
if (entity == null)
{
return false;
}
var parentBlogPostReference = entity.GetAttributeValue<EntityReference>("adx_blogpostid");
if (parentBlogPostReference != null)
{
var post = context.RetrieveSingle(parentBlogPostReference, new ColumnSet());
return this.TestBlogPost(context, post, right, dependencies);
}
return TestParentWebPage(context, entity, right, dependencies);
}
protected virtual bool TestWebPage(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entity != null) && _webPageAccessControlProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestFileWebPage(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
{
return (entity != null) && _webPageAccessControlProvider.TryAssert(context, entity, right, dependencies, map, true);
}
protected virtual bool TestWebPage(OrganizationServiceContext context, EntityReference entityReference, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return (entityReference != null) && _webPageAccessControlProvider.TryAssert(context, entityReference, right, dependencies);
}
protected virtual WebsiteAccessPermissionProvider CreateWebsiteAccessPermissionProvider(Entity website, WebPageAccessControlSecurityProvider webPageAccessControlProvider)
{
return new WebsiteAccessPermissionProvider(website, HttpContext.Current);
}
protected virtual bool TestWebsiteAccessPermission(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
var website = context.GetWebsite(entity);
if (website == null) return false;
var securityProvider = CreateWebsiteAccessPermissionProvider(website, _webPageAccessControlProvider);
return securityProvider.TryAssert(context, entity, right, dependencies);
}
protected virtual bool TestFeedback(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format(@"Testing right {0} on feedback ({1}).", right, entity.Id));
dependencies.AddEntityDependency(entity);
EntityReference relatedReference = entity.GetAttributeValue<EntityReference>("regardingobjectid");
if (relatedReference == null)
{
return false;
}
// Determine the primary ID attribute of the regarding object
var request = new RetrieveEntityRequest
{
LogicalName = relatedReference.LogicalName,
EntityFilters = EntityFilters.Entity
};
var response = context.Execute(request) as RetrieveEntityResponse;
if (response == null || response.EntityMetadata == null)
{
return false;
}
var primaryIdAttribute = response.EntityMetadata.PrimaryIdAttribute;
// Retrieve the regarding object
var relatedEntity = context.CreateQuery(relatedReference.LogicalName)
.FirstOrDefault(e => e.GetAttributeValue<Guid>(primaryIdAttribute) == relatedReference.Id);
if (relatedEntity == null)
{
return false;
}
var approved = entity.GetAttributeValue<bool?>("adx_approved").GetValueOrDefault(false);
// If the right being asserted is Read, and the comment is approved, assert whether the post is readable.
if (right == CrmEntityRight.Read && approved)
{
return TryAssert(context, relatedEntity, right, dependencies);
}
var author = entity.GetAttributeValue<EntityReference>("createdbycontact");
// If there's no author on the post for some reason, only allow posts that are published, and pass the same assertion on the blog.
if (author == null)
{
return approved && TryAssert(context, relatedEntity, right, dependencies);
}
var portal = PortalCrmConfigurationManager.CreatePortalContext();
// If we can't get a current portal user, only allow posts that are published, and pass the same assertion on the blog.
if (portal == null || portal.User == null)
{
return approved && TryAssert(context, relatedEntity, right, dependencies);
}
return TryAssert(context, relatedEntity, right, dependencies);
}
protected virtual bool TestServiceRequest(OrganizationServiceContext context, Entity entity)
{
return (entity.GetAttributeValue<EntityReference>("adx_servicerequest") ?? entity.GetAttributeValue<EntityReference>("adx_servicerequestid")) != null;
}
protected virtual bool TryGetParentPermit(OrganizationServiceContext context, Entity entity, out Entity parentPermit)
{
var permitReference = entity.GetAttributeValue<EntityReference>("adx_permit") ??
entity.GetAttributeValue<EntityReference>("adx_permitid");
if (permitReference != null)
{
parentPermit = context.CreateQuery("adx_permit").FirstOrDefault(
p => p.GetAttributeValue<Guid>("adx_permitid") == permitReference.Id);
return true;
}
parentPermit = null;
return false;
}
protected virtual bool TestParentPermit(OrganizationServiceContext context, Entity entity, CrmEntityRight right)
{
var contactid = entity.GetAttributeValue<EntityReference>("adx_regardingcontact")
?? entity.GetAttributeValue<EntityReference>("adx_regardingcontactid");
var portalContext = PortalCrmConfigurationManager.CreatePortalContext(PortalName);
return right == CrmEntityRight.Read
&& contactid != null
&& portalContext != null
&& portalContext.User != null
&& contactid.Equals(portalContext.User.ToEntityReference());
}
private static bool IsPublicCase(Entity entity)
{
var statecode = entity.GetAttributeValue<OptionSetValue>("statecode");
return entity.GetAttributeValue<bool?>("adx_publishtoweb").GetValueOrDefault()
&& statecode != null
&& statecode.Value == (int)IncidentState.Resolved;
}
private enum KbArticleState
{
Draft = 1,
Unapproved = 2,
Published = 3,
}
private static bool IsPortalKbArticle(Entity entity)
{
return entity != null
&& entity.LogicalName == "kbarticle"
&& (entity.GetAttributeValue<OptionSetValue>("statecode") != null && entity.GetAttributeValue<OptionSetValue>("statecode").Value == (int)KbArticleState.Published)
&& entity.GetAttributeValue<bool?>("msa_publishtoweb").GetValueOrDefault();
}
private enum KnowledgeArticleState
{
Draft = 0,
Approved = 1,
Scheduled = 2,
Published = 3,
Expired = 4,
Archived = 5,
Discarded = 6
}
private static bool IsPublicKnowledgeArticle(Entity entity)
{
return entity != null
&& entity.LogicalName == "knowledgearticle"
&& (entity.GetAttributeValue<OptionSetValue>("statecode") != null && entity.GetAttributeValue<OptionSetValue>("statecode").Value == (int)KnowledgeArticleState.Published)
&& !entity.GetAttributeValue<bool?>("isrootarticle").GetValueOrDefault(false)
&& !entity.GetAttributeValue<bool?>("isinternal").GetValueOrDefault(false);
}
private static bool IsCategory(Entity entity)
{
return entity != null && entity.LogicalName == "category";
}
private static bool IsAnnotation(Entity entity)
{
var notesFilter = HttpContext.Current.GetSiteSetting("KnowledgeManagement/NotesFilter") ?? string.Empty;
return entity != null
&& entity.LogicalName == "annotation"
&& entity.GetAttributeValue<string>("objecttypecode") == "knowledgearticle"
&& entity.GetAttributeValue<string>("notetext").StartsWith(notesFilter);
}
}
internal class ContentMapUncachedProvider : UncachedProvider
{
private readonly IContentMapProvider _contentMapProvider;
public ContentMapUncachedProvider(IContentMapProvider contentMapProvider)
: base(
new WebPageAccessControlSecurityProvider(contentMapProvider),
new PublishedDatesAccessProvider(contentMapProvider),
new PublishingStateAccessProvider(contentMapProvider))
{
_contentMapProvider = contentMapProvider;
}
protected override WebsiteAccessPermissionProvider CreateWebsiteAccessPermissionProvider(Entity website, WebPageAccessControlSecurityProvider webPageAccessControlProvider)
{
return new WebsiteAccessPermissionProvider(website, webPageAccessControlProvider, _contentMapProvider);
}
protected override bool TestShortcutTarget(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
if (entity == null)
{
return false;
}
return _contentMapProvider.Using(map => TestShortcutTarget(context, entity, right, dependencies, map));
}
private bool TestShortcutTarget(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies, ContentMap map)
{
ShortcutNode shortcut;
if (map.TryGetValue(entity, out shortcut))
{
if (!string.IsNullOrWhiteSpace(shortcut.ExternalUrl))
{
return true;
}
if (shortcut.WebPage != null)
{
return !shortcut.WebPage.IsReference && TestWebPage(context, shortcut.WebPage.ToEntity(), right, dependencies);
}
if (shortcut.WebFile != null)
{
return !shortcut.WebFile.IsReference && TestWebFile(context, shortcut.WebFile.ToEntity(), right, dependencies);
}
}
return base.TestShortcutTarget(context, entity, right, dependencies);
}
protected override bool TestShortcutParent(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return _contentMapProvider.Using(map =>
{
ShortcutNode shortcut;
if (map.TryGetValue(entity, out shortcut))
{
return shortcut.Parent != null
&& !shortcut.Parent.IsReference
&& TestWebPage(context, shortcut.Parent.ToEntity(), right, dependencies);
}
return base.TestShortcutParent(context, entity, right, dependencies);
});
}
protected override bool TestWebFile(OrganizationServiceContext context, Entity entity, CrmEntityRight right, CrmEntityCacheDependencyTrace dependencies)
{
return _contentMapProvider.Using(map =>
{
WebFileNode file;
if (map.TryGetValue(entity, out file) && file.Parent != null)
{
return !file.Parent.IsReference
&& TestFileWebPage(context, file.Parent.ToEntity(), right, dependencies, map);
}
return base.TestWebFile(context, entity, right, dependencies);
});
}
}
}
}
| |
// 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 osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Threading;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Settings;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.IPC;
using osu.Game.Tournament.Models;
using osu.Game.Tournament.Screens.Gameplay.Components;
using osu.Game.Tournament.Screens.MapPool;
using osu.Game.Tournament.Screens.TeamWin;
using osuTK.Graphics;
namespace osu.Game.Tournament.Screens.Gameplay
{
public class GameplayScreen : BeatmapInfoScreen, IProvideVideo
{
private readonly BindableBool warmup = new BindableBool();
public readonly Bindable<TourneyState> State = new Bindable<TourneyState>();
private OsuButton warmupButton;
private MatchIPCInfo ipc;
[Resolved(canBeNull: true)]
private TournamentSceneManager sceneManager { get; set; }
[Resolved]
private TournamentMatchChatDisplay chat { get; set; }
private Drawable chroma;
[BackgroundDependencyLoader]
private void load(LadderInfo ladder, MatchIPCInfo ipc)
{
this.ipc = ipc;
AddRangeInternal(new Drawable[]
{
new TourneyVideo("gameplay")
{
Loop = true,
RelativeSizeAxes = Axes.Both,
},
header = new MatchHeader
{
ShowLogo = false
},
new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Y = 110,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Children = new[]
{
chroma = new Container
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Height = 512,
Children = new Drawable[]
{
new ChromaArea
{
Name = "Left chroma",
RelativeSizeAxes = Axes.Both,
Width = 0.5f,
},
new ChromaArea
{
Name = "Right chroma",
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Width = 0.5f,
}
}
},
}
},
scoreDisplay = new TournamentMatchScoreDisplay
{
Y = -147,
Anchor = Anchor.BottomCentre,
Origin = Anchor.TopCentre,
},
new ControlPanel
{
Children = new Drawable[]
{
warmupButton = new TourneyButton
{
RelativeSizeAxes = Axes.X,
Text = "Toggle warmup",
Action = () => warmup.Toggle()
},
new TourneyButton
{
RelativeSizeAxes = Axes.X,
Text = "Toggle chat",
Action = () => { State.Value = State.Value == TourneyState.Idle ? TourneyState.Playing : TourneyState.Idle; }
},
new SettingsSlider<int>
{
LabelText = "Chroma width",
Current = LadderInfo.ChromaKeyWidth,
KeyboardStep = 1,
},
new SettingsSlider<int>
{
LabelText = "Players per team",
Current = LadderInfo.PlayersPerTeam,
KeyboardStep = 1,
}
}
}
});
ladder.ChromaKeyWidth.BindValueChanged(width => chroma.Width = width.NewValue, true);
warmup.BindValueChanged(w =>
{
warmupButton.Alpha = !w.NewValue ? 0.5f : 1;
header.ShowScores = !w.NewValue;
}, true);
}
protected override void LoadComplete()
{
base.LoadComplete();
State.BindTo(ipc.State);
State.BindValueChanged(stateChanged, true);
}
protected override void CurrentMatchChanged(ValueChangedEvent<TournamentMatch> match)
{
base.CurrentMatchChanged(match);
if (match.NewValue == null)
return;
warmup.Value = match.NewValue.Team1Score.Value + match.NewValue.Team2Score.Value == 0;
scheduledOperation?.Cancel();
}
private ScheduledDelegate scheduledOperation;
private TournamentMatchScoreDisplay scoreDisplay;
private TourneyState lastState;
private MatchHeader header;
private void stateChanged(ValueChangedEvent<TourneyState> state)
{
try
{
if (state.NewValue == TourneyState.Ranking)
{
if (warmup.Value || CurrentMatch.Value == null) return;
if (ipc.Score1.Value > ipc.Score2.Value)
CurrentMatch.Value.Team1Score.Value++;
else
CurrentMatch.Value.Team2Score.Value++;
}
scheduledOperation?.Cancel();
void expand()
{
chat?.Contract();
using (BeginDelayedSequence(300))
{
scoreDisplay.FadeIn(100);
SongBar.Expanded = true;
}
}
void contract()
{
SongBar.Expanded = false;
scoreDisplay.FadeOut(100);
using (chat?.BeginDelayedSequence(500))
chat?.Expand();
}
switch (state.NewValue)
{
case TourneyState.Idle:
contract();
const float delay_before_progression = 4000;
// if we've returned to idle and the last screen was ranking
// we should automatically proceed after a short delay
if (lastState == TourneyState.Ranking && !warmup.Value)
{
if (CurrentMatch.Value?.Completed.Value == true)
scheduledOperation = Scheduler.AddDelayed(() => { sceneManager?.SetScreen(typeof(TeamWinScreen)); }, delay_before_progression);
else if (CurrentMatch.Value?.Completed.Value == false)
scheduledOperation = Scheduler.AddDelayed(() => { sceneManager?.SetScreen(typeof(MapPoolScreen)); }, delay_before_progression);
}
break;
case TourneyState.Ranking:
scheduledOperation = Scheduler.AddDelayed(contract, 10000);
break;
default:
chat.Contract();
expand();
break;
}
}
finally
{
lastState = state.NewValue;
}
}
private class ChromaArea : CompositeDrawable
{
[Resolved]
private LadderInfo ladder { get; set; }
[BackgroundDependencyLoader]
private void load()
{
// chroma key area for stable gameplay
Colour = new Color4(0, 255, 0, 255);
ladder.PlayersPerTeam.BindValueChanged(performLayout, true);
}
private void performLayout(ValueChangedEvent<int> playerCount)
{
switch (playerCount.NewValue)
{
case 3:
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Width = 0.5f,
Height = 0.5f,
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
},
new Box
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Height = 0.5f,
},
};
break;
default:
InternalChild = new Box
{
RelativeSizeAxes = Axes.Both,
};
break;
}
}
}
}
}
| |
/*
* Created by Alessandro Binhara
* User: Administrator
* Date: 29/4/2005
* Time: 18:13
*
* Description: An SQL Builder, Object Interface to Database Tables
* Its based on DataObjects from php PEAR
* 1. Builds SQL statements based on the objects vars and the builder methods.
* 2. acts as a datastore for a table row.
* The core class is designed to be extended for each of your tables so that you put the
* data logic inside the data classes.
* included is a Generator to make your configuration files and your base classes.
*
* CSharp DataObject
* Copyright (c) 2005, Alessandro de Oliveira Binhara
* 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 <ORGANIZATION> nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace CsDO.Lib
{
#region Delegates
public delegate int AutoIncrement(DataObject table);
public delegate void OnBeforeManipulation(DataObject sender);
public delegate void OnAfterManipulation(DataObject sender, bool success);
//public delegate int Identity(DataObject table);
#endregion
/// <summary>
/// Represents current state of disposable object.
/// </summary>
public enum DisposableState
{
/// <summary>
/// Disposable object is not disposed.
/// </summary>
Alive = 0,
/// <summary>
/// Disposing aquired and is in progress.
/// </summary>
Disposing,
/// <summary>
/// Disposable object is disposed.
/// </summary>
Disposed,
}
[Serializable()]
public class DataObject: IDisposable, ICloneable
{
#region Properties
private bool debug = false;
[NonSerialized()]
private ObjectDataTable dt = null;
private bool _persisted = false;
private string _table = null;
private string _fields = null;
private string _where = null;
private string _limit = null;
private string _orderBy = null;
private string _groupBy = null;
private IList _primaryKeys = null;
private IList _foreignKeys = null;
private int depth = 3;
[Column(false)]
public int Depth
{
get { return depth; }
set { depth = value; }
}
[Column(false)]
protected string Table
{
get
{
if (_table == null) {
_table = getTableProperties();
if (_table == null) {
string[] fullName = GetType().FullName.Split('.');
return fullName[fullName.Length-1].ToString();
}
}
return _table;
}
}
protected string Fields {
get {
if (_fields == null) {
StringBuilder fields = new StringBuilder();
PropertyInfo [] props = GetType().GetProperties();
foreach (PropertyInfo propriedade in props)
{
string name = null;
bool persist = true;
getColumnProperties(propriedade, ref name, ref persist);
if (!persist)
continue;
if (name == null)
name = propriedade.Name;
fields.Append(name);
fields.Append(",");
}
fields.Remove(fields.Length -1, 1);
_fields = fields.ToString();
}
return _fields;
}
}
protected string ActiveFields {
get
{
StringBuilder _active_fields = new StringBuilder();
PropertyInfo [] props = GetType().GetProperties();
foreach (PropertyInfo propriedade in props)
{
string name = null;
bool persist = true;
getColumnProperties(propriedade, ref name, ref persist);
if (!persist)
continue;
if (!propriedade.PropertyType.IsSubclassOf(typeof(DataObject)))
{
string temp = (propriedade.GetValue(this, null) != null) ?
propriedade.GetValue(this, null).ToString() : null;
if (temp == null)
continue;
if (temp.Equals("0"))
continue;
if (propriedade.GetValue(this, null).GetType() == typeof(System.DateTime))
temp = ((DateTime)propriedade.GetValue(this, null)).ToString("yyyyMMdd HH:mm:ss");
if (temp.Equals("00010101 00:00:00"))
continue;
if (temp.Equals("NULL"))
continue;
}
else
{
DataObject temp = (propriedade.GetValue(this, null) != null) ?
(DataObject) propriedade.GetValue(this, null) : null;
if (temp == null)
continue;
if ((int)temp.getPrimaryKey() == 0)
continue;
}
if (name == null)
name = propriedade.Name;
_active_fields.Append(name);
_active_fields.Append(",");
}
if (_active_fields.Length > 0)
_active_fields.Remove(_active_fields.Length - 1, 1);
return _active_fields.ToString();
}
}
[Column(false)]
protected IList PrimaryKeys {
get {
if (_primaryKeys == null) {
PropertyInfo [] props = GetType().GetProperties();
_primaryKeys = new ArrayList();
foreach (PropertyInfo propriedade in props)
{
object[] attributes = propriedade.GetCustomAttributes(typeof(PrimaryKey), true);
if (attributes.Length > 0)
_primaryKeys.Add(propriedade);
}
}
return _primaryKeys;
}
}
[Column(false)]
protected IList ForeignKeys {
get {
if (_foreignKeys == null) {
PropertyInfo [] props = GetType().GetProperties();
_foreignKeys = new ArrayList();
foreach (PropertyInfo propriedade in props)
{
if (propriedade.PropertyType.IsSubclassOf(typeof(DataObject)))
_foreignKeys.Add(propriedade);
}
}
return _foreignKeys;
}
}
[Column(false)]
protected bool Debug
{
get { return debug; }
set { debug = value; }
}
[Column(false)]
protected string Where
{
get { return _where; }
set { _where = value; }
}
[Column(false)]
protected string Limit
{
get { return _limit; }
set { _limit = value; }
}
[Column(false)]
protected string OrderBy
{
get { return _orderBy; }
set { _orderBy = value; }
}
[Column(false)]
protected string GroupBy
{
get { return _groupBy; }
set { _groupBy = value; }
}
[Column(false)]
protected bool Persisted
{
get { return _persisted; }
set { _persisted = value; }
}
#endregion
#region Constructors
public DataObject() {}
public DataObject(string column, object whereValue)
{
//TODO: Identificar o que foi alterado
//setField(column, whereValue);
//find();
//fetch();
}
#endregion
#region Finders
public bool retrieve(string column, object whereValue)
{
bool result = false;
StringBuilder sb = new StringBuilder("SELECT ");
if (Limit != null && !Limit.Trim().Equals(""))
{
sb.Append("TOP ");
sb.Append(Limit);
sb.Append(" ");
}
sb.Append(Fields);
sb.Append(" FROM ");
sb.Append(Table);
bool found = false;
PropertyInfo propriedade = findColumn(column);
if (propriedade != null)
{
string name = null;
getColumnProperties(propriedade, ref name);
sb.Append(" WHERE ");
sb.Append(name);
if (propriedade.PropertyType == typeof(System.String))
sb.Append(" LIKE ");
else
sb.Append(" = ");
sb.Append(formatObject(whereValue));
found = true;
}
if (!found)
{
throw new CsDOException("Field '" + column + "' not found!");
}
AddModifiers(sb);
try
{
if (debug)
Console.WriteLine("Query: \"" + sb + "\"");
dt = DataBase.New().QueryDT(sb.ToString());
}
catch (Exception e)
{
if (debug)
Console.WriteLine("Exception: \"" + e.Message + "\"");
throw (e);
}
result = true;
return result;
}
protected bool find(object keyValue)
{
string name = getPrimaryKeyName();
setField(name, keyValue);
return find();
}
public bool Get(object keyValue)
{
find(keyValue);
return fetch();
}
#endregion
#region Util methods
private string getPrimaryKeyName()
{
string name = null;
if (PrimaryKeys.Count > 0)
getColumnProperties((PropertyInfo)PrimaryKeys[0], ref name);
else
getColumnProperties((PropertyInfo)GetType().GetProperties()[0], ref name);
return name;
}
public object getPrimaryKey()
{
object result = null;
if (PrimaryKeys.Count > 0)
result = ((PropertyInfo)PrimaryKeys[0]).GetValue(this, null);
else
result = ((PropertyInfo)GetType().GetProperties()[0]).GetValue(this, null);
return result;
}
public void setPrimaryKey (object key)
{
//TODO: Membership provider implementation
}
public string GetTable() {
return Table;
}
public void SetDebug(bool value) {
debug = value;
}
public bool GetDebug() {
return debug;
}
protected bool loadFields(DataRow dr, DataObject obj) {
if (dr != null && obj != null) {
if (Conf.DataPooling)
{
StringBuilder sb = new StringBuilder();
sb.Append(obj.GetType().ToString());
sb.Append("!");
sb.Append(dr[getPrimaryKeyName()]);
DataObject result = Conf.DataPool[sb.ToString()];
if (result != null)
result.Copy(obj);
else
{
obj.setField(dr);
Persisted = true;
if (Conf.DataPooling)
Conf.DataPool.add(obj);
}
if (debug)
Console.WriteLine("Loading from " + GetType() + " Cache");
Persisted = true;
return true;
}
else
{
obj.setField(dr);
Persisted = true;
if (Conf.DataPooling)
Conf.DataPool.add(obj);
return true;
}
} else
{
if (debug && dr == null)
Console.WriteLine("Loading field error: DataReader is NULL in " + GetType());
if (debug && obj == null)
Console.WriteLine("Loading field error: obj is NULL in " + GetType());
return false;
}
}
protected void AddModifiers(StringBuilder sb)
{
string sql = sb.ToString();
if (Where != null && !Where.Trim().Equals(""))
{
if (sql.ToUpper().IndexOf("WHERE") > -1)
{
sb.Append(" AND ");
sb.Append(Where);
}
else
{
sb.Append(" WHERE ");
sb.Append(Where);
}
}
if (GroupBy != null && !GroupBy.Trim().Equals(""))
{
sb.Append(" GROUP BY ");
sb.Append(GroupBy);
}
if (OrderBy != null && !OrderBy.Trim().Equals(""))
{
sb.Append(" ORDER BY ");
sb.Append(OrderBy);
}
}
public IList ToArray()
{
ArrayList result = new ArrayList();
if (dt != null && !dt.IsEmpty)
{
while(dt.Read()) {
DataObject obj = (DataObject) Activator.CreateInstance(GetType());
loadFields(dt[dt.Cursor], obj);
result.Add(obj);
}
}
return result;
}
public IList ToArray(bool listAll)
{
if (dt == null && listAll)
{
find();
}
return ToArray();
}
public override string ToString()
{
StringBuilder result = new StringBuilder();
result.Append(this.GetType().ToString());
result.Append("!");
if (PrimaryKeys.Count > 0) {
result.Append(formatValue((PropertyInfo) PrimaryKeys[0]));
} else {
result.Append(formatValue((PropertyInfo) GetType().GetProperties()[0]));
}
return result.ToString();
}
protected PropertyInfo findColumn(string column) {
PropertyInfo [] props = GetType().GetProperties();
bool persist = false;
foreach (PropertyInfo property in props)
{
string name = null;
getColumnProperties(property, ref name, ref persist);
if (!persist)
continue;
if ((name != null && column.ToLower().Equals(name.ToLower())) ||
(column.ToLower().Equals(property.Name.ToLower())))
{
return property;
}
}
return null;
}
protected string formatValue(PropertyInfo property) {
string result = "";
if (property.PropertyType.IsSubclassOf(typeof(DataObject)))
{
result = (property.GetValue(this, null) != null) ? formatObject(((DataObject)property.GetValue(this, null)).getPrimaryKey()) : "NULL";
} else
result = (property.GetValue(this, null) != null) ? formatObject(property.GetValue(this, null)) : "NULL";
return result;
}
protected string formatObject(object valueObj)
{
if (valueObj != null)
{
CultureInfo culture = new CultureInfo("en-US");
IFormatProvider formatNumber = culture.NumberFormat;
StringBuilder sb;
switch (valueObj.GetType().ToString())
{
case "System.Boolean":
case "System.Nullable`1[System.Boolean]":
return ((Boolean)valueObj ? "'T'" : "'F'");
case "System.Char":
case "System.Nullable`1[System.Char]":
sb = new StringBuilder("'");
sb.Append(((Char)valueObj).ToString());
sb.Append("'");
return sb.ToString();
case "System.DateTime":
case "System.Nullable`1[System.DateTime]":
sb = new StringBuilder("'");
sb.Append(((DateTime)valueObj).ToString("yyyyMMdd HH:mm:ss"));
sb.Append("'");
return sb.ToString();
case "System.Decimal":
case "System.Nullable`1[System.Decimal]":
return ((Decimal)valueObj).ToString(formatNumber);
case "System.Double":
case "System.Nullable`1[System.Double]" :
return ((Double)valueObj).ToString(formatNumber);
case "System.Single":
case "System.Nullable`1[System.Single]":
return ((Single)valueObj).ToString(formatNumber);
case "System.String":
sb = new StringBuilder("'");
sb.Append(valueObj.ToString());
sb.Append("'");
return sb.ToString();
default:
if (valueObj.GetType().IsSubclassOf(typeof(DataObject)))
return formatObject(((DataObject)valueObj).getPrimaryKey());
else //Tipos inteiros
return valueObj.ToString();
}
}
return "NULL";
}
protected string getTableProperties() {
object[] attributes = GetType().GetCustomAttributes(typeof(Table), true);
if (attributes.Length > 0) {
Table table = (Table) attributes[0];
if (table.Name != null)
return table.Name;
}
return null;
}
protected void getColumnProperties(PropertyInfo property, ref string name, ref bool persist) {
object[] attributes = property.GetCustomAttributes(typeof(Column), true);
if (attributes.Length > 0) {
Column column = (Column) attributes[0];
persist = column.Persist;
if (column.Name != null)
name = column.Name;
}
}
protected void getColumnProperties(PropertyInfo property, ref string name, ref bool persist, ref bool primaryKey) {
object[] attributes = property.GetCustomAttributes(typeof(Column), true);
if (attributes.Length > 0) {
Column column = (Column) attributes[0];
persist = column.Persist;
if (column.Name != null)
name = column.Name;
}
attributes = property.GetCustomAttributes(typeof(PrimaryKey), true);
if (attributes.Length > 0)
primaryKey = true;
}
protected void getColumnProperties(PropertyInfo property, ref string name) {
object[] attributes = property.GetCustomAttributes(typeof(Column), true);
if (attributes.Length > 0) {
Column column = (Column) attributes[0];
if (column.Name != null)
name = column.Name;
}
if (name == null)
name = property.Name;
}
protected bool isPrimaryKey(PropertyInfo property) {
object[] attributes = property.GetCustomAttributes(typeof(PrimaryKey), true);
return (attributes.Length > 0);
}
protected bool isIdentity(PropertyInfo property)
{
object[] attributes = property.GetCustomAttributes(typeof(Identity), true);
return (attributes.Length > 0);
}
protected void getColumnProperties(PropertyInfo property, ref bool persist) {
object[] attributes = property.GetCustomAttributes(typeof(Column), true);
if (attributes.Length > 0) {
Column column = (Column) attributes[0];
persist = column.Persist;
}
}
protected void setField(DataRow dr)
{
PropertyInfo [] props = GetType().GetProperties();
bool persist = false;
foreach (PropertyInfo propriedade in props)
{
string name = null;
getColumnProperties(propriedade, ref name, ref persist);
if (!persist)
continue;
if (String.IsNullOrEmpty(name))
name = propriedade.Name;
object val = dr[name];
if (propriedade != null)
{
#region Property holds a Foreign Key
if (propriedade.PropertyType.IsSubclassOf(typeof(DataObject)) &&
!val.GetType().IsSubclassOf(typeof(DataObject)))
{
if (val == null || val.ToString().Equals("0") || val.GetType() == typeof(DBNull))
{
if (debug)
Console.WriteLine("Set " + GetType() + "[" + this + "]." + propriedade.Name + "=null(" + val.GetType() + ")");
propriedade.SetValue(this, null, null);
continue;
}
DataObject obj = (DataObject)propriedade.GetValue(this, null);
if (obj == null)
{
if (debug)
Console.WriteLine("Activating: " + propriedade.PropertyType);
if (depth > 0)
{
obj = (DataObject)Activator.CreateInstance(propriedade.PropertyType);
obj.depth = this.depth - 1;
}
else
{
val = assertField(null, propriedade);
if (debug)
Console.WriteLine("Set " + GetType() + "[" + this + "]." + propriedade.Name + "=" + val + "(" + val.GetType() + ")");
propriedade.SetValue(this, val, null);
continue;
}
}
if (obj.PrimaryKeys.Count > 0)
{
if (debug)
Console.WriteLine("Set " + obj.GetType() + "[" + obj + "]." + ((PropertyInfo)obj.PrimaryKeys[0]).Name + "=" + val + "(" + val.GetType() + ")");
((PropertyInfo)obj.PrimaryKeys[0]).SetValue(obj, val, null);
obj.find();
obj.fetch();
if (!obj.AssertField(((PropertyInfo)obj.PrimaryKeys[0]).Name, val))
{
if (debug)
Console.WriteLine("Set " + GetType() + "[" + this + "]." + propriedade.Name + "=null(" + val.GetType() + ")");
propriedade.SetValue(this, null, null);
}
else
{
if (debug)
Console.WriteLine("Set " + GetType() + "[" + this + "]." + propriedade.Name + "=" + obj + "(" + obj.GetType() + ")");
propriedade.SetValue(this, obj, null);
}
}
else
throw new CsDOException("Class '" + propriedade.PropertyType + "' has no Primary Key!");
continue;
}
#endregion
else
#region Property holds data
{
val = assertField(val, propriedade);
if (debug)
if (val != null)
Console.WriteLine("Set " + GetType() + "[" + this + "]." + propriedade.Name + "=" + val + "(" + val.GetType() + ")");
else
Console.WriteLine("Set " + GetType() + "[" + this + "]." + propriedade.Name + "=" + val);
propriedade.SetValue(this, val, null);
continue;
}
#endregion
}
}
}
//TODO: Eliminar mais tarde
protected void setField(string col, object val)
{
PropertyInfo propriedade = findColumn(col);
if (propriedade != null)
{
if (propriedade.PropertyType.IsSubclassOf(typeof(DataObject)) &&
!val.GetType().IsSubclassOf(typeof(DataObject))) {
if (val == null || val.ToString().Equals("0") || val.GetType() == typeof(DBNull)) {
if (debug)
Console.WriteLine("Set "+ GetType() +"[" + this + "]." + propriedade.Name+"=null(" +val.GetType()+ ")");
propriedade.SetValue(this, null, null);
return;
}
DataObject obj = (DataObject) propriedade.GetValue(this, null);
if (obj == null) {
if (debug)
Console.WriteLine("Activating: "+ propriedade.PropertyType);
if (depth > 0)
{
obj = (DataObject)Activator.CreateInstance(propriedade.PropertyType);
obj.depth = this.depth - 1;
}
else
{
val = assertField(null, propriedade);
if (debug)
Console.WriteLine("Set " + GetType() + "[" + this + "]." + propriedade.Name + "=" + val + "(" + val.GetType() + ")");
propriedade.SetValue(this, val, null);
return;
}
}
if (obj.PrimaryKeys.Count > 0) {
if (debug)
Console.WriteLine("Set "+ obj.GetType() +"[" + obj + "]." + ((PropertyInfo) obj.PrimaryKeys[0]).Name+"=" + val + "(" + val.GetType() + ")");
((PropertyInfo)obj.PrimaryKeys[0]).SetValue(obj, val, null);
obj.find();
obj.fetch();
if (!obj.AssertField(((PropertyInfo) obj.PrimaryKeys[0]).Name, val)) {
if (debug)
Console.WriteLine("Set "+ GetType() +"[" + this + "]." + propriedade.Name + "=null(" +val.GetType() + ")");
propriedade.SetValue(this, null, null);
} else {
if (debug)
Console.WriteLine("Set "+ GetType() +"[" + this + "]." + propriedade.Name + "="+obj+"(" +obj.GetType() + ")");
propriedade.SetValue(this, obj, null);
}
} else
throw new CsDOException("Class '" + propriedade.PropertyType + "' has no Primary Key!");
return;
} else {
val = assertField(val, propriedade);
if (debug)
if (val != null)
Console.WriteLine("Set "+ GetType() +"[" + this + "]." + propriedade.Name+"="+val+"(" +val.GetType()+ ")");
else
Console.WriteLine("Set " + GetType() + "[" + this + "]." + propriedade.Name + "=" + val);
propriedade.SetValue(this, val, null);
return;
}
}
throw new CsDOException("Field '" + col + "' not found!");
}
private static object assertField(object val, PropertyInfo propriedade)
{
Type nullableType = null;
if (propriedade.PropertyType.Name == "Nullable`1")
nullableType = propriedade.PropertyType.GetGenericArguments()[0];
else
nullableType = propriedade.PropertyType;
if (val != null && (val.GetType().IsSubclassOf(typeof(DBNull))
|| val.GetType() == typeof(DBNull)))
{
val = null;
}
else if (nullableType == typeof(bool))
{
if (val.ToString().ToUpper().Equals("T") || val.ToString().ToUpper().Equals("TRUE"))
val = (Boolean)true;
else
val = (Boolean)false;
}
else if (nullableType == typeof(float) &&
val.GetType() == typeof(double))
{
val = float.Parse(((double)val).ToString());
}
return val;
}
protected bool AssertField(string col, object val)
{
PropertyInfo propriedade = findColumn(col);
if (propriedade != null)
{
object obj = propriedade.GetValue(this, null);
if (obj != null)
return obj.ToString().Equals(val.ToString());
else
return obj == val;
}
throw new CsDOException("Field '" + col + "' not found!");
}
public object Clone()
{
return this.MemberwiseClone();
}
public void Copy(DataObject obj)
{
if (obj.GetType().IsSubclassOf(this.GetType()) ||
obj.GetType() == this.GetType())
{
foreach (FieldInfo source in this.GetType().GetFields())
{
BindingFlags flags = 0 ;
flags |= source.IsPublic ? BindingFlags.Public : BindingFlags.NonPublic;
flags |= source.IsStatic ? BindingFlags.Static : BindingFlags.Instance;
FieldInfo destination = obj.GetType().GetField(source.Name, flags |
BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase);
if (!source.IsInitOnly && !source.IsStatic)
destination.SetValue(obj, source.GetValue(this));
}
foreach (PropertyInfo source in this.GetType().GetProperties())
{
BindingFlags flags = 0;
flags |= BindingFlags.Public;
flags |= BindingFlags.Instance;
PropertyInfo destination = obj.GetType().GetProperty(source.Name, flags |
BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase);
if (source.CanWrite)
destination.SetValue(obj, source.GetValue(this, null), null);
}
}
}
#endregion
#region Data manipulation
public bool insert(DataObject obj)
{
if (obj != null && (this.GetType() == obj.GetType()))
return obj.insert();
else
return false;
}
public bool update(DataObject obj)
{
if (obj != null && (this.GetType() == obj.GetType()))
return obj.update();
else
return false;
}
public bool delete(DataObject obj)
{
if (obj != null && (this.GetType() == obj.GetType()))
return obj.delete();
else
return false;
}
public bool insert()
{
if (BeforeInsert != null)
BeforeInsert(this);
PropertyInfo propriedadeIdentity = null;
string ident = null;
StringBuilder sql = new StringBuilder("INSERT INTO ");
sql.Append(Table);
StringBuilder values = new StringBuilder(" Values (");
PropertyInfo [] props = GetType().GetProperties();
foreach (PropertyInfo propriedade in props)
{
bool persist = true;
string data = null;
getColumnProperties(propriedade, ref persist);
if (!persist)
continue;
if (autoIncrement != null && isPrimaryKey(propriedade))
{
if (propriedade.PropertyType == typeof(int))
propriedade.SetValue(this, autoIncrement(this), null);
if (debug)
Console.WriteLine("PrimaryKEY = " + ident);
}
if (isIdentity(propriedade))
{
getColumnProperties(propriedade, ref ident);
propriedadeIdentity = propriedade;
if (debug)
Console.WriteLine("PrimaryKEY" + ident);
}
data = formatValue(propriedade);
if ((data != null) && !data.Equals("0")
&& !data.Equals("'00010101 00:00:00'")
&& !data.Equals("NULL"))
{
values.Append(data);
values.Append(",");
}
}
values.Remove(values.Length -1, 1);
values.Append(")");
sql.Append(" (");
sql.Append(ActiveFields);
sql.Append(")");
sql.Append(values);
int i=0;
if (debug)
Console.WriteLine("Ident = "+ident);
if (ident != null)
{
sql.Append(" SELECT ");
sql.Append(ident);
sql.Append("=@@Identity FROM ");
sql.Append(Table);
if (debug)
Console.WriteLine("Exec: \"" + sql + "\"");
//int cod = DataBase.New().Exec(sql);
int result = 0;
IDataReader dr1 = DataBase.New().Query(sql.ToString());
if (dr1.Read())
{
if (debug)
Console.WriteLine("Vou pegar os dados da consulta");
result = Convert.ToInt32(dr1[ident]);
if (debug)
Console.WriteLine("Codigo = " + result);
}
//i = result;
if (propriedadeIdentity.PropertyType == typeof(int))
propriedadeIdentity.SetValue(this, result, null);
// propriedadeIdentity.SetValue(this, identity(this), null);
}
else
{
if (debug)
Console.WriteLine("Exec: \"" + sql.ToString() + "\"");
i = DataBase.New().Exec(sql.ToString());
if (Conf.DataPooling)
Conf.DataPool.add(this);
}
if (debug)
Console.WriteLine("Affected " + i +" rows");
Persisted = (i == 1);
if (AfterInsert != null)
AfterInsert(this, Persisted);
return (Persisted);
}
public bool deleteCascade()
{
bool result = true;
if (Persisted)
result &= delete();
if (ForeignKeys.Count > 0)
foreach(PropertyInfo foreignKey in ForeignKeys) {
DataObject obj = (DataObject) foreignKey.GetValue(this, null);
if (obj != null && obj.Persisted) {
if (debug)
Console.WriteLine("**** Deleting " + foreignKey.Name + " ...");
result &= obj.deleteCascade();
obj = null;
foreignKey.SetValue(this, null, null);
}
else if (debug)
if (obj != null)
Console.WriteLine("**** Skipped " + foreignKey.Name + "[" + obj.ToString() + "] ...");
else
Console.WriteLine("**** Skipped " + foreignKey.Name + " ...");
}
return result;
}
public bool delete()
{
if (BeforeDelete != null)
BeforeDelete(this);
StringBuilder sql = new StringBuilder("DELETE ");
StringBuilder clausule = new StringBuilder();
string search = "";
string operador = "";
bool hasWhere = false;
PropertyInfo [] props = GetType().GetProperties();
foreach (PropertyInfo propriedade in props)
{
bool primaryKey = false;
bool persist = true;
string name = null;
getColumnProperties(propriedade, ref name, ref persist, ref primaryKey);
if (!persist)
continue;
if (name == null)
name = propriedade.Name;
operador = " = ";
if (propriedade.PropertyType == typeof(System.String))
{
operador = " LIKE ";
}
search = formatValue(propriedade);
//TODO: Identificar o que foi alterado
if ((search != null) && !search.Equals("0"))
{
StringBuilder item = new StringBuilder();
item.Append("(");
item.Append(name);
item.Append(operador);
item.Append(search);
item.Append(")");
hasWhere = true;
clausule.Append(item);
clausule.Append(" AND ");
}
if (primaryKey)
break;
}
if (hasWhere) {
clausule.Remove(clausule.Length - 4, 4);
sql.Append("FROM ");
sql.Append(Table);
sql.Append(" WHERE ");
sql.Append(clausule);
}
bool result = false;
if (hasWhere) {
try {
if (debug)
Console.WriteLine("Exec: \"" +sql +"\"");
int i = DataBase.New().Exec(sql.ToString());
if (debug)
Console.WriteLine("Affected " + i +" rows");
if (Conf.DataPooling)
Conf.DataPool.remove(this);
result = (i == 1);
} catch (Exception e) {
if (debug)
Console.WriteLine(e.Message + "\n" + e.StackTrace);
throw (e);
}
} else
result = false;
if (AfterDelete != null)
AfterDelete(this, result);
return result;
}
public bool update()
{
if (BeforeUpdate != null)
BeforeUpdate(this);
StringBuilder sql = new StringBuilder("UPDATE ");
StringBuilder clausule = new StringBuilder();
string search = "";
string operador = "";
StringBuilder values = new StringBuilder();
bool hasWhere = false;
PropertyInfo [] props = GetType().GetProperties();
foreach (PropertyInfo propriedade in props)
{
bool primaryKey = false;
bool persist = true;
string name = null;
getColumnProperties(propriedade, ref name, ref persist, ref primaryKey);
if (!persist)
continue;
if (name == null)
name = propriedade.Name;
operador = " = ";
if (propriedade.PropertyType == typeof(System.String))
{
operador = " LIKE ";
}
search = formatValue(propriedade);
//TODO: Identificar o que foi alterado
if (primaryKey && (search != null) && !search.Equals("0")
&& !search.Equals("'00010101 00:00:00'")
&& !search.Equals("NULL"))
{
StringBuilder item = new StringBuilder();
item.Append("(");
item.Append(name);
item.Append(operador);
item.Append(search);
item.Append(")");
hasWhere = true;
clausule.Append(item);
clausule.Append(" AND ");
}
else if(propriedade.PropertyType.Name == "Nullable`1")
{
values.Append(name);
values.Append("=");
values.Append(search);
values.Append(",");
}
else if ((search != null)
&& !search.Equals("0")
&& !search.Equals("'00010101 00:00:00'")
&& !search.Equals("NULL"))
{
values.Append(name);
values.Append("=");
values.Append(search);
values.Append(",");
}
}
if (!values.ToString().Equals(""))
values.Remove(values.Length - 1, 1);
if (hasWhere) {
clausule.Remove(clausule.Length - 4, 4);
sql.Append(Table);
sql.Append(" SET ");
sql.Append(values);
sql.Append(" WHERE ");
sql.Append(clausule);
}
bool result = false;
if (hasWhere) {
if (debug)
Console.WriteLine("Exec: \"" +sql +"\"");
int i = DataBase.New().Exec(sql.ToString());
if (debug)
Console.WriteLine("Affected " +i +" rows");
if (Conf.DataPooling)
{
Conf.DataPool.remove(this);
Conf.DataPool.add(this);
}
Persisted = (i >= 1);
result = (i >= 1);
} else
result = false;
if (AfterUpdate != null)
AfterUpdate(this, result);
return result;
}
#endregion
#region Query
public IList select(object keyValue)
{
if (keyValue != null)
{
find(keyValue);
}
else
{
find();
}
return ToArray();
}
public bool find()
{
StringBuilder sb = new StringBuilder("SELECT ");
StringBuilder clausule = new StringBuilder();
if (Limit != null && !Limit.Trim().Equals(""))
{
sb.Append("TOP ");
sb.Append(Limit);
sb.Append(" ");
}
string search = "";
string operador = "";
bool hasWhere = false;
PropertyInfo [] props = GetType().GetProperties();
foreach (PropertyInfo propriedade in props)
{
bool primaryKey = false;
bool persist = true;
string name = null;
getColumnProperties(propriedade, ref name, ref persist, ref primaryKey);
if (!persist)
continue;
if (name == null)
name = propriedade.Name;
if (propriedade.PropertyType == typeof(bool) ||
propriedade.PropertyType == typeof(System.Boolean))
continue;
operador = " = ";
if (propriedade.PropertyType == typeof(System.String))
{
operador = " LIKE ";
}
search = formatValue(propriedade);
//TODO: Identificar o que foi alterado
if (search != null && !search.Equals("0")
&& !search.Equals("'00010101 00:00:00'")
&& !search.Equals("NULL"))
{
StringBuilder item = new StringBuilder();
item.Append("(");
item.Append(name);
item.Append(operador);
item.Append(search);
item.Append(")");
hasWhere = true;
clausule.Append(item);
clausule.Append(" AND ");
}
if (primaryKey && (search != null) && !search.Equals("0")
&& !search.Equals("00010101 00:00:00"))
break;
}
if (hasWhere)
{
clausule.Remove(clausule.Length - 4, 4);
sb.Append(Fields);
sb.Append(" FROM ");
sb.Append(Table);
sb.Append(" WHERE ");
sb.Append(clausule);
}
else
{
sb.Append(Fields);
sb.Append(" FROM ");
sb.Append(Table);
}
AddModifiers(sb);
try
{
if (debug)
Console.WriteLine("Query: \"" +sb +"\"");
dt = DataBase.New().QueryDT(sb.ToString());
} catch(Exception e) {
if (debug)
Console.WriteLine("Exception: \"" + e.Message +"\"");
throw (e);
}
return true;
}
///<summary>Repassa dos dados da consulta para o objeto</summary>
public bool fetch()
{
if ((dt != null) && !dt.IsEmpty) {
bool result = dt.Read();
if (debug)
{
if (result)
Console.WriteLine("*** Reading DataReader and loading fields ...");
else
Console.WriteLine("*** Closing DataReader ...");
}
if (result)
{
if (BeforeFetch != null)
BeforeFetch(this);
result = loadFields(dt[dt.Cursor], this);
if (AfterFetch != null)
AfterFetch(this, result);
}
return result;
}
if (debug) {
if (dt == null)
Console.WriteLine("*** DataReader is NULL !!!");
if (dt.IsEmpty)
Console.WriteLine("*** DataReader is EMPTY !!!");
}
return false;
}
#endregion
#region Operators
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
public static bool operator ==(DataObject o1, DataObject o2)
{
if ((Object)o1 == null)
return (Object)o2 == null;
else
{
if ((Object)o2 == null)
return false;
if (o1.GetType().IsInstanceOfType(o2.GetType()))
return false;
else
return o1.Equals(o2);
}
}
public static bool operator !=(DataObject o1, DataObject o2)
{
return !(o1 == o2);
}
public override bool Equals(Object obj)
{
if (obj == null)
return false;
else
{
if (Object.ReferenceEquals(this, obj))
return true;
DataObject dataObject = obj as DataObject;
if ((Object)dataObject == null)
return false;
else
return (this.GetHashCode() == dataObject.GetHashCode());
}
}
#endregion
#region IDisposable implementation
private DisposableState state = DisposableState.Alive;
private void InternalDispose(bool disposing)
{
state = DisposableState.Disposing;
Dispose(disposing);
state = DisposableState.Disposed;
}
public void Dispose()
{
if (state == DisposableState.Alive)
{
InternalDispose(true);
GC.SuppressFinalize(this);
}
}
protected void Dispose(bool disposing)
{
if (_foreignKeys != null)
foreach (PropertyInfo foreign in _foreignKeys)
{
if (foreign.PropertyType.IsSubclassOf(typeof(DataObject)))
((DataObject)foreign.GetValue(this, new object[] {})).Dispose();
}
}
~DataObject()
{
InternalDispose(false);
}
/// <summary>
/// Gets is object in disposing process now.
/// </summary>
[Column(false)]
protected bool Disposing
{
get { return state == DisposableState.Disposing; }
}
/// <summary>
/// Gets is object disposed and in nonoperational state.
/// </summary>
[Column(false)]
protected bool Disposed
{
get { return state == DisposableState.Disposed; }
}
/// <summary>
/// Gets disposable object state.
/// </summary>
[Column(false)]
protected DisposableState State
{
get
{
return state;
}
}
public DisposableState getState()
{
return State;
}
#endregion
#region Events
// protected event Identity identity = null; //for SQL SERVER
protected event AutoIncrement autoIncrement = null;
public event OnAfterManipulation AfterDelete = null;
public event OnBeforeManipulation BeforeDelete = null;
public event OnAfterManipulation AfterInsert = null;
public event OnBeforeManipulation BeforeInsert = null;
public event OnAfterManipulation AfterUpdate = null;
public event OnBeforeManipulation BeforeUpdate = null;
public event OnAfterManipulation AfterFetch = null;
public event OnBeforeManipulation BeforeFetch= null;
#endregion
#region TODO
/*
//-- send a raw query
public bool query()
{
return true;
}
// Perform a select count() request
public bool count()
{
return true;
}
//-- Add selected columns
public bool selectAdd()
{
return true;
}
//-- Escape a string for use with Like queries
public bool escape()
{
return true;
}
// Automatic Table Linking and Joins
//-- Automatic Table Linking - ::getLink(), ::getLinks(), ::joinAdd(), ::selectAs()
// -- fetch and return a related object
//public object getLink()
{
object ob;
return ob;
}
//-- load related objects
public ArrayList getLinks()
{
ArrayList list = new ArrayList();
return list;
}
//-- Build the select component of a query (usually for joins)
public bool selectAs()
{
return true;
}
//-- add another dataobject to build a create join query
public bool joinAdd()
{
return true;
}
//-- Copy items from Array or Object (for form posting)
public bool setFrom()
{
return true;
}
//-- check object data, and call objects validation methods.
public bool validate()
{
return true;
}
*/
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.Odbc;
using ByteFX.Data.MySqlClient;
using ByteFX.Data;
using System.Collections;
using JCSLA;
using QED.DataValidation;
namespace QED.Business{
public enum SearchBy {
RollDate, ScheduledDate
}
public class Rollouts : BusinessCollectionBase {
#region Instance Data
#endregion
const string _table = "roll";
MySqlDBLayer _dbLayer;
#region Collection Members
public Rollout Add(Rollout obj) {
obj.BusinessCollection = this;
List.Add(obj); return obj;
}
public bool Contains(Rollout obj) {
foreach(Rollout child in List) {
if (obj.Equals(child)){
return true;
}
}
return false;
}
public Rollout this[int id] {
get{
return (Rollout) List[id];
}
}
public Rollout item(int id) {
foreach(Rollout obj in List) {
if (obj.Id == id)
return obj;
}
return null;
}
#endregion
#region DB Access and ctors
public object Conn {
get {
return Connections.Inst.item("QED_DB").MySqlConnection;
}
}
public Rollouts() {
}
public Rollouts(Client client, DateTime date, SearchBy searchBy) {
MySqlCommand cmd;
Rollout roll;
string dateField = (searchBy == SearchBy.RollDate) ? "rolledDate" : "scheduledDate";
date = date.Date; // Store date part, time part not needed.
using(MySqlConnection conn = (MySqlConnection)this.Conn){
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM " + _table + " WHERE clientId = @clientId AND " + dateField + " = @" + dateField;
cmd.Parameters.Add("@clientId", client.Id);
cmd.Parameters.Add("@" + dateField, date);
using(MySqlDataReader dr = cmd.ExecuteReader()){
if(!dr.HasRows && dateField == "scheduledDate"){
roll = new Rollout();
roll.Client = client;
roll.ScheduledDate = date;
roll.BusinessCollection = this;
List.Add(roll);
}else{
while (dr.Read()){
roll = new Rollout(dr);
roll.BusinessCollection = this;
List.Add(roll);
}
}
}
}
}
public void Update() {
foreach (Rollout obj in List) {
obj.Update();
}
}
public static Rollouts GetAllUnrolled(string ORDER_BY){
Rollouts rollouts = new Rollouts();
Rollout rollout;
using (MySqlConnection conn = Connections.Inst.item("QED_DB").MySqlConnection){
conn.Open();
using(MySqlCommand cmd = conn.CreateCommand()){
cmd.CommandText = "SELECT * FROM " + _table + " WHERE rolled = 0" + ((ORDER_BY.Trim().Length == 0) ? "" : " ORDER BY " + ORDER_BY);
using(MySqlDataReader dr = cmd.ExecuteReader()){
while(dr.Read()){
rollout = new Rollout(dr);
rollouts.Add(rollout);
}
}
}
}
return rollouts;
}
public static Rollouts Get(DateTime from, DateTime to, string orderBy){
Rollouts rollouts = new Rollouts();
Rollout rollout;
using (MySqlConnection conn = Connections.Inst.item("QED_DB").MySqlConnection){
conn.Open();
using(MySqlCommand cmd = conn.CreateCommand()){
cmd.CommandText = "SELECT * FROM " + _table + " WHERE scheduledDate BETWEEN @FROM AND @TO ORDER BY " + orderBy;
cmd.Parameters.Add("@FROM", from);
cmd.Parameters.Add("@TO", to);
using(MySqlDataReader dr = cmd.ExecuteReader()){
while(dr.Read()){
rollout = new Rollout(dr);
rollouts.Add(rollout);
}
}
}
}
return rollouts;
}
public static Rollouts Get(DateTime from, DateTime to, bool rolled, string orderBy){
Rollouts rollouts = new Rollouts();
Rollout rollout;
using (MySqlConnection conn = Connections.Inst.item("QED_DB").MySqlConnection){
conn.Open();
using(MySqlCommand cmd = conn.CreateCommand()){
cmd.CommandText = "SELECT * FROM " + _table + " WHERE scheduledDate BETWEEN @FROM AND @TO AND rolled = @ROLLED ORDER BY " + orderBy;
cmd.Parameters.Add("@FROM", from);
cmd.Parameters.Add("@TO", to);
cmd.Parameters.Add("@ROLLED", rolled);
using(MySqlDataReader dr = cmd.ExecuteReader()){
while(dr.Read()){
rollout = new Rollout(dr);
rollouts.Add(rollout);
}
}
}
}
return rollouts;
}
#endregion
#region Business Members
public Times GetTimes(string userEmail){
Times times = new Times();
foreach(Rollout roll in this){
foreach(Time time in roll.Times){
if (time.User == userEmail){
times.Add(time);
}
}
}
return times;
}
#endregion
#region System.Object overrides
public override string ToString(){
return this.ToString();
}
#endregion
}
public class Rollout : BusinessBase {
#region Instance Data
string _table = "roll";
int _clientId = -1;
DateTime _scheduledDate = DateTime.MinValue;
DateTime _rolledDate = DateTime.MinValue;
bool _rolled = false;
bool _rolledBack= false;
string _finalComments = "";
Defects _defects;
Messages _messages;
MySqlDBLayer _dbLayer;
int _id = -1;
Client _client;
BusinessCollectionBase _businessCollection;
string _rolledBy = "";
Times _times;
EffortRollouts _effortRollouts;
Efforts _cachedEfforts = null;
#endregion
#region DB Access / ctors
public override string Table {
get {
return _table;
}
}
public override object Conn {
get {
return Connections.Inst.item("QED_DB").MySqlConnection;
}
}
private void Setup() {
if (_dbLayer == null) {
_dbLayer = new MySqlDBLayer(this);
}
}
public override void SetId(int id) {
/* This function is public for technical reasons. It is intended to be used only by the db
* layer*/
_id = id;
}
public override BusinessCollectionBase BusinessCollection {
get{
return _businessCollection;
}
set {
_businessCollection = value;
}
}
public Rollout() {
Setup();
base.MarkNew();
}
public Rollout(int id) {
Setup();
this.Load(id);
}
public Rollout(MySqlDataReader dr) {
this.Load(dr);
}
public void Load(int id) {
SetId(id);
using(MySqlConnection conn = (MySqlConnection) this.Conn){
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + this.Table + " WHERE ID = @ID", conn);
cmd.Parameters.Add("@Id", this.Id);
using(MySqlDataReader dr = cmd.ExecuteReader()){
if (dr.HasRows) {
dr.Read();
this.Load(dr);
}else{
throw new Exception("Rollout " + id + " doesn't exist.");
}
}
}
}
public void Load(MySqlDataReader dr) {
Setup();
SetId(Convert.ToInt32(dr["Id"]));
this._clientId = Convert.ToInt32(dr["clientId"]);
this._finalComments= Convert.ToString(dr["finalComments"]);
this._rolledBack = Convert.ToBoolean(dr["rolledBack"]);
this._rolledDate= Convert.ToDateTime(dr["rolledDate"]);
this._scheduledDate = Convert.ToDateTime(dr["scheduledDate"]);
this._rolledBy = Convert.ToString(dr["rolledBy"]);
this.Rolled = Convert.ToBoolean(dr["rolled"]);
MarkOld();
}
public override void Update(){
_dbLayer.Update();
if (_effortRollouts != null)
_effortRollouts.Update();
}
public override Hashtable ParamHash {
get {
Hashtable paramHash = new Hashtable();
paramHash.Add("@ClientId", this._clientId);
paramHash.Add("@FinalComments", this.FinalComments);
paramHash.Add("@RolledBack", this.RolledBack);
paramHash.Add("@RolledDate", this.RolledDate);
paramHash.Add("@ScheduledDate", this.ScheduledDate);
paramHash.Add("@rolledBy", this.RolledBy);
paramHash.Add("@rolled", this.Rolled);
return paramHash;
}
}
#endregion
#region Business Properties
public override int Id{
get {
return _id;
}
}
public int ClientId{
get{
return _clientId;
}
set{
SetValue(ref _clientId, value);
}
}
public DateTime ScheduledDate{
get{
return _scheduledDate;
}
set{
SetValue(ref _scheduledDate, value);
}
}
public DateTime RolledDate{
get{
return _rolledDate;
}
set{
SetValue(ref _rolledDate, value);
}
}
public bool Rolled{
get{
return _rolled;
}
set{
SetValue(ref _rolled, value);
}
}
public bool RolledBack{
get{
return _rolledBack;
}
set{
SetValue(ref _rolledBack, value);
}
}
public string FinalComments{
get{
return _finalComments;
}
set{
SetValue(ref _finalComments, value);
}
}
public Messages Messages{
get {
if (_messages == null)
_messages = new Messages((BusinessBase)this);
return _messages;
}
}
public Defects Defects{
get {
if (_defects == null)
_defects = new Defects(this);
return _defects;
}
}
public Client Client{
get{
if (_client == null)
_client = new Client(_clientId);
return _client;
}
set{
_client = (Client)SetValue(value);
_clientId = _client.Id;
}
}
public EffortRollouts EffortRollouts{
get{
if (_effortRollouts == null)
_effortRollouts = new EffortRollouts(this);
return _effortRollouts;
}
}
public EffortRollout GetEffortRollout(Effort eff){
foreach (EffortRollout er in this.EffortRollouts){
if (er.Effort.Id == eff.Id){
return er;
}
}
return null;
}
public Efforts Efforts{
get{
return this.EffortRollouts.Efforts;
}
}
public Efforts GetCachedEfforts(bool reload){
if (reload || _cachedEfforts == null)
_cachedEfforts = this.Efforts;
return _cachedEfforts;
}
public Efforts RolledEfforts{
get{
Efforts effs = new Efforts();
foreach (EffortRollout effRoll in this.EffortRollouts){
if (effRoll.Rolled)
effs.Add(effRoll.Effort);
}
return effs;
}
}
public Efforts UnrolledEfforts{
get{
Efforts effs = new Efforts();
foreach (EffortRollout effRoll in this.EffortRollouts){
if (!effRoll.Rolled)
effs.Add(effRoll.Effort);
}
return effs;
}
}
public void AddUnrolled(Effort eff){
EffortRollout effRoll = new EffortRollout();
effRoll.Effort = eff;
_effortRollouts.Add(effRoll);
}
public void Delete(Effort eff){
EffortRollout effRoll = _effortRollouts.item(eff);
effRoll.Delete();
}
public void Roll(Effort eff){
_effortRollouts.item(eff).Rolled = true;
}
public void Unroll(Effort eff){
_effortRollouts.item(eff).Rolled = false;
}
public void ToggleRolledState(Effort eff){
EffortRollout effRoll =_effortRollouts.item(eff);
effRoll.Rolled = !effRoll.Rolled;
}
public string RolledBy{
get{
return _rolledBy;
}
set{
SetValue(ref _rolledBy, value);
}
}
public Times Times{
get{
_times = new Times(this);
return _times;
}
}
public Defects GetDefects(Effort eff){
Defects ret = new Defects();
ret.Parent = this;
foreach(Defect def in this.Defects){
if (def.Effort.Id == eff.Id){
ret.Add(def);
}
}
return ret;
}
#endregion
#region Validation Management
public override bool IsValid {
get {
return (this.BrokenRules.Count == 0);
}
}
public override BrokenRules BrokenRules {
get {
EmailValidator eValid = new EmailValidator();
BrokenRules br = new BrokenRules();
br.Assert("A rollout can't be rolled and rolledback at the same time", this.Rolled && this.RolledBack);
br.Assert("\"Rolled By\" is not a valid email address", this.RolledBy != "" && !eValid.Parse(this.RolledBy));
br.Add(this._effortRollouts);
return br;
}
}
#endregion
#region System.Object overrides
public override string ToString(){
return "Client:\"" + this.Client.Name + "\" Scheduled:" + this.ScheduledDate.ToShortDateString();
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Management.Automation.Internal;
using Microsoft.Win32;
namespace System.Management.Automation
{
/// <summary>
/// These are platform abstractions and platform specific implementations.
/// </summary>
public static class Platform
{
/// <summary>
/// True if the current platform is Linux.
/// </summary>
public static bool IsLinux
{
get
{
return OperatingSystem.IsLinux();
}
}
/// <summary>
/// True if the current platform is macOS.
/// </summary>
public static bool IsMacOS
{
get
{
return OperatingSystem.IsMacOS();
}
}
/// <summary>
/// True if the current platform is Windows.
/// </summary>
public static bool IsWindows
{
get
{
return OperatingSystem.IsWindows();
}
}
/// <summary>
/// True if PowerShell was built targeting .NET Core.
/// </summary>
public static bool IsCoreCLR
{
get
{
return true;
}
}
/// <summary>
/// True if the underlying system is NanoServer.
/// </summary>
public static bool IsNanoServer
{
get
{
#if UNIX
return false;
#else
if (_isNanoServer.HasValue) { return _isNanoServer.Value; }
_isNanoServer = false;
using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels"))
{
if (regKey != null)
{
object value = regKey.GetValue("NanoServer");
if (value != null && regKey.GetValueKind("NanoServer") == RegistryValueKind.DWord)
{
_isNanoServer = (int)value == 1;
}
}
}
return _isNanoServer.Value;
#endif
}
}
/// <summary>
/// True if the underlying system is IoT.
/// </summary>
public static bool IsIoT
{
get
{
#if UNIX
return false;
#else
if (_isIoT.HasValue) { return _isIoT.Value; }
_isIoT = false;
using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
{
if (regKey != null)
{
object value = regKey.GetValue("ProductName");
if (value != null && regKey.GetValueKind("ProductName") == RegistryValueKind.String)
{
_isIoT = string.Equals("IoTUAP", (string)value, StringComparison.OrdinalIgnoreCase);
}
}
}
return _isIoT.Value;
#endif
}
}
/// <summary>
/// True if underlying system is Windows Desktop.
/// </summary>
public static bool IsWindowsDesktop
{
get
{
#if UNIX
return false;
#else
if (_isWindowsDesktop.HasValue) { return _isWindowsDesktop.Value; }
_isWindowsDesktop = !IsNanoServer && !IsIoT;
return _isWindowsDesktop.Value;
#endif
}
}
/// <summary>
/// Gets a value indicating whether the underlying system supports single-threaded apartment.
/// </summary>
public static bool IsStaSupported
{
get
{
#if UNIX
return false;
#else
return _isStaSupported.Value;
#endif
}
}
#if UNIX
// Gets the location for cache and config folders.
internal static readonly string CacheDirectory = Platform.SelectProductNameForDirectory(Platform.XDG_Type.CACHE);
internal static readonly string ConfigDirectory = Platform.SelectProductNameForDirectory(Platform.XDG_Type.CONFIG);
#else
// Gets the location for cache and config folders.
internal static readonly string CacheDirectory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Microsoft\PowerShell";
internal static readonly string ConfigDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\PowerShell";
private static readonly Lazy<bool> _isStaSupported = new Lazy<bool>(() =>
{
// See objbase.h
const int COINIT_APARTMENTTHREADED = 0x2;
const int E_NOTIMPL = unchecked((int)0X80004001);
int result = Windows.NativeMethods.CoInitializeEx(IntPtr.Zero, COINIT_APARTMENTTHREADED);
// If 0 is returned the thread has been initialized for the first time
// as an STA and thus supported and needs to be uninitialized.
if (result > 0)
{
Windows.NativeMethods.CoUninitialize();
}
return result != E_NOTIMPL;
});
private static bool? _isNanoServer = null;
private static bool? _isIoT = null;
private static bool? _isWindowsDesktop = null;
#endif
// format files
internal static readonly string[] FormatFileNames = new string[]
{
"Certificate.format.ps1xml",
"Diagnostics.format.ps1xml",
"DotNetTypes.format.ps1xml",
"Event.format.ps1xml",
"FileSystem.format.ps1xml",
"Help.format.ps1xml",
"HelpV3.format.ps1xml",
"PowerShellCore.format.ps1xml",
"PowerShellTrace.format.ps1xml",
"Registry.format.ps1xml",
"WSMan.format.ps1xml"
};
/// <summary>
/// Some common environment variables used in PS have different
/// names in different OS platforms.
/// </summary>
internal static class CommonEnvVariableNames
{
#if UNIX
internal const string Home = "HOME";
#else
internal const string Home = "USERPROFILE";
#endif
}
#if UNIX
private static string s_tempHome = null;
/// <summary>
/// Get the 'HOME' environment variable or create a temporary home diretory if the environment variable is not set.
/// </summary>
private static string GetHomeOrCreateTempHome()
{
const string tempHomeFolderName = "pwsh-{0}-98288ff9-5712-4a14-9a11-23693b9cd91a";
string envHome = Environment.GetEnvironmentVariable("HOME") ?? s_tempHome;
if (envHome is not null)
{
return envHome;
}
try
{
s_tempHome = Path.Combine(Path.GetTempPath(), StringUtil.Format(tempHomeFolderName, Environment.UserName));
Directory.CreateDirectory(s_tempHome);
}
catch (UnauthorizedAccessException)
{
// Directory creation may fail if the account doesn't have filesystem permission such as some service accounts.
// Return an empty string in this case so the process working directory will be used.
s_tempHome = string.Empty;
}
return s_tempHome;
}
/// <summary>
/// X Desktop Group configuration type enum.
/// </summary>
public enum XDG_Type
{
/// <summary> XDG_CONFIG_HOME/powershell </summary>
CONFIG,
/// <summary> XDG_CACHE_HOME/powershell </summary>
CACHE,
/// <summary> XDG_DATA_HOME/powershell </summary>
DATA,
/// <summary> XDG_DATA_HOME/powershell/Modules </summary>
USER_MODULES,
/// <summary> /usr/local/share/powershell/Modules </summary>
SHARED_MODULES,
/// <summary> XDG_CONFIG_HOME/powershell </summary>
DEFAULT
}
/// <summary>
/// Function for choosing directory location of PowerShell for profile loading.
/// </summary>
public static string SelectProductNameForDirectory(XDG_Type dirpath)
{
// TODO: XDG_DATA_DIRS implementation as per GitHub issue #1060
string xdgconfighome = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
string xdgdatahome = Environment.GetEnvironmentVariable("XDG_DATA_HOME");
string xdgcachehome = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
string envHome = GetHomeOrCreateTempHome();
string xdgConfigHomeDefault = Path.Combine(envHome, ".config", "powershell");
string xdgDataHomeDefault = Path.Combine(envHome, ".local", "share", "powershell");
string xdgModuleDefault = Path.Combine(xdgDataHomeDefault, "Modules");
string xdgCacheDefault = Path.Combine(envHome, ".cache", "powershell");
try
{
switch (dirpath)
{
case XDG_Type.CONFIG:
// Use 'XDG_CONFIG_HOME' if it's set, otherwise use the default path.
return string.IsNullOrEmpty(xdgconfighome)
? xdgConfigHomeDefault
: Path.Combine(xdgconfighome, "powershell");
case XDG_Type.DATA:
// Use 'XDG_DATA_HOME' if it's set, otherwise use the default path.
if (string.IsNullOrEmpty(xdgdatahome))
{
// Create the default data directory if it doesn't exist.
Directory.CreateDirectory(xdgDataHomeDefault);
return xdgDataHomeDefault;
}
return Path.Combine(xdgdatahome, "powershell");
case XDG_Type.USER_MODULES:
// Use 'XDG_DATA_HOME' if it's set, otherwise use the default path.
if (string.IsNullOrEmpty(xdgdatahome))
{
Directory.CreateDirectory(xdgModuleDefault);
return xdgModuleDefault;
}
return Path.Combine(xdgdatahome, "powershell", "Modules");
case XDG_Type.SHARED_MODULES:
return "/usr/local/share/powershell/Modules";
case XDG_Type.CACHE:
// Use 'XDG_CACHE_HOME' if it's set, otherwise use the default path.
if (string.IsNullOrEmpty(xdgcachehome))
{
Directory.CreateDirectory(xdgCacheDefault);
return xdgCacheDefault;
}
string cachePath = Path.Combine(xdgcachehome, "powershell");
Directory.CreateDirectory(cachePath);
return cachePath;
case XDG_Type.DEFAULT:
// Use 'xdgConfigHomeDefault' for 'XDG_Type.DEFAULT' and create the directory if it doesn't exist.
Directory.CreateDirectory(xdgConfigHomeDefault);
return xdgConfigHomeDefault;
default:
throw new InvalidOperationException("Unreachable code.");
}
}
catch (UnauthorizedAccessException)
{
// Directory creation may fail if the account doesn't have filesystem permission such as some service accounts.
// Return an empty string in this case so the process working directory will be used.
return string.Empty;
}
}
#endif
/// <summary>
/// Mimic 'Environment.GetFolderPath(folder)' on Unix.
/// </summary>
internal static string GetFolderPath(Environment.SpecialFolder folder)
{
#if UNIX
return folder switch
{
Environment.SpecialFolder.ProgramFiles => Directory.Exists("/bin") ? "/bin" : string.Empty,
Environment.SpecialFolder.MyDocuments => GetHomeOrCreateTempHome(),
_ => throw new NotSupportedException()
};
#else
return Environment.GetFolderPath(folder);
#endif
}
// Platform methods prefixed NonWindows are:
// - non-windows by the definition of the IsWindows method above
// - here, because porting to Linux and other operating systems
// should not move the original Windows code out of the module
// it belongs to, so this way the windows code can remain in it's
// original source file and only the non-windows code has been moved
// out here
// - only to be used with the IsWindows feature query, and only if
// no other more specific feature query makes sense
internal static bool NonWindowsIsHardLink(ref IntPtr handle)
{
return Unix.IsHardLink(ref handle);
}
internal static bool NonWindowsIsHardLink(FileSystemInfo fileInfo)
{
return Unix.IsHardLink(fileInfo);
}
internal static string NonWindowsGetUserFromPid(int path)
{
return Unix.NativeMethods.GetUserFromPid(path);
}
internal static string NonWindowsInternalGetLinkType(FileSystemInfo fileInfo)
{
if (fileInfo.Attributes.HasFlag(System.IO.FileAttributes.ReparsePoint))
{
return "SymbolicLink";
}
if (NonWindowsIsHardLink(fileInfo))
{
return "HardLink";
}
return null;
}
internal static bool NonWindowsCreateSymbolicLink(string path, string target)
{
// Linux doesn't care if target is a directory or not
return Unix.NativeMethods.CreateSymLink(path, target) == 0;
}
internal static bool NonWindowsCreateHardLink(string path, string strTargetPath)
{
return Unix.NativeMethods.CreateHardLink(path, strTargetPath) == 0;
}
internal static unsafe bool NonWindowsSetDate(DateTime dateToUse)
{
Unix.NativeMethods.UnixTm tm = Unix.NativeMethods.DateTimeToUnixTm(dateToUse);
return Unix.NativeMethods.SetDate(&tm) == 0;
}
internal static bool NonWindowsIsSameFileSystemItem(string pathOne, string pathTwo)
{
return Unix.NativeMethods.IsSameFileSystemItem(pathOne, pathTwo);
}
internal static bool NonWindowsGetInodeData(string path, out ValueTuple<ulong, ulong> inodeData)
{
var result = Unix.NativeMethods.GetInodeData(path, out ulong device, out ulong inode);
inodeData = (device, inode);
return result == 0;
}
internal static bool NonWindowsIsExecutable(string path)
{
return Unix.NativeMethods.IsExecutable(path);
}
internal static uint NonWindowsGetThreadId()
{
return Unix.NativeMethods.GetCurrentThreadId();
}
internal static int NonWindowsGetProcessParentPid(int pid)
{
return IsMacOS ? Unix.NativeMethods.GetPPid(pid) : Unix.GetProcFSParentPid(pid);
}
internal static bool NonWindowsKillProcess(int pid)
{
return Unix.NativeMethods.KillProcess(pid);
}
internal static int NonWindowsWaitPid(int pid, bool nohang)
{
return Unix.NativeMethods.WaitPid(pid, nohang);
}
internal static class Windows
{
/// <summary>The native methods class.</summary>
internal static class NativeMethods
{
private const string ole32Lib = "api-ms-win-core-com-l1-1-0.dll";
[DllImport(ole32Lib)]
internal static extern int CoInitializeEx(IntPtr reserve, int coinit);
[DllImport(ole32Lib)]
internal static extern void CoUninitialize();
}
}
// Please note that `Win32Exception(Marshal.GetLastWin32Error())`
// works *correctly* on Linux in that it creates an exception with
// the string perror would give you for the last set value of errno.
// No manual mapping is required. .NET Core maps the Linux errno
// to a PAL value and calls strerror_r underneath to generate the message.
/// <summary>Unix specific implementations of required functionality.</summary>
internal static class Unix
{
private static readonly Dictionary<int, string> usernameCache = new();
private static readonly Dictionary<int, string> groupnameCache = new();
/// <summary>The type of a Unix file system item.</summary>
public enum ItemType
{
/// <summary>The item is a Directory.</summary>
Directory,
/// <summary>The item is a File.</summary>
File,
/// <summary>The item is a Symbolic Link.</summary>
SymbolicLink,
/// <summary>The item is a Block Device.</summary>
BlockDevice,
/// <summary>The item is a Character Device.</summary>
CharacterDevice,
/// <summary>The item is a Named Pipe.</summary>
NamedPipe,
/// <summary>The item is a Socket.</summary>
Socket,
}
/// <summary>The mask to use to retrieve specific mode bits from the mode value in the stat class.</summary>
public enum StatMask
{
/// <summary>The mask to collect the owner mode.</summary>
OwnerModeMask = 0x1C0,
/// <summary>The mask to get the owners read bit.</summary>
OwnerRead = 0x100,
/// <summary>The mask to get the owners write bit.</summary>
OwnerWrite = 0x080,
/// <summary>The mask to get the owners execute bit.</summary>
OwnerExecute = 0x040,
/// <summary>The mask to get the group mode.</summary>
GroupModeMask = 0x038,
/// <summary>The mask to get the group mode.</summary>
GroupRead = 0x20,
/// <summary>The mask to get the group mode.</summary>
GroupWrite = 0x10,
/// <summary>The mask to get the group mode.</summary>
GroupExecute = 0x8,
/// <summary>The mask to get the "other" mode.</summary>
OtherModeMask = 0x007,
/// <summary>The mask to get the "other" read bit.</summary>
OtherRead = 0x004,
/// <summary>The mask to get the "other" write bit.</summary>
OtherWrite = 0x002,
/// <summary>The mask to get the "other" execute bit.</summary>
OtherExecute = 0x001,
/// <summary>The mask to retrieve the sticky bit.</summary>
SetStickyMask = 0x200,
/// <summary>The mask to retrieve the setgid bit.</summary>
SetGidMask = 0x400,
/// <summary>The mask to retrieve the setuid bit.</summary>
SetUidMask = 0x800,
}
/// <summary>The Common Stat class.</summary>
public class CommonStat
{
/// <summary>The inode of the filesystem item.</summary>
public long Inode;
/// <summary>The Mode of the filesystem item.</summary>
public int Mode;
/// <summary>The user id of the filesystem item.</summary>
public int UserId;
/// <summary>The group id of the filesystem item.</summary>
public int GroupId;
/// <summary>The number of hard links for the filesystem item.</summary>
public int HardlinkCount;
/// <summary>The size in bytes of the filesystem item.</summary>
public long Size;
/// <summary>The last access time of the filesystem item.</summary>
public DateTime AccessTime;
/// <summary>The last modified time for the filesystem item.</summary>
public DateTime ModifiedTime;
/// <summary>The last time the status changes for the filesystem item.</summary>
public DateTime StatusChangeTime;
/// <summary>The block size of the filesystem.</summary>
public long BlockSize;
/// <summary>The device id of the filesystem item.</summary>
public int DeviceId;
/// <summary>The number of blocks used by the filesystem item.</summary>
public int NumberOfBlocks;
/// <summary>The type of the filesystem item.</summary>
public ItemType ItemType;
/// <summary>Whether the filesystem item has the setuid bit enabled.</summary>
public bool IsSetUid;
/// <summary>Whether the filesystem item has the setgid bit enabled.</summary>
public bool IsSetGid;
/// <summary>Whether the filesystem item has the sticky bit enabled. This is only available for directories.</summary>
public bool IsSticky;
private const char CanRead = 'r';
private const char CanWrite = 'w';
private const char CanExecute = 'x';
// helper for getting unix mode
private readonly Dictionary<StatMask, char> modeMap = new()
{
{ StatMask.OwnerRead, CanRead },
{ StatMask.OwnerWrite, CanWrite },
{ StatMask.OwnerExecute, CanExecute },
{ StatMask.GroupRead, CanRead },
{ StatMask.GroupWrite, CanWrite },
{ StatMask.GroupExecute, CanExecute },
{ StatMask.OtherRead, CanRead },
{ StatMask.OtherWrite, CanWrite },
{ StatMask.OtherExecute, CanExecute },
};
private readonly StatMask[] permissions = new StatMask[]
{
StatMask.OwnerRead,
StatMask.OwnerWrite,
StatMask.OwnerExecute,
StatMask.GroupRead,
StatMask.GroupWrite,
StatMask.GroupExecute,
StatMask.OtherRead,
StatMask.OtherWrite,
StatMask.OtherExecute
};
// The item type and the character representation for the first element in the stat string
private readonly Dictionary<ItemType, char> itemTypeTable = new()
{
{ ItemType.BlockDevice, 'b' },
{ ItemType.CharacterDevice, 'c' },
{ ItemType.Directory, 'd' },
{ ItemType.File, '-' },
{ ItemType.NamedPipe, 'p' },
{ ItemType.Socket, 's' },
{ ItemType.SymbolicLink, 'l' },
};
/// <summary>Convert the mode to a string which is usable in our formatting.</summary>
/// <returns>The mode converted into a Unix style string similar to the output of ls.</returns>
public string GetModeString()
{
int offset = 0;
char[] modeCharacters = new char[10];
modeCharacters[offset++] = itemTypeTable[ItemType];
foreach (StatMask permission in permissions)
{
// determine whether we are setuid, sticky, or the usual rwx.
if ((Mode & (int)permission) == (int)permission)
{
if ((permission == StatMask.OwnerExecute && IsSetUid) || (permission == StatMask.GroupExecute && IsSetGid))
{
// Check for setuid and add 's'
modeCharacters[offset] = 's';
}
else if (permission == StatMask.OtherExecute && IsSticky && (ItemType == ItemType.Directory))
{
// Directories are sticky, rather than setuid
modeCharacters[offset] = 't';
}
else
{
modeCharacters[offset] = modeMap[permission];
}
}
else
{
modeCharacters[offset] = '-';
}
offset++;
}
return new string(modeCharacters);
}
/// <summary>
/// Get the user name. This is used in formatting, but we shouldn't
/// do the pinvoke this unless we're going to use it.
/// </summary>
/// <returns>The user name.</returns>
public string GetUserName()
{
if (usernameCache.TryGetValue(UserId, out string username))
{
return username;
}
// Get and add the user name to the cache so we don't need to
// have a pinvoke for each file.
username = NativeMethods.GetPwUid(UserId);
usernameCache.Add(UserId, username);
return username;
}
/// <summary>
/// Get the group name. This is used in formatting, but we shouldn't
/// do the pinvoke this unless we're going to use it.
/// </summary>
/// <returns>The name of the group.</returns>
public string GetGroupName()
{
if (groupnameCache.TryGetValue(GroupId, out string groupname))
{
return groupname;
}
// Get and add the group name to the cache so we don't need to
// have a pinvoke for each file.
groupname = NativeMethods.GetGrGid(GroupId);
groupnameCache.Add(GroupId, groupname);
return groupname;
}
}
// This is a helper that attempts to map errno into a PowerShell ErrorCategory
internal static ErrorCategory GetErrorCategory(int errno)
{
return (ErrorCategory)Unix.NativeMethods.GetErrorCategory(errno);
}
/// <summary>Is this a hardlink.</summary>
/// <param name="handle">The handle to a file.</param>
/// <returns>A boolean that represents whether the item is a hardlink.</returns>
public static bool IsHardLink(ref IntPtr handle)
{
// TODO:PSL implement using fstat to query inode refcount to see if it is a hard link
return false;
}
/// <summary>Determine if the item is a hardlink.</summary>
/// <param name="fs">A FileSystemInfo to check to determine if it is a hardlink.</param>
/// <returns>A boolean that represents whether the item is a hardlink.</returns>
public static bool IsHardLink(FileSystemInfo fs)
{
if (!fs.Exists || (fs.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
return false;
}
int count;
string filePath = fs.FullName;
int ret = NativeMethods.GetLinkCount(filePath, out count);
if (ret == 0)
{
return count > 1;
}
throw new Win32Exception(Marshal.GetLastWin32Error());
}
/// <summary>
/// Create a managed replica of the native stat structure.
/// </summary>
/// <param name="css">The common stat structure from which we copy.</param>
/// <returns>A managed common stat class instance.</returns>
private static CommonStat CopyStatStruct(NativeMethods.CommonStatStruct css)
{
CommonStat cs = new();
cs.Inode = css.Inode;
cs.Mode = css.Mode;
cs.UserId = css.UserId;
cs.GroupId = css.GroupId;
cs.HardlinkCount = css.HardlinkCount;
cs.Size = css.Size;
// These can sometime throw if we get too large a number back (seen on Raspbian).
// As a fallback, set the time to UnixEpoch.
try
{
cs.AccessTime = DateTime.UnixEpoch.AddSeconds(css.AccessTime).ToLocalTime();
}
catch
{
cs.AccessTime = DateTime.UnixEpoch.ToLocalTime();
}
try
{
cs.ModifiedTime = DateTime.UnixEpoch.AddSeconds(css.ModifiedTime).ToLocalTime();
}
catch
{
cs.ModifiedTime = DateTime.UnixEpoch.ToLocalTime();
}
try
{
cs.StatusChangeTime = DateTime.UnixEpoch.AddSeconds(css.StatusChangeTime).ToLocalTime();
}
catch
{
cs.StatusChangeTime = DateTime.UnixEpoch.ToLocalTime();
}
cs.BlockSize = css.BlockSize;
cs.DeviceId = css.DeviceId;
cs.NumberOfBlocks = css.NumberOfBlocks;
if (css.IsDirectory == 1)
{
cs.ItemType = ItemType.Directory;
}
else if (css.IsFile == 1)
{
cs.ItemType = ItemType.File;
}
else if (css.IsSymbolicLink == 1)
{
cs.ItemType = ItemType.SymbolicLink;
}
else if (css.IsBlockDevice == 1)
{
cs.ItemType = ItemType.BlockDevice;
}
else if (css.IsCharacterDevice == 1)
{
cs.ItemType = ItemType.CharacterDevice;
}
else if (css.IsNamedPipe == 1)
{
cs.ItemType = ItemType.NamedPipe;
}
else
{
cs.ItemType = ItemType.Socket;
}
cs.IsSetUid = css.IsSetUid == 1;
cs.IsSetGid = css.IsSetGid == 1;
cs.IsSticky = css.IsSticky == 1;
return cs;
}
/// <summary>Get the lstat info from a path.</summary>
/// <param name="path">The path to the lstat information.</param>
/// <returns>An instance of the CommonStat for the path.</returns>
public static CommonStat GetLStat(string path)
{
NativeMethods.CommonStatStruct css;
if (NativeMethods.GetCommonLStat(path, out css) == 0)
{
return CopyStatStruct(css);
}
throw new Win32Exception(Marshal.GetLastWin32Error());
}
/// <summary>Get the stat info from a path.</summary>
/// <param name="path">The path to the stat information.</param>
/// <returns>An instance of the CommonStat for the path.</returns>
public static CommonStat GetStat(string path)
{
NativeMethods.CommonStatStruct css;
if (NativeMethods.GetCommonStat(path, out css) == 0)
{
return CopyStatStruct(css);
}
throw new Win32Exception(Marshal.GetLastWin32Error());
}
/// <summary>Read the /proc file system for information about the parent.</summary>
/// <param name="pid">The process id used to get the parent process.</param>
/// <returns>The process id.</returns>
public static int GetProcFSParentPid(int pid)
{
const int invalidPid = -1;
// read /proc/<pid>/stat
// 4th column will contain the ppid, 92 in the example below
// ex: 93 (bash) S 92 93 2 4294967295 ...
var path = $"/proc/{pid}/stat";
try
{
var stat = System.IO.File.ReadAllText(path);
var parts = stat.Split(' ', 5);
if (parts.Length < 5)
{
return invalidPid;
}
return int.Parse(parts[3]);
}
catch (Exception)
{
return invalidPid;
}
}
/// <summary>The native methods class.</summary>
internal static class NativeMethods
{
private const string psLib = "libpsl-native";
// Ansi is a misnomer, it is hardcoded to UTF-8 on Linux and macOS
// C bools are 1 byte and so must be marshaled as I1
[DllImport(psLib, CharSet = CharSet.Ansi)]
internal static extern int GetErrorCategory(int errno);
[DllImport(psLib)]
internal static extern int GetPPid(int pid);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int GetLinkCount([MarshalAs(UnmanagedType.LPStr)] string filePath, out int linkCount);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.I1)]
internal static extern bool IsExecutable([MarshalAs(UnmanagedType.LPStr)] string filePath);
[DllImport(psLib, CharSet = CharSet.Ansi)]
internal static extern uint GetCurrentThreadId();
[DllImport(psLib)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool KillProcess(int pid);
[DllImport(psLib)]
internal static extern int WaitPid(int pid, bool nohang);
// This is a struct tm from <time.h>.
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct UnixTm
{
/// <summary>Seconds (0-60).</summary>
internal int tm_sec;
/// <summary>Minutes (0-59).</summary>
internal int tm_min;
/// <summary>Hours (0-23).</summary>
internal int tm_hour;
/// <summary>Day of the month (1-31).</summary>
internal int tm_mday;
/// <summary>Month (0-11).</summary>
internal int tm_mon;
/// <summary>The year - 1900.</summary>
internal int tm_year;
/// <summary>Day of the week (0-6, Sunday = 0).</summary>
internal int tm_wday;
/// <summary>Day in the year (0-365, 1 Jan = 0).</summary>
internal int tm_yday;
/// <summary>Daylight saving time.</summary>
internal int tm_isdst;
}
// We need a way to convert a DateTime to a unix date.
internal static UnixTm DateTimeToUnixTm(DateTime date)
{
UnixTm tm;
tm.tm_sec = date.Second;
tm.tm_min = date.Minute;
tm.tm_hour = date.Hour;
tm.tm_mday = date.Day;
tm.tm_mon = date.Month - 1; // needs to be 0 indexed
tm.tm_year = date.Year - 1900; // years since 1900
tm.tm_wday = 0; // this is ignored by mktime
tm.tm_yday = 0; // this is also ignored
tm.tm_isdst = date.IsDaylightSavingTime() ? 1 : 0;
return tm;
}
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern unsafe int SetDate(UnixTm* tm);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int CreateSymLink([MarshalAs(UnmanagedType.LPStr)] string filePath,
[MarshalAs(UnmanagedType.LPStr)] string target);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int CreateHardLink([MarshalAs(UnmanagedType.LPStr)] string filePath,
[MarshalAs(UnmanagedType.LPStr)] string target);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.LPStr)]
internal static extern string GetUserFromPid(int pid);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.I1)]
internal static extern bool IsSameFileSystemItem([MarshalAs(UnmanagedType.LPStr)] string filePathOne,
[MarshalAs(UnmanagedType.LPStr)] string filePathTwo);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int GetInodeData([MarshalAs(UnmanagedType.LPStr)] string path,
out ulong device, out ulong inode);
/// <summary>
/// This is a struct from getcommonstat.h in the native library.
/// It presents each member of the stat structure as the largest type of that member across
/// all stat structures on the platforms we support. This allows us to present a common
/// stat structure for all our platforms.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct CommonStatStruct
{
/// <summary>The inode of the filesystem item.</summary>
internal long Inode;
/// <summary>The mode of the filesystem item.</summary>
internal int Mode;
/// <summary>The user id of the filesystem item.</summary>
internal int UserId;
/// <summary>The group id of the filesystem item.</summary>
internal int GroupId;
/// <summary>The number of hard links to the filesystem item.</summary>
internal int HardlinkCount;
/// <summary>The size in bytes of the filesystem item.</summary>
internal long Size;
/// <summary>The time of the last access for the filesystem item.</summary>
internal long AccessTime;
/// <summary>The time of the last modification for the filesystem item.</summary>
internal long ModifiedTime;
/// <summary>The time of the last status change for the filesystem item.</summary>
internal long StatusChangeTime;
/// <summary>The size in bytes of the file system.</summary>
internal long BlockSize;
/// <summary>The device id for the filesystem item.</summary>
internal int DeviceId;
/// <summary>The number of filesystem blocks that the filesystem item uses.</summary>
internal int NumberOfBlocks;
/// <summary>This filesystem item is a directory.</summary>
internal int IsDirectory;
/// <summary>This filesystem item is a file.</summary>
internal int IsFile;
/// <summary>This filesystem item is a symbolic link.</summary>
internal int IsSymbolicLink;
/// <summary>This filesystem item is a block device.</summary>
internal int IsBlockDevice;
/// <summary>This filesystem item is a character device.</summary>
internal int IsCharacterDevice;
/// <summary>This filesystem item is a named pipe.</summary>
internal int IsNamedPipe;
/// <summary>This filesystem item is a socket.</summary>
internal int IsSocket;
/// <summary>This filesystem item will run as the owner if executed.</summary>
internal int IsSetUid;
/// <summary>This filesystem item will run as the group if executed.</summary>
internal int IsSetGid;
/// <summary>Whether the sticky bit is set on the filesystem item.</summary>
internal int IsSticky;
}
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern unsafe int GetCommonLStat(string filePath, [Out] out CommonStatStruct cs);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern unsafe int GetCommonStat(string filePath, [Out] out CommonStatStruct cs);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern string GetPwUid(int id);
[DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern string GetGrGid(int id);
}
}
}
}
| |
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using java.lang;
using java.util;
namespace stab.query {
public interface OrderedIterable<TSource> : Iterable<TSource> {
OrderedIterable<TSource> createOrderedIterable<TKey>(FunctionTT<TSource, TKey> keySelector,
Comparator<TKey> comparator, bool descending);
OrderedIterable<TSource> createOrderedIterable(FunctionTInt<TSource> keySelector, bool descending);
OrderedIterable<TSource> createOrderedIterable(FunctionTLong<TSource> keySelector, bool descending);
OrderedIterable<TSource> createOrderedIterable(FunctionTFloat<TSource> keySelector, bool descending);
OrderedIterable<TSource> createOrderedIterable(FunctionTDouble<TSource> keySelector, bool descending);
}
abstract class OrderedEnumerable<TSource> : OrderedIterable<TSource> {
protected Iterable<TSource> source*;
protected bool descending*;
OrderedEnumerable(Iterable<TSource> source, bool descending) {
if (source == null) {
throw new NullPointerException("source");
}
this.source = source;
this.descending = descending;
}
abstract Sorter getSorter(List<TSource> values, Sorter next);
public OrderedIterable<TSource> createOrderedIterable<TKey>(FunctionTT<TSource, TKey> keySelector,
Comparator<TKey> comparator, bool descending) {
return new KeyOrderedIterable<TSource, TKey>(source, keySelector, comparator, descending, this);
}
public OrderedIterable<TSource> createOrderedIterable(FunctionTInt<TSource> keySelector, bool descending) {
return new IntKeyOrderedIterable<TSource>(source, keySelector, descending, this);
}
public OrderedIterable<TSource> createOrderedIterable(FunctionTLong<TSource> keySelector, bool descending) {
return new LongKeyOrderedIterable<TSource>(source, keySelector, descending, this);
}
public OrderedIterable<TSource> createOrderedIterable(FunctionTFloat<TSource> keySelector, bool descending) {
return new FloatKeyOrderedIterable<TSource>(source, keySelector, descending, this);
}
public OrderedIterable<TSource> createOrderedIterable(FunctionTDouble<TSource> keySelector, bool descending) {
return new DoubleKeyOrderedIterable<TSource>(source, keySelector, descending, this);
}
protected OrderedIterable<TSource> getOrderedEnumerable() {
return this;
}
}
class KeyOrderedIterable<TSource, TKey> : OrderedEnumerable<TSource> {
private FunctionTT<TSource, TKey> keySelector;
private Comparator<TKey> comparator;
private OrderedEnumerable<TSource> parent;
KeyOrderedIterable(Iterable<TSource> source, FunctionTT<TSource, TKey> keySelector, Comparator<TKey> comparator,
bool descending, OrderedEnumerable<TSource> parent)
: super(source, descending) {
if (keySelector == null) {
throw new NullPointerException("keySelector");
}
this.keySelector = keySelector;
if (comparator == null) {
#pragma warning disable 270 // Ignore warning about raw generic types
comparator = (Comparator<TKey>)DefaultComparator.INSTANCE; // Assumes that TKey extends Comparable<TKey>
#pragma warning restore
}
this.comparator = comparator;
this.parent = parent;
}
public override Sorter getSorter(List<TSource> values, Sorter next) {
Sorter result = new KeySorter<TSource, TKey>(values, keySelector, comparator, descending, next);
if (parent != null) {
result = parent.getSorter(values, result);
}
return result;
}
public Iterator<TSource> iterator() {
var values = source.toList();
int size = values.size();
if (size == 0) {
yield break;
}
var sorter = getSorter(values, null);
var map = Sorter.createMap(size);
sorter.sort(map, 0, size - 1);
for (int i = 0; i < size; i++) {
yield return values[map[i]];
}
}
private class DefaultComparator<T> : Comparator<T>
where T : Comparable<T>
{
#pragma warning disable 252 // Ignore warning about raw generic types
static Comparator INSTANCE = new DefaultComparator();
#pragma warning restore
public int compare(T o1, T o2) {
return o1.compareTo(o2);
}
}
private class KeySorter<TSource, TKey> : Sorter {
private Sorter next;
private TKey[] keys;
private Comparator<TKey> comparator;
private bool descending;
private List<TSource> values;
private FunctionTT<TSource, TKey> keySelector;
KeySorter(List<TSource> values, FunctionTT<TSource, TKey> keySelector,
Comparator<TKey> comparator, bool descending, Sorter next) {
this.values = values;
this.keySelector = keySelector;
this.comparator = comparator;
this.descending = descending;
this.next = next;
}
protected override int compare(int index1, int index2) {
if (keys == null) {
#pragma warning disable 313
keys = new TKey[values.size()];
#pragma warning restore
for (int i = 0; i < sizeof(keys); i++) {
keys[i] = keySelector.invoke(values[i]);
}
}
int comp = comparator.compare(keys[index1], keys[index2]);
if (comp == 0) {
if (next == null) {
return index1 - index2;
} else {
return next.compare(index1, index2);
}
}
if (descending) {
return -comp;
} else {
return comp;
}
}
}
}
class IntKeyOrderedIterable<TSource> : OrderedEnumerable<TSource> {
private FunctionTInt<TSource> keySelector;
private OrderedEnumerable<TSource> parent;
IntKeyOrderedIterable(Iterable<TSource> source, FunctionTInt<TSource> keySelector, bool descending, OrderedEnumerable<TSource> parent)
: super(source, descending) {
if (keySelector == null) {
throw new NullPointerException("keySelector");
}
this.keySelector = keySelector;
this.parent = parent;
}
public override Sorter getSorter(List<TSource> values, Sorter next) {
Sorter result = new KeySorter<TSource>(values, keySelector, descending, next);
if (parent != null) {
result = parent.getSorter(values, result);
}
return result;
}
public Iterator<TSource> iterator() {
var values = source.toList();
int size = values.size();
if (size == 0) {
yield break;
}
var sorter = getSorter(values, null);
var map = Sorter.createMap(size);
sorter.sort(map, 0, size - 1);
for (int i = 0; i < size; i++) {
yield return values[map[i]];
}
}
private class KeySorter<TSource> : Sorter {
private Sorter next;
private int[] keys;
private bool descending;
private List<TSource> values;
private FunctionTInt<TSource> keySelector;
KeySorter(List<TSource> values, FunctionTInt<TSource> keySelector, bool descending, Sorter next) {
this.values = values;
this.keySelector = keySelector;
this.descending = descending;
this.next = next;
}
protected override int compare(int index1, int index2) {
if (keys == null) {
keys = new int[values.size()];
for (int i = 0; i < sizeof(keys); i++) {
keys[i] = keySelector.invoke(values[i]);
}
}
var k1 = keys[index1];
var k2 = keys[index2];
int comp = (k1 < k2) ? -1 : (k1 == k2) ? 0 : 1;
if (comp == 0) {
if (next == null) {
return index1 - index2;
} else {
return next.compare(index1, index2);
}
}
return (descending) ? -comp : comp;
}
}
}
class LongKeyOrderedIterable<TSource> : OrderedEnumerable<TSource> {
private FunctionTLong<TSource> keySelector;
private OrderedEnumerable<TSource> parent;
LongKeyOrderedIterable(Iterable<TSource> source, FunctionTLong<TSource> keySelector, bool descending, OrderedEnumerable<TSource> parent)
: super(source, descending) {
if (keySelector == null) {
throw new NullPointerException("keySelector");
}
this.keySelector = keySelector;
this.parent = parent;
}
public override Sorter getSorter(List<TSource> values, Sorter next) {
Sorter result = new KeySorter<TSource>(values, keySelector, descending, next);
if (parent != null) {
result = parent.getSorter(values, result);
}
return result;
}
public Iterator<TSource> iterator() {
var values = source.toList();
int size = values.size();
if (size == 0) {
yield break;
}
var sorter = getSorter(values, null);
var map = Sorter.createMap(size);
sorter.sort(map, 0, size - 1);
for (int i = 0; i < size; i++) {
yield return values[map[i]];
}
}
private class KeySorter<TSource> : Sorter {
private Sorter next;
private long[] keys;
private bool descending;
private List<TSource> values;
private FunctionTLong<TSource> keySelector;
KeySorter(List<TSource> values, FunctionTLong<TSource> keySelector, bool descending, Sorter next) {
this.values = values;
this.keySelector = keySelector;
this.descending = descending;
this.next = next;
}
protected override int compare(int index1, int index2) {
if (keys == null) {
keys = new long[values.size()];
for (int i = 0; i < sizeof(keys); i++) {
keys[i] = keySelector.invoke(values[i]);
}
}
var k1 = keys[index1];
var k2 = keys[index2];
int comp = (k1 < k2) ? -1 : (k1 == k2) ? 0 : 1;
if (comp == 0) {
if (next == null) {
return index1 - index2;
} else {
return next.compare(index1, index2);
}
}
return (descending) ? -comp : comp;
}
}
}
class FloatKeyOrderedIterable<TSource> : OrderedEnumerable<TSource> {
private FunctionTFloat<TSource> keySelector;
private OrderedEnumerable<TSource> parent;
FloatKeyOrderedIterable(Iterable<TSource> source, FunctionTFloat<TSource> keySelector, bool descending,
OrderedEnumerable<TSource> parent)
: super(source, descending) {
if (keySelector == null) {
throw new NullPointerException("keySelector");
}
this.keySelector = keySelector;
this.parent = parent;
}
public override Sorter getSorter(List<TSource> values, Sorter next) {
Sorter result = new KeySorter<TSource>(values, keySelector, descending, next);
if (parent != null) {
result = parent.getSorter(values, result);
}
return result;
}
public Iterator<TSource> iterator() {
var values = source.toList();
int size = values.size();
if (size == 0) {
yield break;
}
var sorter = getSorter(values, null);
var map = Sorter.createMap(size);
sorter.sort(map, 0, size - 1);
for (int i = 0; i < size; i++) {
yield return values[map[i]];
}
}
private class KeySorter<TSource> : Sorter {
private Sorter next;
private float[] keys;
private bool descending;
private List<TSource> values;
private FunctionTFloat<TSource> keySelector;
KeySorter(List<TSource> values, FunctionTFloat<TSource> keySelector, bool descending, Sorter next) {
this.values = values;
this.keySelector = keySelector;
this.descending = descending;
this.next = next;
}
protected override int compare(int index1, int index2) {
if (keys == null) {
keys = new float[values.size()];
for (int i = 0; i < sizeof(keys); i++) {
keys[i] = keySelector.invoke(values[i]);
}
}
var k1 = keys[index1];
var k2 = keys[index2];
int comp = (k1 < k2) ? -1 : (k1 == k2) ? 0 : 1;
if (comp == 0) {
if (next == null) {
return index1 - index2;
} else {
return next.compare(index1, index2);
}
}
return (descending) ? -comp : comp;
}
}
}
class DoubleKeyOrderedIterable<TSource> : OrderedEnumerable<TSource> {
private FunctionTDouble<TSource> keySelector;
private OrderedEnumerable<TSource> parent;
DoubleKeyOrderedIterable(Iterable<TSource> source, FunctionTDouble<TSource> keySelector, bool descending,
OrderedEnumerable<TSource> parent)
: super(source, descending) {
if (keySelector == null) {
throw new NullPointerException("keySelector");
}
this.keySelector = keySelector;
this.parent = parent;
}
public override Sorter getSorter(List<TSource> values, Sorter next) {
Sorter result = new KeySorter<TSource>(values, keySelector, descending, next);
if (parent != null) {
result = parent.getSorter(values, result);
}
return result;
}
public Iterator<TSource> iterator() {
var values = source.toList();
int size = values.size();
if (size == 0) {
yield break;
}
var sorter = getSorter(values, null);
var map = Sorter.createMap(size);
sorter.sort(map, 0, size - 1);
for (int i = 0; i < size; i++) {
yield return values[map[i]];
}
}
private class KeySorter<TSource> : Sorter {
private Sorter next;
private double[] keys;
private bool descending;
private List<TSource> values;
private FunctionTDouble<TSource> keySelector;
KeySorter(List<TSource> values, FunctionTDouble<TSource> keySelector, bool descending, Sorter next) {
this.values = values;
this.keySelector = keySelector;
this.descending = descending;
this.next = next;
}
protected override int compare(int index1, int index2) {
if (keys == null) {
keys = new double[values.size()];
for (int i = 0; i < sizeof(keys); i++) {
keys[i] = keySelector.invoke(values[i]);
}
}
var k1 = keys[index1];
var k2 = keys[index2];
int comp = (k1 < k2) ? -1 : (k1 == k2) ? 0 : 1;
if (comp == 0) {
if (next == null) {
return index1 - index2;
} else {
return next.compare(index1, index2);
}
}
return (descending) ? -comp : comp;
}
}
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using NUnit.Framework;
namespace OpenMetaverse.Tests
{
[TestFixture]
public class TypeTests : Assert
{
[Test]
public void UUIDs()
{
// Creation
UUID a = new UUID();
byte[] bytes = a.GetBytes();
for (int i = 0; i < 16; i++)
Assert.IsTrue(bytes[i] == 0x00);
// Comparison
a = new UUID(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF }, 0);
UUID b = new UUID(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x0B, 0x0C, 0x0D, 0x0E, 0x0F }, 0);
Assert.IsTrue(a == b, "UUID comparison operator failed, " + a.ToString() + " should equal " +
b.ToString());
// From string
a = new UUID(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x0B, 0x0C, 0x0D, 0x0E, 0x0F }, 0);
string zeroonetwo = "00010203-0405-0607-0809-0a0b0c0d0e0f";
b = new UUID(zeroonetwo);
Assert.IsTrue(a == b, "UUID hyphenated string constructor failed, should have " + a.ToString() +
" but we got " + b.ToString());
// ToString()
Assert.IsTrue(a == b);
Assert.IsTrue(a == (UUID)zeroonetwo);
// TODO: CRC test
}
[Test]
public void Vector3ApproxEquals()
{
Vector3 a = new Vector3(1f, 0f, 0f);
Vector3 b = new Vector3(0f, 0f, 0f);
Assert.IsFalse(a.ApproxEquals(b, 0.9f), "ApproxEquals failed (1)");
Assert.IsTrue(a.ApproxEquals(b, 1.0f), "ApproxEquals failed (2)");
a = new Vector3(-1f, 0f, 0f);
b = new Vector3(1f, 0f, 0f);
Assert.IsFalse(a.ApproxEquals(b, 1.9f), "ApproxEquals failed (3)");
Assert.IsTrue(a.ApproxEquals(b, 2.0f), "ApproxEquals failed (4)");
a = new Vector3(0f, -1f, 0f);
b = new Vector3(0f, -1.1f, 0f);
Assert.IsFalse(a.ApproxEquals(b, 0.09f), "ApproxEquals failed (5)");
Assert.IsTrue(a.ApproxEquals(b, 0.11f), "ApproxEquals failed (6)");
a = new Vector3(0f, 0f, 0.00001f);
b = new Vector3(0f, 0f, 0f);
Assert.IsFalse(b.ApproxEquals(a, Single.Epsilon), "ApproxEquals failed (6)");
Assert.IsTrue(b.ApproxEquals(a, 0.0001f), "ApproxEquals failed (7)");
}
[Test]
public void VectorCasting()
{
Dictionary<string, double> testNumbers;
testNumbers = new Dictionary<string, double>();
testNumbers["1.0"] = 1.0;
testNumbers["1.1"] = 1.1;
testNumbers["1.01"] = 1.01;
testNumbers["1.001"] = 1.001;
testNumbers["1.0001"] = 1.0001;
testNumbers["1.00001"] = 1.00001;
testNumbers["1.000001"] = 1.000001;
testNumbers["1.0000001"] = 1.0000001;
testNumbers["1.00000001"] = 1.00000001;
foreach (KeyValuePair<string, double> kvp in testNumbers)
{
double testNumber = kvp.Value;
double testNumber2 = (double)((float)testNumber);
bool noPrecisionLoss = testNumber == testNumber2;
Vector3 a = new Vector3(
(float)testNumber,
(float)testNumber, (float)testNumber);
Vector3d b = new Vector3d(testNumber, testNumber, testNumber);
Vector3 c = (Vector3)b;
Vector3d d = a;
if (noPrecisionLoss)
{
Console.Error.WriteLine("Unsuitable test value used-" +
" test number should have precision loss when" +
" cast to float ({0}).", kvp.Key);
}
else
{
Assert.IsFalse(a == b, string.Format(
"Vector casting failed, precision loss should" +
" have occurred. " +
"{0}: {1}, {2}", kvp.Key, a.X, b.X));
Assert.IsFalse(b == d, string.Format(
"Vector casting failed, explicit cast of double" +
" to float should result in precision loss" +
" whichwas should not magically disappear when" +
" Vector3 is implicitly cast to Vector3d." +
" {0}: {1}, {2}", kvp.Key, b.X, d.X));
}
Assert.IsTrue(a == c, string.Format(
"Vector casting failed, Vector3 compared to" +
" explicit cast of Vector3d to Vector3 should" +
" result in identical precision loss." +
" {0}: {1}, {2}", kvp.Key, a.X, c.X));
Assert.IsTrue(a == d, string.Format(
"Vector casting failed, implicit cast of Vector3" +
" to Vector3d should not result in precision loss." +
" {0}: {1}, {2}", kvp.Key, a.X, d.X));
}
}
[Test]
public void Quaternions()
{
Quaternion a = new Quaternion(1, 0, 0, 0);
Quaternion b = new Quaternion(1, 0, 0, 0);
Assert.IsTrue(a == b, "Quaternion comparison operator failed");
Quaternion expected = new Quaternion(0, 0, 0, -1);
Quaternion result = a * b;
Assert.IsTrue(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() +
" instead of " + expected.ToString());
a = new Quaternion(1, 0, 0, 0);
b = new Quaternion(0, 1, 0, 0);
expected = new Quaternion(0, 0, 1, 0);
result = a * b;
Assert.IsTrue(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() +
" instead of " + expected.ToString());
a = new Quaternion(0, 0, 1, 0);
b = new Quaternion(0, 1, 0, 0);
expected = new Quaternion(-1, 0, 0, 0);
result = a * b;
Assert.IsTrue(result == expected, a.ToString() + " * " + b.ToString() + " produced " + result.ToString() +
" instead of " + expected.ToString());
}
//[Test]
//public void VectorQuaternionMath()
//{
// // Convert a vector to a quaternion and back
// Vector3 a = new Vector3(1f, 0.5f, 0.75f);
// Quaternion b = a.ToQuaternion();
// Vector3 c;
// b.GetEulerAngles(out c.X, out c.Y, out c.Z);
// Assert.IsTrue(a == c, c.ToString() + " does not equal " + a.ToString());
//}
[Test]
public void FloatsToTerseStrings()
{
float f = 1.20f;
string a = String.Empty;
string b = "1.2";
a = Helpers.FloatToTerseString(f);
Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b);
f = 24.00f;
b = "24";
a = Helpers.FloatToTerseString(f);
Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b);
f = -0.59f;
b = "-.59";
a = Helpers.FloatToTerseString(f);
Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b);
f = 0.59f;
b = ".59";
a = Helpers.FloatToTerseString(f);
Assert.IsTrue(a == b, f.ToString() + " converted to " + a + ", expecting " + b);
}
[Test]
public void BitUnpacking()
{
byte[] data = new byte[] { 0x80, 0x00, 0x0F, 0x50, 0x83, 0x7D };
BitPack bitpacker = new BitPack(data, 0);
int b = bitpacker.UnpackBits(1);
Assert.IsTrue(b == 1, "Unpacked " + b + " instead of 1");
b = bitpacker.UnpackBits(1);
Assert.IsTrue(b == 0, "Unpacked " + b + " instead of 0");
bitpacker = new BitPack(data, 2);
b = bitpacker.UnpackBits(4);
Assert.IsTrue(b == 0, "Unpacked " + b + " instead of 0");
b = bitpacker.UnpackBits(8);
Assert.IsTrue(b == 0xF5, "Unpacked " + b + " instead of 0xF5");
b = bitpacker.UnpackBits(4);
Assert.IsTrue(b == 0, "Unpacked " + b + " instead of 0");
b = bitpacker.UnpackBits(10);
Assert.IsTrue(b == 0x0183, "Unpacked " + b + " instead of 0x0183");
}
[Test]
public void BitPacking()
{
byte[] packedBytes = new byte[12];
BitPack bitpacker = new BitPack(packedBytes, 0);
bitpacker.PackBits(0x0ABBCCDD, 32);
bitpacker.PackBits(25, 5);
bitpacker.PackFloat(123.321f);
bitpacker.PackBits(1000, 16);
bitpacker = new BitPack(packedBytes, 0);
int b = bitpacker.UnpackBits(32);
Assert.IsTrue(b == 0x0ABBCCDD, "Unpacked " + b + " instead of 2864434397");
b = bitpacker.UnpackBits(5);
Assert.IsTrue(b == 25, "Unpacked " + b + " instead of 25");
float f = bitpacker.UnpackFloat();
Assert.IsTrue(f == 123.321f, "Unpacked " + f + " instead of 123.321");
b = bitpacker.UnpackBits(16);
Assert.IsTrue(b == 1000, "Unpacked " + b + " instead of 1000");
packedBytes = new byte[1];
bitpacker = new BitPack(packedBytes, 0);
bitpacker.PackBit(true);
bitpacker = new BitPack(packedBytes, 0);
b = bitpacker.UnpackBits(1);
Assert.IsTrue(b == 1, "Unpacked " + b + " instead of 1");
packedBytes = new byte[1] { Byte.MaxValue };
bitpacker = new BitPack(packedBytes, 0);
bitpacker.PackBit(false);
bitpacker = new BitPack(packedBytes, 0);
b = bitpacker.UnpackBits(1);
Assert.IsTrue(b == 0, "Unpacked " + b + " instead of 0");
}
[Test]
public void LLSDTerseParsing()
{
string testOne = "[r0.99967899999999998428,r-0.025334599999999998787,r0]";
string testTwo = "[[r1,r1,r1],r0]";
string testThree = "{'region_handle':[r255232, r256512], 'position':[r33.6, r33.71, r43.13], 'look_at':[r34.6, r33.71, r43.13]}";
OSD obj = OSDParser.DeserializeLLSDNotation(testOne);
Assert.IsInstanceOfType(typeof(OSDArray), obj, "Expected SDArray, got " + obj.GetType().ToString());
OSDArray array = (OSDArray)obj;
Assert.IsTrue(array.Count == 3, "Expected three contained objects, got " + array.Count);
Assert.IsTrue(array[0].AsReal() > 0.9d && array[0].AsReal() < 1.0d, "Unexpected value for first real " + array[0].AsReal());
Assert.IsTrue(array[1].AsReal() < 0.0d && array[1].AsReal() > -0.03d, "Unexpected value for second real " + array[1].AsReal());
Assert.IsTrue(array[2].AsReal() == 0.0d, "Unexpected value for third real " + array[2].AsReal());
obj = OSDParser.DeserializeLLSDNotation(testTwo);
Assert.IsInstanceOfType(typeof(OSDArray), obj, "Expected SDArray, got " + obj.GetType().ToString());
array = (OSDArray)obj;
Assert.IsTrue(array.Count == 2, "Expected two contained objects, got " + array.Count);
Assert.IsTrue(array[1].AsReal() == 0.0d, "Unexpected value for real " + array[1].AsReal());
obj = array[0];
Assert.IsInstanceOfType(typeof(OSDArray), obj, "Expected ArrayList, got " + obj.GetType().ToString());
array = (OSDArray)obj;
Assert.IsTrue(array[0].AsReal() == 1.0d && array[1].AsReal() == 1.0d && array[2].AsReal() == 1.0d,
"Unexpected value(s) for nested array: " + array[0].AsReal() + ", " + array[1].AsReal() + ", " +
array[2].AsReal());
obj = OSDParser.DeserializeLLSDNotation(testThree);
Assert.IsInstanceOfType(typeof(OSDMap), obj, "Expected LLSDMap, got " + obj.GetType().ToString());
OSDMap hashtable = (OSDMap)obj;
Assert.IsTrue(hashtable.Count == 3, "Expected three contained objects, got " + hashtable.Count);
Assert.IsInstanceOfType(typeof(OSDArray), hashtable["region_handle"]);
Assert.IsTrue(((OSDArray)hashtable["region_handle"]).Count == 2);
Assert.IsInstanceOfType(typeof(OSDArray), hashtable["position"]);
Assert.IsTrue(((OSDArray)hashtable["position"]).Count == 3);
Assert.IsInstanceOfType(typeof(OSDArray), hashtable["look_at"]);
Assert.IsTrue(((OSDArray)hashtable["look_at"]).Count == 3);
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.ProjectModel.Compilation;
using Microsoft.DotNet.ProjectModel.Graph;
using Microsoft.DotNet.ProjectModel.Resolution;
using Microsoft.DotNet.Tools.Test.Utilities;
using FluentAssertions;
using Xunit;
namespace Microsoft.DotNet.ProjectModel.Tests
{
public class LibraryExporterPackageTests
{
private const string PackagePath = "PackagePath";
private PackageDescription CreateDescription(LockFileTargetLibrary target = null, LockFilePackageLibrary package = null)
{
return new PackageDescription(PackagePath,
package ?? new LockFilePackageLibrary(),
target ?? new LockFileTargetLibrary(),
new List<LibraryRange>(), compatible: true, resolved: true);
}
[Fact]
public void ExportsPackageNativeLibraries()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
NativeLibraries = new List<LockFileItem>()
{
{ new LockFileItem() { Path = "lib/Native.so" } }
}
});
var result = ExportSingle(description);
result.NativeLibraryGroups.Should().HaveCount(1);
var libraryAsset = result.NativeLibraryGroups.GetDefaultAssets().First();
libraryAsset.Name.Should().Be("Native");
libraryAsset.Transform.Should().BeNull();
libraryAsset.RelativePath.Should().Be("lib/Native.so");
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "lib/Native.so"));
}
[Fact]
public void ExportsPackageCompilationAssebmlies()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
CompileTimeAssemblies = new List<LockFileItem>()
{
{ new LockFileItem() { Path = "ref/Native.dll" } }
}
});
var result = ExportSingle(description);
result.CompilationAssemblies.Should().HaveCount(1);
var libraryAsset = result.CompilationAssemblies.First();
libraryAsset.Name.Should().Be("Native");
libraryAsset.Transform.Should().BeNull();
libraryAsset.RelativePath.Should().Be("ref/Native.dll");
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "ref/Native.dll"));
}
[Fact]
public void ExportsPackageRuntimeAssebmlies()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
RuntimeAssemblies = new List<LockFileItem>()
{
{ new LockFileItem() { Path = "ref/Native.dll" } }
}
});
var result = ExportSingle(description);
result.RuntimeAssemblyGroups.Should().HaveCount(1);
var libraryAsset = result.RuntimeAssemblyGroups.GetDefaultAssets().First();
libraryAsset.Name.Should().Be("Native");
libraryAsset.Transform.Should().BeNull();
libraryAsset.RelativePath.Should().Be("ref/Native.dll");
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "ref/Native.dll"));
}
[Fact]
public void ExportsPackageRuntimeTargets()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
RuntimeTargets = new List<LockFileRuntimeTarget>()
{
new LockFileRuntimeTarget("native/native.dylib", "osx", "native"),
new LockFileRuntimeTarget("lib/Something.OSX.dll", "osx", "runtime")
}
});
var result = ExportSingle(description);
result.RuntimeAssemblyGroups.Should().HaveCount(2);
result.RuntimeAssemblyGroups.First(g => g.Runtime == string.Empty).Assets.Should().HaveCount(0);
result.RuntimeAssemblyGroups.First(g => g.Runtime == "osx").Assets.Should().HaveCount(1);
result.NativeLibraryGroups.Should().HaveCount(2);
result.NativeLibraryGroups.First(g => g.Runtime == string.Empty).Assets.Should().HaveCount(0);
result.NativeLibraryGroups.First(g => g.Runtime == "osx").Assets.Should().HaveCount(1);
var nativeAsset = result.NativeLibraryGroups.GetRuntimeAssets("osx").First();
nativeAsset.Name.Should().Be("native");
nativeAsset.Transform.Should().BeNull();
nativeAsset.RelativePath.Should().Be("native/native.dylib");
nativeAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "native/native.dylib"));
var runtimeAsset = result.RuntimeAssemblyGroups.GetRuntimeAssets("osx").First();
runtimeAsset.Name.Should().Be("Something.OSX");
runtimeAsset.Transform.Should().BeNull();
runtimeAsset.RelativePath.Should().Be("lib/Something.OSX.dll");
runtimeAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "lib/Something.OSX.dll"));
}
[Fact]
public void ExportsPackageResourceAssemblies()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
ResourceAssemblies = new List<LockFileItem>()
{
new LockFileItem("resources/en-US/Res.dll", new Dictionary<string, string>() { { "locale", "en-US"} }),
new LockFileItem("resources/ru-RU/Res.dll", new Dictionary<string, string>() { { "locale", "ru-RU" } }),
}
});
var result = ExportSingle(description);
result.ResourceAssemblies.Should().HaveCount(2);
var asset = result.ResourceAssemblies.Should().Contain(g => g.Locale == "en-US").Subject.Asset;
asset.Name.Should().Be("Res");
asset.Transform.Should().BeNull();
asset.RelativePath.Should().Be("resources/en-US/Res.dll");
asset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "resources/en-US/Res.dll"));
asset = result.ResourceAssemblies.Should().Contain(g => g.Locale == "ru-RU").Subject.Asset;
asset.Name.Should().Be("Res");
asset.Transform.Should().BeNull();
asset.RelativePath.Should().Be("resources/ru-RU/Res.dll");
asset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "resources/ru-RU/Res.dll"));
}
[Fact]
public void ExportsSources()
{
var description = CreateDescription(
package: new LockFilePackageLibrary()
{
Files = new List<string>()
{
Path.Combine("shared", "file.cs")
}
});
var result = ExportSingle(description);
result.SourceReferences.Should().HaveCount(1);
var libraryAsset = result.SourceReferences.First();
libraryAsset.Name.Should().Be("file");
libraryAsset.Transform.Should().BeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("shared", "file.cs"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "shared", "file.cs"));
}
[Fact]
public void ExportsCopyToOutputContentFiles()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
ContentFiles = new List<LockFileContentFile>()
{
new LockFileContentFile()
{
CopyToOutput = true,
Path = Path.Combine("content", "file.txt"),
OutputPath = Path.Combine("Out","Path.txt"),
PPOutputPath = "something"
}
}
});
var result = ExportSingle(description);
result.RuntimeAssets.Should().HaveCount(1);
var libraryAsset = result.RuntimeAssets.First();
libraryAsset.Transform.Should().NotBeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("Out", "Path.txt"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.txt"));
}
[Fact]
public void ExportsResourceContentFiles()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
ContentFiles = new List<LockFileContentFile>()
{
new LockFileContentFile()
{
BuildAction = BuildAction.EmbeddedResource,
Path = Path.Combine("content", "file.txt"),
PPOutputPath = "something"
}
}
});
var result = ExportSingle(description);
result.EmbeddedResources.Should().HaveCount(1);
var libraryAsset = result.EmbeddedResources.First();
libraryAsset.Transform.Should().NotBeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.txt"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.txt"));
}
[Fact]
public void ExportsCompileContentFiles()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
ContentFiles = new List<LockFileContentFile>()
{
new LockFileContentFile()
{
BuildAction = BuildAction.Compile,
Path = Path.Combine("content", "file.cs"),
PPOutputPath = "something"
}
}
});
var result = ExportSingle(description);
result.SourceReferences.Should().HaveCount(1);
var libraryAsset = result.SourceReferences.First();
libraryAsset.Transform.Should().NotBeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.cs"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.cs"));
}
[Fact]
public void SelectsContentFilesOfProjectCodeLanguage()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
ContentFiles = new List<LockFileContentFile>()
{
new LockFileContentFile()
{
BuildAction = BuildAction.Compile,
Path = Path.Combine("content", "file.cs"),
PPOutputPath = "something",
CodeLanguage = "cs"
},
new LockFileContentFile()
{
BuildAction = BuildAction.Compile,
Path = Path.Combine("content", "file.vb"),
PPOutputPath = "something",
CodeLanguage = "vb"
},
new LockFileContentFile()
{
BuildAction = BuildAction.Compile,
Path = Path.Combine("content", "file.any"),
PPOutputPath = "something",
}
}
});
var result = ExportSingle(description);
result.SourceReferences.Should().HaveCount(1);
var libraryAsset = result.SourceReferences.First();
libraryAsset.Transform.Should().NotBeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.cs"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.cs"));
}
[Fact]
public void SelectsContentFilesWithNoLanguageIfProjectLanguageNotMathed()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
ContentFiles = new List<LockFileContentFile>()
{
new LockFileContentFile()
{
BuildAction = BuildAction.Compile,
Path = Path.Combine("content", "file.vb"),
PPOutputPath = "something",
CodeLanguage = "vb"
},
new LockFileContentFile()
{
BuildAction = BuildAction.Compile,
Path = Path.Combine("content", "file.any"),
PPOutputPath = "something",
}
}
});
var result = ExportSingle(description);
result.SourceReferences.Should().HaveCount(1);
var libraryAsset = result.SourceReferences.First();
libraryAsset.Transform.Should().NotBeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.any"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.any"));
}
private LibraryExport ExportSingle(LibraryDescription description = null)
{
var rootProject = new Project()
{
Name = "RootProject",
_defaultCompilerOptions = new CommonCompilerOptions
{
CompilerName = "csc"
}
};
var rootProjectDescription = new ProjectDescription(
new LibraryRange(),
rootProject,
new LibraryRange[] { },
new TargetFrameworkInformation(),
true);
if (description == null)
{
description = rootProjectDescription;
}
else
{
description.Parents.Add(rootProjectDescription);
}
var libraryManager = new LibraryManager(new[] { description }, new DiagnosticMessage[] { }, "");
var allExports = new LibraryExporter(rootProjectDescription, libraryManager, "config", "runtime", null, "basepath", "solutionroot").GetAllExports();
var export = allExports.Single();
return export;
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.ComponentModel.Design;
using EnvDTE;
using EnvDTE80;
using Gallio.Runtime.Extensibility;
using Gallio.Runtime.Logging;
using Gallio.Runtime;
namespace Gallio.VisualStudio.Shell.Core
{
/// <summary>
/// Default implementation of the shell.
/// </summary>
public class DefaultShell : IShell
{
private readonly ComponentHandle<IShellExtension, ShellExtensionTraits>[] extensionHandles;
private readonly IRuntime runtime;
private readonly ShellHooks shellHooks;
private ShellPackage shellPackage;
private ShellAddInHandler shellAddInHandler;
private ILogger logger;
/// <summary>
/// Creates an uninitialized shell.
/// </summary>
/// <param name="extensionHandles">The array of shell extensions handles.</param>
/// <param name="runtime">The runtime.</param>
public DefaultShell(ComponentHandle<IShellExtension, ShellExtensionTraits>[] extensionHandles, IRuntime runtime)
{
this.extensionHandles = extensionHandles;
this.runtime = runtime;
shellHooks = new ShellHooks();
}
/// <inheritdoc />
public bool IsInitialized
{
get { return shellPackage != null; }
}
/// <inheritdoc />
public DTE2 DTE
{
get
{
ThrowIfNotInitialized();
return shellAddInHandler.DTE;
}
}
object IShell.DTE { get { return DTE; } }
/// <inheritdoc />
public ShellPackage ShellPackage
{
get
{
ThrowIfNotInitialized();
return shellPackage;
}
}
object IShell.ShellPackage { get { return ShellPackage; } }
/// <inheritdoc />
public AddIn ShellAddIn
{
get
{
ThrowIfNotInitialized();
return shellAddInHandler.AddIn;
}
}
object IShell.ShellAddIn { get { return ShellAddIn; } }
/// <inheritdoc />
public ShellAddInHandler ShellAddInHandler
{
get
{
ThrowIfNotInitialized();
return shellAddInHandler;
}
}
object IShell.ShellAddInHandler { get { return ShellAddInHandler; } }
/// <inheritdoc />
public ILogger Logger
{
get
{
ThrowIfNotInitialized();
return logger;
}
}
/// <inheritdoc />
public IServiceProvider VsServiceProvider
{
get
{
ThrowIfNotInitialized();
return shellPackage;
}
}
/// <summary>
/// Gets the Shell hooks with which to install handlers for Visual Studio events.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the Shell has not been initialized.</exception>
public ShellHooks ShellHooks
{
get
{
ThrowIfNotInitialized();
return shellHooks;
}
}
/// <inheritdoc />
public object GetVsService(Type serviceType)
{
ThrowIfNotInitialized();
return VsServiceProvider.GetService(serviceType);
}
/// <inheritdoc />
public T GetVsService<T>(Type serviceInterface)
{
return (T)GetVsService(serviceInterface);
}
/// <inheritdoc />
public void ProfferVsService(Type serviceType, ServiceFactory factory)
{
IServiceContainer container = GetVsService<IServiceContainer>(typeof(IServiceContainer));
if (container != null)
{
ServiceCreatorCallback callback = delegate {
try
{
return factory();
}
catch (Exception ex)
{
logger.Log(LogSeverity.Error,
string.Format("Failed to create service '{0}'.", serviceType),
ex);
throw;
}
};
container.AddService(serviceType, callback, true);
}
}
internal void Initialize(ShellPackage shellPackage, ShellAddInHandler shellAddInHandler)
{
if (IsInitialized)
Shutdown();
this.shellPackage = shellPackage;
this.shellAddInHandler = shellAddInHandler;
logger = new ShellLogger(shellPackage);
runtime.AddLogListener(logger);
foreach (var extensionHandle in extensionHandles)
{
try
{
extensionHandle.GetComponent().Initialize();
}
catch (Exception ex)
{
logger.Log(LogSeverity.Error,
string.Format("Failed to initialize shell extension '{0}'.", extensionHandle.Id),
ex);
}
}
}
internal void Shutdown()
{
try
{
if (IsInitialized)
{
foreach (var extensionHandle in extensionHandles)
{
try
{
extensionHandle.GetComponent().Shutdown();
}
catch (Exception ex)
{
logger.Log(LogSeverity.Error,
string.Format("Failed to shutdown shell extension '{0}'.", extensionHandle.Id),
ex);
}
}
}
}
finally
{
if (logger != null)
runtime.RemoveLogListener(logger);
logger = null;
shellPackage = null;
shellAddInHandler = null;
}
}
private void ThrowIfNotInitialized()
{
if (! IsInitialized)
throw new InvalidOperationException("The Shell has not been initialized.");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.Parser;
using DotVVM.Framework.Runtime;
namespace DotVVM.Framework.Controls.Bootstrap
{
public class GlyphIcon : HtmlGenericControl
{
public GlyphIcons Icon
{
get { return (GlyphIcons)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
}
public static readonly DotvvmProperty IconProperty =
DotvvmProperty.Register<GlyphIcons, GlyphIcon>(t => t.Icon, GlyphIcons.Empty);
public GlyphIcon() : base("span")
{
ResourceDependencies.Add(Constants.BootstrapResourceName);
}
protected override void AddAttributesToRender(IHtmlWriter writer, RenderContext context)
{
if (Icon != GlyphIcons.Empty)
{
var iconName = KnockoutHelper.ConvertToCamelCase(Icon.ToString().Replace("_", "-"));
writer.AddAttribute("class", "glyphicon glyphicon-" + iconName);
}
base.AddAttributesToRender(writer, context);
}
}
public enum GlyphIcons
{
Empty,
Asterisk,
Plus,
Euro,
Minus,
Cloud,
Envelope,
Pencil,
Glass,
Music,
Search,
Heart,
Star,
Star_empty,
User,
Film,
Th_large,
Th,
Th_list,
Ok,
Remove,
Zoom_in,
Zoom_out,
Off,
Signal,
Cog,
Trash,
Home,
File,
Time,
Road,
Download_alt,
Download,
Upload,
Inbox,
Play_circle,
Repeat,
Refresh,
List_alt,
Lock,
Flag,
Headphones,
Volume_off,
Volume_down,
Volume_up,
Qrcode,
Barcode,
Tag,
Tags,
Book,
Bookmark,
Print,
Camera,
Font,
Bold,
Italic,
Text_height,
Text_width,
Align_left,
Align_center,
Align_right,
Align_justify,
List,
Indent_left,
Indent_right,
Facetime_video,
Picture,
Map_marker,
Adjust,
Tint,
Edit,
Share,
Check,
Move,
Step_backward,
Fast_backward,
Backward,
Play,
Pause,
Stop,
Forward,
Fast_forward,
Step_forward,
Eject,
Chevron_left,
Chevron_right,
Plus_sign,
Minus_sign,
Remove_sign,
Ok_sign,
Question_sign,
Info_sign,
Screenshot,
Remove_circle,
Ok_circle,
Ban_circle,
Arrow_left,
Arrow_right,
Arrow_up,
Arrow_down,
Share_alt,
Resize_full,
Resize_small,
Exclamation_sign,
Gift,
Leaf,
Fire,
Eye_open,
Eye_close,
Warning_sign,
Plane,
Calendar,
Random,
Comment,
Magnet,
Chevron_up,
Chevron_down,
Retweet,
Shopping_cart,
Folder_close,
Folder_open,
Resize_vertical,
Resize_horizontal,
Hdd,
Bullhorn,
Bell,
Certificate,
Thumbs_up,
Thumbs_down,
Hand_right,
Hand_left,
Hand_up,
Hand_down,
Circle_arrow_right,
Circle_arrow_left,
Circle_arrow_up,
Circle_arrow_down,
Globe,
Wrench,
Tasks,
Filter,
Briefcase,
Fullscreen,
Dashboard,
Paperclip,
Heart_empty,
Link,
Phone,
Pushpin,
Usd,
Gbp,
Sort,
Sort_by_alphabet,
Sort_by_alphabet_alt,
Sort_by_order,
Sort_by_order_alt,
Sort_by_attributes,
Sort_by_attributes_alt,
Unchecked,
Expand,
Collapse_down,
Collapse_up,
Log_in,
Flash,
Log_out,
New_window,
Record,
Save,
Open,
Saved,
Import,
Export,
Send,
Floppy_disk,
Floppy_saved,
Floppy_remove,
Floppy_save,
Floppy_open,
Credit_card,
Transfer,
Cutlery,
Header,
Compressed,
Earphone,
Phone_alt,
Tower,
Stats,
Sd_video,
Hd_video,
Subtitles,
Sound_stereo,
Sound_dolby,
Sound_5_1,
Sound_6_1,
Sound_7_1,
Copyright_mark,
Registration_mark,
Cloud_download,
Cloud_upload,
Tree_conifer,
Tree_deciduous
}
}
| |
using System;
using Eto.Forms;
using Eto.Drawing;
using Eto.GtkSharp.Drawing;
using System.Collections.Generic;
using Eto.GtkSharp.Forms.Menu;
namespace Eto.GtkSharp.Forms.Controls
{
public class TreeViewHandler : GtkControl<Gtk.ScrolledWindow, TreeView, TreeView.ICallback>, TreeView.IHandler, IGtkListModelHandler<ITreeItem, ITreeStore>
{
GtkTreeModel<ITreeItem, ITreeStore> model;
CollectionHandler collection;
readonly Gtk.TreeView tree;
ContextMenu contextMenu;
bool cancelExpandCollapseEvents;
readonly Gtk.CellRendererText textCell;
public static Size MaxImageSize = new Size(16, 16);
public override Gtk.Widget EventControl
{
get { return tree; }
}
public class CollectionHandler : DataStoreChangedHandler<ITreeItem, ITreeStore>
{
WeakReference handler;
public TreeViewHandler Handler { get { return (TreeViewHandler)handler.Target; } set { handler = new WeakReference(value); } }
public void ExpandItems(ITreeStore store, Gtk.TreePath path)
{
Handler.cancelExpandCollapseEvents = true;
PerformExpandItems(store, path);
Handler.cancelExpandCollapseEvents = false;
}
void PerformExpandItems(ITreeStore store, Gtk.TreePath path)
{
if (store == null)
return;
var newpath = path.Copy();
newpath.AppendIndex(0);
for (int i = 0; i < store.Count; i++)
{
var item = store[i];
if (item.Expandable)
{
if (item.Expanded)
{
Handler.tree.ExpandToPath(newpath);
PerformExpandItems(item, newpath);
}
else
{
Handler.tree.CollapseRow(newpath);
}
}
newpath.Next();
}
}
public void ExpandItems()
{
var store = Handler.collection.Collection;
ExpandItems(store, new Gtk.TreePath());
}
public override void AddRange(IEnumerable<ITreeItem> items)
{
Handler.UpdateModel();
ExpandItems();
}
public override void AddItem(ITreeItem item)
{
var path = new Gtk.TreePath();
path.AppendIndex(Collection.Count);
var iter = Handler.model.GetIterFromItem(item, path);
Handler.tree.Model.EmitRowInserted(path, iter);
}
public override void InsertItem(int index, ITreeItem item)
{
var path = new Gtk.TreePath();
path.AppendIndex(index);
var iter = Handler.model.GetIterFromItem(item, path);
Handler.tree.Model.EmitRowInserted(path, iter);
}
public override void RemoveItem(int index)
{
var path = new Gtk.TreePath();
path.AppendIndex(index);
Handler.tree.Model.EmitRowDeleted(path);
}
public override void RemoveAllItems()
{
Handler.UpdateModel();
}
}
void UpdateModel()
{
model = new GtkTreeModel<ITreeItem, ITreeStore> { Handler = this };
tree.Model = new Gtk.TreeModelAdapter(model);
}
public TreeViewHandler()
{
tree = new Gtk.TreeView();
UpdateModel();
tree.HeadersVisible = false;
var col = new Gtk.TreeViewColumn();
var pbcell = new Gtk.CellRendererPixbuf();
col.PackStart(pbcell, false);
col.SetAttributes(pbcell, "pixbuf", 1);
textCell = new Gtk.CellRendererText();
col.PackStart(textCell, true);
col.SetAttributes(textCell, "text", 0);
tree.AppendColumn(col);
tree.ShowExpanders = true;
Control = new Gtk.ScrolledWindow();
Control.ShadowType = Gtk.ShadowType.In;
Control.Add(tree);
tree.Events |= Gdk.EventMask.ButtonPressMask;
}
protected override void Initialize()
{
base.Initialize();
tree.ButtonPressEvent += Connector.HandleTreeButtonPressEvent;
}
public override void AttachEvent(string id)
{
switch (id)
{
case TreeView.ExpandingEvent:
tree.TestExpandRow += Connector.HandleTestExpandRow;
break;
case TreeView.ExpandedEvent:
tree.RowExpanded += Connector.HandleRowExpanded;
break;
case TreeView.CollapsingEvent:
tree.TestCollapseRow += Connector.HandleTestCollapseRow;
break;
case TreeView.CollapsedEvent:
tree.RowCollapsed += Connector.HandleRowCollapsed;
break;
case TreeView.ActivatedEvent:
tree.RowActivated += Connector.HandleRowActivated;
break;
case TreeView.SelectionChangedEvent:
tree.Selection.Changed += Connector.HandleSelectionChanged;
break;
case TreeView.LabelEditingEvent:
textCell.EditingStarted += Connector.HandleEditingStarted;
break;
case TreeView.LabelEditedEvent:
textCell.Edited += Connector.HandleEdited;
break;
default:
base.AttachEvent(id);
break;
}
}
public object GetItem(Gtk.TreePath path)
{
return model.GetItemAtPath(path);
}
protected new TreeViewConnector Connector { get { return (TreeViewConnector)base.Connector; } }
protected override WeakConnector CreateConnector()
{
return new TreeViewConnector();
}
protected class TreeViewConnector : GtkControlConnector
{
public new TreeViewHandler Handler { get { return (TreeViewHandler)base.Handler; } }
public void HandleTestExpandRow(object o, Gtk.TestExpandRowArgs args)
{
var handler = Handler;
if (handler.cancelExpandCollapseEvents)
return;
var e = new TreeViewItemCancelEventArgs(handler.GetItem(args.Path) as ITreeItem);
handler.Callback.OnExpanding(handler.Widget, e);
args.RetVal = e.Cancel;
}
public void HandleTestCollapseRow(object o, Gtk.TestCollapseRowArgs args)
{
var handler = Handler;
if (handler.cancelExpandCollapseEvents)
return;
var e = new TreeViewItemCancelEventArgs(handler.GetItem(args.Path) as ITreeItem);
handler.Callback.OnCollapsing(handler.Widget, e);
args.RetVal = e.Cancel;
}
public void HandleRowExpanded(object o, Gtk.RowExpandedArgs args)
{
var handler = Handler;
if (handler.cancelExpandCollapseEvents)
return;
var item = handler.GetItem(args.Path) as ITreeItem;
if (item != null && !item.Expanded)
{
item.Expanded = true;
handler.collection.ExpandItems(item, args.Path);
handler.Callback.OnExpanded(handler.Widget, new TreeViewItemEventArgs(item));
}
}
public void HandleRowCollapsed(object o, Gtk.RowCollapsedArgs args)
{
var handler = Handler;
if (handler.cancelExpandCollapseEvents)
return;
var item = handler.GetItem(args.Path) as ITreeItem;
if (item != null && item.Expanded)
{
item.Expanded = false;
handler.Callback.OnCollapsed(handler.Widget, new TreeViewItemEventArgs(item));
}
}
public void HandleRowActivated(object o, Gtk.RowActivatedArgs args)
{
Handler.Callback.OnActivated(Handler.Widget, new TreeViewItemEventArgs(Handler.model.GetItemAtPath(args.Path)));
}
public void HandleSelectionChanged(object sender, EventArgs e)
{
Handler.Callback.OnSelectionChanged(Handler.Widget, EventArgs.Empty);
}
public void HandleEditingStarted(object o, Gtk.EditingStartedArgs args)
{
var handler = Handler;
var item = handler.model.GetItemAtPath(args.Path);
if (item != null)
{
var itemArgs = new TreeViewItemCancelEventArgs(item);
handler.Callback.OnLabelEditing(handler.Widget, itemArgs);
args.RetVal = itemArgs.Cancel;
}
}
public void HandleEdited(object o, Gtk.EditedArgs args)
{
var handler = Handler;
var item = handler.model.GetItemAtPath(args.Path);
if (item != null)
{
handler.Callback.OnLabelEdited(handler.Widget, new TreeViewItemEditEventArgs(item, args.NewText));
item.Text = args.NewText;
}
}
[GLib.ConnectBefore]
public void HandleTreeButtonPressEvent(object o, Gtk.ButtonPressEventArgs args)
{
var handler = Handler;
if (handler.contextMenu != null && args.Event.Button == 3 && args.Event.Type == Gdk.EventType.ButtonPress)
{
var menu = ((ContextMenuHandler)handler.contextMenu.Handler).Control;
menu.Popup();
menu.ShowAll();
}
}
}
public ITreeStore DataStore
{
get { return collection != null ? collection.Collection : null; }
set
{
if (collection != null)
collection.Unregister();
collection = new CollectionHandler { Handler = this };
collection.Register(value);
}
}
public ContextMenu ContextMenu
{
get { return contextMenu; }
set { contextMenu = value; }
}
public ITreeItem SelectedItem
{
get
{
Gtk.TreeIter iter;
if (tree.Selection.GetSelected(out iter))
{
return model.GetItemAtIter(iter);
}
return null;
}
set
{
if (value != null)
{
var path = model.GetPathFromItem(value);
if (path != null)
{
tree.ExpandToPath(path);
tree.Selection.SelectPath(path);
tree.ScrollToCell(path, null, false, 0, 0);
}
}
else
tree.Selection.UnselectAll();
}
}
public GLib.Value GetColumnValue(ITreeItem item, int column, int row)
{
switch (column)
{
case 0:
return new GLib.Value(item.Text);
case 1:
if (item.Image != null)
{
var image = item.Image.Handler as IGtkPixbuf;
if (image != null)
return new GLib.Value(image.GetPixbuf(MaxImageSize));
}
return new GLib.Value((Gdk.Pixbuf)null);
}
throw new InvalidOperationException();
}
public int NumberOfColumns
{
get { return 2; }
}
public int GetRowOfItem(ITreeItem item)
{
return collection != null ? collection.IndexOf(item) : -1;
}
public void RefreshData()
{
UpdateModel();
collection.ExpandItems();
}
public void RefreshItem(ITreeItem item)
{
var path = model.GetPathFromItem(item);
if (path != null && path.Depth > 0 && !object.ReferenceEquals(item, collection.Collection))
{
Gtk.TreeIter iter;
tree.Model.GetIter(out iter, path);
tree.Model.EmitRowChanged(path, iter);
tree.Model.EmitRowHasChildToggled(path, iter);
cancelExpandCollapseEvents = true;
if (item.Expanded)
{
tree.CollapseRow(path);
tree.ExpandRow(path, false);
collection.ExpandItems(item, path);
}
else
tree.CollapseRow(path);
cancelExpandCollapseEvents = false;
}
else
RefreshData();
}
public ITreeItem GetNodeAt(PointF point)
{
Gtk.TreePath path;
if (tree.GetPathAtPos((int)point.X, (int)point.Y, out path))
{
return model.GetItemAtPath(path);
}
return null;
}
public bool LabelEdit
{
get { return textCell.Editable; }
set { textCell.Editable = value; }
}
public Color TextColor
{
get { return textCell.ForegroundGdk.ToEto(); }
set { textCell.ForegroundGdk = value.ToGdk(); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace nullc_debugger_component
{
namespace DkmDebugger
{
enum NullcTypeIndex
{
Void,
Bool,
Char,
Short,
Int,
Long,
Float,
Double,
TypeId,
Function,
Nullptr,
Generic,
Auto,
AutoRef,
VoidRef,
AutoArray,
}
enum NullcTypeCategory
{
Complex,
Void,
Int,
Float,
Long,
Double,
Short,
Char
};
enum NullcTypeSubCategory
{
None,
Array,
Pointer,
Function,
Class
};
enum NullcTypeFlags
{
HasFinalizer = 1 << 0,
DependsOnGeneric = 1 << 1,
IsExtendable = 1 << 2,
Internal = 1 << 3
}
class NullcTypeInfo
{
public string name;
public NullcTypeInfo nullcSubType;
public List<NullcMemberInfo> nullcMembers = new List<NullcMemberInfo>();
public List<NullcConstantInfo> nullcConstants = new List<NullcConstantInfo>();
public NullcTypeInfo nullcBaseType;
public NullcTypeIndex index;
public uint offsetToName;
public uint size;
public uint padding;
public NullcTypeCategory typeCategory;
public NullcTypeSubCategory subCat;
public byte defaultAlign;
public NullcTypeFlags typeFlags;
public ushort pointerCount;
public int arrSize;
public int memberCount;
public int constantCount;
public int constantOffset;
public int subType;
public int memberOffset;
public uint nameHash;
public uint definitionModule; // Index of the module containing the definition
public uint definitionLocationStart;
public uint definitionLocationEnd;
public uint definitionLocationName;
// For generic types
public uint definitionOffsetStart; // Offset in a lexeme stream to the point of class definition start
public uint definitionOffset; // Offset in a lexeme stream to the point of type argument list
public uint genericTypeCount;
public uint namespaceHash;
public int baseType;
public void ReadFrom(BinaryReader reader)
{
offsetToName = reader.ReadUInt32();
size = reader.ReadUInt32();
padding = reader.ReadUInt32();
typeCategory = (NullcTypeCategory)reader.ReadUInt32();
subCat = (NullcTypeSubCategory)reader.ReadUInt32();
defaultAlign = reader.ReadByte();
typeFlags = (NullcTypeFlags)reader.ReadByte();
pointerCount = reader.ReadUInt16();
arrSize = reader.ReadInt32();
memberCount = arrSize;
constantCount = reader.ReadInt32();
constantOffset = reader.ReadInt32();
subType = reader.ReadInt32();
memberOffset = subType;
nameHash = reader.ReadUInt32();
definitionModule = reader.ReadUInt32();
definitionLocationStart = reader.ReadUInt32();
definitionLocationEnd = reader.ReadUInt32();
definitionLocationName = reader.ReadUInt32();
definitionOffsetStart = reader.ReadUInt32();
definitionOffset = reader.ReadUInt32();
genericTypeCount = reader.ReadUInt32();
namespaceHash = reader.ReadUInt32();
baseType = reader.ReadInt32();
}
}
class NullcMemberInfo
{
public NullcTypeInfo nullcType;
public string name;
public uint type;
public uint alignment;
public uint offset;
public void ReadFrom(BinaryReader reader)
{
type = reader.ReadUInt32();
alignment = reader.ReadUInt32();
offset = reader.ReadUInt32();
}
}
class NullcConstantInfo
{
public NullcTypeInfo nullcType;
public string name;
public uint type;
public long value;
public void ReadFrom(BinaryReader reader)
{
type = reader.ReadUInt32();
value = reader.ReadInt64();
}
}
class NullcVarInfo
{
public string name;
public NullcTypeInfo nullcType;
public uint offsetToName;
public uint nameHash;
public uint type; // index in type array
public uint offset;
public void ReadFrom(BinaryReader reader)
{
offsetToName = reader.ReadUInt32();
nameHash = reader.ReadUInt32();
type = reader.ReadUInt32();
offset = reader.ReadUInt32();
}
}
class NullcFuncInfo
{
public string name;
public List<NullcLocalInfo> arguments = new List<NullcLocalInfo>();
public List<NullcLocalInfo> locals = new List<NullcLocalInfo>();
public List<NullcLocalInfo> externs = new List<NullcLocalInfo>();
public NullcTypeInfo nullcFunctionType;
public NullcTypeInfo nullcParentType;
public NullcTypeInfo nullcContextType;
public uint offsetToName;
public uint regVmAddress;
public uint regVmCodeSize;
public uint regVmRegisters;
public uint builtinIndex;
public uint attributes;
public uint isVisible;
public ulong funcPtrRaw;
public ulong funcPtrWrapTarget;
public ulong funcPtrWrap;
public byte retType; // one of the ReturnType enumeration values
public byte funcCat;
public byte isGenericInstance;
public byte isOperator;
public byte returnShift; // Amount of dwords to remove for result type after raw external function call
public uint returnSize; // Return size of the wrapped external function call
public int funcType; // index to the type array
public uint startInByteCode;
public int parentType; // Type inside which the function is defined
public int contextType; // Type of the function context
public int offsetToFirstLocal;
public int paramCount;
public int localCount;
public int externCount;
public uint namespaceHash;
public int bytesToPop; // Arguments size
public int stackSize; // Including arguments
// For generic functions
public uint genericOffsetStart; // Position in the lexeme stream of the definition
public uint genericOffset;
public uint genericReturnType;
// Size of the explicit type list for generic functions and generic function instances
public uint explicitTypeCount;
public uint nameHash;
public uint definitionModule; // Index of the module containing the definition
public uint definitionLocationModule;
public uint definitionLocationStart;
public uint definitionLocationEnd;
public uint definitionLocationName;
public void ReadFrom(BinaryReader reader)
{
offsetToName = reader.ReadUInt32();
regVmAddress = reader.ReadUInt32();
regVmCodeSize = reader.ReadUInt32();
regVmRegisters = reader.ReadUInt32();
builtinIndex = reader.ReadUInt32();
attributes = reader.ReadUInt32();
isVisible = reader.ReadUInt32();
funcPtrRaw = reader.ReadUInt64();
funcPtrWrapTarget = reader.ReadUInt64();
funcPtrWrap = reader.ReadUInt64();
retType = reader.ReadByte();
funcCat = reader.ReadByte();
isGenericInstance = reader.ReadByte();
isOperator = reader.ReadByte();
returnShift = reader.ReadByte();
reader.ReadBytes(3); // Padding
returnSize = reader.ReadUInt32();
funcType = reader.ReadInt32();
startInByteCode = reader.ReadUInt32();
parentType = reader.ReadInt32();
contextType = reader.ReadInt32();
offsetToFirstLocal = reader.ReadInt32();
paramCount = reader.ReadInt32();
localCount = reader.ReadInt32();
externCount = reader.ReadInt32();
namespaceHash = reader.ReadUInt32();
bytesToPop = reader.ReadInt32();
stackSize = reader.ReadInt32();
genericOffsetStart = reader.ReadUInt32();
genericOffset = reader.ReadUInt32();
genericReturnType = reader.ReadUInt32();
explicitTypeCount = reader.ReadUInt32();
nameHash = reader.ReadUInt32();
definitionModule = reader.ReadUInt32();
definitionLocationModule = reader.ReadUInt32();
definitionLocationStart = reader.ReadUInt32();
definitionLocationEnd = reader.ReadUInt32();
definitionLocationName = reader.ReadUInt32();
}
}
enum NullcLocalType
{
Parameter,
Local,
External,
}
class NullcLocalInfo
{
public string name;
public NullcTypeInfo nullcType;
public NullcLocalType paramType;
public byte paramFlags;
public ushort defaultFuncId;
public uint type;
public uint size;
public uint offset;
public uint closeListID;
public uint alignmentLog2; // 1 << value
public uint offsetToName;
public void ReadFrom(BinaryReader reader)
{
paramType = (NullcLocalType)reader.ReadByte();
paramFlags = reader.ReadByte();
defaultFuncId = reader.ReadUInt16();
type = reader.ReadUInt32();
size = reader.ReadUInt32();
offset = reader.ReadUInt32();
closeListID = reader.ReadUInt32();
alignmentLog2 = reader.ReadUInt32();
offsetToName = reader.ReadUInt32();
}
}
class NullcModuleInfo
{
public string name;
public uint nameHash;
public uint nameOffset;
public uint funcStart;
public uint funcCount;
public uint variableOffset;
public int sourceOffset;
public int sourceSize;
public void ReadFrom(BinaryReader reader)
{
nameHash = reader.ReadUInt32();
nameOffset = reader.ReadUInt32();
funcStart = reader.ReadUInt32();
funcCount = reader.ReadUInt32();
variableOffset = reader.ReadUInt32();
sourceOffset = reader.ReadInt32();
sourceSize = reader.ReadInt32();
}
}
enum NullcInstructionCode
{
rviNop,
rviLoadByte,
rviLoadWord,
rviLoadDword,
rviLoadLong,
rviLoadFloat,
rviLoadDouble,
rviLoadImm,
rviStoreByte,
rviStoreWord,
rviStoreDword,
rviStoreLong,
rviStoreFloat,
rviStoreDouble,
rviCombinedd,
rviBreakupdd,
rviMov,
rviMovMult,
rviDtoi,
rviDtol,
rviDtof,
rviItod,
rviLtod,
rviItol,
rviLtoi,
rviIndex,
rviGetAddr,
rviSetRange,
rviMemCopy,
rviJmp,
rviJmpz,
rviJmpnz,
rviCall,
rviCallPtr,
rviReturn,
rviAddImm,
rviAdd,
rviSub,
rviMul,
rviDiv,
rviPow,
rviMod,
rviLess,
rviGreater,
rviLequal,
rviGequal,
rviEqual,
rviNequal,
rviShl,
rviShr,
rviBitAnd,
rviBitOr,
rviBitXor,
rviAddImml,
rviAddl,
rviSubl,
rviMull,
rviDivl,
rviPowl,
rviModl,
rviLessl,
rviGreaterl,
rviLequall,
rviGequall,
rviEquall,
rviNequall,
rviShll,
rviShrl,
rviBitAndl,
rviBitOrl,
rviBitXorl,
rviAddd,
rviSubd,
rviMuld,
rviDivd,
rviAddf,
rviSubf,
rviMulf,
rviDivf,
rviPowd,
rviModd,
rviLessd,
rviGreaterd,
rviLequald,
rviGequald,
rviEquald,
rviNequald,
rviNeg,
rviNegl,
rviNegd,
rviBitNot,
rviBitNotl,
rviLogNot,
rviLogNotl,
rviConvertPtr,
// Temporary instructions, no execution
rviFuncAddr,
rviTypeid,
};
class NullcInstruction
{
public NullcInstructionCode code;
public byte rA;
public byte rB;
public byte rC;
public uint argument;
public void ReadFrom(BinaryReader reader)
{
code = (NullcInstructionCode)reader.ReadByte();
rA = reader.ReadByte();
rB = reader.ReadByte();
rC = reader.ReadByte();
argument = reader.ReadUInt32();
}
}
class NullcSourceInfo
{
public uint instruction;
public uint definitionModule; // Index of the module containing the definition
public int sourceOffset;
public void ReadFrom(BinaryReader reader)
{
instruction = reader.ReadUInt32();
definitionModule = reader.ReadUInt32();
sourceOffset = reader.ReadInt32();
}
}
class NullcBytecode
{
public List<NullcTypeInfo> types;
public List<NullcMemberInfo> typeMembers;
public List<NullcConstantInfo> typeConstants;
public List<NullcVarInfo> variables;
public List<NullcFuncInfo> functions;
public uint[] functionExplicitTypeArrayOffsets;
public uint[] functionExplicitTypes;
public List<NullcLocalInfo> locals;
public List<NullcModuleInfo> modules;
public char[] symbols;
public char[] source;
public uint[] dependencies;
public string[] importPaths;
public string mainModuleName;
public List<NullcInstruction> instructions;
public List<NullcSourceInfo> sourceInfo;
public uint[] constants;
public ulong[] instructionPositions;
public int globalVariableSize = 0;
internal List<T> InitList<T>(int size) where T : new()
{
List<T> array = new List<T>();
for (int i = 0; i < size; i++)
{
array.Add(new T());
}
return array;
}
public void ReadFrom(byte[] data, bool is64Bit)
{
char[] rawImportPaths;
using (var stream = new MemoryStream(data))
{
using (var reader = new BinaryReader(stream))
{
types = InitList<NullcTypeInfo>(reader.ReadInt32());
int typeIndex = 0;
foreach (var el in types)
{
el.index = (NullcTypeIndex)typeIndex++;
el.ReadFrom(reader);
}
typeMembers = InitList<NullcMemberInfo>(reader.ReadInt32());
foreach (var el in typeMembers)
{
el.ReadFrom(reader);
}
typeConstants = InitList<NullcConstantInfo>(reader.ReadInt32());
foreach (var el in typeConstants)
{
el.ReadFrom(reader);
}
variables = InitList<NullcVarInfo>(reader.ReadInt32());
foreach (var el in variables)
{
el.ReadFrom(reader);
}
functions = InitList<NullcFuncInfo>(reader.ReadInt32());
foreach (var el in functions)
{
el.ReadFrom(reader);
}
functionExplicitTypeArrayOffsets = new uint[reader.ReadInt32()];
for (var i = 0; i < functionExplicitTypeArrayOffsets.Length; i++)
{
functionExplicitTypeArrayOffsets[i] = reader.ReadUInt32();
}
functionExplicitTypes = new uint[reader.ReadInt32()];
for (var i = 0; i < functionExplicitTypes.Length; i++)
{
functionExplicitTypes[i] = reader.ReadUInt32();
}
locals = InitList<NullcLocalInfo>(reader.ReadInt32());
foreach (var el in locals)
{
el.ReadFrom(reader);
}
modules = InitList<NullcModuleInfo>(reader.ReadInt32());
foreach (var el in modules)
{
el.ReadFrom(reader);
}
symbols = reader.ReadChars(reader.ReadInt32());
source = reader.ReadChars(reader.ReadInt32());
dependencies = new uint[reader.ReadInt32()];
for (var i = 0; i < dependencies.Length; i++)
{
dependencies[i] = reader.ReadUInt32();
}
rawImportPaths = reader.ReadChars(reader.ReadInt32());
mainModuleName = new string(reader.ReadChars(reader.ReadInt32()));
instructions = InitList<NullcInstruction>(reader.ReadInt32());
foreach (var el in instructions)
{
el.ReadFrom(reader);
}
sourceInfo = InitList<NullcSourceInfo>(reader.ReadInt32());
foreach (var el in sourceInfo)
{
el.ReadFrom(reader);
}
constants = new uint[reader.ReadInt32()];
for (var i = 0; i < constants.Length; i++)
{
constants[i] = reader.ReadUInt32();
}
instructionPositions = new ulong[reader.ReadInt32()];
for (var i = 0; i < instructionPositions.Length; i++)
{
instructionPositions[i] = is64Bit ? reader.ReadUInt64() : (ulong)reader.ReadUInt32();
}
globalVariableSize = reader.ReadInt32();
}
}
// Finalize
foreach (var el in types)
{
var ending = Array.FindIndex(symbols, (int)el.offsetToName, (x) => x == 0);
el.name = new string(symbols, (int)el.offsetToName, ending - (int)el.offsetToName);
if (el.subCat == NullcTypeSubCategory.Array || el.subCat == NullcTypeSubCategory.Pointer)
{
el.nullcSubType = el.subType == 0 ? null : types[el.subType];
}
if (el.subCat == NullcTypeSubCategory.Function || el.subCat == NullcTypeSubCategory.Class)
{
uint memberNameOffset = el.offsetToName + (uint)el.name.Length + 1;
// One extra member for function return type
for (int i = 0; i < el.memberCount + (el.subCat == NullcTypeSubCategory.Function ? 1 : 0); i++)
{
var member = typeMembers[el.memberOffset + i];
member.name = new string(symbols, (int)memberNameOffset, Array.FindIndex(symbols, (int)memberNameOffset, (x) => x == 0) - (int)memberNameOffset);
memberNameOffset = memberNameOffset + (uint)member.name.Length + 1;
el.nullcMembers.Add(member);
}
for (int i = 0; i < el.constantCount; i++)
{
var constant = typeConstants[el.constantOffset + i];
constant.name = new string(symbols, (int)memberNameOffset, Array.FindIndex(symbols, (int)memberNameOffset, (x) => x == 0) - (int)memberNameOffset);
memberNameOffset = memberNameOffset + (uint)constant.name.Length + 1;
el.nullcConstants.Add(constant);
}
}
el.nullcBaseType = el.baseType == 0 ? null : types[el.baseType];
}
foreach (var el in typeMembers)
{
el.nullcType = types[(int)el.type];
}
foreach (var el in typeConstants)
{
el.nullcType = types[(int)el.type];
}
foreach (var el in variables)
{
var ending = Array.FindIndex(symbols, (int)el.offsetToName, (x) => x == 0);
el.name = new string(symbols, (int)el.offsetToName, ending - (int)el.offsetToName);
el.nullcType = types[(int)el.type];
}
foreach (var el in functions)
{
var ending = Array.FindIndex(symbols, (int)el.offsetToName, (x) => x == 0);
el.name = new string(symbols, (int)el.offsetToName, ending - (int)el.offsetToName);
for (int i = 0; i < el.localCount + el.externCount; i++)
{
var local = locals[el.offsetToFirstLocal + i];
switch (local.paramType)
{
case NullcLocalType.Parameter:
el.arguments.Add(local);
break;
case NullcLocalType.Local:
el.locals.Add(local);
break;
case NullcLocalType.External:
el.externs.Add(local);
break;
}
}
el.nullcFunctionType = types[el.funcType];
el.nullcParentType = el.parentType == -1 ? null : types[el.parentType];
el.nullcContextType = el.contextType == 0 ? null : types[el.contextType];
}
foreach (var el in locals)
{
var ending = Array.FindIndex(symbols, (int)el.offsetToName, (x) => x == 0);
el.name = new string(symbols, (int)el.offsetToName, ending - (int)el.offsetToName);
el.nullcType = types[(int)el.type];
}
foreach (var el in modules)
{
var ending = Array.FindIndex(symbols, (int)el.nameOffset, (x) => x == 0);
el.name = new string(symbols, (int)el.nameOffset, ending - (int)el.nameOffset);
}
importPaths = (new string(rawImportPaths)).Split(';');
}
public int ConvertNativeAddressToInstruction(ulong address)
{
int lowerBound = 0;
int upperBound = instructionPositions.Length - 1;
int index = 0;
while (lowerBound <= upperBound)
{
index = (lowerBound + upperBound) >> 1;
if (address < instructionPositions[index])
{
upperBound = index - 1;
}
else if (address > instructionPositions[index])
{
lowerBound = index + 1;
}
else
{
break;
}
}
if (index != 0 && address < instructionPositions[index])
{
index--;
}
if (index == instructionPositions.Length - 1 && address > instructionPositions[index])
{
return 0;
}
return index;
}
public ulong ConvertInstructionToNativeAddress(int instruction)
{
return instructionPositions[instruction];
}
public NullcFuncInfo GetFunctionAtAddress(int instruction)
{
for (int i = 0; i < functions.Count; i++)
{
var function = functions[i];
if (instruction >= function.regVmAddress && instruction < (function.regVmAddress + function.regVmCodeSize))
{
return function;
}
}
return null;
}
public NullcFuncInfo GetFunctionAtNativeAddress(ulong address)
{
return GetFunctionAtAddress(ConvertNativeAddressToInstruction(address));
}
public int GetInstructionSourceLocation(int instruction)
{
Debug.Assert(instruction > 0);
for (int i = 0; i < sourceInfo.Count; i++)
{
if (instruction == sourceInfo[i].instruction)
{
return sourceInfo[i].sourceOffset;
}
if (i + 1 < sourceInfo.Count && instruction < sourceInfo[i + 1].instruction)
{
return sourceInfo[i].sourceOffset;
}
}
return sourceInfo[sourceInfo.Count - 1].sourceOffset;
}
public int GetSourceLocationModuleIndex(int sourceLocation)
{
Debug.Assert(sourceLocation != -1);
for (int i = 0; i < modules.Count; i++)
{
var moduleInfo = modules[i];
int start = moduleInfo.sourceOffset;
int end = start + moduleInfo.sourceSize;
if (sourceLocation >= start && sourceLocation < end)
{
return i;
}
}
return -1;
}
public int GetSourceLocationLineAndColumn(int sourceLocation, int moduleIndex, out int column)
{
Debug.Assert(sourceLocation != -1);
var moduleCount = modules.Count;
int sourceStart = moduleIndex != -1 ? modules[moduleIndex].sourceOffset : modules[moduleCount - 1].sourceOffset + modules[moduleCount - 1].sourceSize;
int line = 0;
int pos = sourceStart;
int lastLineStart = pos;
while (pos < sourceLocation)
{
if (source[pos] == '\r')
{
line++;
pos++;
if (source[pos] == '\n')
{
pos++;
}
lastLineStart = pos;
}
else if (source[pos] == '\n')
{
line++;
pos++;
lastLineStart = pos;
}
else
{
pos++;
}
}
column = pos - lastLineStart + 1;
return line + 1;
}
public int GetInstructionSourceLocationLine(int instruction, out int moduleIndex)
{
int sourceLocation = GetInstructionSourceLocation(instruction);
moduleIndex = GetSourceLocationModuleIndex(sourceLocation);
return GetSourceLocationLineAndColumn(sourceLocation, moduleIndex, out _);
}
int GetLineStartOffset(int moduleSourceCodeOffset, int line)
{
int start = moduleSourceCodeOffset;
int startLine = 0;
while (source[start] != 0 && startLine < line)
{
if (source[start] == '\r')
{
start++;
if (source[start] == '\n')
{
start++;
}
startLine++;
}
else if (source[start] == '\n')
{
start++;
startLine++;
}
else
{
start++;
}
}
return start;
}
int GetLineEndOffset(int lineStartOffset)
{
int pos = lineStartOffset;
while (source[pos] != 0)
{
if (source[pos] == '\r')
{
return pos;
}
if (source[pos] == '\n')
{
return pos;
}
pos++;
}
return pos;
}
int ConvertLinePositionRangeToInstruction(int lineStartOffset, int lineEndOffset)
{
// Find instruction
for (int i = 0; i < sourceInfo.Count; i++)
{
if (sourceInfo[i].sourceOffset >= lineStartOffset && sourceInfo[i].sourceOffset <= lineEndOffset)
{
return (int)sourceInfo[i].instruction;
}
}
return 0;
}
public int ConvertLineToInstruction(int moduleSourceCodeOffset, int line)
{
int lineStartOffset = GetLineStartOffset(moduleSourceCodeOffset, line);
if (lineStartOffset == 0)
{
return 0;
}
int lineEndOffset = GetLineEndOffset(lineStartOffset);
return ConvertLinePositionRangeToInstruction(lineStartOffset, lineEndOffset);
}
public int GetModuleSourceLocation(int moduleIndex)
{
Debug.Assert(moduleIndex >= -1 && moduleIndex < modules.Count);
if (moduleIndex == -1)
{
return modules.Last().sourceOffset + modules.Last().sourceSize;
}
if (moduleIndex < modules.Count)
{
return modules[moduleIndex].sourceOffset;
}
return -1;
}
}
}
}
| |
using System;
using System.Xml.Linq;
namespace Alchemy4Tridion.Plugins.Clients.CoreService
{
public interface ISessionAwareCoreServiceBase
{
SchemaData GetVirtualFolderTypeSchema(string namespaceUri);
IAsyncResult BeginGetVirtualFolderTypeSchema(string namespaceUri, AsyncCallback callback, object asyncState);
SchemaData EndGetVirtualFolderTypeSchema(IAsyncResult result);
TridionEnumValue[] GetEnumValues(string type);
IAsyncResult BeginGetEnumValues(string type, AsyncCallback callback, object asyncState);
TridionEnumValue[] EndGetEnumValues(IAsyncResult result);
BundleTypeData[] ResolveBundleTypes(string[] itemIds, bool pruneTree);
IAsyncResult BeginResolveBundleTypes(string[] itemIds, bool pruneTree, AsyncCallback callback, object asyncState);
BundleTypeData[] EndResolveBundleTypes(IAsyncResult result);
KeywordData CopyToKeyword(string sourceKeywordId, string destinationId, ReadOptions readBackOptions);
IAsyncResult BeginCopyToKeyword(string sourceKeywordId, string destinationId, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
KeywordData EndCopyToKeyword(IAsyncResult result);
KeywordData MoveToKeyword(string sourceKeywordId, string destinationId, ReadOptions readBackOptions);
IAsyncResult BeginMoveToKeyword(string sourceKeywordId, string destinationId, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
KeywordData EndMoveToKeyword(IAsyncResult result);
TridionLanguageInfo[] GetTridionLanguages();
IAsyncResult BeginGetTridionLanguages(AsyncCallback callback, object asyncState);
TridionLanguageInfo[] EndGetTridionLanguages(IAsyncResult result);
WorkflowScriptType[] GetListWorkflowScriptTypes();
IAsyncResult BeginGetListWorkflowScriptTypes(AsyncCallback callback, object asyncState);
WorkflowScriptType[] EndGetListWorkflowScriptTypes(IAsyncResult result);
WorkItemData[] AddToWorkflow(string[] subjectIds, string activityInstanceId, ReadOptions readBackOptions);
IAsyncResult BeginAddToWorkflow(string[] subjectIds, string activityInstanceId, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
WorkItemData[] EndAddToWorkflow(IAsyncResult result);
WorkItemData[] RemoveFromWorkflow(string[] subjectIds, ReadOptions readBackOptions);
IAsyncResult BeginRemoveFromWorkflow(string[] subjectIds, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
WorkItemData[] EndRemoveFromWorkflow(IAsyncResult result);
OrganizationalItemData Lock(string organizationalItemId, ReadOptions readBackOptions);
IAsyncResult BeginLock(string organizationalItemId, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
OrganizationalItemData EndLock(IAsyncResult result);
OrganizationalItemData Unlock(string organizationalItemId, ReadOptions readBackOptions);
IAsyncResult BeginUnlock(string organizationalItemId, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
OrganizationalItemData EndUnlock(IAsyncResult result);
ProcessInstanceData StartWorkflow(string repositoryId, StartWorkflowInstructionData instruction, ReadOptions readBackOptions);
IAsyncResult BeginStartWorkflow(string repositoryId, StartWorkflowInstructionData instruction, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
ProcessInstanceData EndStartWorkflow(IAsyncResult result);
PublishTransactionData UndoPublishTransaction(string publishTransactionId, QueueMessagePriority? priority, ReadOptions readBackOptions);
IAsyncResult BeginUndoPublishTransaction(string publishTransactionId, QueueMessagePriority? priority, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
PublishTransactionData EndUndoPublishTransaction(IAsyncResult result);
ProcessDefinitionAssociationDictionary GetProcessDefinitionsForItems(string[] itemIds, ProcessDefinitionType processDefinitionType);
IAsyncResult BeginGetProcessDefinitionsForItems(string[] itemIds, ProcessDefinitionType processDefinitionType, AsyncCallback callback, object asyncState);
ProcessDefinitionAssociationDictionary EndGetProcessDefinitionsForItems(IAsyncResult result);
string GetSystemXsd(string filename);
IAsyncResult BeginGetSystemXsd(string filename, AsyncCallback callback, object asyncState);
string EndGetSystemXsd(IAsyncResult result);
LinkToSchemaData[] GetSchemasByNamespaceUri(string repositoryId, string namespaceUri, string rootElementName);
IAsyncResult BeginGetSchemasByNamespaceUri(string repositoryId, string namespaceUri, string rootElementName, AsyncCallback callback, object asyncState);
LinkToSchemaData[] EndGetSchemasByNamespaceUri(IAsyncResult result);
ValidationErrorData[] Validate(IdentifiableObjectData deltaData);
IAsyncResult BeginValidate(IdentifiableObjectData deltaData, AsyncCallback callback, object asyncState);
ValidationErrorData[] EndValidate(IAsyncResult result);
BinaryContentData GetExternalBinaryContentData(string uri);
IAsyncResult BeginGetExternalBinaryContentData(string uri, AsyncCallback callback, object asyncState);
BinaryContentData EndGetExternalBinaryContentData(IAsyncResult result);
SynchronizationResult SynchronizeWithSchema(IdentifiableObjectData dataObject, SynchronizeOptions synchronizeOptions);
IAsyncResult BeginSynchronizeWithSchema(IdentifiableObjectData dataObject, SynchronizeOptions synchronizeOptions, AsyncCallback callback, object asyncState);
SynchronizationResult EndSynchronizeWithSchema(IAsyncResult result);
SynchronizationResult SynchronizeWithSchemaAndUpdate(string itemId, SynchronizeOptions synchronizeOptions);
IAsyncResult BeginSynchronizeWithSchemaAndUpdate(string itemId, SynchronizeOptions synchronizeOptions, AsyncCallback callback, object asyncState);
SynchronizationResult EndSynchronizeWithSchemaAndUpdate(IAsyncResult result);
void DecommissionPublicationTarget(string publicationTargetId);
IAsyncResult BeginDecommissionPublicationTarget(string publicationTargetId, AsyncCallback callback, object asyncState);
void EndDecommissionPublicationTarget(IAsyncResult result);
SchemaFieldsData ConvertXsdToSchemaFields(XElement xsd, SchemaPurpose purpose, string rootElementName, ReadOptions readOptions);
IAsyncResult BeginConvertXsdToSchemaFields(XElement xsd, SchemaPurpose purpose, string rootElementName, ReadOptions readOptions, AsyncCallback callback, object asyncState);
SchemaFieldsData EndConvertXsdToSchemaFields(IAsyncResult result);
string GetPublishUrl(string id, string targetTypeIdOrPurpose);
IAsyncResult BeginGetPublishUrl(string id, string targetTypeIdOrPurpose, AsyncCallback callback, object asyncState);
string EndGetPublishUrl(IAsyncResult result);
LinkToBusinessProcessTypeData[] GetBusinessProcessTypes(string cdTopologyTypeId);
IAsyncResult BeginGetBusinessProcessTypes(string cdTopologyTypeId, AsyncCallback callback, object asyncState);
LinkToBusinessProcessTypeData[] EndGetBusinessProcessTypes(IAsyncResult result);
PublishSourceData GetPublishSourceByUrl(string url);
IAsyncResult BeginGetPublishSourceByUrl(string url, AsyncCallback callback, object asyncState);
PublishSourceData EndGetPublishSourceByUrl(IAsyncResult result);
void RemovePublishStates(string publicationId, string targetTypeIdOrPurpose);
IAsyncResult BeginRemovePublishStates(string publicationId, string targetTypeIdOrPurpose, AsyncCallback callback, object asyncState);
void EndRemovePublishStates(IAsyncResult result);
ContainingPagesDictionary ResolveContainingPages(string componentId, ResolveContainingPagesInstructionData instruction);
IAsyncResult BeginResolveContainingPages(string componentId, ResolveContainingPagesInstructionData instruction, AsyncCallback callback, object asyncState);
ContainingPagesDictionary EndResolveContainingPages(IAsyncResult result);
void PurgeWorkflowHistory(PurgeWorkflowHistoryInstructionData instruction);
IAsyncResult BeginPurgeWorkflowHistory(PurgeWorkflowHistoryInstructionData instruction, AsyncCallback callback, object asyncState);
void EndPurgeWorkflowHistory(IAsyncResult result);
string GetApiVersion();
IAsyncResult BeginGetApiVersion(AsyncCallback callback, object asyncState);
string EndGetApiVersion(IAsyncResult result);
AccessTokenData GetCurrentUser();
IAsyncResult BeginGetCurrentUser(AsyncCallback callback, object asyncState);
AccessTokenData EndGetCurrentUser(IAsyncResult result);
bool IsExistingObject(string id);
IAsyncResult BeginIsExistingObject(string id, AsyncCallback callback, object asyncState);
bool EndIsExistingObject(IAsyncResult result);
string GetTcmUri(string baseUri, string contextRepositoryUri, uint? version);
IAsyncResult BeginGetTcmUri(string baseUri, string contextRepositoryUri, uint? version, AsyncCallback callback, object asyncState);
string EndGetTcmUri(IAsyncResult result);
string TryGetTcmUri(string baseUri, string contextRepositoryUri, uint? version);
IAsyncResult BeginTryGetTcmUri(string baseUri, string contextRepositoryUri, uint? version, AsyncCallback callback, object asyncState);
string EndTryGetTcmUri(IAsyncResult result);
IdentifiableObjectData Read(string id, ReadOptions readOptions);
IAsyncResult BeginRead(string id, ReadOptions readOptions, AsyncCallback callback, object asyncState);
IdentifiableObjectData EndRead(IAsyncResult result);
IdentifiableObjectData TryRead(string id, ReadOptions readOptions);
IAsyncResult BeginTryRead(string id, ReadOptions readOptions, AsyncCallback callback, object asyncState);
IdentifiableObjectData EndTryRead(IAsyncResult result);
ItemReadResultDictionary BulkRead(string[] ids, ReadOptions readOptions);
IAsyncResult BeginBulkRead(string[] ids, ReadOptions readOptions, AsyncCallback callback, object asyncState);
ItemReadResultDictionary EndBulkRead(IAsyncResult result);
SchemaFieldsData ReadSchemaFields(string schemaId, bool expandEmbeddedFields, ReadOptions readOptions);
IAsyncResult BeginReadSchemaFields(string schemaId, bool expandEmbeddedFields, ReadOptions readOptions, AsyncCallback callback, object asyncState);
SchemaFieldsData EndReadSchemaFields(IAsyncResult result);
XElement ConvertSchemaFieldsToXsd(SchemaFieldsData schemaFieldsData);
IAsyncResult BeginConvertSchemaFieldsToXsd(SchemaFieldsData schemaFieldsData, AsyncCallback callback, object asyncState);
XElement EndConvertSchemaFieldsToXsd(IAsyncResult result);
IdentifiableObjectData Save(IdentifiableObjectData deltaData, ReadOptions readBackOptions);
IAsyncResult BeginSave(IdentifiableObjectData deltaData, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
IdentifiableObjectData EndSave(IAsyncResult result);
void Delete(string id);
IAsyncResult BeginDelete(string id, AsyncCallback callback, object asyncState);
void EndDelete(IAsyncResult result);
void DeleteTaxonomyNode(string id, DeleteTaxonomyNodeMode deleteTaxonomyNodeMode);
IAsyncResult BeginDeleteTaxonomyNode(string id, DeleteTaxonomyNodeMode deleteTaxonomyNodeMode, AsyncCallback callback, object asyncState);
void EndDeleteTaxonomyNode(IAsyncResult result);
IdentifiableObjectData GetDefaultData(ItemType itemType, string containerId, ReadOptions readOptions);
IAsyncResult BeginGetDefaultData(ItemType itemType, string containerId, ReadOptions readOptions, AsyncCallback callback, object asyncState);
IdentifiableObjectData EndGetDefaultData(IAsyncResult result);
RepositoryLocalObjectData Move(string id, string destinationId, ReadOptions readBackOptions);
IAsyncResult BeginMove(string id, string destinationId, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
RepositoryLocalObjectData EndMove(IAsyncResult result);
RepositoryLocalObjectData Copy(string id, string destinationId, bool makeUnique, ReadOptions readBackOptions);
IAsyncResult BeginCopy(string id, string destinationId, bool makeUnique, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
RepositoryLocalObjectData EndCopy(IAsyncResult result);
InstanceData GetInstanceData(string schemaId, string containerItemId, ReadOptions readOptions);
IAsyncResult BeginGetInstanceData(string schemaId, string containerItemId, ReadOptions readOptions, AsyncCallback callback, object asyncState);
InstanceData EndGetInstanceData(IAsyncResult result);
IdentifiableObjectData TryCheckOut(string id, ReadOptions readBackOptions);
IAsyncResult BeginTryCheckOut(string id, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
IdentifiableObjectData EndTryCheckOut(IAsyncResult result);
VersionedItemData CheckOut(string id, bool permanentLock, ReadOptions readBackOptions);
IAsyncResult BeginCheckOut(string id, bool permanentLock, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
VersionedItemData EndCheckOut(IAsyncResult result);
VersionedItemData CheckIn(string id, bool removePermanentLock, string userComment, ReadOptions readBackOptions);
IAsyncResult BeginCheckIn(string id, bool removePermanentLock, string userComment, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
VersionedItemData EndCheckIn(IAsyncResult result);
IdentifiableObjectData Update(IdentifiableObjectData deltaData, ReadOptions readBackOptions);
IAsyncResult BeginUpdate(IdentifiableObjectData deltaData, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
IdentifiableObjectData EndUpdate(IAsyncResult result);
IdentifiableObjectData Create(IdentifiableObjectData data, ReadOptions readBackOptions);
IAsyncResult BeginCreate(IdentifiableObjectData data, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
IdentifiableObjectData EndCreate(IAsyncResult result);
VersionedItemData UndoCheckOut(string id, bool permanentLock, ReadOptions readBackOptions);
IAsyncResult BeginUndoCheckOut(string id, bool permanentLock, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
VersionedItemData EndUndoCheckOut(IAsyncResult result);
VersionedItemData Rollback(string id, bool deleteVersions, string comment, ReadOptions readBackOptions);
IAsyncResult BeginRollback(string id, bool deleteVersions, string comment, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
VersionedItemData EndRollback(IAsyncResult result);
RepositoryLocalObjectData Localize(string id, ReadOptions readBackOptions);
IAsyncResult BeginLocalize(string id, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
RepositoryLocalObjectData EndLocalize(IAsyncResult result);
RepositoryLocalObjectData UnLocalize(string id, ReadOptions readBackOptions);
IAsyncResult BeginUnLocalize(string id, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
RepositoryLocalObjectData EndUnLocalize(IAsyncResult result);
OperationResultDataOfRepositoryLocalObjectData Promote(string id, string destinationRepositoryId, OperationInstruction instruction, ReadOptions readBackOptions);
IAsyncResult BeginPromote(string id, string destinationRepositoryId, OperationInstruction instruction, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
OperationResultDataOfRepositoryLocalObjectData EndPromote(IAsyncResult result);
OperationResultDataOfRepositoryLocalObjectData Demote(string id, string destinationRepositoryId, OperationInstruction instruction, ReadOptions readBackOptions);
IAsyncResult BeginDemote(string id, string destinationRepositoryId, OperationInstruction instruction, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
OperationResultDataOfRepositoryLocalObjectData EndDemote(IAsyncResult result);
TemplateType[] GetListTemplateTypes(ItemType? itemType);
IAsyncResult BeginGetListTemplateTypes(ItemType? itemType, AsyncCallback callback, object asyncState);
TemplateType[] EndGetListTemplateTypes(IAsyncResult result);
PublicationType[] GetListPublicationTypes();
IAsyncResult BeginGetListPublicationTypes(AsyncCallback callback, object asyncState);
PublicationType[] EndGetListPublicationTypes(IAsyncResult result);
XElement GetSystemWideListXml(SystemWideListFilterData filter);
IAsyncResult BeginGetSystemWideListXml(SystemWideListFilterData filter, AsyncCallback callback, object asyncState);
XElement EndGetSystemWideListXml(IAsyncResult result);
IdentifiableObjectData[] GetSystemWideList(SystemWideListFilterData filter);
IAsyncResult BeginGetSystemWideList(SystemWideListFilterData filter, AsyncCallback callback, object asyncState);
IdentifiableObjectData[] EndGetSystemWideList(IAsyncResult result);
XElement GetListXml(string id, SubjectRelatedListFilterData filter);
IAsyncResult BeginGetListXml(string id, SubjectRelatedListFilterData filter, AsyncCallback callback, object asyncState);
XElement EndGetListXml(IAsyncResult result);
IdentifiableObjectData[] GetList(string id, SubjectRelatedListFilterData filter);
IAsyncResult BeginGetList(string id, SubjectRelatedListFilterData filter, AsyncCallback callback, object asyncState);
IdentifiableObjectData[] EndGetList(IAsyncResult result);
string[] GetListDirectoryServiceNames();
IAsyncResult BeginGetListDirectoryServiceNames(AsyncCallback callback, object asyncState);
string[] EndGetListDirectoryServiceNames(IAsyncResult result);
WindowsUser[] GetListWindowsDomainUsers(string domainName);
IAsyncResult BeginGetListWindowsDomainUsers(string domainName, AsyncCallback callback, object asyncState);
WindowsUser[] EndGetListWindowsDomainUsers(IAsyncResult result);
DirectoryServiceUser[] GetListDirectoryServiceAllUsers(string directoryServiceName);
IAsyncResult BeginGetListDirectoryServiceAllUsers(string directoryServiceName, AsyncCallback callback, object asyncState);
DirectoryServiceUser[] EndGetListDirectoryServiceAllUsers(IAsyncResult result);
DirectoryServiceUser[] GetListDirectoryServiceGroupMembers(string directoryServiceName, string groupDN);
IAsyncResult BeginGetListDirectoryServiceGroupMembers(string directoryServiceName, string groupDN, AsyncCallback callback, object asyncState);
DirectoryServiceUser[] EndGetListDirectoryServiceGroupMembers(IAsyncResult result);
DirectoryServiceUser[] GetListDirectoryServiceUsers(string directoryServiceName, DirectoryUsersFilter filter);
IAsyncResult BeginGetListDirectoryServiceUsers(string directoryServiceName, DirectoryUsersFilter filter, AsyncCallback callback, object asyncState);
DirectoryServiceUser[] EndGetListDirectoryServiceUsers(IAsyncResult result);
ClassificationInfoData Classify(string id, string[] keywordIds, ReadOptions readOptions);
IAsyncResult BeginClassify(string id, string[] keywordIds, ReadOptions readOptions, AsyncCallback callback, object asyncState);
ClassificationInfoData EndClassify(IAsyncResult result);
ClassificationInfoData UnClassify(string id, string[] keywordIds, ReadOptions readOptions);
IAsyncResult BeginUnClassify(string id, string[] keywordIds, ReadOptions readOptions, AsyncCallback callback, object asyncState);
ClassificationInfoData EndUnClassify(IAsyncResult result);
ClassificationInfoData ReClassify(string id, string[] keywordIdsToRemove, string[] keywordIdsToAdd, ReadOptions readOptions);
IAsyncResult BeginReClassify(string id, string[] keywordIdsToRemove, string[] keywordIdsToAdd, ReadOptions readOptions, AsyncCallback callback, object asyncState);
ClassificationInfoData EndReClassify(IAsyncResult result);
ActivityInstanceData StartActivity(string activityInstanceId, ReadOptions readBackOptions);
IAsyncResult BeginStartActivity(string activityInstanceId, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
ActivityInstanceData EndStartActivity(IAsyncResult result);
ActivityInstanceData SuspendActivity(string activityInstanceId, string reason, DateTime? resumeAt, string resumeBookmark, ReadOptions readBackOptions);
IAsyncResult BeginSuspendActivity(string activityInstanceId, string reason, DateTime? resumeAt, string resumeBookmark, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
ActivityInstanceData EndSuspendActivity(IAsyncResult result);
ActivityInstanceData RestartActivity(string activityInstanceId, ReadOptions readBackOptions);
IAsyncResult BeginRestartActivity(string activityInstanceId, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
ActivityInstanceData EndRestartActivity(IAsyncResult result);
ActivityInstanceData ReAssignActivity(string activityInstanceId, string newAssigneeId, ReadOptions readBackOptions);
IAsyncResult BeginReAssignActivity(string activityInstanceId, string newAssigneeId, ReadOptions readBackOptions, AsyncCallback callback, object asyncState);
ActivityInstanceData EndReAssignActivity(IAsyncResult result);
ActivityInstanceData FinishActivity(string activityInstanceId, ActivityFinishData activityFinishData, ReadOptions readOptions);
IAsyncResult BeginFinishActivity(string activityInstanceId, ActivityFinishData activityFinishData, ReadOptions readOptions, AsyncCallback callback, object asyncState);
ActivityInstanceData EndFinishActivity(IAsyncResult result);
ProcessHistoryData ForceFinishProcess(string processInstanceId, string approvalStatusId, ReadOptions readOptions);
IAsyncResult BeginForceFinishProcess(string processInstanceId, string approvalStatusId, ReadOptions readOptions, AsyncCallback callback, object asyncState);
ProcessHistoryData EndForceFinishProcess(IAsyncResult result);
ActivityInstanceData ResumeActivity(string activityInstanceId, ReadOptions readOptions);
IAsyncResult BeginResumeActivity(string activityInstanceId, ReadOptions readOptions, AsyncCallback callback, object asyncState);
ActivityInstanceData EndResumeActivity(IAsyncResult result);
QueueMessageData[] GetListQueueMessages(int queueId);
IAsyncResult BeginGetListQueueMessages(int queueId, AsyncCallback callback, object asyncState);
QueueMessageData[] EndGetListQueueMessages(IAsyncResult result);
void PurgeQueue(int queueId);
IAsyncResult BeginPurgeQueue(int queueId, AsyncCallback callback, object asyncState);
void EndPurgeQueue(IAsyncResult result);
QueueData[] GetListQueues();
IAsyncResult BeginGetListQueues(AsyncCallback callback, object asyncState);
QueueData[] EndGetListQueues(IAsyncResult result);
ApplicationData ReadApplicationData(string subjectId, string applicationId);
IAsyncResult BeginReadApplicationData(string subjectId, string applicationId, AsyncCallback callback, object asyncState);
ApplicationData EndReadApplicationData(IAsyncResult result);
ApplicationData[] ReadAllApplicationData(string subjectId);
IAsyncResult BeginReadAllApplicationData(string subjectId, AsyncCallback callback, object asyncState);
ApplicationData[] EndReadAllApplicationData(IAsyncResult result);
void SaveApplicationData(string subjectId, ApplicationData[] applicationData);
IAsyncResult BeginSaveApplicationData(string subjectId, ApplicationData[] applicationData, AsyncCallback callback, object asyncState);
void EndSaveApplicationData(IAsyncResult result);
void DeleteApplicationData(string subjectId, string applicationId);
IAsyncResult BeginDeleteApplicationData(string subjectId, string applicationId, AsyncCallback callback, object asyncState);
void EndDeleteApplicationData(IAsyncResult result);
string[] GetApplicationIds();
IAsyncResult BeginGetApplicationIds(AsyncCallback callback, object asyncState);
string[] EndGetApplicationIds(IAsyncResult result);
void PurgeApplicationData(string applicationId);
IAsyncResult BeginPurgeApplicationData(string applicationId, AsyncCallback callback, object asyncState);
void EndPurgeApplicationData(IAsyncResult result);
PredefinedBatchOperation? ParsePredefinedBatchOperation(string operation);
IAsyncResult BeginParsePredefinedBatchOperation(string operation, AsyncCallback callback, object asyncState);
PredefinedBatchOperation? EndParsePredefinedBatchOperation(IAsyncResult result);
string GetPredefinedBatchOperationName(PredefinedBatchOperation operation);
IAsyncResult BeginGetPredefinedBatchOperationName(PredefinedBatchOperation operation, AsyncCallback callback, object asyncState);
string EndGetPredefinedBatchOperationName(IAsyncResult result);
PublishContextData[] ResolveItems(string[] ids, ResolveInstructionData resolveInstruction, string[] targetIdsOrPurposes, ReadOptions readOptions);
IAsyncResult BeginResolveItems(string[] ids, ResolveInstructionData resolveInstruction, string[] targetIdsOrPurposes, ReadOptions readOptions, AsyncCallback callback, object asyncState);
PublishContextData[] EndResolveItems(IAsyncResult result);
XElement GetSearchResultsXml(SearchQueryData filter);
IAsyncResult BeginGetSearchResultsXml(SearchQueryData filter, AsyncCallback callback, object asyncState);
XElement EndGetSearchResultsXml(IAsyncResult result);
XElement GetSearchResultsXmlPaged(SearchQueryData filter, int startRowIndex, int maxRows);
IAsyncResult BeginGetSearchResultsXmlPaged(SearchQueryData filter, int startRowIndex, int maxRows, AsyncCallback callback, object asyncState);
XElement EndGetSearchResultsXmlPaged(IAsyncResult result);
IdentifiableObjectData[] GetSearchResults(SearchQueryData filter);
IAsyncResult BeginGetSearchResults(SearchQueryData filter, AsyncCallback callback, object asyncState);
IdentifiableObjectData[] EndGetSearchResults(IAsyncResult result);
IdentifiableObjectData[] GetSearchResultsPaged(SearchQueryData filter, int startRowIndex, int maxRows);
IAsyncResult BeginGetSearchResultsPaged(SearchQueryData filter, int startRowIndex, int maxRows, AsyncCallback callback, object asyncState);
IdentifiableObjectData[] EndGetSearchResultsPaged(IAsyncResult result);
RenderedItemData RenderItem(string itemId, string templateId, PublishInstructionData publishInstruction, string publicationTargetIdOrPurpose);
IAsyncResult BeginRenderItem(string itemId, string templateId, PublishInstructionData publishInstruction, string publicationTargetIdOrPurpose, AsyncCallback callback, object asyncState);
RenderedItemData EndRenderItem(IAsyncResult result);
RenderedItemData PreviewItem(RepositoryLocalObjectData itemData, TemplateData templateData, PublishInstructionData publishInstruction, string publicationTargetId);
IAsyncResult BeginPreviewItem(RepositoryLocalObjectData itemData, TemplateData templateData, PublishInstructionData publishInstruction, string publicationTargetId, AsyncCallback callback, object asyncState);
RenderedItemData EndPreviewItem(IAsyncResult result);
PublishTransactionData[] Publish(string[] ids, PublishInstructionData publishInstruction, string[] targetIdsOrPurposes, PublishPriority? priority, ReadOptions readOptions);
IAsyncResult BeginPublish(string[] ids, PublishInstructionData publishInstruction, string[] targetIdsOrPurposes, PublishPriority? priority, ReadOptions readOptions, AsyncCallback callback, object asyncState);
PublishTransactionData[] EndPublish(IAsyncResult result);
PublishTransactionData[] UnPublish(string[] ids, UnPublishInstructionData unPublishInstruction, string[] targetIdsOrPurposes, PublishPriority? priority, ReadOptions readOptions);
IAsyncResult BeginUnPublish(string[] ids, UnPublishInstructionData unPublishInstruction, string[] targetIdsOrPurposes, PublishPriority? priority, ReadOptions readOptions, AsyncCallback callback, object asyncState);
PublishTransactionData[] EndUnPublish(IAsyncResult result);
bool IsPublished(string itemId, string publishingTargetIdOrPurpose, bool isPublishedInContext);
IAsyncResult BeginIsPublished(string itemId, string publishingTargetIdOrPurpose, bool isPublishedInContext, AsyncCallback callback, object asyncState);
bool EndIsPublished(IAsyncResult result);
RenderedItemData GetWorkItemSnapshot(string workItemId);
IAsyncResult BeginGetWorkItemSnapshot(string workItemId, AsyncCallback callback, object asyncState);
RenderedItemData EndGetWorkItemSnapshot(IAsyncResult result);
PublishInfoData[] GetListPublishInfo(string itemId);
IAsyncResult BeginGetListPublishInfo(string itemId, AsyncCallback callback, object asyncState);
PublishInfoData[] EndGetListPublishInfo(IAsyncResult result);
ActionFlags CastActions(int numericActions);
IAsyncResult BeginCastActions(int numericActions, AsyncCallback callback, object asyncState);
ActionFlags EndCastActions(IAsyncResult result);
void ValidateXml(IdentifiableObjectData data);
IAsyncResult BeginValidateXml(IdentifiableObjectData data, AsyncCallback callback, object asyncState);
void EndValidateXml(IAsyncResult result);
bool IsValidTridionWebSchemaXml(SchemaData data);
IAsyncResult BeginIsValidTridionWebSchemaXml(SchemaData data, AsyncCallback callback, object asyncState);
bool EndIsValidTridionWebSchemaXml(IAsyncResult result);
ArrayOfTcmUri GetSubjectIdsWithApplicationData(string applicationId);
IAsyncResult BeginGetSubjectIdsWithApplicationData(string applicationId, AsyncCallback callback, object asyncState);
ArrayOfTcmUri EndGetSubjectIdsWithApplicationData(IAsyncResult result);
ApplicationDataDictionary ReadApplicationDataForSubjectsIds(string[] subjectIds, string[] applicationIds);
IAsyncResult BeginReadApplicationDataForSubjectsIds(string[] subjectIds, string[] applicationIds, AsyncCallback callback, object asyncState);
ApplicationDataDictionary EndReadApplicationDataForSubjectsIds(IAsyncResult result);
SecurityDescriptorDataDictionary GetSecurityDescriptorsForSubjectsIds(string[] subjectIds);
IAsyncResult BeginGetSecurityDescriptorsForSubjectsIds(string[] subjectIds, AsyncCallback callback, object asyncState);
SecurityDescriptorDataDictionary EndGetSecurityDescriptorsForSubjectsIds(IAsyncResult result);
SecurityDescriptorDataDictionary GetContentSecurityDescriptorsForOrgItemIds(string[] organizationalItemIds);
IAsyncResult BeginGetContentSecurityDescriptorsForOrgItemIds(string[] organizationalItemIds, AsyncCallback callback, object asyncState);
SecurityDescriptorDataDictionary EndGetContentSecurityDescriptorsForOrgItemIds(IAsyncResult result);
void ReIndex(string id);
IAsyncResult BeginReIndex(string id, AsyncCallback callback, object asyncState);
void EndReIndex(IAsyncResult result);
PredefinedQueue? CastPredefinedQueue(int queueId);
IAsyncResult BeginCastPredefinedQueue(int queueId, AsyncCallback callback, object asyncState);
PredefinedQueue? EndCastPredefinedQueue(IAsyncResult result);
int PurgeOldVersions(PurgeOldVersionsInstructionData instruction);
IAsyncResult BeginPurgeOldVersions(PurgeOldVersionsInstructionData instruction, AsyncCallback callback, object asyncState);
int EndPurgeOldVersions(IAsyncResult result);
XElement GetListExternalLinks(string id);
IAsyncResult BeginGetListExternalLinks(string id, AsyncCallback callback, object asyncState);
XElement EndGetListExternalLinks(IAsyncResult result);
SearchQueryData ConvertXmlToSearchQuery(XElement searchQueryXml);
IAsyncResult BeginConvertXmlToSearchQuery(XElement searchQueryXml, AsyncCallback callback, object asyncState);
SearchQueryData EndConvertXmlToSearchQuery(IAsyncResult result);
XElement ConvertSearchQueryToXml(SearchQueryData searchQueryData);
IAsyncResult BeginConvertSearchQueryToXml(SearchQueryData searchQueryData, AsyncCallback callback, object asyncState);
XElement EndConvertSearchQueryToXml(IAsyncResult result);
AccessTokenData Impersonate(string userName);
IAsyncResult BeginImpersonate(string userName, AsyncCallback callback, object asyncState);
AccessTokenData EndImpersonate(IAsyncResult result);
void ImpersonateWithToken(AccessTokenData accessToken);
IAsyncResult BeginImpersonateWithToken(AccessTokenData accessToken, AsyncCallback callback, object asyncState);
void EndImpersonateWithToken(IAsyncResult result);
AccessTokenData ImpersonateWithClaims(ClaimData[] claims);
IAsyncResult BeginImpersonateWithClaims(ClaimData[] claims, AsyncCallback callback, object asyncState);
AccessTokenData EndImpersonateWithClaims(IAsyncResult result);
void TerminateSession();
IAsyncResult BeginTerminateSession(AsyncCallback callback, object asyncState);
void EndTerminateSession(IAsyncResult result);
string GetSessionId();
IAsyncResult BeginGetSessionId(AsyncCallback callback, object asyncState);
string EndGetSessionId(IAsyncResult result);
void SetSessionContextData(ApplicationData appData);
IAsyncResult BeginSetSessionContextData(ApplicationData appData, AsyncCallback callback, object asyncState);
void EndSetSessionContextData(IAsyncResult result);
void SetSessionTransactionTimeout(int transactionTimeout);
IAsyncResult BeginSetSessionTransactionTimeout(int transactionTimeout, AsyncCallback callback, object asyncState);
void EndSetSessionTransactionTimeout(IAsyncResult result);
int GetSessionTransactionTimeout();
IAsyncResult BeginGetSessionTransactionTimeout(AsyncCallback callback, object asyncState);
int EndGetSessionTransactionTimeout(IAsyncResult result);
bool StartCaching();
IAsyncResult BeginStartCaching(AsyncCallback callback, object asyncState);
bool EndStartCaching(IAsyncResult result);
void StopCaching();
IAsyncResult BeginStopCaching(AsyncCallback callback, object asyncState);
void EndStopCaching(IAsyncResult result);
void SetWebDavUrlPrefix(string prefix);
IAsyncResult BeginSetWebDavUrlPrefix(string prefix, AsyncCallback callback, object asyncState);
void EndSetWebDavUrlPrefix(IAsyncResult result);
void EnlistInTransaction();
IAsyncResult BeginEnlistInTransaction(AsyncCallback callback, object asyncState);
void EndEnlistInTransaction(IAsyncResult result);
UserData ElevatePrivileges(Privileges privileges);
IAsyncResult BeginElevatePrivileges(Privileges privileges, AsyncCallback callback, object asyncState);
UserData EndElevatePrivileges(IAsyncResult result);
UserData RestorePrivileges();
IAsyncResult BeginRestorePrivileges(AsyncCallback callback, object asyncState);
UserData EndRestorePrivileges(IAsyncResult result);
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 11/11/2009 2:34:48 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Globalization;
using DotSpatial.Serialization;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
/// <summary>
/// Extent works like an envelope but is faster acting, has a minimum memory profile,
/// only works in 2D and has no events.
/// </summary>
[Serializable, TypeConverter(typeof(ExpandableObjectConverter))]
public class Extent : ICloneable, IExtent//, IRectangle
{
/// <summary>
/// Creates a new instance of Extent. This introduces no error checking and assumes
/// that the user knows what they are doing when working with this.
/// </summary>
public Extent()
{
MinX = double.NaN; //changed by jany_ (2015-07-17) default extent is empty because if there is no content there is no extent
MaxX = double.NaN;
MinY = double.NaN;
MaxY = double.NaN;
}
/// <summary>
/// Creates a new extent from the specified ordinates
/// </summary>
/// <param name="xMin"></param>
/// <param name="yMin"></param>
/// <param name="xMax"></param>
/// <param name="yMax"></param>
public Extent(double xMin, double yMin, double xMax, double yMax)
{
MinX = xMin;
MinY = yMin;
MaxX = xMax;
MaxY = yMax;
}
/// <summary>
/// Given a long array of doubles, this builds an extent from a small part of that
/// xmin, ymin, xmax, ymax
/// </summary>
/// <param name="values"></param>
/// <param name="offset"></param>
public Extent(double[] values, int offset)
{
if (values.Length < 4 + offset)
throw new IndexOutOfRangeException(
"The length of the array of double values should be greater than or equal to 4 plus the value of the offset.");
MinX = values[0 + offset];
MinY = values[1 + offset];
MaxX = values[2 + offset];
MaxY = values[3 + offset];
}
/// <summary>
/// XMin, YMin, XMax, YMax order
/// </summary>
/// <param name="values"></param>
public Extent(double[] values)
{
if (values.Length < 4)
throw new IndexOutOfRangeException("The length of the array of double values should be greater than or equal to 4.");
MinX = values[0];
MinY = values[1];
MaxX = values[2];
MaxY = values[3];
}
/// <summary>
/// Creates a new extent from the specified envelope
/// </summary>
/// <param name="env"></param>
public Extent(Envelope env)
{
if (Equals(env, null))
throw new ArgumentNullException("env");
MinX = env.MinX;
MinY = env.MinY;
MaxX = env.MaxX;
MaxY = env.MaxY;
}
/// <summary>
/// Gets the Center of this extent.
/// </summary>
public Coordinate Center
{
get
{
double x = MinX + (MaxX - MinX) / 2;
double y = MinY + (MaxY - MinY) / 2;
return new Coordinate(x, y);
}
}
#region ICloneable Members
/// <summary>
/// Produces a clone, rather than using this same object.
/// </summary>
/// <returns></returns>
public virtual object Clone()
{
return new Extent(MinX, MinY, MaxX, MaxY);
}
#endregion
#region IExtent Members
/// <summary>
/// Gets or sets whether the M values are used. M values are considered optional,
/// and not mandatory. Unused could mean either bound is NaN for some reason, or
/// else that the bounds are invalid by the Min being less than the Max.
/// </summary>
public virtual bool HasM
{
get { return false; }
}
/// <summary>
/// Gets or sets whether the M values are used. M values are considered optional,
/// and not mandatory. Unused could mean either bound is NaN for some reason, or
/// else that the bounds are invalid by the Min being less than the Max.
/// </summary>
public virtual bool HasZ
{
get { return false; }
}
/// <summary>
/// Max X
/// </summary>
[Serialize("MaxX")]
public double MaxX { get; set; }
/// <summary>
/// Max Y
/// </summary>
[Serialize("MaxY")]
public double MaxY { get; set; }
/// <summary>
/// Min X
/// </summary>
[Serialize("MinX")]
public double MinX { get; set; }
/// <summary>
/// Min Y
/// </summary>
[Serialize("MinY")]
public double MinY { get; set; }
#endregion
#region IRectangle Members
/// <summary>
/// Gets MaxY - MinY. Setting this will update MinY, keeping MaxY the same. (Pinned at top left corner).
/// </summary>
public double Height
{
get { return MaxY - MinY; }
set { MinY = MaxY - value; }
}
/// <summary>
/// Gets MaxX - MinX. Setting this will update MaxX, keeping MinX the same. (Pinned at top left corner).
/// </summary>
public double Width
{
get { return MaxX - MinX; }
set { MaxX = MinX + value; }
}
/// <summary>
/// Gets MinX. Setting this will shift both MinX and MaxX, keeping the width the same.
/// </summary>
public double X
{
get { return MinX; }
set
{
double w = Width;
MinX = value;
Width = w;
}
}
/// <summary>
/// Gets MaxY. Setting this will shift both MinY and MaxY, keeping the height the same.
/// </summary>
public double Y
{
get { return MaxY; }
set
{
double h = Height;
MaxY = value;
Height = h;
}
}
#endregion
/// <summary>
/// Equality test
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(Extent left, IExtent right)
{
if (((object)left) == null) return ((right) == null);
return left.Equals(right);
}
/// <summary>
/// Inequality test
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(Extent left, IExtent right)
{
if (((object)left) == null) return ((right) != null);
return !left.Equals(right);
}
/// <summary>
/// Tests if this envelope is contained by the specified envelope
/// </summary>
/// <param name="ext"></param>
/// <returns></returns>
public virtual bool Contains(IExtent ext)
{
if (Equals(ext, null))
throw new ArgumentNullException("ext");
if (MinX > ext.MinX)
{
return false;
}
if (MaxX < ext.MaxX)
{
return false;
}
if (MinY > ext.MinY)
{
return false;
}
return !(MaxY < ext.MaxY);
}
/// <summary>
/// Tests if this envelope is contained by the specified envelope
/// </summary>
/// <param name="c">The coordinate to test.</param>
/// <returns>Boolean</returns>
public virtual bool Contains(Coordinate c)
{
if (Equals(c, null))
throw new ArgumentNullException("c");
if (MinX > c.X)
{
return false;
}
if (MaxX < c.X)
{
return false;
}
if (MinY > c.Y)
{
return false;
}
return !(MaxY < c.Y);
}
/// <summary>
/// Tests if this envelope is contained by the specified envelope
/// </summary>
/// <param name="env"></param>
/// <returns></returns>
public virtual bool Contains(Envelope env)
{
if (Equals(env, null))
throw new ArgumentNullException("env");
if (MinX > env.MinX)
{
return false;
}
if (MaxX < env.MaxX)
{
return false;
}
if (MinY > env.MinY)
{
return false;
}
return !(MaxY < env.MaxY);
}
/// <summary>
/// Copies the MinX, MaxX, MinY, MaxY values from extent.
/// </summary>
/// <param name="extent">Any IExtent implementation.</param>
public virtual void CopyFrom(IExtent extent)
{
if (Equals(extent, null))
throw new ArgumentNullException("extent");
MinX = extent.MinX;
MaxX = extent.MaxX;
MinY = extent.MinY;
MaxY = extent.MaxY;
}
/// <summary>
/// Allows equality testing for extents that is derived on the extent itself.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
// Check the identity case for reference equality
if (base.Equals(obj))
{
return true;
}
IExtent other = obj as IExtent;
if (other == null)
{
return false;
}
if (MinX != other.MinX)
{
return false;
}
if (MaxX != other.MaxX)
{
return false;
}
if (MinY != other.MinY)
{
return false;
}
if (MaxY != other.MaxY)
{
return false;
}
return true;
}
/// <summary>
/// Expand will adjust both the minimum and maximum by the specified sizeX and sizeY
/// </summary>
/// <param name="padX">The amount to expand left and right.</param>
/// <param name="padY">The amount to expand up and down.</param>
public void ExpandBy(double padX, double padY)
{
MinX -= padX;
MaxX += padX;
MinY -= padY;
MaxY += padY;
}
/// <summary>
/// This expand the extent by the specified padding on all bounds. So the width will
/// change by twice the padding for instance. To Expand only x and y, use
/// the overload with those values explicitly specified.
/// </summary>
/// <param name="padding">The double padding to expand the extent.</param>
public virtual void ExpandBy(double padding)
{
MinX -= padding;
MaxX += padding;
MinY -= padding;
MaxY += padding;
}
/// <summary>
/// Expands this extent to include the domain of the specified extent
/// </summary>
/// <param name="ext">The extent to expand to include</param>
public virtual void ExpandToInclude(IExtent ext)
{
if (ext == null) //Simplify, avoiding nested if
return;
if (double.IsNaN(MinX) || ext.MinX < MinX)
{
MinX = ext.MinX;
}
if (double.IsNaN(MinY) || ext.MinY < MinY)
{
MinY = ext.MinY;
}
if (double.IsNaN(MaxX) || ext.MaxX > MaxX)
{
MaxX = ext.MaxX;
}
if (double.IsNaN(MaxY) || ext.MaxY > MaxY)
{
MaxY = ext.MaxY;
}
}
/// <summary>
/// Expands this extent to include the domain of the specified point
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void ExpandToInclude(double x, double y)
{
if (double.IsNaN(MinX) || x < MinX)
{
MinX = x;
}
if (double.IsNaN(MinY) || y < MinY)
{
MinY = y;
}
if (double.IsNaN(MaxX) || x > MaxX)
{
MaxX = x;
}
if (double.IsNaN(MaxY) || y > MaxY)
{
MaxY = y;
}
}
/// <summary>
/// Spreads the values for the basic X, Y extents across the whole range of int.
/// Repetition will occur, but it should be rare.
/// </summary>
/// <returns>Integer</returns>
public override int GetHashCode()
{
// 215^4 ~ Int.MaxValue so the value will cover the range based mostly on first 2 sig figs.
int xmin = Convert.ToInt32(MinX * 430 / MinX - 215);
int xmax = Convert.ToInt32(MaxX * 430 / MaxX - 215);
int ymin = Convert.ToInt32(MinY * 430 / MinY - 215);
int ymax = Convert.ToInt32(MaxY * 430 / MaxY - 215);
return (xmin * xmax * ymin * ymax);
}
/// <summary>
/// Calculates the intersection of this extent and the other extent. A result
/// with a min greater than the max in either direction is considered invalid
/// and represents no intersection.
/// </summary>
/// <param name="other">The other extent to intersect with.</param>
public virtual Extent Intersection(Extent other)
{
if (Equals(other, null))
throw new ArgumentNullException("other");
Extent result = new Extent
{
MinX = (MinX > other.MinX) ? MinX : other.MinX,
MaxX = (MaxX < other.MaxX) ? MaxX : other.MaxX,
MinY = (MinY > other.MinY) ? MinY : other.MinY,
MaxY = (MaxY < other.MaxY) ? MaxY : other.MaxY
};
return result;
}
/// <summary>
/// Returns true if the coordinate exists anywhere within this envelope
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public virtual bool Intersects(Coordinate c)
{
if (Equals(c, null))
throw new ArgumentNullException("c");
if (double.IsNaN(c.X) || double.IsNaN(c.Y))
{
return false;
}
return c.X >= MinX && c.X <= MaxX && c.Y >= MinY && c.Y <= MaxY;
}
/// <summary>
/// Tests for intersection with the specified coordinate
/// </summary>
/// <param name="x">The double ordinate to test intersection with in the X direction</param>
/// <param name="y">The double ordinate to test intersection with in the Y direction</param>
/// <returns>True if a point with the specified x and y coordinates is within or on the border
/// of this extent object. NAN values will always return false.</returns>
public bool Intersects(double x, double y)
{
if (double.IsNaN(x) || double.IsNaN(y))
{
return false;
}
return x >= MinX && x <= MaxX && y >= MinY && y <= MaxY;
}
/// <summary>
/// Tests to see if the point is inside or on the boundary of this extent.
/// </summary>
/// <param name="vert"></param>
/// <returns></returns>
public bool Intersects(Vertex vert)
{
if (vert.X < MinX)
{
return false;
}
if (vert.X > MaxX)
{
return false;
}
if (vert.Y < MinY)
{
return false;
}
return !(vert.Y > MaxY);
}
/// <summary>
/// Tests for an intersection with the specified extent
/// </summary>
/// <param name="ext">The other extent</param>
/// <returns>Boolean, true if they overlap anywhere, or even touch</returns>
public virtual bool Intersects(IExtent ext)
{
if (Equals(ext, null))
throw new ArgumentNullException("ext");
if (ext.MaxX < MinX)
{
return false;
}
if (ext.MaxY < MinY)
{
return false;
}
if (ext.MinX > MaxX)
{
return false;
}
return !(ext.MinY > MaxY);
}
/// <summary>
/// Tests with the specified envelope for a collision
/// </summary>
/// <param name="env"></param>
/// <returns></returns>
public virtual bool Intersects(Envelope env)
{
if (Equals(env, null))
throw new ArgumentNullException("env");
if (env.MaxX < MinX)
{
return false;
}
if (env.MaxY < MinY)
{
return false;
}
if (env.MinX > MaxX)
{
return false;
}
return !(env.MinY > MaxY);
}
/// <summary>
/// If this is undefined, it will have a min that is larger than the max, or else
/// any value is NaN. This only applies to the X and Z terms. Check HasM or HasZ higher dimensions.
/// </summary>
/// <returns>Boolean, true if the envelope has not had values set for it yet.</returns>
public bool IsEmpty()
{
if (double.IsNaN(MinX) || double.IsNaN(MaxX))
{
return true;
}
if (double.IsNaN(MinY) || double.IsNaN(MaxY))
{
return true;
}
return (MinX > MaxX || MinY > MaxY); // Simplified
}
/// <summary>
/// This allows parsing the X and Y values from a string version of the extent as:
/// 'X[-180|180], Y[-90|90]' Where minimum always precedes maximum. The correct
/// M or MZ version of extent will be returned if the string has those values.
/// </summary>
/// <param name="text">The string text to parse.</param>
public static Extent Parse(string text)
{
Extent result;
string fail;
if (TryParse(text, out result, out fail)) return result;
var ep = new ExtentParseException(String.Format("Attempting to read an extent string failed while reading the {0} term.", fail))
{
Expression = text
};
throw ep;
}
/// <summary>
/// This reads the string and attempts to derive values from the text.
/// </summary>
/// <param name="text"></param>
/// <param name="result"></param>
/// <param name="nameFailed"></param>
/// <returns></returns>
public static bool TryParse(string text, out Extent result, out string nameFailed)
{
double xmin, xmax, ymin, ymax, mmin, mmax;
result = null;
if (text.Contains("Z"))
{
double zmin, zmax;
nameFailed = "Z";
ExtentMZ mz = new ExtentMZ();
if (TryExtract(text, "Z", out zmin, out zmax) == false) return false;
mz.MinZ = zmin;
mz.MaxZ = zmax;
nameFailed = "M";
if (TryExtract(text, "M", out mmin, out mmax) == false) return false;
mz.MinM = mmin;
mz.MaxM = mmax;
result = mz;
}
else if (text.Contains("M"))
{
nameFailed = "M";
ExtentM me = new ExtentM();
if (TryExtract(text, "M", out mmin, out mmax) == false) return false;
me.MinM = mmin;
me.MaxM = mmax;
result = me;
}
else
{
result = new Extent();
}
nameFailed = "X";
if (TryExtract(text, "X", out xmin, out xmax) == false) return false;
result.MinX = xmin;
result.MaxX = xmax;
nameFailed = "Y";
if (TryExtract(text, "Y", out ymin, out ymax) == false) return false;
result.MinY = ymin;
result.MaxY = ymax;
return true;
}
/// <summary>
/// This centers the X and Y aspect of the extent on the specified center location.
/// </summary>
/// <param name="centerX"></param>
/// <param name="centerY"></param>
/// <param name="width"></param>
/// <param name="height"></param>
public void SetCenter(double centerX, double centerY, double width, double height)
{
MinX = centerX - width / 2;
MaxX = centerX + width / 2;
MinY = centerY - height / 2;
MaxY = centerY + height / 2;
}
/// <summary>
/// This centers the X and Y aspect of the extent on the specified center location.
/// </summary>
/// <param name="center">The center coordinate to to set.</param>
/// <param name="width"></param>
/// <param name="height"></param>
public void SetCenter(Coordinate center, double width, double height)
{
SetCenter(center.X, center.Y, width, height);
}
/// <summary>
/// This centers the extent on the specified coordinate, keeping the width and height the same.
/// </summary>
public void SetCenter(Coordinate center)
{
//prevents NullReferenceException when accessing center.X and center.Y
if (Equals(center, null))
throw new ArgumentNullException("center");
SetCenter(center.X, center.Y, Width, Height);
}
/// <summary>
/// Sets the values for xMin, xMax, yMin and yMax.
/// </summary>
/// <param name="minX">The double Minimum in the X direction.</param>
/// <param name="minY">The double Minimum in the Y direction.</param>
/// <param name="maxX">The double Maximum in the X direction.</param>
/// <param name="maxY">The double Maximum in the Y direction.</param>
public void SetValues(double minX, double minY, double maxX, double maxY)
{
MinX = minX;
MinY = minY;
MaxX = maxX;
MaxY = maxY;
}
/// <summary>
/// Creates a geometric envelope interface from this
/// </summary>
/// <returns></returns>
public Envelope ToEnvelope()
{
if (double.IsNaN(MinX)) return new Envelope();
return new Envelope(MinX, MaxX, MinY, MaxY);
}
/// <summary>
/// Creates a string that shows the extent.
/// </summary>
/// <returns>The string form of the extent.</returns>
public override string ToString()
{
return "X[" + MinX + "|" + MaxX + "], Y[" + MinY + "|" + MaxY + "]";
}
/// <summary>
/// Tests if this envelope is contained by the specified envelope
/// </summary>
/// <param name="ext"></param>
/// <returns></returns>
public virtual bool Within(IExtent ext)
{
if (Equals(ext, null))
throw new ArgumentNullException("ext");
if (MinX < ext.MinX)
{
return false;
}
if (MaxX > ext.MaxX)
{
return false;
}
if (MinY < ext.MinY)
{
return false;
}
return !(MaxY > ext.MaxY);
}
/// <summary>
/// Tests if this envelope is contained by the specified envelope
/// </summary>
/// <param name="env"></param>
/// <returns></returns>
public virtual bool Within(Envelope env)
{
if (Equals(env, null))
throw new ArgumentNullException("env");
if (MinX < env.MinX)
{
return false;
}
if (MaxX > env.MaxX)
{
return false;
}
if (MinY < env.MinY)
{
return false;
}
return !(MaxY > env.MaxY);
}
/// <summary>
/// Attempts to extract the min and max from one element of text. The element should be
/// formatted like X[1.5, 2.7] using an invariant culture.
/// </summary>
/// <param name="entireText"></param>
/// <param name="name">The name of the dimension, like X.</param>
/// <param name="min">The minimum that gets assigned</param>
/// <param name="max">The maximum that gets assigned</param>
/// <returns>Boolean, true if the parse was successful.</returns>
private static bool TryExtract(string entireText, string name, out double min, out double max)
{
int i = entireText.IndexOf(name, StringComparison.Ordinal);
i += name.Length + 1;
int j = entireText.IndexOf(']', i);
string vals = entireText.Substring(i, j - i);
return TryParseExtremes(vals, out min, out max);
}
/// <summary>
/// This method converts the X and Y text into two doubles.
/// </summary>
/// <returns></returns>
private static bool TryParseExtremes(string numeric, out double min, out double max)
{
string[] res = numeric.Split('|');
max = double.NaN;
if (double.TryParse(res[0].Trim(), NumberStyles.Any,
CultureInfo.InvariantCulture, out min) == false) return false;
if (double.TryParse(res[1].Trim(), NumberStyles.Any,
CultureInfo.InvariantCulture, out max) == false) return false;
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using PSycheTest.Core;
using PSycheTest.Runners.Framework.Extensions;
using PSycheTest.Runners.Framework.Results;
using PSycheTest.Runners.Framework.Timers;
using PSycheTest.Runners.Framework.Utilities.Collections;
namespace PSycheTest.Runners.Framework
{
/// <summary>
/// Executes PowerShell tests.
/// </summary>
public class PowerShellTestExecutor : IPowerShellTestExecutor
{
/// <summary>
/// Initializes a new <see cref="PowerShellTestExecutor"/>.
/// </summary>
/// <param name="logger">A message logger</param>
public PowerShellTestExecutor(ILogger logger)
: this(logger, () => new StopwatchTimer(), TaskScheduler.Default)
{
}
/// <summary>
/// Initializes a new <see cref="PowerShellTestExecutor"/>.
/// </summary>
/// <param name="logger">A message logger</param>
/// <param name="timerFactory">Creates new <see cref="ITestTimer"/>s</param>
/// <param name="taskScheduler">The scheduler to use for tasks</param>
public PowerShellTestExecutor(ILogger logger, Func<ITestTimer> timerFactory, TaskScheduler taskScheduler)
{
_logger = logger;
_timerFactory = timerFactory;
_taskScheduler = taskScheduler;
_testTransactionFactory = (p, ts, tf, d) => new TestExecutionTransaction(p, new TestLocationManager(d, ts, tf));
InitialModules = new List<string>
{
Assembly.GetAssembly(typeof(AssertionCmdletBase)).Location
};
_initialSessionState = new Lazy<InitialSessionState>(() =>
{
var initialState = InitialSessionState.CreateDefault();
initialState.ThrowOnRunspaceOpenError = true;
foreach (var moduleName in InitialModules)
initialState.ImportPSModule(new[] { moduleName });
return initialState;
});
}
/// <summary>
/// A collection of modules that will be added to a test run's initial session state
/// and which will persist across test executions.
/// </summary>
public ICollection<string> InitialModules { get; private set; }
/// <summary>
/// The root directory where test results and artifacts should be placed.
/// </summary>
public DirectoryInfo OutputDirectory { get; set; }
#region Events
/// <summary>
/// Event raised when a test script is about to start.
/// </summary>
public event EventHandler<TestScriptStartingEventArgs> TestScriptStarting;
private void OnTestScriptStarting(ITestScript script)
{
var localEvent = TestScriptStarting;
if (localEvent != null)
localEvent(this, new TestScriptStartingEventArgs(script));
}
/// <summary>
/// Event raised when a test is about to start.
/// </summary>
public event EventHandler<TestStartingEventArgs> TestStarting;
private void OnTestStarting(ITestFunction test)
{
var localEvent = TestStarting;
if (localEvent != null)
localEvent(this, new TestStartingEventArgs(test));
}
/// <summary>
/// Event raised when a test has ended.
/// </summary>
public event EventHandler<TestEndedEventArgs> TestEnded;
private void OnTestEnded(ITestFunction test, TestResult result)
{
var localEvent = TestEnded;
if (localEvent != null)
localEvent(this, new TestEndedEventArgs(test, result));
}
/// <summary>
/// Event raised when a test script has ended.
/// </summary>
public event EventHandler<TestScriptEndedEventArgs> TestScriptEnded;
private void OnTestScriptEnded(ITestScript script)
{
var localEvent = TestScriptEnded;
if (localEvent != null)
localEvent(this, new TestScriptEndedEventArgs(script));
}
#endregion Events
/// <summary>
/// Executes a collection of tests.
/// </summary>
/// <param name="testScripts">The test scripts to execute</param>
/// <param name="filter">An optional predicate that determines whether a test should be run</param>
/// <param name="cancellationToken">An optional cancellation token</param>
public async Task ExecuteAsync(IEnumerable<ITestScript> testScripts, Predicate<ITestFunction> filter = null, CancellationToken cancellationToken = default(CancellationToken))
{
filter = filter ?? (_ => true);
using (var runspace = RunspaceFactory.CreateRunspace(_initialSessionState.Value))
{
runspace.Open();
foreach (var testScript in testScripts)
{
_logger.Info("Executing test script: '{0}':", testScript.Source.FullName);
OnTestScriptStarting(testScript);
using (var powershell = PowerShell.Create(RunspaceMode.NewRunspace))
using (var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
linkedTokenSource.Token.Register(() =>
{
_logger.Info("Cancelling test execution...");
powershell.Stop();
});
powershell.Runspace = runspace;
foreach (var test in testScript.Tests.Where(test => filter(test)))
{
_logger.Info("Executing test '{0}'", test.DisplayName);
cancellationToken.ThrowIfCancellationRequested();
using (var transaction = _testTransactionFactory(powershell, testScript, test, OutputDirectory))
{
OnTestStarting(test);
var results = await ExecuteAsync(transaction, powershell, test, testScript).ConfigureAwait(false);
foreach (var result in results)
{
_logger.Info("Test '{0}': {1}", test.DisplayName, result.Status);
test.AddResult(result);
OnTestEnded(test, result);
}
}
}
}
OnTestScriptEnded(testScript);
}
}
}
/// <summary>
/// Executes a test function.
/// </summary>
/// <param name="transaction">The current test transaction</param>
/// <param name="powershell">The PowerShell instance to us</param>
/// <param name="test">The test to run</param>
/// <param name="script">The parent script</param>
private async Task<IEnumerable<TestResult>> ExecuteAsync(ITestExecutionTransaction transaction, PowerShell powershell, ITestFunction test, ITestScript script)
{
var timer = _timerFactory();
try
{
if (test.ShouldSkip)
return new SkippedResult(test.SkipReason).ToEnumerable();
var testContext = InitializeTestContext(powershell, transaction.OutputDirectory);
IReadOnlyCollection<ErrorRecord> errors;
using (timer.Start())
{
errors = await ExecuteCoreAsync(powershell, test, script).ConfigureAwait(false);
}
if (errors.Any())
return new FailedResult(timer.Elapsed, new PSScriptError(new ErrorRecordWrapper(errors.First()), test.Source.File)).ToEnumerable();
return new PassedResult(timer.Elapsed, testContext.Artifacts).ToEnumerable();
}
catch (CmdletInvocationException cmdletException)
{
return CreateFailed(timer.Elapsed, cmdletException.InnerException ?? cmdletException).ToEnumerable();
}
catch (Exception exception)
{
_logger.Error("Exception occurred during test '{0}': {1}{2}{3}", test.UniqueName, exception.Message, Environment.NewLine, exception.StackTrace);
return CreateFailed(timer.Elapsed, exception).ToEnumerable();
}
}
private async Task<IReadOnlyCollection<ErrorRecord>> ExecuteCoreAsync(PowerShell powershell, ITestFunction test, ITestScript script)
{
// Add the script's functions/variables to the pipeline.
powershell.AddScript(script.Text);
var scriptErrors = await powershell.InvokeAsync(_taskScheduler).ConfigureAwait(false);
powershell.Commands.Clear(); // Clear the pipeline.
if (scriptErrors.Any())
return scriptErrors;
// Now execute the test function plus setup/teardown.
script.TestSetup.Apply(s => powershell.AddCommand(s.Name));
powershell.AddCommand(test.FunctionName);
script.TestCleanup.Apply(s => powershell.AddCommand(s.Name));
var testErrors = await powershell.InvokeAsync(_taskScheduler).ConfigureAwait(false);
if (testErrors.Any())
return testErrors;
return new ErrorRecord[0];
}
private static TestExecutionContext InitializeTestContext(PowerShell powershell, DirectoryInfo outputDirectory)
{
var testContext = new TestExecutionContext
{
OutputDirectory = outputDirectory
};
powershell.Runspace.SessionStateProxy.Variables().__testContext__ = testContext;
return testContext;
}
private static TestResult CreateFailed(TimeSpan elapsed, Exception exception)
{
return new FailedResult(elapsed, new ExceptionScriptError(exception));
}
private readonly Lazy<InitialSessionState> _initialSessionState;
private readonly ILogger _logger;
private readonly Func<ITestTimer> _timerFactory;
private readonly Func<PowerShell, ITestScript, ITestFunction, DirectoryInfo, ITestExecutionTransaction> _testTransactionFactory;
private readonly TaskScheduler _taskScheduler;
}
}
| |
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Repository;
using Ocelot.Logging;
using Ocelot.Responses;
using Ocelot.UnitTests.Responder;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Threading;
using TestStack.BDDfy;
using Xunit;
using static Ocelot.Infrastructure.Wait;
namespace Ocelot.UnitTests.Configuration
{
public class FileConfigurationPollerTests : IDisposable
{
private readonly FileConfigurationPoller _poller;
private Mock<IOcelotLoggerFactory> _factory;
private readonly Mock<IFileConfigurationRepository> _repo;
private readonly FileConfiguration _fileConfig;
private Mock<IFileConfigurationPollerOptions> _config;
private readonly Mock<IInternalConfigurationRepository> _internalConfigRepo;
private readonly Mock<IInternalConfigurationCreator> _internalConfigCreator;
private IInternalConfiguration _internalConfig;
public FileConfigurationPollerTests()
{
var logger = new Mock<IOcelotLogger>();
_factory = new Mock<IOcelotLoggerFactory>();
_factory.Setup(x => x.CreateLogger<FileConfigurationPoller>()).Returns(logger.Object);
_repo = new Mock<IFileConfigurationRepository>();
_fileConfig = new FileConfiguration();
_config = new Mock<IFileConfigurationPollerOptions>();
_repo.Setup(x => x.Get()).ReturnsAsync(new OkResponse<FileConfiguration>(_fileConfig));
_config.Setup(x => x.Delay).Returns(100);
_internalConfigRepo = new Mock<IInternalConfigurationRepository>();
_internalConfigCreator = new Mock<IInternalConfigurationCreator>();
_internalConfigCreator.Setup(x => x.Create(It.IsAny<FileConfiguration>())).ReturnsAsync(new OkResponse<IInternalConfiguration>(_internalConfig));
_poller = new FileConfigurationPoller(_factory.Object, _repo.Object, _config.Object, _internalConfigRepo.Object, _internalConfigCreator.Object);
}
[Fact]
public void should_start()
{
this.Given(x => GivenPollerHasStarted())
.Given(x => ThenTheSetterIsCalled(_fileConfig, 1))
.BDDfy();
}
[Fact]
public void should_call_setter_when_gets_new_config()
{
var newConfig = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "test"
}
},
}
}
};
this.Given(x => GivenPollerHasStarted())
.Given(x => WhenTheConfigIsChanged(newConfig, 0))
.Then(x => ThenTheSetterIsCalledAtLeast(newConfig, 1))
.BDDfy();
}
[Fact]
public void should_not_poll_if_already_polling()
{
var newConfig = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "test"
}
},
}
}
};
this.Given(x => GivenPollerHasStarted())
.Given(x => WhenTheConfigIsChanged(newConfig, 10))
.Then(x => ThenTheSetterIsCalled(newConfig, 1))
.BDDfy();
}
[Fact]
public void should_do_nothing_if_call_to_provider_fails()
{
var newConfig = new FileConfiguration
{
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "test"
}
},
}
}
};
this.Given(x => GivenPollerHasStarted())
.Given(x => WhenProviderErrors())
.Then(x => ThenTheSetterIsCalled(newConfig, 0))
.BDDfy();
}
[Fact]
public void should_dispose_cleanly_without_starting()
{
this.When(x => WhenPollerIsDisposed())
.BDDfy();
}
private void GivenPollerHasStarted()
{
_poller.StartAsync(CancellationToken.None);
}
private void WhenProviderErrors()
{
_repo
.Setup(x => x.Get())
.ReturnsAsync(new ErrorResponse<FileConfiguration>(new AnyError()));
}
private void WhenTheConfigIsChanged(FileConfiguration newConfig, int delay)
{
_repo
.Setup(x => x.Get())
.Callback(() => Thread.Sleep(delay))
.ReturnsAsync(new OkResponse<FileConfiguration>(newConfig));
}
private void WhenPollerIsDisposed()
{
_poller.Dispose();
}
private void ThenTheSetterIsCalled(FileConfiguration fileConfig, int times)
{
var result = WaitFor(4000).Until(() =>
{
try
{
_internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig), Times.Exactly(times));
_internalConfigCreator.Verify(x => x.Create(fileConfig), Times.Exactly(times));
return true;
}
catch (Exception)
{
return false;
}
});
result.ShouldBeTrue();
}
private void ThenTheSetterIsCalledAtLeast(FileConfiguration fileConfig, int times)
{
var result = WaitFor(4000).Until(() =>
{
try
{
_internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig), Times.AtLeast(times));
_internalConfigCreator.Verify(x => x.Create(fileConfig), Times.AtLeast(times));
return true;
}
catch (Exception)
{
return false;
}
});
result.ShouldBeTrue();
}
public void Dispose()
{
_poller.Dispose();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OpenSim.Region.CoreModules.Avatar.Appearance
{
/// <summary>
/// A module that just holds commands for inspecting avatar appearance.
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AppearanceInfoModule")]
public class AppearanceInfoModule : ISharedRegionModule
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
// private IAvatarFactoryModule m_avatarFactory;
public string Name { get { return "Appearance Information Module"; } }
public Type ReplaceableInterface { get { return null; } }
public void AddRegion(Scene scene)
{
// m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName);
}
public void Close()
{
// m_log.DebugFormat("[APPEARANCE INFO MODULE]: CLOSED MODULE");
}
public void Initialise(IConfigSource source)
{
// m_log.DebugFormat("[APPEARANCE INFO MODULE]: INITIALIZED MODULE");
}
public void PostInitialise()
{
// m_log.DebugFormat("[APPEARANCE INFO MODULE]: POST INITIALIZED MODULE");
}
public void RegionLoaded(Scene scene)
{
// m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName);
lock (m_scenes)
m_scenes[scene.RegionInfo.RegionID] = scene;
scene.AddCommand(
"Users", this, "show appearance",
"show appearance [<first-name> <last-name>]",
"Synonym for 'appearance show'",
HandleShowAppearanceCommand);
scene.AddCommand(
"Users", this, "appearance show",
"appearance show [<first-name> <last-name>]",
"Show appearance information for each avatar in the simulator.",
"This command checks whether the simulator has all the baked textures required to display an avatar to other viewers. "
+ "\nIf not, then appearance is 'corrupt' and other avatars will continue to see it as a cloud."
+ "\nOptionally, you can view just a particular avatar's appearance information."
+ "\nIn this case, the texture UUID for each bake type is also shown and whether the simulator can find the referenced texture.",
HandleShowAppearanceCommand);
scene.AddCommand(
"Users", this, "appearance send",
"appearance send [<first-name> <last-name>]",
"Send appearance data for each avatar in the simulator to other viewers.",
"Optionally, you can specify that only a particular avatar's appearance data is sent.",
HandleSendAppearanceCommand);
scene.AddCommand(
"Users", this, "appearance rebake",
"appearance rebake <first-name> <last-name>",
"Send a request to the user's viewer for it to rebake and reupload its appearance textures.",
"This is currently done for all baked texture references previously received, whether the simulator can find the asset or not."
+ "\nThis will only work for texture ids that the viewer has already uploaded."
+ "\nIf the viewer has not yet sent the server any texture ids then nothing will happen"
+ "\nsince requests can only be made for ids that the client has already sent us",
HandleRebakeAppearanceCommand);
scene.AddCommand(
"Users", this, "appearance find",
"appearance find <uuid-or-start-of-uuid>",
"Find out which avatar uses the given asset as a baked texture, if any.",
"You can specify just the beginning of the uuid, e.g. 2008a8d. A longer UUID must be in dashed format.",
HandleFindAppearanceCommand);
}
public void RemoveRegion(Scene scene)
{
// m_log.DebugFormat("[APPEARANCE INFO MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName);
lock (m_scenes)
m_scenes.Remove(scene.RegionInfo.RegionID);
}
protected void HandleFindAppearanceCommand(string module, string[] cmd)
{
if (cmd.Length != 3)
{
MainConsole.Instance.OutputFormat("Usage: appearance find <uuid-or-start-of-uuid>");
return;
}
string rawUuid = cmd[2];
HashSet<ScenePresence> matchedAvatars = new HashSet<ScenePresence>();
lock (m_scenes)
{
foreach (Scene scene in m_scenes.Values)
{
scene.ForEachRootScenePresence(
sp =>
{
Dictionary<BakeType, Primitive.TextureEntryFace> bakedFaces = scene.AvatarFactory.GetBakedTextureFaces(sp.UUID);
foreach (Primitive.TextureEntryFace face in bakedFaces.Values)
{
if (face != null && face.TextureID.ToString().StartsWith(rawUuid))
matchedAvatars.Add(sp);
}
});
}
}
if (matchedAvatars.Count == 0)
{
MainConsole.Instance.OutputFormat("{0} did not match any baked avatar textures in use", rawUuid);
}
else
{
MainConsole.Instance.OutputFormat(
"{0} matched {1}",
rawUuid,
string.Join(", ", matchedAvatars.ToList().ConvertAll<string>(sp => sp.Name).ToArray()));
}
}
protected void HandleShowAppearanceCommand(string module, string[] cmd)
{
if (cmd.Length != 2 && cmd.Length < 4)
{
MainConsole.Instance.OutputFormat("Usage: appearance show [<first-name> <last-name>]");
return;
}
bool targetNameSupplied = false;
string optionalTargetFirstName = null;
string optionalTargetLastName = null;
if (cmd.Length >= 4)
{
targetNameSupplied = true;
optionalTargetFirstName = cmd[2];
optionalTargetLastName = cmd[3];
}
lock (m_scenes)
{
foreach (Scene scene in m_scenes.Values)
{
if (targetNameSupplied)
{
ScenePresence sp = scene.GetScenePresence(optionalTargetFirstName, optionalTargetLastName);
if (sp != null && !sp.IsChildAgent)
scene.AvatarFactory.WriteBakedTexturesReport(sp, MainConsole.Instance.OutputFormat);
}
else
{
scene.ForEachRootScenePresence(
sp =>
{
bool bakedTextureValid = scene.AvatarFactory.ValidateBakedTextureCache(sp);
MainConsole.Instance.OutputFormat(
"{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete");
}
);
}
}
}
}
private void HandleRebakeAppearanceCommand(string module, string[] cmd)
{
if (cmd.Length != 4)
{
MainConsole.Instance.OutputFormat("Usage: appearance rebake <first-name> <last-name>");
return;
}
string firstname = cmd[2];
string lastname = cmd[3];
lock (m_scenes)
{
foreach (Scene scene in m_scenes.Values)
{
ScenePresence sp = scene.GetScenePresence(firstname, lastname);
if (sp != null && !sp.IsChildAgent)
{
int rebakesRequested = scene.AvatarFactory.RequestRebake(sp, false);
if (rebakesRequested > 0)
MainConsole.Instance.OutputFormat(
"Requesting rebake of {0} uploaded textures for {1} in {2}",
rebakesRequested, sp.Name, scene.RegionInfo.RegionName);
else
MainConsole.Instance.OutputFormat(
"No texture IDs available for rebake request for {0} in {1}",
sp.Name, scene.RegionInfo.RegionName);
}
}
}
}
private void HandleSendAppearanceCommand(string module, string[] cmd)
{
if (cmd.Length != 2 && cmd.Length < 4)
{
MainConsole.Instance.OutputFormat("Usage: appearance send [<first-name> <last-name>]");
return;
}
bool targetNameSupplied = false;
string optionalTargetFirstName = null;
string optionalTargetLastName = null;
if (cmd.Length >= 4)
{
targetNameSupplied = true;
optionalTargetFirstName = cmd[2];
optionalTargetLastName = cmd[3];
}
lock (m_scenes)
{
foreach (Scene scene in m_scenes.Values)
{
if (targetNameSupplied)
{
ScenePresence sp = scene.GetScenePresence(optionalTargetFirstName, optionalTargetLastName);
if (sp != null && !sp.IsChildAgent)
{
MainConsole.Instance.OutputFormat(
"Sending appearance information for {0} to all other avatars in {1}",
sp.Name, scene.RegionInfo.RegionName);
scene.AvatarFactory.SendAppearance(sp.UUID);
}
}
else
{
scene.ForEachRootScenePresence(
sp =>
{
MainConsole.Instance.OutputFormat(
"Sending appearance information for {0} to all other avatars in {1}",
sp.Name, scene.RegionInfo.RegionName);
scene.AvatarFactory.SendAppearance(sp.UUID);
}
);
}
}
}
}
}
}
| |
// 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.Globalization;
using Xunit;
public static class CharTests
{
[Fact]
public static void TestCompareTo()
{
// Int32 Char.CompareTo(Char)
char h = 'h';
Assert.True(h.CompareTo('h') == 0);
Assert.True(h.CompareTo('a') > 0);
Assert.True(h.CompareTo('z') < 0);
}
[Fact]
public static void TestSystemIComparableCompareTo()
{
// Int32 Char.System.IComparable.CompareTo(Object)
IComparable h = 'h';
Assert.True(h.CompareTo('h') == 0);
Assert.True(h.CompareTo('a') > 0);
Assert.True(h.CompareTo('z') < 0);
Assert.True(h.CompareTo(null) > 0);
Assert.Throws<ArgumentException>(() => h.CompareTo("H"));
}
private static void ValidateConvertFromUtf32(int i, string expected)
{
try
{
string s = char.ConvertFromUtf32(i);
Assert.Equal(expected, s);
}
catch (ArgumentOutOfRangeException)
{
Assert.True(expected == null, "Expected an ArgumentOutOfRangeException");
}
}
[Fact]
public static void TestConvertFromUtf32()
{
// String Char.ConvertFromUtf32(Int32)
ValidateConvertFromUtf32(0x10000, "\uD800\uDC00");
ValidateConvertFromUtf32(0x103FF, "\uD800\uDFFF");
ValidateConvertFromUtf32(0xFFFFF, "\uDBBF\uDFFF");
ValidateConvertFromUtf32(0x10FC00, "\uDBFF\uDC00");
ValidateConvertFromUtf32(0x10FFFF, "\uDBFF\uDFFF");
ValidateConvertFromUtf32(0, "\0");
ValidateConvertFromUtf32(0x3FF, "\u03FF");
ValidateConvertFromUtf32(0xE000, "\uE000");
ValidateConvertFromUtf32(0xFFFF, "\uFFFF");
ValidateConvertFromUtf32(0xD800, null);
ValidateConvertFromUtf32(0xDC00, null);
ValidateConvertFromUtf32(0xDFFF, null);
ValidateConvertFromUtf32(0x110000, null);
ValidateConvertFromUtf32(-1, null);
ValidateConvertFromUtf32(int.MaxValue, null);
ValidateConvertFromUtf32(int.MinValue, null);
}
private static void ValidateconverToUtf32<T>(string s, int i, int expected) where T : Exception
{
try
{
int result = char.ConvertToUtf32(s, i);
Assert.Equal(result, expected);
}
catch (T)
{
Assert.True(expected == int.MinValue, "Expected an exception to be thrown");
}
}
[Fact]
public static void TestConvertToUtf32StrInt()
{
// Int32 Char.ConvertToUtf32(String, Int32)
ValidateconverToUtf32<Exception>("\uD800\uDC00", 0, 0x10000);
ValidateconverToUtf32<Exception>("\uD800\uD800\uDFFF", 1, 0x103FF);
ValidateconverToUtf32<Exception>("\uDBBF\uDFFF", 0, 0xFFFFF);
ValidateconverToUtf32<Exception>("\uDBFF\uDC00", 0, 0x10FC00);
ValidateconverToUtf32<Exception>("\uDBFF\uDFFF", 0, 0x10FFFF);
// Not surrogate pairs
ValidateconverToUtf32<Exception>("\u0000\u0001", 0, 0);
ValidateconverToUtf32<Exception>("\u0000\u0001", 1, 1);
ValidateconverToUtf32<Exception>("\u0000", 0, 0);
ValidateconverToUtf32<Exception>("\u0020\uD7FF", 0, 32);
ValidateconverToUtf32<Exception>("\u0020\uD7FF", 1, 0xD7FF);
ValidateconverToUtf32<Exception>("abcde", 4, (int)'e');
ValidateconverToUtf32<Exception>("\uD800\uD7FF", 1, 0xD7FF); // high, non-surrogate
ValidateconverToUtf32<Exception>("\uD800\u0000", 1, 0); // high, non-surrogate
ValidateconverToUtf32<Exception>("\uDF01\u0000", 1, 0); // low, non-surrogate
// Invalid inputs
ValidateconverToUtf32<ArgumentException>("\uD800\uD800", 0, int.MinValue); // high, high
ValidateconverToUtf32<ArgumentException>("\uD800\uD7FF", 0, int.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentException>("\uD800\u0000", 0, int.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentException>("\uDC01\uD940", 0, int.MinValue); // low, high
ValidateconverToUtf32<ArgumentException>("\uDD00\uDE00", 0, int.MinValue); // low, low
ValidateconverToUtf32<ArgumentException>("\uDF01\u0000", 0, int.MinValue); // low, non-surrogate
ValidateconverToUtf32<ArgumentException>("\uD800\uD800", 1, int.MinValue); // high, high
ValidateconverToUtf32<ArgumentException>("\uDC01\uD940", 1, int.MinValue); // low, high
ValidateconverToUtf32<ArgumentException>("\uDD00\uDE00", 1, int.MinValue); // low, low
ValidateconverToUtf32<ArgumentNullException>(null, 0, int.MinValue); // null string
ValidateconverToUtf32<ArgumentOutOfRangeException>("", 0, int.MinValue); // index out of range
ValidateconverToUtf32<ArgumentOutOfRangeException>("", -1, int.MinValue); // index out of range
ValidateconverToUtf32<ArgumentOutOfRangeException>("abcde", -1, int.MinValue); // index out of range
ValidateconverToUtf32<ArgumentOutOfRangeException>("abcde", 5, int.MinValue); // index out of range
}
private static void ValidateconverToUtf32<T>(char c1, char c2, int expected) where T : Exception
{
try
{
int result = char.ConvertToUtf32(c1, c2);
Assert.Equal(result, expected);
}
catch (T)
{
Assert.True(expected == int.MinValue, "Expected an exception to be thrown");
}
}
[Fact]
public static void TestConvertToUtf32()
{
// Int32 Char.ConvertToUtf32(Char, Char)
ValidateconverToUtf32<Exception>('\uD800', '\uDC00', 0x10000);
ValidateconverToUtf32<Exception>('\uD800', '\uDFFF', 0x103FF);
ValidateconverToUtf32<Exception>('\uDBBF', '\uDFFF', 0xFFFFF);
ValidateconverToUtf32<Exception>('\uDBFF', '\uDC00', 0x10FC00);
ValidateconverToUtf32<Exception>('\uDBFF', '\uDFFF', 0x10FFFF);
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\uD800', int.MinValue); // high, high
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\uD7FF', int.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\u0000', int.MinValue); // high, non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDC01', '\uD940', int.MinValue); // low, high
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDD00', '\uDE00', int.MinValue); // low, low
ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDF01', '\u0000', int.MinValue); // low, non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\u0032', '\uD7FF', int.MinValue); // both non-surrogate
ValidateconverToUtf32<ArgumentOutOfRangeException>('\u0000', '\u0000', int.MinValue); // both non-surrogate
}
[Fact]
public static void TestEquals()
{
// Boolean Char.Equals(Char)
char a = 'a';
Assert.True(a.Equals('a'));
Assert.False(a.Equals('b'));
Assert.False(a.Equals('A'));
}
[Fact]
public static void TestEqualsObj()
{
// Boolean Char.Equals(Object)
char a = 'a';
Assert.True(a.Equals((object)'a'));
Assert.False(a.Equals((object)'b'));
Assert.False(a.Equals((object)'A'));
Assert.False(a.Equals(null));
int i = (int)'a';
Assert.False(a.Equals(i));
Assert.False(a.Equals("a"));
}
[Fact]
public static void TestGetHashCode()
{
// Int32 Char.GetHashCode()
char a = 'a';
char b = 'b';
Assert.NotEqual(a.GetHashCode(), b.GetHashCode());
}
[Fact]
public static void TestGetNumericValueStrInt()
{
Assert.Equal(Char.GetNumericValue("\uD800\uDD07", 0), 1);
Assert.Equal(Char.GetNumericValue("9", 0), 9);
Assert.Equal(Char.GetNumericValue("Test 7", 5), 7);
Assert.Equal(Char.GetNumericValue("T", 0), -1);
}
[Fact]
public static void TestGetNumericValue()
{
Assert.Equal(Char.GetNumericValue('9'), 9);
Assert.Equal(Char.GetNumericValue('z'), -1);
}
[Fact]
public static void TestIsControl()
{
// Boolean Char.IsControl(Char)
foreach (var c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c));
}
[Fact]
public static void TestIsControlStrInt()
{
// Boolean Char.IsControl(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.Control))
Assert.True(char.IsControl(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.Control))
Assert.False(char.IsControl(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsControl(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsControl("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsControl("abc", 4));
}
[Fact]
public static void TestIsDigit()
{
// Boolean Char.IsDigit(Char)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c));
}
[Fact]
public static void TestIsDigitStrInt()
{
// Boolean Char.IsDigit(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsDigit(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsDigit(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsDigit(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsDigit("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsDigit("abc", 4));
}
[Fact]
public static void TestIsLetter()
{
// Boolean Char.IsLetter(Char)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.True(char.IsLetter(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.False(char.IsLetter(c));
}
[Fact]
public static void TestIsLetterStrInt()
{
// Boolean Char.IsLetter(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.True(char.IsLetter(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter))
Assert.False(char.IsLetter(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLetter(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetter("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetter("abc", 4));
}
[Fact]
public static void TestIsLetterOrDigit()
{
// Boolean Char.IsLetterOrDigit(Char)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsLetterOrDigit(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsLetterOrDigit(c));
}
[Fact]
public static void TestIsLetterOrDigitStrInt()
{
// Boolean Char.IsLetterOrDigit(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.True(char.IsLetterOrDigit(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter,
UnicodeCategory.LowercaseLetter,
UnicodeCategory.TitlecaseLetter,
UnicodeCategory.ModifierLetter,
UnicodeCategory.OtherLetter,
UnicodeCategory.DecimalDigitNumber))
Assert.False(char.IsLetterOrDigit(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLetterOrDigit(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetterOrDigit("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetterOrDigit("abc", 4));
}
[Fact]
public static void TestIsLower()
{
// Boolean Char.IsLower(Char)
foreach (var c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c));
}
[Fact]
public static void TestIsLowerStrInt()
{
// Boolean Char.IsLower(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.LowercaseLetter))
Assert.True(char.IsLower(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter))
Assert.False(char.IsLower(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLower(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLower("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLower("abc", 4));
}
[Fact]
public static void TestIsNumber()
{
// Boolean Char.IsNumber(Char)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.True(char.IsNumber(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.False(char.IsNumber(c));
}
[Fact]
public static void TestIsNumberStrInt()
{
// Boolean Char.IsNumber(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.True(char.IsNumber(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber,
UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber))
Assert.False(char.IsNumber(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsNumber(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsNumber("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsNumber("abc", 4));
}
[Fact]
public static void TestIsPunctuation()
{
// Boolean Char.IsPunctuation(Char)
foreach (var c in GetTestChars(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.True(char.IsPunctuation(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.False(char.IsPunctuation(c));
}
[Fact]
public static void TestIsPunctuationStrInt()
{
// Boolean Char.IsPunctuation(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.True(char.IsPunctuation(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.ConnectorPunctuation,
UnicodeCategory.DashPunctuation,
UnicodeCategory.OpenPunctuation,
UnicodeCategory.ClosePunctuation,
UnicodeCategory.InitialQuotePunctuation,
UnicodeCategory.FinalQuotePunctuation,
UnicodeCategory.OtherPunctuation))
Assert.False(char.IsPunctuation(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsPunctuation(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsPunctuation("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsPunctuation("abc", 4));
}
[Fact]
public static void TestIsSeparator()
{
// Boolean Char.IsSeparator(Char)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsSeparator(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.False(char.IsSeparator(c));
}
[Fact]
public static void TestIsSeparatorStrInt()
{
// Boolean Char.IsSeparator(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsSeparator(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.False(char.IsSeparator(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsSeparator(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSeparator("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSeparator("abc", 4));
}
[Fact]
public static void TestIsLowSurrogate()
{
// Boolean Char.IsLowSurrogate(Char)
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c));
}
[Fact]
public static void TestIsLowSurrogateStrInt()
{
// Boolean Char.IsLowSurrogate(String, Int32)
foreach (char c in s_lowSurrogates)
Assert.True(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_highSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsLowSurrogate(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsLowSurrogate(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLowSurrogate("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLowSurrogate("abc", 4));
}
[Fact]
public static void TestIsHighSurrogate()
{
// Boolean Char.IsHighSurrogate(Char)
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c));
}
[Fact]
public static void TestIsHighSurrogateStrInt()
{
// Boolean Char.IsHighSurrogate(String, Int32)
foreach (char c in s_highSurrogates)
Assert.True(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsHighSurrogate(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsHighSurrogate(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsHighSurrogate("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsHighSurrogate("abc", 4));
}
[Fact]
public static void TestIsSurrogate()
{
// Boolean Char.IsSurrogate(Char)
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c));
}
[Fact]
public static void TestIsSurrogateStrInt()
{
// Boolean Char.IsSurrogate(String, Int32)
foreach (char c in s_highSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_lowSurrogates)
Assert.True(char.IsSurrogate(c.ToString(), 0));
foreach (char c in s_nonSurrogates)
Assert.False(char.IsSurrogate(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsSurrogate(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSurrogate("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSurrogate("abc", 4));
}
[Fact]
public static void TestIsSurrogatePair()
{
// Boolean Char.IsSurrogatePair(Char, Char)
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(Char.IsSurrogatePair(hs, ls));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(Char.IsSurrogatePair(hs, ls));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(Char.IsSurrogatePair(hs, ls));
}
[Fact]
public static void TestIsSurrogatePairStrInt()
{
// Boolean Char.IsSurrogatePair(String, Int32)
foreach (char hs in s_highSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.True(Char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_nonSurrogates)
foreach (char ls in s_lowSurrogates)
Assert.False(Char.IsSurrogatePair(hs.ToString() + ls, 0));
foreach (char hs in s_highSurrogates)
foreach (char ls in s_nonSurrogates)
Assert.False(Char.IsSurrogatePair(hs.ToString() + ls, 0));
}
[Fact]
public static void TestIsSymbol()
{
// Boolean Char.IsSymbol(Char)
foreach (var c in GetTestChars(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.True(char.IsSymbol(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.False(char.IsSymbol(c));
}
[Fact]
public static void TestIsSymbolStrInt()
{
// Boolean Char.IsSymbol(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.True(char.IsSymbol(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.MathSymbol,
UnicodeCategory.ModifierSymbol,
UnicodeCategory.CurrencySymbol,
UnicodeCategory.OtherSymbol))
Assert.False(char.IsSymbol(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsSymbol(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSymbol("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSymbol("abc", 4));
}
[Fact]
public static void TestIsUpper()
{
// Boolean Char.IsUpper(Char)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c));
}
[Fact]
public static void TestIsUpperStrInt()
{
// Boolean Char.IsUpper(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter))
Assert.True(char.IsUpper(c.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter))
Assert.False(char.IsUpper(c.ToString(), 0));
Assert.Throws<ArgumentNullException>(() => char.IsUpper(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsUpper("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsUpper("abc", 4));
}
[Fact]
public static void TestIsWhiteSpace()
{
// Boolean Char.IsWhiteSpace(Char)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsWhiteSpace(c));
// Some control chars are also considered whitespace for legacy reasons.
//if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085')
Assert.True(char.IsWhiteSpace('\u000b'));
Assert.True(char.IsWhiteSpace('\u0085'));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c));
}
}
[Fact]
public static void TestIsWhiteSpaceStrInt()
{
// Boolean Char.IsWhiteSpace(String, Int32)
foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
Assert.True(char.IsWhiteSpace(c.ToString(), 0));
// Some control chars are also considered whitespace for legacy reasons.
//if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085')
Assert.True(char.IsWhiteSpace('\u000b'.ToString(), 0));
Assert.True(char.IsWhiteSpace('\u0085'.ToString(), 0));
foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator,
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator))
{
// Need to special case some control chars that are treated as whitespace
if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue;
Assert.False(char.IsWhiteSpace(c.ToString(), 0));
}
Assert.Throws<ArgumentNullException>(() => char.IsWhiteSpace(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsWhiteSpace("abc", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => char.IsWhiteSpace("abc", 4));
}
[Fact]
public static void TestMaxValue()
{
// Char Char.MaxValue
Assert.Equal(0xffff, char.MaxValue);
}
[Fact]
public static void TestMinValue()
{
// Char Char.MinValue
Assert.Equal(0, char.MinValue);
}
[Fact]
public static void TestToLower()
{
// Char Char.ToLower(Char)
Assert.Equal('a', char.ToLower('A'));
Assert.Equal('a', char.ToLower('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLower(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToLower(c);
Assert.Equal(c, lc);
}
}
[Fact]
public static void TestToLowerInvariant()
{
// Char Char.ToLowerInvariant(Char)
Assert.Equal('a', char.ToLowerInvariant('A'));
Assert.Equal('a', char.ToLowerInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter))
{
char lc = char.ToLowerInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsLower(lc));
}
// TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj')
// LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToLowerInvariant(c);
Assert.Equal(c, lc);
}
}
[Fact]
public static void TestToString()
{
// String Char.ToString()
Assert.Equal(new string('a', 1), 'a'.ToString());
Assert.Equal(new string('\uabcd', 1), '\uabcd'.ToString());
}
[Fact]
public static void TestToStringChar()
{
// String Char.ToString(Char)
Assert.Equal(new string('a', 1), char.ToString('a'));
Assert.Equal(new string('\uabcd', 1), char.ToString('\uabcd'));
}
[Fact]
public static void TestToUpper()
{
// Char Char.ToUpper(Char)
Assert.Equal('A', char.ToUpper('A'));
Assert.Equal('A', char.ToUpper('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpper(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToUpper(c);
Assert.Equal(c, lc);
}
}
[Fact]
public static void TestToUpperInvariant()
{
// Char Char.ToUpperInvariant(Char)
Assert.Equal('A', char.ToUpperInvariant('A'));
Assert.Equal('A', char.ToUpperInvariant('a'));
foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter))
{
char lc = char.ToUpperInvariant(c);
Assert.NotEqual(c, lc);
Assert.True(char.IsUpper(lc));
}
// TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ')
// LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III')
foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber))
{
char lc = char.ToUpperInvariant(c);
Assert.Equal(c, lc);
}
}
private static void ValidateTryParse(string s, char expected, bool shouldSucceed)
{
char result;
Assert.Equal(shouldSucceed, char.TryParse(s, out result));
if (shouldSucceed)
Assert.Equal(expected, result);
}
[Fact]
public static void TestTryParse()
{
// Boolean Char.TryParse(String, Char)
ValidateTryParse("a", 'a', true);
ValidateTryParse("4", '4', true);
ValidateTryParse(" ", ' ', true);
ValidateTryParse("\n", '\n', true);
ValidateTryParse("\0", '\0', true);
ValidateTryParse("\u0135", '\u0135', true);
ValidateTryParse("\u05d9", '\u05d9', true);
ValidateTryParse("\ud801", '\ud801', true); // high surrogate
ValidateTryParse("\udc01", '\udc01', true); // low surrogate
ValidateTryParse("\ue001", '\ue001', true); // private use codepoint
// Fail cases
ValidateTryParse(null, '\0', false);
ValidateTryParse("", '\0', false);
ValidateTryParse("\n\r", '\0', false);
ValidateTryParse("kj", '\0', false);
ValidateTryParse(" a", '\0', false);
ValidateTryParse("a ", '\0', false);
ValidateTryParse("\\u0135", '\0', false);
ValidateTryParse("\u01356", '\0', false);
ValidateTryParse("\ud801\udc01", '\0', false); // surrogate pair
}
private static IEnumerable<char> GetTestCharsNotInCategory(params UnicodeCategory[] categories)
{
Assert.Equal(s_latinTestSet.Length, s_unicodeTestSet.Length);
for (int i = 0; i < s_latinTestSet.Length; i++)
{
if (Array.Exists(categories, uc => uc == (UnicodeCategory)i))
continue;
char[] latinSet = s_latinTestSet[i];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[i];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static IEnumerable<char> GetTestChars(params UnicodeCategory[] categories)
{
for (int i = 0; i < categories.Length; i++)
{
char[] latinSet = s_latinTestSet[(int)categories[i]];
for (int j = 0; j < latinSet.Length; j++)
yield return latinSet[j];
char[] unicodeSet = s_unicodeTestSet[(int)categories[i]];
for (int k = 0; k < unicodeSet.Length; k++)
yield return unicodeSet[k];
}
}
private static char[][] s_latinTestSet = new char[][] {
new char[] {'\u0047','\u004c','\u0051','\u0056','\u00c0','\u00c5','\u00ca','\u00cf','\u00d4','\u00da'}, // UnicodeCategory.UppercaseLetter
new char[] {'\u0062','\u0068','\u006e','\u0074','\u007a','\u00e1','\u00e7','\u00ed','\u00f3','\u00fa'}, // UnicodeCategory.LowercaseLetter
new char[] {}, // UnicodeCategory.TitlecaseLetter
new char[] {}, // UnicodeCategory.ModifierLetter
new char[] {}, // UnicodeCategory.OtherLetter
new char[] {}, // UnicodeCategory.NonSpacingMark
new char[] {}, // UnicodeCategory.SpacingCombiningMark
new char[] {}, // UnicodeCategory.EnclosingMark
new char[] {'\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039'}, // UnicodeCategory.DecimalDigitNumber
new char[] {}, // UnicodeCategory.LetterNumber
new char[] {'\u00b2','\u00b3','\u00b9','\u00bc','\u00bd','\u00be'}, // UnicodeCategory.OtherNumber
new char[] {'\u0020','\u00a0'}, // UnicodeCategory.SpaceSeparator
new char[] {}, // UnicodeCategory.LineSeparator
new char[] {}, // UnicodeCategory.ParagraphSeparator
new char[] {'\u0005','\u000b','\u0011','\u0017','\u001d','\u0082','\u0085','\u008e','\u0094','\u009a'}, // UnicodeCategory.Control
new char[] {}, // UnicodeCategory.Format
new char[] {}, // UnicodeCategory.Surrogate
new char[] {}, // UnicodeCategory.PrivateUse
new char[] {'\u005f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u002d','\u00ad'}, // UnicodeCategory.DashPunctuation
new char[] {'\u0028','\u005b','\u007b'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u0029','\u005d','\u007d'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u00ab'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u00bb'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u002e','\u002f','\u003a','\u003b','\u003f','\u0040','\u005c','\u00a1','\u00b7','\u00bf'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u002b','\u003c','\u003d','\u003e','\u007c','\u007e','\u00ac','\u00b1','\u00d7','\u00f7'}, // UnicodeCategory.MathSymbol
new char[] {'\u0024','\u00a2','\u00a3','\u00a4','\u00a5'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u005e','\u0060','\u00a8','\u00af','\u00b4','\u00b8'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u00a6','\u00a7','\u00a9','\u00ae','\u00b0','\u00b6'}, // UnicodeCategory.OtherSymbol
new char[] {}, // UnicodeCategory.OtherNotAssigned
};
private static char[][] s_unicodeTestSet = new char[][] {
new char[] {'\u0102','\u01ac','\u0392','\u0428','\u0508','\u10c4','\u1eb4','\u1fba','\u2c28','\ua668'}, // UnicodeCategory.UppercaseLetter
new char[] { '\u0107', '\u012D', '\u0140', '\u0151', '\u013A', '\u01A1', '\u01F9', '\u022D', '\u1E09','\uFF45' }, // UnicodeCategory.LowercaseLetter
new char[] {'\u01c8','\u1f88','\u1f8b','\u1f8e','\u1f99','\u1f9c','\u1f9f','\u1faa','\u1fad','\u1fbc'}, // UnicodeCategory.TitlecaseLetter
new char[] {'\u02b7','\u02cd','\u07f4','\u1d2f','\u1d41','\u1d53','\u1d9d','\u1daf','\u2091','\u30fe'}, // UnicodeCategory.ModifierLetter
new char[] {'\u01c0','\u37be','\u4970','\u5b6c','\u6d1e','\u7ed0','\u9082','\ua271','\ub985','\ucb37'}, // UnicodeCategory.OtherLetter
new char[] {'\u0303','\u034e','\u05b5','\u0738','\u0a4d','\u0e49','\u0fad','\u180b','\u1dd5','\u2dfd'}, // UnicodeCategory.NonSpacingMark
new char[] {'\u0982','\u0b03','\u0c41','\u0d40','\u0df3','\u1083','\u1925','\u19b9','\u1b44','\ua8b5'}, // UnicodeCategory.SpacingCombiningMark
new char[] {'\u20dd','\u20de','\u20df','\u20e0','\u20e2','\u20e3','\u20e4','\ua670','\ua671','\ua672'}, // UnicodeCategory.EnclosingMark
new char[] {'\u0660','\u0966','\u0ae6','\u0c66','\u0e50','\u1040','\u1810','\u1b50','\u1c50','\ua900'}, // UnicodeCategory.DecimalDigitNumber
new char[] {'\u2162','\u2167','\u216c','\u2171','\u2176','\u217b','\u2180','\u2187','\u3023','\u3028'}, // UnicodeCategory.LetterNumber
new char[] {'\u0c78','\u136b','\u17f7','\u2158','\u2471','\u248a','\u24f1','\u2780','\u3220','\u3280'}, // UnicodeCategory.OtherNumber
new char[] {'\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200a','\u202f','\u205f','\u3000'}, // UnicodeCategory.SpaceSeparator
new char[] {'\u2028'}, // UnicodeCategory.LineSeparator
new char[] {'\u2029'}, // UnicodeCategory.ParagraphSeparator
new char[] {}, // UnicodeCategory.Control
new char[] {'\u0603','\u17b4','\u200c','\u200f','\u202c','\u2060','\u2063','\u206b','\u206e','\ufff9'}, // UnicodeCategory.Format
new char[] {'\ud808','\ud8d4','\ud9a0','\uda6c','\udb38','\udc04','\udcd0','\udd9c','\ude68','\udf34'}, // UnicodeCategory.Surrogate
new char[] {'\ue000','\ue280','\ue500','\ue780','\uea00','\uec80','\uef00','\uf180','\uf400','\uf680'}, // UnicodeCategory.PrivateUse
new char[] {'\u203f','\u2040','\u2054','\ufe33','\ufe34','\ufe4d','\ufe4e','\ufe4f','\uff3f'}, // UnicodeCategory.ConnectorPunctuation
new char[] {'\u2e17','\u2e1a','\u301c','\u3030','\u30a0','\ufe31','\ufe32','\ufe58','\ufe63','\uff0d'}, // UnicodeCategory.DashPunctuation
new char[] {'\u2768','\u2774','\u27ee','\u298d','\u29d8','\u2e28','\u3014','\ufe17','\ufe3f','\ufe5d'}, // UnicodeCategory.OpenPunctuation
new char[] {'\u276b','\u27c6','\u2984','\u2990','\u29db','\u3009','\u3017','\ufe18','\ufe40','\ufe5e'}, // UnicodeCategory.ClosePunctuation
new char[] {'\u201b','\u201c','\u201f','\u2039','\u2e02','\u2e04','\u2e09','\u2e0c','\u2e1c','\u2e20'}, // UnicodeCategory.InitialQuotePunctuation
new char[] {'\u2019','\u201d','\u203a','\u2e03','\u2e05','\u2e0a','\u2e0d','\u2e1d','\u2e21'}, // UnicodeCategory.FinalQuotePunctuation
new char[] {'\u0589','\u0709','\u0f10','\u16ec','\u1b5b','\u2034','\u2058','\u2e16','\ua8cf','\ufe55'}, // UnicodeCategory.OtherPunctuation
new char[] {'\u2052','\u2234','\u2290','\u22ec','\u27dd','\u2943','\u29b5','\u2a17','\u2a73','\u2acf'}, // UnicodeCategory.MathSymbol
new char[] {'\u17db','\u20a2','\u20a5','\u20a8','\u20ab','\u20ae','\u20b1','\u20b4','\ufe69','\uffe1'}, // UnicodeCategory.CurrencySymbol
new char[] {'\u02c5','\u02da','\u02e8','\u02f3','\u02fc','\u1fc0','\u1fee','\ua703','\ua70c','\ua715'}, // UnicodeCategory.ModifierSymbol
new char[] {'\u0bf3','\u2316','\u24ac','\u25b2','\u26af','\u285c','\u2e8f','\u2f8c','\u3292','\u3392'}, // UnicodeCategory.OtherSymbol
new char[] {'\u09c6','\u0dfa','\u2e5c','\ua9f9','\uabbd'}, // UnicodeCategory.OtherNotAssigned
};
private static char[] s_highSurrogates = new char[] { '\ud800', '\udaaa', '\udbff' }; // range from '\ud800' to '\udbff'
private static char[] s_lowSurrogates = new char[] { '\udc00', '\udeee', '\udfff' }; // range from '\udc00' to '\udfff'
private static char[] s_nonSurrogates = new char[] { '\u0000', '\ud7ff', '\ue000', '\uffff' };
}
| |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Xml.Serialization;
using VotingInfo.Database.Contracts;
using VotingInfo.Database.Contracts.Data;
//////////////////////////////////////////////////////////////
//Do not modify this file. Use a partial class to extend. //
//Override methods in the logic front class. //
//////////////////////////////////////////////////////////////
namespace VotingInfo.Database.Logic.Data
{
[Serializable]
public abstract partial class ContentInspectionLogicBase : LogicBase<ContentInspectionLogicBase>
{
//Put your code in a separate file. This is auto generated.
[XmlArray] public List<ContentInspectionContract> Results;
public ContentInspectionLogicBase()
{
Results = new List<ContentInspectionContract>();
}
/// <summary>
/// Run ContentInspection_Insert.
/// </summary>
/// <param name="fldIsArchived">Value for IsArchived</param>
/// <param name="fldIsBeingProposed">Value for IsBeingProposed</param>
/// <param name="fldProposedByUserId">Value for ProposedByUserId</param>
/// <param name="fldConfirmedByUserId">Value for ConfirmedByUserId</param>
/// <param name="fldFalseInfoCount">Value for FalseInfoCount</param>
/// <param name="fldTrueInfoCount">Value for TrueInfoCount</param>
/// <param name="fldAdminInpsected">Value for AdminInpsected</param>
/// <param name="fldDateLastChecked">Value for DateLastChecked</param>
/// <param name="fldSourceUrl">Value for SourceUrl</param>
/// <returns>The new ID</returns>
public virtual int? Insert(bool fldIsArchived
, bool fldIsBeingProposed
, int fldProposedByUserId
, int fldConfirmedByUserId
, int fldFalseInfoCount
, int fldTrueInfoCount
, bool fldAdminInpsected
, DateTime fldDateLastChecked
, string fldSourceUrl
)
{
int? result = null;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Insert]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@IsArchived", fldIsArchived)
,
new SqlParameter("@IsBeingProposed", fldIsBeingProposed)
,
new SqlParameter("@ProposedByUserId", fldProposedByUserId)
,
new SqlParameter("@ConfirmedByUserId", fldConfirmedByUserId)
,
new SqlParameter("@FalseInfoCount", fldFalseInfoCount)
,
new SqlParameter("@TrueInfoCount", fldTrueInfoCount)
,
new SqlParameter("@AdminInpsected", fldAdminInpsected)
,
new SqlParameter("@DateLastChecked", fldDateLastChecked)
,
new SqlParameter("@SourceUrl", fldSourceUrl)
});
result = (int?)cmd.ExecuteScalar();
}
});
return result;
}
/// <summary>
/// Run ContentInspection_Insert.
/// </summary>
/// <param name="fldIsArchived">Value for IsArchived</param>
/// <param name="fldIsBeingProposed">Value for IsBeingProposed</param>
/// <param name="fldProposedByUserId">Value for ProposedByUserId</param>
/// <param name="fldConfirmedByUserId">Value for ConfirmedByUserId</param>
/// <param name="fldFalseInfoCount">Value for FalseInfoCount</param>
/// <param name="fldTrueInfoCount">Value for TrueInfoCount</param>
/// <param name="fldAdminInpsected">Value for AdminInpsected</param>
/// <param name="fldDateLastChecked">Value for DateLastChecked</param>
/// <param name="fldSourceUrl">Value for SourceUrl</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The new ID</returns>
public virtual int? Insert(bool fldIsArchived
, bool fldIsBeingProposed
, int fldProposedByUserId
, int fldConfirmedByUserId
, int fldFalseInfoCount
, int fldTrueInfoCount
, bool fldAdminInpsected
, DateTime fldDateLastChecked
, string fldSourceUrl
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Insert]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@IsArchived", fldIsArchived)
,
new SqlParameter("@IsBeingProposed", fldIsBeingProposed)
,
new SqlParameter("@ProposedByUserId", fldProposedByUserId)
,
new SqlParameter("@ConfirmedByUserId", fldConfirmedByUserId)
,
new SqlParameter("@FalseInfoCount", fldFalseInfoCount)
,
new SqlParameter("@TrueInfoCount", fldTrueInfoCount)
,
new SqlParameter("@AdminInpsected", fldAdminInpsected)
,
new SqlParameter("@DateLastChecked", fldDateLastChecked)
,
new SqlParameter("@SourceUrl", fldSourceUrl)
});
return (int?)cmd.ExecuteScalar();
}
}
/// <summary>
/// Insert by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>1, if insert was successful</returns>
public int Insert(ContentInspectionContract row)
{
int? result = null;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Insert]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@IsArchived", row.IsArchived)
,
new SqlParameter("@IsBeingProposed", row.IsBeingProposed)
,
new SqlParameter("@ProposedByUserId", row.ProposedByUserId)
,
new SqlParameter("@ConfirmedByUserId", row.ConfirmedByUserId)
,
new SqlParameter("@FalseInfoCount", row.FalseInfoCount)
,
new SqlParameter("@TrueInfoCount", row.TrueInfoCount)
,
new SqlParameter("@AdminInpsected", row.AdminInpsected)
,
new SqlParameter("@DateLastChecked", row.DateLastChecked)
,
new SqlParameter("@SourceUrl", row.SourceUrl)
});
result = (int?)cmd.ExecuteScalar();
row.ContentInspectionId = result;
}
});
return result != null ? 1 : 0;
}
/// <summary>
/// Insert by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>1, if insert was successful</returns>
public int Insert(ContentInspectionContract row, SqlConnection connection, SqlTransaction transaction)
{
int? result = null;
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Insert]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@IsArchived", row.IsArchived)
,
new SqlParameter("@IsBeingProposed", row.IsBeingProposed)
,
new SqlParameter("@ProposedByUserId", row.ProposedByUserId)
,
new SqlParameter("@ConfirmedByUserId", row.ConfirmedByUserId)
,
new SqlParameter("@FalseInfoCount", row.FalseInfoCount)
,
new SqlParameter("@TrueInfoCount", row.TrueInfoCount)
,
new SqlParameter("@AdminInpsected", row.AdminInpsected)
,
new SqlParameter("@DateLastChecked", row.DateLastChecked)
,
new SqlParameter("@SourceUrl", row.SourceUrl)
});
result = (int?)cmd.ExecuteScalar();
row.ContentInspectionId = result;
}
return result != null ? 1 : 0;
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <returns>The number of rows affected.</returns>
public virtual int InsertAll(List<ContentInspectionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
rowCount = InsertAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Insert</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int InsertAll(List<ContentInspectionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Insert(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Run ContentInspection_Update.
/// </summary>
/// <returns>The number of rows affected.</returns>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="fldIsArchived">Value for IsArchived</param>
/// <param name="fldIsBeingProposed">Value for IsBeingProposed</param>
/// <param name="fldProposedByUserId">Value for ProposedByUserId</param>
/// <param name="fldConfirmedByUserId">Value for ConfirmedByUserId</param>
/// <param name="fldFalseInfoCount">Value for FalseInfoCount</param>
/// <param name="fldTrueInfoCount">Value for TrueInfoCount</param>
/// <param name="fldAdminInpsected">Value for AdminInpsected</param>
/// <param name="fldDateLastChecked">Value for DateLastChecked</param>
/// <param name="fldSourceUrl">Value for SourceUrl</param>
public virtual int Update(int fldContentInspectionId
, bool fldIsArchived
, bool fldIsBeingProposed
, int fldProposedByUserId
, int fldConfirmedByUserId
, int fldFalseInfoCount
, int fldTrueInfoCount
, bool fldAdminInpsected
, DateTime fldDateLastChecked
, string fldSourceUrl
)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Update]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
,
new SqlParameter("@IsArchived", fldIsArchived)
,
new SqlParameter("@IsBeingProposed", fldIsBeingProposed)
,
new SqlParameter("@ProposedByUserId", fldProposedByUserId)
,
new SqlParameter("@ConfirmedByUserId", fldConfirmedByUserId)
,
new SqlParameter("@FalseInfoCount", fldFalseInfoCount)
,
new SqlParameter("@TrueInfoCount", fldTrueInfoCount)
,
new SqlParameter("@AdminInpsected", fldAdminInpsected)
,
new SqlParameter("@DateLastChecked", fldDateLastChecked)
,
new SqlParameter("@SourceUrl", fldSourceUrl)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Run ContentInspection_Update.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="fldIsArchived">Value for IsArchived</param>
/// <param name="fldIsBeingProposed">Value for IsBeingProposed</param>
/// <param name="fldProposedByUserId">Value for ProposedByUserId</param>
/// <param name="fldConfirmedByUserId">Value for ConfirmedByUserId</param>
/// <param name="fldFalseInfoCount">Value for FalseInfoCount</param>
/// <param name="fldTrueInfoCount">Value for TrueInfoCount</param>
/// <param name="fldAdminInpsected">Value for AdminInpsected</param>
/// <param name="fldDateLastChecked">Value for DateLastChecked</param>
/// <param name="fldSourceUrl">Value for SourceUrl</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(int fldContentInspectionId
, bool fldIsArchived
, bool fldIsBeingProposed
, int fldProposedByUserId
, int fldConfirmedByUserId
, int fldFalseInfoCount
, int fldTrueInfoCount
, bool fldAdminInpsected
, DateTime fldDateLastChecked
, string fldSourceUrl
, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Update]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
,
new SqlParameter("@IsArchived", fldIsArchived)
,
new SqlParameter("@IsBeingProposed", fldIsBeingProposed)
,
new SqlParameter("@ProposedByUserId", fldProposedByUserId)
,
new SqlParameter("@ConfirmedByUserId", fldConfirmedByUserId)
,
new SqlParameter("@FalseInfoCount", fldFalseInfoCount)
,
new SqlParameter("@TrueInfoCount", fldTrueInfoCount)
,
new SqlParameter("@AdminInpsected", fldAdminInpsected)
,
new SqlParameter("@DateLastChecked", fldDateLastChecked)
,
new SqlParameter("@SourceUrl", fldSourceUrl)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Update by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(ContentInspectionContract row)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Update]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", row.ContentInspectionId)
,
new SqlParameter("@IsArchived", row.IsArchived)
,
new SqlParameter("@IsBeingProposed", row.IsBeingProposed)
,
new SqlParameter("@ProposedByUserId", row.ProposedByUserId)
,
new SqlParameter("@ConfirmedByUserId", row.ConfirmedByUserId)
,
new SqlParameter("@FalseInfoCount", row.FalseInfoCount)
,
new SqlParameter("@TrueInfoCount", row.TrueInfoCount)
,
new SqlParameter("@AdminInpsected", row.AdminInpsected)
,
new SqlParameter("@DateLastChecked", row.DateLastChecked)
,
new SqlParameter("@SourceUrl", row.SourceUrl)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Update by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Update(ContentInspectionContract row, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Update]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", row.ContentInspectionId)
,
new SqlParameter("@IsArchived", row.IsArchived)
,
new SqlParameter("@IsBeingProposed", row.IsBeingProposed)
,
new SqlParameter("@ProposedByUserId", row.ProposedByUserId)
,
new SqlParameter("@ConfirmedByUserId", row.ConfirmedByUserId)
,
new SqlParameter("@FalseInfoCount", row.FalseInfoCount)
,
new SqlParameter("@TrueInfoCount", row.TrueInfoCount)
,
new SqlParameter("@AdminInpsected", row.AdminInpsected)
,
new SqlParameter("@DateLastChecked", row.DateLastChecked)
,
new SqlParameter("@SourceUrl", row.SourceUrl)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <returns>The number of rows affected.</returns>
public virtual int UpdateAll(List<ContentInspectionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
rowCount = UpdateAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Update</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int UpdateAll(List<ContentInspectionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Update(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Run ContentInspection_Delete.
/// </summary>
/// <returns>The number of rows affected.</returns>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
public virtual int Delete(int fldContentInspectionId
)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Delete]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Run ContentInspection_Delete.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(int fldContentInspectionId
, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Delete]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Delete by providing a populated data row container
/// </summary>
/// <param name="row">The table row data to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(ContentInspectionContract row)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Delete]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", row.ContentInspectionId)
});
rowCount = cmd.ExecuteNonQuery();
}
});
return rowCount;
}
/// <summary>
/// Delete by providing a populated data contract
/// </summary>
/// <param name="row">The table row data to use</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Delete(ContentInspectionContract row, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Delete]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", row.ContentInspectionId)
});
rowCount = cmd.ExecuteNonQuery();
}
return rowCount;
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <returns>The number of rows affected.</returns>
public virtual int DeleteAll(List<ContentInspectionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
rowCount = DeleteAll(rows, x, null);
});
return rowCount;
}
/// <summary>
/// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Delete</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int DeleteAll(List<ContentInspectionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Delete(row, connection, transaction);
return rowCount;
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldContentInspectionId
)
{
bool result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Exists]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
});
result = (bool)cmd.ExecuteScalar();
}
});
return result;
}
/// <summary>
/// Determine if the table contains a row with the existing values
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>True, if the values exist, or false.</returns>
public virtual bool Exists(int fldContentInspectionId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Exists]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
});
return (bool)cmd.ExecuteScalar();
}
}
/// <summary>
/// Run ContentInspection_Search, and return results as a list of ContentInspectionRow.
/// </summary>
/// <param name="fldSourceUrl">Value for SourceUrl</param>
/// <returns>A collection of ContentInspectionRow.</returns>
public virtual bool Search(string fldSourceUrl
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Search]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@SourceUrl", fldSourceUrl)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run ContentInspection_Search, and return results as a list of ContentInspectionRow.
/// </summary>
/// <param name="fldSourceUrl">Value for SourceUrl</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ContentInspectionRow.</returns>
public virtual bool Search(string fldSourceUrl
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_Search]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@SourceUrl", fldSourceUrl)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run ContentInspection_SelectAll, and return results as a list of ContentInspectionRow.
/// </summary>
/// <returns>A collection of ContentInspectionRow.</returns>
public virtual bool SelectAll()
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_SelectAll]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run ContentInspection_SelectAll, and return results as a list of ContentInspectionRow.
/// </summary>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ContentInspectionRow.</returns>
public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_SelectAll]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run ContentInspection_SelectBy_ContentInspectionId, and return results as a list of ContentInspectionRow.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <returns>A collection of ContentInspectionRow.</returns>
public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_SelectBy_ContentInspectionId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run ContentInspection_SelectBy_ContentInspectionId, and return results as a list of ContentInspectionRow.
/// </summary>
/// <param name="fldContentInspectionId">Value for ContentInspectionId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ContentInspectionRow.</returns>
public virtual bool SelectBy_ContentInspectionId(int fldContentInspectionId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_SelectBy_ContentInspectionId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ContentInspectionId", fldContentInspectionId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run ContentInspection_SelectBy_ProposedByUserId, and return results as a list of ContentInspectionRow.
/// </summary>
/// <param name="fldProposedByUserId">Value for ProposedByUserId</param>
/// <returns>A collection of ContentInspectionRow.</returns>
public virtual bool SelectBy_ProposedByUserId(int fldProposedByUserId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_SelectBy_ProposedByUserId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ProposedByUserId", fldProposedByUserId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run ContentInspection_SelectBy_ProposedByUserId, and return results as a list of ContentInspectionRow.
/// </summary>
/// <param name="fldProposedByUserId">Value for ProposedByUserId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ContentInspectionRow.</returns>
public virtual bool SelectBy_ProposedByUserId(int fldProposedByUserId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_SelectBy_ProposedByUserId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ProposedByUserId", fldProposedByUserId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Run ContentInspection_SelectBy_ConfirmedByUserId, and return results as a list of ContentInspectionRow.
/// </summary>
/// <param name="fldConfirmedByUserId">Value for ConfirmedByUserId</param>
/// <returns>A collection of ContentInspectionRow.</returns>
public virtual bool SelectBy_ConfirmedByUserId(int fldConfirmedByUserId
)
{
var result = false;
VotingInfoDb.ConnectThen(x =>
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_SelectBy_ConfirmedByUserId]", x)
{
CommandType = CommandType.StoredProcedure,
CommandTimeout = DefaultCommandTimeout
})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ConfirmedByUserId", fldConfirmedByUserId)
});
using(var r = cmd.ExecuteReader()) result = ReadAll(r);
}
});
return result;
}
/// <summary>
/// Run ContentInspection_SelectBy_ConfirmedByUserId, and return results as a list of ContentInspectionRow.
/// </summary>
/// <param name="fldConfirmedByUserId">Value for ConfirmedByUserId</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>A collection of ContentInspectionRow.</returns>
public virtual bool SelectBy_ConfirmedByUserId(int fldConfirmedByUserId
, SqlConnection connection, SqlTransaction transaction)
{
using (
var cmd = new SqlCommand("[Data].[ContentInspection_SelectBy_ConfirmedByUserId]", connection)
{CommandType = CommandType.StoredProcedure,Transaction = transaction})
{
cmd.Parameters.AddRange(new[] {
new SqlParameter("@ConfirmedByUserId", fldConfirmedByUserId)
});
using(var r = cmd.ExecuteReader()) return ReadAll(r);
}
}
/// <summary>
/// Read all items into this collection
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadAll(SqlDataReader reader)
{
var canRead = ReadOne(reader);
var result = canRead;
while (canRead) canRead = ReadOne(reader);
return result;
}
/// <summary>
/// Read one item into Results
/// </summary>
/// <param name="reader">The result of running a sql command.</param>
public virtual bool ReadOne(SqlDataReader reader)
{
if (reader.Read())
{
Results.Add(
new ContentInspectionContract
{
ContentInspectionId = reader.GetInt32(0),
IsArchived = reader.GetBoolean(1),
IsBeingProposed = reader.GetBoolean(2),
ProposedByUserId = reader.GetInt32(3),
ConfirmedByUserId = reader.GetInt32(4),
FalseInfoCount = reader.GetInt32(5),
TrueInfoCount = reader.GetInt32(6),
AdminInpsected = reader.GetBoolean(7),
DateLastChecked = reader.GetDateTime(8),
SourceUrl = reader.GetString(9),
});
return true;
}
return false;
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <returns>The number of rows affected.</returns>
public virtual int Save(ContentInspectionContract row)
{
if(row == null) return 0;
if(row.ContentInspectionId != null) return Update(row);
return Insert(row);
}
/// <summary>
/// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value).
/// </summary>
/// <param name="row">The data to save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int Save(ContentInspectionContract row, SqlConnection connection, SqlTransaction transaction)
{
if(row == null) return 0;
if(row.ContentInspectionId != null) return Update(row, connection, transaction);
return Insert(row, connection, transaction);
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster).
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <returns>The number of rows affected.</returns>
public virtual int SaveAll(List<ContentInspectionContract> rows)
{
var rowCount = 0;
VotingInfoDb.ConnectThen(x =>
{
foreach(var row in rows) rowCount += Save(row, x, null);
});
return rowCount;
}
/// <summary>
/// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope.
/// </summary>
/// <param name="rows">The table rows to Save</param>
/// <param name="connection">The SqlConnection to use</param>
/// <param name="transaction">The SqlTransaction to use</param>
/// <returns>The number of rows affected.</returns>
public virtual int SaveAll(List<ContentInspectionContract> rows, SqlConnection connection, SqlTransaction transaction)
{
var rowCount = 0;
foreach(var row in rows) rowCount += Save(row, connection, transaction);
return rowCount;
}
}
}
| |
/*
* 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.Linq;
using System.Net;
using System.Text.RegularExpressions;
using log4net;
using log4net.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Capabilities.Handlers;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
namespace OpenSim.Capabilities.Handlers.FetchInventory.Tests
{
[TestFixture]
public class FetchInventoryDescendents2HandlerTests : OpenSimTestCase
{
private UUID m_userID = UUID.Zero;
private Scene m_scene;
private UUID m_rootFolderID;
private int m_rootDescendents;
private UUID m_notecardsFolder;
private UUID m_objectsFolder;
private void Init()
{
// Create an inventory that looks like this:
//
// /My Inventory
// <other system folders>
// /Objects
// Some Object
// /Notecards
// Notecard 1
// Notecard 2
// /Test Folder
// Link to notecard -> /Notecards/Notecard 2
// Link to Objects folder -> /Objects
m_scene = new SceneHelpers().SetupScene();
m_scene.InventoryService.CreateUserInventory(m_userID);
m_rootFolderID = m_scene.InventoryService.GetRootFolder(m_userID).ID;
InventoryFolderBase of = m_scene.InventoryService.GetFolderForType(m_userID, FolderType.Object);
m_objectsFolder = of.ID;
// Add an object
InventoryItemBase item = new InventoryItemBase(new UUID("b0000000-0000-0000-0000-00000000000b"), m_userID);
item.AssetID = UUID.Random();
item.AssetType = (int)AssetType.Object;
item.Folder = m_objectsFolder;
item.Name = "Some Object";
m_scene.InventoryService.AddItem(item);
InventoryFolderBase ncf = m_scene.InventoryService.GetFolderForType(m_userID, FolderType.Notecard);
m_notecardsFolder = ncf.ID;
// Add a notecard
item = new InventoryItemBase(new UUID("10000000-0000-0000-0000-000000000001"), m_userID);
item.AssetID = UUID.Random();
item.AssetType = (int)AssetType.Notecard;
item.Folder = m_notecardsFolder;
item.Name = "Test Notecard 1";
m_scene.InventoryService.AddItem(item);
// Add another notecard
item.ID = new UUID("20000000-0000-0000-0000-000000000002");
item.AssetID = new UUID("a0000000-0000-0000-0000-00000000000a");
item.Name = "Test Notecard 2";
m_scene.InventoryService.AddItem(item);
// Add a folder
InventoryFolderBase folder = new InventoryFolderBase(new UUID("f0000000-0000-0000-0000-00000000000f"), "Test Folder", m_userID, m_rootFolderID);
m_scene.InventoryService.AddFolder(folder);
// Add a link to notecard 2 in Test Folder
item.AssetID = item.ID; // use item ID of notecard 2
item.ID = new UUID("40000000-0000-0000-0000-000000000004");
item.AssetType = (int)AssetType.Link;
item.Folder = folder.ID;
item.Name = "Link to notecard";
m_scene.InventoryService.AddItem(item);
// Add a link to the Objects folder in Test Folder
item.AssetID = m_scene.InventoryService.GetFolderForType(m_userID, FolderType.Object).ID; // use item ID of Objects folder
item.ID = new UUID("50000000-0000-0000-0000-000000000005");
item.AssetType = (int)AssetType.LinkFolder;
item.Folder = folder.ID;
item.Name = "Link to Objects folder";
m_scene.InventoryService.AddItem(item);
InventoryCollection coll = m_scene.InventoryService.GetFolderContent(m_userID, m_rootFolderID);
m_rootDescendents = coll.Items.Count + coll.Folders.Count;
Console.WriteLine("Number of descendents: " + m_rootDescendents);
}
[Test]
public void Test_001_SimpleFolder()
{
TestHelpers.InMethod();
Init();
FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += m_rootFolderID;
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>";
string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
Assert.That(llsdresponse != null, Is.True, "Incorrect null response");
Assert.That(llsdresponse != string.Empty, Is.True, "Incorrect empty response");
Assert.That(llsdresponse.Contains("00000000-0000-0000-0000-000000000000"), Is.True, "Response should contain userID");
string descendents = "descendents</key><integer>" + m_rootDescendents + "</integer>";
Assert.That(llsdresponse.Contains(descendents), Is.True, "Incorrect number of descendents");
Console.WriteLine(llsdresponse);
}
[Test]
public void Test_002_MultipleFolders()
{
TestHelpers.InMethod();
FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
string request = "<llsd><map><key>folders</key><array>";
request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += m_rootFolderID;
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>";
request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += m_notecardsFolder;
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>";
request += "</array></map></llsd>";
string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
Console.WriteLine(llsdresponse);
string descendents = "descendents</key><integer>" + m_rootDescendents + "</integer>";
Assert.That(llsdresponse.Contains(descendents), Is.True, "Incorrect number of descendents for root folder");
descendents = "descendents</key><integer>2</integer>";
Assert.That(llsdresponse.Contains(descendents), Is.True, "Incorrect number of descendents for Notecard folder");
Assert.That(llsdresponse.Contains("10000000-0000-0000-0000-000000000001"), Is.True, "Notecard 1 is missing from response");
Assert.That(llsdresponse.Contains("20000000-0000-0000-0000-000000000002"), Is.True, "Notecard 2 is missing from response");
}
[Test]
public void Test_003_Links()
{
TestHelpers.InMethod();
FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += "f0000000-0000-0000-0000-00000000000f";
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>";
string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
Console.WriteLine(llsdresponse);
string descendents = "descendents</key><integer>2</integer>";
Assert.That(llsdresponse.Contains(descendents), Is.True, "Incorrect number of descendents for Test Folder");
// Make sure that the note card link is included
Assert.That(llsdresponse.Contains("Link to notecard"), Is.True, "Link to notecard is missing");
//Make sure the notecard item itself is included
Assert.That(llsdresponse.Contains("Test Notecard 2"), Is.True, "Notecard 2 item (the source) is missing");
// Make sure that the source item is before the link item
int pos1 = llsdresponse.IndexOf("Test Notecard 2");
int pos2 = llsdresponse.IndexOf("Link to notecard");
Assert.Less(pos1, pos2, "Source of link is after link");
// Make sure the folder link is included
Assert.That(llsdresponse.Contains("Link to Objects folder"), Is.True, "Link to Objects folder is missing");
/* contents of link folder are not supposed to be listed
// Make sure the objects inside the Objects folder are included
// Note: I'm not entirely sure this is needed, but that's what I found in the implementation
Assert.That(llsdresponse.Contains("Some Object"), Is.True, "Some Object item (contents of the source) is missing");
*/
// Make sure that the source item is before the link item
pos1 = llsdresponse.IndexOf("Some Object");
pos2 = llsdresponse.IndexOf("Link to Objects folder");
Assert.Less(pos1, pos2, "Contents of source of folder link is after folder link");
}
[Test]
public void Test_004_DuplicateFolders()
{
TestHelpers.InMethod();
FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
string request = "<llsd><map><key>folders</key><array>";
request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += m_rootFolderID;
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>";
request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += m_notecardsFolder;
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>";
request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += m_rootFolderID;
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>";
request += "<map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += m_notecardsFolder;
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map>";
request += "</array></map></llsd>";
string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
Console.WriteLine(llsdresponse);
string root_folder = "<key>folder_id</key><uuid>" + m_rootFolderID + "</uuid>";
string notecards_folder = "<key>folder_id</key><uuid>" + m_notecardsFolder + "</uuid>";
Assert.That(llsdresponse.Contains(root_folder), "Missing root folder");
Assert.That(llsdresponse.Contains(notecards_folder), "Missing notecards folder");
int count = Regex.Matches(llsdresponse, root_folder).Count;
Assert.AreEqual(1, count, "More than 1 root folder in response");
count = Regex.Matches(llsdresponse, notecards_folder).Count;
Assert.AreEqual(2, count, "More than 1 notecards folder in response"); // Notecards will also be under root, so 2
}
[Test]
public void Test_005_FolderZero()
{
TestHelpers.InMethod();
Init();
FetchInvDescHandler handler = new FetchInvDescHandler(m_scene.InventoryService, null, m_scene);
TestOSHttpRequest req = new TestOSHttpRequest();
TestOSHttpResponse resp = new TestOSHttpResponse();
string request = "<llsd><map><key>folders</key><array><map><key>fetch_folders</key><integer>1</integer><key>fetch_items</key><boolean>1</boolean><key>folder_id</key><uuid>";
request += UUID.Zero;
request += "</uuid><key>owner_id</key><uuid>00000000-0000-0000-0000-000000000000</uuid><key>sort_order</key><integer>1</integer></map></array></map></llsd>";
string llsdresponse = handler.FetchInventoryDescendentsRequest(request, "/FETCH", string.Empty, req, resp);
Assert.That(llsdresponse != null, Is.True, "Incorrect null response");
Assert.That(llsdresponse != string.Empty, Is.True, "Incorrect empty response");
Assert.That(llsdresponse.Contains("bad_folders</key><array><uuid>00000000-0000-0000-0000-000000000000"), Is.True, "Folder Zero should be a bad folder");
Console.WriteLine(llsdresponse);
}
}
}
| |
/*
* Copyright (c) 2014 Tenebrous
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Latest version: http://hg.tenebrous.co.uk/unityeditorenhancements/wiki/Home
*/
using System;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Tenebrous.EditorEnhancements
{
internal static class AssetInfo
{
public static string GetPreviewInfo(this object pObject)
{
string info = "";
string typename = pObject.GetType().ToString().Replace("UnityEngine.", "");
if (pObject is AudioClip)
info = ((AudioClip) pObject).GetPreviewInfo();
else if (pObject is Texture2D)
info = ((Texture2D) pObject).GetPreviewInfo();
else if (pObject is Material)
info = ((Material) pObject).GetPreviewInfo();
else if (pObject is Mesh)
info = ((Mesh) pObject).GetPreviewInfo();
else if (pObject is MeshFilter)
info = ((MeshFilter) pObject).GetPreviewInfo();
else if (pObject is MeshRenderer)
info = ((MeshRenderer) pObject).GetPreviewInfo();
else if (pObject is GameObject)
info = ((GameObject) pObject).GetPreviewInfo();
else if (pObject is MonoScript)
{
typename = "";
info = ((MonoScript) pObject).GetPreviewInfo();
}
else if (pObject is Shader)
info = ((Shader) pObject).GetPreviewInfo();
else if (pObject is MonoBehaviour)
{
typename = pObject.GetType().BaseType.ToString().Replace("UnityEngine.", "");
info = ((MonoBehaviour) pObject).GetPreviewInfo();
}
else if (pObject is Behaviour)
info = ((Behaviour) pObject).GetPreviewInfo();
if (typename != "")
if (info == "")
info += typename;
else
info += " (" + typename + ")";
return (info);
}
public static string GetPreviewInfo(this AudioClip pObject)
{
string info = "";
TimeSpan clipTimespan = TimeSpan.FromSeconds(pObject.length);
if (clipTimespan.Hours > 0)
info += clipTimespan.Hours + ":";
info += clipTimespan.Minutes.ToString("00") + ":" + clipTimespan.Seconds.ToString("00") + "." +
clipTimespan.Milliseconds.ToString("000") + " ";
if (pObject.channels == 1)
info += "Mono\n";
else if (pObject.channels == 2)
info += "Stereo\n";
else
info += pObject.channels + " channels\n";
return (info);
}
public static string GetPreviewInfo(this Texture2D pObject)
{
if( pObject != null )
return pObject.format.ToString() + "\n"
+ pObject.width + "x" + pObject.height;
return "";
}
public static string GetPreviewInfo(this Material pObject)
{
string info = "";
info = pObject.shader.name;
foreach (Object obj in EditorUtility.CollectDependencies(new Object[] {pObject}))
if (obj is Texture)
info += "\n - " + obj.name;
return (info);
}
public static string GetPreviewInfo(this MeshFilter pObject)
{
if( pObject != null && pObject.sharedMesh != null )
return pObject.sharedMesh.GetPreviewInfo();
return "";
}
public static string GetPreviewInfo(this Mesh pObject)
{
if( pObject != null )
return pObject.vertexCount + " verts " + pObject.triangles.Length + " tris"
+ "\n" + pObject.name;
return "";
}
public static string GetPreviewInfo(this MeshRenderer pObject)
{
return "";
}
public static string GetPreviewInfo(this MonoScript pObject)
{
if( pObject != null )
{
Type assetclass = pObject.GetClass();
if( assetclass != null )
return assetclass.ToString() + "\n(" + assetclass.BaseType.ToString().Replace( "UnityEngine.", "" ) + ")";
else
return "(multiple classes)";
}
return "";
}
public static string GetPreviewInfo(this Shader pObject)
{
if( pObject != null )
return pObject.renderQueue.ToString();
return "";
}
public static string GetPreviewInfo(this MonoBehaviour pObject)
{
if( pObject != null )
{
MonoScript ms = MonoScript.FromMonoBehaviour( pObject );
if( ms != null )
return ms.name;
}
return "";
}
public static string GetPreviewInfo(this GameObject pObject)
{
if( pObject != null )
{
GameObject parent = PrefabUtility.GetPrefabParent( pObject ) as GameObject;
if( parent != null )
return AssetDatabase.GetAssetPath( parent );
}
return "";
}
// components
public static string GetPreviewInfo(this Behaviour pObject)
{
if( pObject == null )
return "";
else if (pObject is Light)
return (pObject as Light).GetPreviewInfo();
else if (pObject is Camera)
return (pObject as Camera).GetPreviewInfo();
else if (pObject is AudioSource)
return (pObject as AudioSource).GetPreviewInfo();
else if (pObject is AudioReverbFilter)
return (pObject as AudioReverbFilter).GetPreviewInfo();
return "";
}
public static string GetPreviewInfo(this Light pObject)
{
if( pObject != null )
return pObject.type.ToString();
return "";
}
public static string GetPreviewInfo(this Camera pObject)
{
if( pObject != null )
{
if( pObject.orthographic )
return "Orthographic";
else
return "Perspective";
}
return "";
}
public static string GetPreviewInfo(this AudioSource pObject)
{
if( pObject != null && pObject.clip != null )
return pObject.clip.name;
return "";
}
public static string GetPreviewInfo(this AudioReverbFilter pObject)
{
if( pObject != null )
return pObject.reverbPreset.ToString();
return "";
}
// other extensions
public static bool HasAnyRenderers(this GameObject pObject)
{
if( pObject == null )
return false;
if (pObject.GetComponent<Renderer>() != null)
return (true);
foreach (Transform child in pObject.transform)
if (child.gameObject.HasAnyRenderers())
return (true);
return false;
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Interactive
{
/// <summary>
/// Represents a process that hosts an interactive session.
/// </summary>
/// <remarks>
/// Handles spawning of the host process and communication between the local callers and the remote session.
/// </remarks>
internal sealed partial class InteractiveHost : MarshalByRefObject
{
private readonly Type _replType;
private readonly string _hostPath;
private readonly string _initialWorkingDirectory;
// adjustable for testing purposes
private readonly int _millisecondsTimeout;
private const int MaxAttemptsToCreateProcess = 2;
private LazyRemoteService _lazyRemoteService;
private int _remoteServiceInstanceId;
// Remoting channel to communicate with the remote service.
private IpcServerChannel _serverChannel;
private TextWriter _output;
private TextWriter _errorOutput;
internal event Action<InteractiveHostOptions> ProcessStarting;
public InteractiveHost(
Type replType,
string hostPath,
string workingDirectory,
int millisecondsTimeout = 5000)
{
_millisecondsTimeout = millisecondsTimeout;
_output = TextWriter.Null;
_errorOutput = TextWriter.Null;
_replType = replType;
_hostPath = hostPath;
_initialWorkingDirectory = workingDirectory;
var serverProvider = new BinaryServerFormatterSinkProvider { TypeFilterLevel = TypeFilterLevel.Full };
_serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), "ReplChannel-" + Guid.NewGuid(), serverProvider);
ChannelServices.RegisterChannel(_serverChannel, ensureSecurity: false);
}
#region Test hooks
internal event Action<char[], int> OutputReceived;
internal event Action<char[], int> ErrorOutputReceived;
internal Process TryGetProcess()
{
InitializedRemoteService initializedService;
return (_lazyRemoteService?.InitializedService != null &&
_lazyRemoteService.InitializedService.TryGetValue(out initializedService)) ? initializedService.ServiceOpt.Process : null;
}
internal Service TryGetService()
{
var initializedService = TryGetOrCreateRemoteServiceAsync().Result;
return initializedService.ServiceOpt?.Service;
}
// Triggered whenever we create a fresh process.
// The ProcessExited event is not hooked yet.
internal event Action<Process> InteractiveHostProcessCreated;
internal IpcServerChannel _ServerChannel
{
get { return _serverChannel; }
}
internal void Dispose(bool joinThreads)
{
Dispose(joinThreads, disposing: true);
}
#endregion
private static string GenerateUniqueChannelLocalName()
{
return typeof(InteractiveHost).FullName + Guid.NewGuid();
}
public override object InitializeLifetimeService()
{
return null;
}
private RemoteService TryStartProcess(CancellationToken cancellationToken)
{
Process newProcess = null;
int newProcessId = -1;
Semaphore semaphore = null;
try
{
int currentProcessId = Process.GetCurrentProcess().Id;
bool semaphoreCreated;
string semaphoreName;
while (true)
{
semaphoreName = "InteractiveHostSemaphore-" + Guid.NewGuid();
semaphore = new Semaphore(0, 1, semaphoreName, out semaphoreCreated);
if (semaphoreCreated)
{
break;
}
semaphore.Close();
cancellationToken.ThrowIfCancellationRequested();
}
var remoteServerPort = "InteractiveHostChannel-" + Guid.NewGuid();
var processInfo = new ProcessStartInfo(_hostPath);
processInfo.Arguments = remoteServerPort + " " + semaphoreName + " " + currentProcessId;
processInfo.WorkingDirectory = _initialWorkingDirectory;
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardError = true;
processInfo.StandardErrorEncoding = Encoding.UTF8;
processInfo.StandardOutputEncoding = Encoding.UTF8;
newProcess = new Process();
newProcess.StartInfo = processInfo;
// enables Process.Exited event to be raised:
newProcess.EnableRaisingEvents = true;
newProcess.Start();
// test hook:
var processCreated = InteractiveHostProcessCreated;
if (processCreated != null)
{
processCreated(newProcess);
}
cancellationToken.ThrowIfCancellationRequested();
try
{
newProcessId = newProcess.Id;
}
catch
{
newProcessId = 0;
}
// sync:
while (!semaphore.WaitOne(_millisecondsTimeout))
{
if (!CheckAlive(newProcess))
{
return null;
}
_output.WriteLine(FeaturesResources.AttemptToConnectToProcess, newProcessId);
cancellationToken.ThrowIfCancellationRequested();
}
// instantiate remote service:
Service newService;
try
{
newService = (Service)Activator.GetObject(
typeof(Service),
"ipc://" + remoteServerPort + "/" + Service.ServiceName);
cancellationToken.ThrowIfCancellationRequested();
newService.Initialize(_replType);
}
catch (RemotingException) when (!CheckAlive(newProcess))
{
return null;
}
return new RemoteService(this, newProcess, newProcessId, newService);
}
catch (OperationCanceledException)
{
if (newProcess != null)
{
RemoteService.InitiateTermination(newProcess, newProcessId);
}
return null;
}
finally
{
if (semaphore != null)
{
semaphore.Close();
}
}
}
private bool CheckAlive(Process process)
{
bool alive = process.IsAlive();
if (!alive)
{
_errorOutput.WriteLine(FeaturesResources.FailedToLaunchProcess, _hostPath, process.ExitCode);
_errorOutput.WriteLine(process.StandardError.ReadToEnd());
}
return alive;
}
~InteractiveHost()
{
Dispose(joinThreads: false, disposing: false);
}
public void Dispose()
{
Dispose(joinThreads: false, disposing: true);
}
private void Dispose(bool joinThreads, bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
DisposeChannel();
}
if (_lazyRemoteService != null)
{
_lazyRemoteService.Dispose(joinThreads);
_lazyRemoteService = null;
}
}
private void DisposeChannel()
{
if (_serverChannel != null)
{
ChannelServices.UnregisterChannel(_serverChannel);
_serverChannel = null;
}
}
public TextWriter Output
{
get
{
return _output;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var oldOutput = Interlocked.Exchange(ref _output, value);
oldOutput.Flush();
}
}
public TextWriter ErrorOutput
{
get
{
return _errorOutput;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
var oldOutput = Interlocked.Exchange(ref _errorOutput, value);
oldOutput.Flush();
}
}
internal void OnOutputReceived(bool error, char[] buffer, int count)
{
var notification = error ? ErrorOutputReceived : OutputReceived;
if (notification != null)
{
notification(buffer, count);
}
var writer = error ? ErrorOutput : Output;
writer.Write(buffer, 0, count);
}
private LazyRemoteService CreateRemoteService(InteractiveHostOptions options, bool skipInitialization)
{
return new LazyRemoteService(this, options, Interlocked.Increment(ref _remoteServiceInstanceId), skipInitialization);
}
private Task OnProcessExited(Process process)
{
ReportProcessExited(process);
return TryGetOrCreateRemoteServiceAsync();
}
private void ReportProcessExited(Process process)
{
int? exitCode;
try
{
exitCode = process.HasExited ? process.ExitCode : (int?)null;
}
catch
{
exitCode = null;
}
if (exitCode.HasValue)
{
_errorOutput.WriteLine(FeaturesResources.HostingProcessExitedWithExitCode, exitCode.Value);
}
}
private async Task<InitializedRemoteService> TryGetOrCreateRemoteServiceAsync()
{
try
{
LazyRemoteService currentRemoteService = _lazyRemoteService;
// disposed or not reset:
Debug.Assert(currentRemoteService != null);
for (int attempt = 0; attempt < MaxAttemptsToCreateProcess; attempt++)
{
var initializedService = await currentRemoteService.InitializedService.GetValueAsync(currentRemoteService.CancellationSource.Token).ConfigureAwait(false);
if (initializedService.ServiceOpt != null && initializedService.ServiceOpt.Process.IsAlive())
{
return initializedService;
}
// Service failed to start or initialize or the process died.
var newService = CreateRemoteService(currentRemoteService.Options, skipInitialization: !initializedService.InitializationResult.Success);
var previousService = Interlocked.CompareExchange(ref _lazyRemoteService, newService, currentRemoteService);
if (previousService == currentRemoteService)
{
// we replaced the service whose process we know is dead:
currentRemoteService.Dispose(joinThreads: false);
currentRemoteService = newService;
}
else
{
// the process was reset in between our checks, try to use the new service:
newService.Dispose(joinThreads: false);
currentRemoteService = previousService;
}
}
_errorOutput.WriteLine(FeaturesResources.UnableToCreateHostingProcess);
}
catch (OperationCanceledException)
{
// The user reset the process during initialization.
// The reset operation will recreate the process.
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
return default(InitializedRemoteService);
}
private async Task<TResult> Async<TResult>(Action<Service, RemoteAsyncOperation<TResult>> action)
{
try
{
var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false);
if (initializedService.ServiceOpt == null)
{
return default(TResult);
}
return await new RemoteAsyncOperation<TResult>(initializedService.ServiceOpt).AsyncExecute(action).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private static async Task<TResult> Async<TResult>(RemoteService remoteService, Action<Service, RemoteAsyncOperation<TResult>> action)
{
try
{
return await new RemoteAsyncOperation<TResult>(remoteService).AsyncExecute(action).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
#region Operations
/// <summary>
/// Restarts and reinitializes the host process (or starts a new one if it is not running yet).
/// </summary>
/// <param name="optionsOpt">The options to initialize the new process with, or null to use the current options (or default options if the process isn't running yet).</param>
public async Task<RemoteExecutionResult> ResetAsync(InteractiveHostOptions optionsOpt)
{
try
{
// replace the existing service with a new one:
var newService = CreateRemoteService(optionsOpt ?? _lazyRemoteService?.Options ?? InteractiveHostOptions.Default, skipInitialization: false);
LazyRemoteService oldService = Interlocked.Exchange(ref _lazyRemoteService, newService);
if (oldService != null)
{
oldService.Dispose(joinThreads: false);
}
var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false);
if (initializedService.ServiceOpt == null)
{
return default(RemoteExecutionResult);
}
return initializedService.InitializationResult;
}
catch (Exception e) when (FatalError.Report(e))
{
throw ExceptionUtilities.Unreachable;
}
}
/// <summary>
/// Asynchronously executes given code in the remote interactive session.
/// </summary>
/// <param name="code">The code to execute.</param>
/// <remarks>
/// This method is thread safe but operations are sent to the remote process
/// asynchronously so tasks should be executed serially if order is important.
/// </remarks>
public Task<RemoteExecutionResult> ExecuteAsync(string code)
{
Debug.Assert(code != null);
return Async<RemoteExecutionResult>((service, operation) => service.ExecuteAsync(operation, code));
}
/// <summary>
/// Asynchronously executes given code in the remote interactive session.
/// </summary>
/// <param name="path">The file to execute.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <remarks>
/// This method is thread safe but operations are sent to the remote process
/// asynchronously so tasks should be executed serially if order is important.
/// </remarks>
public Task<RemoteExecutionResult> ExecuteFileAsync(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
return Async<RemoteExecutionResult>((service, operation) => service.ExecuteFileAsync(operation, path));
}
/// <summary>
/// Asynchronously adds a reference to the set of available references for next submission.
/// </summary>
/// <param name="reference">The reference to add.</param>
/// <remarks>
/// This method is thread safe but operations are sent to the remote process
/// asynchronously so tasks should be executed serially if order is important.
/// </remarks>
public Task<bool> AddReferenceAsync(string reference)
{
Debug.Assert(reference != null);
return Async<bool>((service, operation) => service.AddReferenceAsync(operation, reference));
}
/// <summary>
/// Sets the current session's search paths and base directory.
/// </summary>
public Task SetPathsAsync(string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory)
{
Debug.Assert(referenceSearchPaths != null);
Debug.Assert(sourceSearchPaths != null);
Debug.Assert(baseDirectory != null);
return Async<object>((service, operation) => service.SetPathsAsync(operation, referenceSearchPaths, sourceSearchPaths, baseDirectory));
}
#endregion
}
}
| |
using System;
using Csla;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERCLevel;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F06_Country (editable child object).<br/>
/// This is a generated base class of <see cref="F06_Country"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="F07_RegionObjects"/> of type <see cref="F07_RegionColl"/> (1:M relation to <see cref="F08_Region"/>)<br/>
/// This class is an item of <see cref="F05_CountryColl"/> collection.
/// </remarks>
[Serializable]
public partial class F06_Country : BusinessBase<F06_Country>
{
#region Static Fields
private static int _lastID;
#endregion
#region State Fields
[NotUndoable]
[NonSerialized]
internal int parent_SubContinent_ID = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Countries ID");
/// <summary>
/// Gets the Countries ID.
/// </summary>
/// <value>The Countries ID.</value>
public int Country_ID
{
get { return GetProperty(Country_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Country_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Countries Name");
/// <summary>
/// Gets or sets the Countries Name.
/// </summary>
/// <value>The Countries Name.</value>
public string Country_Name
{
get { return GetProperty(Country_NameProperty); }
set { SetProperty(Country_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F07_Country_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<F07_Country_Child> F07_Country_SingleObjectProperty = RegisterProperty<F07_Country_Child>(p => p.F07_Country_SingleObject, "F07 Country Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the F07 Country Single Object ("parent load" child property).
/// </summary>
/// <value>The F07 Country Single Object.</value>
public F07_Country_Child F07_Country_SingleObject
{
get { return GetProperty(F07_Country_SingleObjectProperty); }
private set { LoadProperty(F07_Country_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F07_Country_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<F07_Country_ReChild> F07_Country_ASingleObjectProperty = RegisterProperty<F07_Country_ReChild>(p => p.F07_Country_ASingleObject, "F07 Country ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the F07 Country ASingle Object ("parent load" child property).
/// </summary>
/// <value>The F07 Country ASingle Object.</value>
public F07_Country_ReChild F07_Country_ASingleObject
{
get { return GetProperty(F07_Country_ASingleObjectProperty); }
private set { LoadProperty(F07_Country_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="F07_RegionObjects"/> property.
/// </summary>
public static readonly PropertyInfo<F07_RegionColl> F07_RegionObjectsProperty = RegisterProperty<F07_RegionColl>(p => p.F07_RegionObjects, "F07 Region Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the F07 Region Objects ("parent load" child property).
/// </summary>
/// <value>The F07 Region Objects.</value>
public F07_RegionColl F07_RegionObjects
{
get { return GetProperty(F07_RegionObjectsProperty); }
private set { LoadProperty(F07_RegionObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F06_Country"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="F06_Country"/> object.</returns>
internal static F06_Country NewF06_Country()
{
return DataPortal.CreateChild<F06_Country>();
}
/// <summary>
/// Factory method. Loads a <see cref="F06_Country"/> object from the given F06_CountryDto.
/// </summary>
/// <param name="data">The <see cref="F06_CountryDto"/>.</param>
/// <returns>A reference to the fetched <see cref="F06_Country"/> object.</returns>
internal static F06_Country GetF06_Country(F06_CountryDto data)
{
F06_Country obj = new F06_Country();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.LoadProperty(F07_RegionObjectsProperty, F07_RegionColl.NewF07_RegionColl());
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F06_Country"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F06_Country()
{
// 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="F06_Country"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(F07_Country_SingleObjectProperty, DataPortal.CreateChild<F07_Country_Child>());
LoadProperty(F07_Country_ASingleObjectProperty, DataPortal.CreateChild<F07_Country_ReChild>());
LoadProperty(F07_RegionObjectsProperty, DataPortal.CreateChild<F07_RegionColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="F06_Country"/> object from the given <see cref="F06_CountryDto"/>.
/// </summary>
/// <param name="data">The F06_CountryDto to use.</param>
private void Fetch(F06_CountryDto data)
{
// Value properties
LoadProperty(Country_IDProperty, data.Country_ID);
LoadProperty(Country_NameProperty, data.Country_Name);
// parent properties
parent_SubContinent_ID = data.Parent_SubContinent_ID;
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Loads child <see cref="F07_Country_Child"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(F07_Country_Child child)
{
LoadProperty(F07_Country_SingleObjectProperty, child);
}
/// <summary>
/// Loads child <see cref="F07_Country_ReChild"/> object.
/// </summary>
/// <param name="child">The child object to load.</param>
internal void LoadChild(F07_Country_ReChild child)
{
LoadProperty(F07_Country_ASingleObjectProperty, child);
}
/// <summary>
/// Inserts a new <see cref="F06_Country"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(F04_SubContinent parent)
{
var dto = new F06_CountryDto();
dto.Parent_SubContinent_ID = parent.SubContinent_ID;
dto.Country_Name = Country_Name;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IF06_CountryDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(Country_IDProperty, resultDto.Country_ID);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="F06_Country"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new F06_CountryDto();
dto.Country_ID = Country_ID;
dto.Country_Name = Country_Name;
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IF06_CountryDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="F06_Country"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<IF06_CountryDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(Country_IDProperty));
}
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
}
}
| |
#region Copyright & License
//
// Author: Ian Davis <ian.f.davis@gmail.com>
// Copyright (c) 2007, Ian Davs
//
// Portions of this software were developed for NUnit.
// See NOTICE.txt for more information.
//
// 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;
using Ensurance.SyntaxHelpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Ensurance.Tests
{
/// <summary>
/// Summary description for ArrayEqualTests.
/// </summary>
[TestClass]
public class ArrayEqualsFixture : EnsuranceHelper
{
[TestMethod]
public void ArrayIsEqualToItself()
{
string[] array = {"one", "two", "three"};
AreSame( array, array );
AreEqual( array, array );
Expect( array, Is.EqualTo( array ) );
}
[TestMethod]
public void ArraysOfString()
{
string[] array1 = {"one", "two", "three"};
string[] array2 = {"one", "two", "three"};
IsFalse( array1 == array2 );
AreEqual( array1, array2 );
Expect( array1, Is.EqualTo( array2 ) );
AreEqual( array2, array1 );
Expect( array2, Is.EqualTo( array1 ) );
}
[TestMethod]
public void ArraysOfInt()
{
int[] a = new int[] {1, 2, 3};
int[] b = new int[] {1, 2, 3};
AreEqual( a, b );
AreEqual( b, a );
Expect( a, Is.EqualTo( b ) );
Expect( b, Is.EqualTo( a ) );
}
[TestMethod]
public void ArraysOfDouble()
{
double[] a = new double[] {1.0, 2.0, 3.0};
double[] b = new double[] {1.0, 2.0, 3.0};
AreEqual( a, b );
AreEqual( b, a );
Expect( a, Is.EqualTo( b ) );
Expect( b, Is.EqualTo( a ) );
}
[TestMethod]
public void ArraysOfDecimal()
{
decimal[] a = new decimal[] {1.0m, 2.0m, 3.0m};
decimal[] b = new decimal[] {1.0m, 2.0m, 3.0m};
AreEqual( a, b );
AreEqual( b, a );
Expect( a, Is.EqualTo( b ) );
Expect( b, Is.EqualTo( a ) );
}
[TestMethod]
public void ArrayOfIntAndArrayOfDouble()
{
int[] a = new int[] {1, 2, 3};
double[] b = new double[] {1.0, 2.0, 3.0};
AreEqual( a, b );
AreEqual( b, a );
Expect( a, Is.EqualTo( b ) );
Expect( b, Is.EqualTo( a ) );
}
[TestMethod]
public void ArraysDeclaredAsDifferentTypes()
{
string[] array1 = {"one", "two", "three"};
object[] array2 = {"one", "two", "three"};
AreEqual( array1, array2, "String[] not equal to Object[]" );
AreEqual( array2, array1, "Object[] not equal to String[]" );
Expect( array1, Is.EqualTo( array2 ), "String[] not equal to Object[]" );
Expect( array2, Is.EqualTo( array1 ), "Object[] not equal to String[]" );
}
[TestMethod]
public void ArraysOfMixedTypes()
{
DateTime now = DateTime.Now;
object[] array1 = new object[] {1, 2.0f, 3.5d, 7.000m, "Hello", now};
object[] array2 = new object[] {1.0d, 2, 3.5, 7, "Hello", now};
AreEqual( array1, array2 );
AreEqual( array2, array1 );
Expect( array1, Is.EqualTo( array2 ) );
Expect( array2, Is.EqualTo( array1 ) );
}
[TestMethod]
public void DoubleDimensionedArrays()
{
int[,] a = new int[,] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[,] b = new int[,] {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
AreEqual( a, b );
AreEqual( b, a );
Expect( a, Is.EqualTo( b ) );
Expect( b, Is.EqualTo( a ) );
}
[TestMethod]
public void TripleDimensionedArrays()
{
int[,,] expected = new int[,,] {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
int[,,] actual = new int[,,] {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
AreEqual( expected, actual );
Expect( actual, Is.EqualTo( expected ) );
}
[TestMethod]
public void FiveDimensionedArrays()
{
int[,,,,] expected = new int[2,2,2,2,2] {{{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}, {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}}, {{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}, {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}}};
int[,,,,] actual = new int[2,2,2,2,2] {{{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}, {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}}, {{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}, {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}}};
AreEqual( expected, actual );
Expect( actual, Is.EqualTo( expected ) );
}
[TestMethod]
public void ArraysOfArrays()
{
int[][] a = new int[][] {new int[] {1, 2, 3}, new int[] {4, 5, 6}, new int[] {7, 8, 9}};
int[][] b = new int[][] {new int[] {1, 2, 3}, new int[] {4, 5, 6}, new int[] {7, 8, 9}};
AreEqual( a, b );
AreEqual( b, a );
Expect( a, Is.EqualTo( b ) );
Expect( b, Is.EqualTo( a ) );
}
[TestMethod]
public void JaggedArrays()
{
int[][] expected = new int[][] {new int[] {1, 2, 3}, new int[] {4, 5, 6, 7}, new int[] {8, 9}};
int[][] actual = new int[][] {new int[] {1, 2, 3}, new int[] {4, 5, 6, 7}, new int[] {8, 9}};
AreEqual( expected, actual );
Expect( actual, Is.EqualTo( expected ) );
}
[TestMethod]
public void ArraysPassedAsObjects()
{
object a = new int[] {1, 2, 3};
object b = new double[] {1.0, 2.0, 3.0};
AreEqual( a, b );
AreEqual( b, a );
Expect( a, Is.EqualTo( b ) );
Expect( b, Is.EqualTo( a ) );
}
[TestMethod]
public void ArrayAndCollection()
{
int[] a = new int[] {1, 2, 3};
ICollection b = new ArrayList( a );
AreEqual( a, b );
AreEqual( b, a );
Expect( a, Is.EqualTo( b ) );
Expect( b, Is.EqualTo( a ) );
}
[TestMethod]
public void ArraysWithDifferentRanksComparedAsCollection()
{
int[] expected = new int[] {1, 2, 3, 4};
int[,] actual = new int[,] {{1, 2}, {3, 4}};
AreNotEqual( expected, actual );
Expect( actual, Is.Not.EqualTo( expected ) );
Expect( actual, Is.EqualTo( expected ).AsCollection );
}
[TestMethod]
public void ArraysWithDifferentDimensionsMatchedAsCollection()
{
int[,] expected = new int[,] {{1, 2, 3}, {4, 5, 6}};
int[,] actual = new int[,] {{1, 2}, {3, 4}, {5, 6}};
AreNotEqual( expected, actual );
Expect( actual, Is.Not.EqualTo( expected ) );
Expect( actual, Is.EqualTo( expected ).AsCollection );
}
}
}
| |
//
// MD4Managed.cs - Message Digest 4 Managed Implementation
//
// Author:
// Sebastien Pouliot (sebastien@ximian.com)
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 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;
namespace Mono.Security.Cryptography {
// References:
// a. RFC1320: The MD4 Message-Digest Algorithm
// http://www.ietf.org/rfc/rfc1320.txt
public class MD4Managed : MD4 {
private uint[] state;
private byte[] buffer;
private uint[] count;
private uint[] x;
private const int S11 = 3;
private const int S12 = 7;
private const int S13 = 11;
private const int S14 = 19;
private const int S21 = 3;
private const int S22 = 5;
private const int S23 = 9;
private const int S24 = 13;
private const int S31 = 3;
private const int S32 = 9;
private const int S33 = 11;
private const int S34 = 15;
private byte[] digest;
//--- constructor -----------------------------------------------------------
public MD4Managed ()
{
// we allocate the context memory
state = new uint [4];
count = new uint [2];
buffer = new byte [64];
digest = new byte [16];
// temporary buffer in MD4Transform that we don't want to keep allocate on each iteration
x = new uint [16];
// the initialize our context
Initialize ();
}
public override void Initialize ()
{
count [0] = 0;
count [1] = 0;
state [0] = 0x67452301;
state [1] = 0xefcdab89;
state [2] = 0x98badcfe;
state [3] = 0x10325476;
// Zeroize sensitive information
Array.Clear (buffer, 0, 64);
Array.Clear (x, 0, 16);
}
protected override void HashCore (byte[] array, int ibStart, int cbSize)
{
/* Compute number of bytes mod 64 */
int index = (int) ((count [0] >> 3) & 0x3F);
/* Update number of bits */
count [0] += (uint) (cbSize << 3);
if (count [0] < (cbSize << 3))
count [1]++;
count [1] += (uint) (cbSize >> 29);
int partLen = 64 - index;
int i = 0;
/* Transform as many times as possible. */
if (cbSize >= partLen) {
//MD4_memcpy((POINTER)&context->buffer[index], (POINTER)input, partLen);
Buffer.BlockCopy (array, ibStart, buffer, index, partLen);
MD4Transform (state, buffer, 0);
for (i = partLen; i + 63 < cbSize; i += 64) {
// MD4Transform (context->state, &input[i]);
MD4Transform (state, array, i);
}
index = 0;
}
/* Buffer remaining input */
//MD4_memcpy ((POINTER)&context->buffer[index], (POINTER)&input[i], inputLen-i);
Buffer.BlockCopy (array, ibStart + i, buffer, index, (cbSize-i));
}
protected override byte[] HashFinal ()
{
/* Save number of bits */
byte[] bits = new byte [8];
Encode (bits, count);
/* Pad out to 56 mod 64. */
uint index = ((count [0] >> 3) & 0x3f);
int padLen = (int) ((index < 56) ? (56 - index) : (120 - index));
HashCore (Padding (padLen), 0, padLen);
/* Append length (before padding) */
HashCore (bits, 0, 8);
/* Store state in digest */
Encode (digest, state);
// Zeroize sensitive information.
Initialize ();
return digest;
}
//--- private methods ---------------------------------------------------
private byte[] Padding (int nLength)
{
if (nLength > 0) {
byte[] padding = new byte [nLength];
padding [0] = 0x80;
return padding;
}
return null;
}
/* F, G and H are basic MD4 functions. */
private uint F (uint x, uint y, uint z)
{
return (uint) (((x) & (y)) | ((~x) & (z)));
}
private uint G (uint x, uint y, uint z)
{
return (uint) (((x) & (y)) | ((x) & (z)) | ((y) & (z)));
}
private uint H (uint x, uint y, uint z)
{
return (uint) ((x) ^ (y) ^ (z));
}
/* ROTATE_LEFT rotates x left n bits. */
private uint ROL (uint x, byte n)
{
return (uint) (((x) << (n)) | ((x) >> (32-(n))));
}
/* FF, GG and HH are transformations for rounds 1, 2 and 3 */
/* Rotation is separate from addition to prevent recomputation */
private void FF (ref uint a, uint b, uint c, uint d, uint x, byte s)
{
a += F (b, c, d) + x;
a = ROL (a, s);
}
private void GG (ref uint a, uint b, uint c, uint d, uint x, byte s)
{
a += G (b, c, d) + x + 0x5a827999;
a = ROL (a, s);
}
private void HH (ref uint a, uint b, uint c, uint d, uint x, byte s)
{
a += H (b, c, d) + x + 0x6ed9eba1;
a = ROL (a, s);
}
private void Encode (byte[] output, uint[] input)
{
for (int i = 0, j = 0; j < output.Length; i++, j += 4) {
output [j] = (byte)(input [i]);
output [j+1] = (byte)(input [i] >> 8);
output [j+2] = (byte)(input [i] >> 16);
output [j+3] = (byte)(input [i] >> 24);
}
}
private void Decode (uint[] output, byte[] input, int index)
{
for (int i = 0, j = index; i < output.Length; i++, j += 4) {
output [i] = (uint) ((input [j]) | (input [j+1] << 8) | (input [j+2] << 16) | (input [j+3] << 24));
}
}
private void MD4Transform (uint[] state, byte[] block, int index)
{
uint a = state [0];
uint b = state [1];
uint c = state [2];
uint d = state [3];
Decode (x, block, index);
/* Round 1 */
FF (ref a, b, c, d, x[ 0], S11); /* 1 */
FF (ref d, a, b, c, x[ 1], S12); /* 2 */
FF (ref c, d, a, b, x[ 2], S13); /* 3 */
FF (ref b, c, d, a, x[ 3], S14); /* 4 */
FF (ref a, b, c, d, x[ 4], S11); /* 5 */
FF (ref d, a, b, c, x[ 5], S12); /* 6 */
FF (ref c, d, a, b, x[ 6], S13); /* 7 */
FF (ref b, c, d, a, x[ 7], S14); /* 8 */
FF (ref a, b, c, d, x[ 8], S11); /* 9 */
FF (ref d, a, b, c, x[ 9], S12); /* 10 */
FF (ref c, d, a, b, x[10], S13); /* 11 */
FF (ref b, c, d, a, x[11], S14); /* 12 */
FF (ref a, b, c, d, x[12], S11); /* 13 */
FF (ref d, a, b, c, x[13], S12); /* 14 */
FF (ref c, d, a, b, x[14], S13); /* 15 */
FF (ref b, c, d, a, x[15], S14); /* 16 */
/* Round 2 */
GG (ref a, b, c, d, x[ 0], S21); /* 17 */
GG (ref d, a, b, c, x[ 4], S22); /* 18 */
GG (ref c, d, a, b, x[ 8], S23); /* 19 */
GG (ref b, c, d, a, x[12], S24); /* 20 */
GG (ref a, b, c, d, x[ 1], S21); /* 21 */
GG (ref d, a, b, c, x[ 5], S22); /* 22 */
GG (ref c, d, a, b, x[ 9], S23); /* 23 */
GG (ref b, c, d, a, x[13], S24); /* 24 */
GG (ref a, b, c, d, x[ 2], S21); /* 25 */
GG (ref d, a, b, c, x[ 6], S22); /* 26 */
GG (ref c, d, a, b, x[10], S23); /* 27 */
GG (ref b, c, d, a, x[14], S24); /* 28 */
GG (ref a, b, c, d, x[ 3], S21); /* 29 */
GG (ref d, a, b, c, x[ 7], S22); /* 30 */
GG (ref c, d, a, b, x[11], S23); /* 31 */
GG (ref b, c, d, a, x[15], S24); /* 32 */
HH (ref a, b, c, d, x[ 0], S31); /* 33 */
HH (ref d, a, b, c, x[ 8], S32); /* 34 */
HH (ref c, d, a, b, x[ 4], S33); /* 35 */
HH (ref b, c, d, a, x[12], S34); /* 36 */
HH (ref a, b, c, d, x[ 2], S31); /* 37 */
HH (ref d, a, b, c, x[10], S32); /* 38 */
HH (ref c, d, a, b, x[ 6], S33); /* 39 */
HH (ref b, c, d, a, x[14], S34); /* 40 */
HH (ref a, b, c, d, x[ 1], S31); /* 41 */
HH (ref d, a, b, c, x[ 9], S32); /* 42 */
HH (ref c, d, a, b, x[ 5], S33); /* 43 */
HH (ref b, c, d, a, x[13], S34); /* 44 */
HH (ref a, b, c, d, x[ 3], S31); /* 45 */
HH (ref d, a, b, c, x[11], S32); /* 46 */
HH (ref c, d, a, b, x[ 7], S33); /* 47 */
HH (ref b, c, d, a, x[15], S34); /* 48 */
state [0] += a;
state [1] += b;
state [2] += c;
state [3] += d;
}
}
}
| |
using SharpBox2D.Common;
using SharpBox2D.Pooling;
namespace SharpBox2D.Dynamics.Joints
{
/**
* A rope joint enforces a maximum distance between two points on two bodies. It has no other
* effect. Warning: if you attempt to change the maximum length during the simulation you will get
* some non-physical behavior. A model that would allow you to dynamically modify the length would
* have some sponginess, so I chose not to implement it that way. See DistanceJoint if you want to
* dynamically control length.
*
* @author Daniel Murphy
*/
public class RopeJoint : Joint
{
// Solver shared
private Vec2 m_localAnchorA = new Vec2();
private Vec2 m_localAnchorB = new Vec2();
private float m_maxLength;
private float m_length;
private float m_impulse;
// Solver temp
private int m_indexA;
private int m_indexB;
private Vec2 m_u = new Vec2();
private Vec2 m_rA = new Vec2();
private Vec2 m_rB = new Vec2();
private Vec2 m_localCenterA = new Vec2();
private Vec2 m_localCenterB = new Vec2();
private float m_invMassA;
private float m_invMassB;
private float m_invIA;
private float m_invIB;
private float m_mass;
private LimitState m_state;
internal RopeJoint(IWorldPool worldPool, RopeJointDef def) :
base(worldPool, def)
{
m_localAnchorA.set(def.localAnchorA);
m_localAnchorB.set(def.localAnchorB);
m_maxLength = def.maxLength;
m_mass = 0.0f;
m_impulse = 0.0f;
m_state = LimitState.INACTIVE;
m_length = 0.0f;
}
public override void initVelocityConstraints(SolverData data)
{
m_indexA = m_bodyA.m_islandIndex;
m_indexB = m_bodyB.m_islandIndex;
m_localCenterA.set(m_bodyA.m_sweep.localCenter);
m_localCenterB.set(m_bodyB.m_sweep.localCenter);
m_invMassA = m_bodyA.m_invMass;
m_invMassB = m_bodyB.m_invMass;
m_invIA = m_bodyA.m_invI;
m_invIB = m_bodyB.m_invI;
Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
Rot qA = pool.popRot();
Rot qB = pool.popRot();
Vec2 temp = pool.popVec2();
qA.set(aA);
qB.set(aB);
// Compute the effective masses.
temp.set(m_localAnchorA);
temp.subLocal(m_localCenterA);
Rot.mulToOutUnsafe(qA, temp, ref m_rA);
temp.set(m_localAnchorB);
temp.subLocal(m_localCenterB);
Rot.mulToOutUnsafe(qB, temp, ref m_rB);
m_u.set(cB);
m_u.addLocal(m_rB);
m_u.subLocal(cA);
m_u.subLocal(m_rA);
m_length = m_u.length();
float C = m_length - m_maxLength;
if (C > 0.0f)
{
m_state = LimitState.AT_UPPER;
}
else
{
m_state = LimitState.INACTIVE;
}
if (m_length > Settings.linearSlop)
{
m_u.mulLocal(1.0f/m_length);
}
else
{
m_u.setZero();
m_mass = 0.0f;
m_impulse = 0.0f;
return;
}
// Compute effective mass.
float crA = Vec2.cross(m_rA, m_u);
float crB = Vec2.cross(m_rB, m_u);
float invMass = m_invMassA + m_invIA*crA*crA + m_invMassB + m_invIB*crB*crB;
m_mass = invMass != 0.0f ? 1.0f/invMass : 0.0f;
if (data.step.warmStarting)
{
// Scale the impulse to support a variable time step.
m_impulse *= data.step.dtRatio;
float Px = m_impulse*m_u.x;
float Py = m_impulse*m_u.y;
vA.x -= m_invMassA*Px;
vA.y -= m_invMassA*Py;
wA -= m_invIA*(m_rA.x*Py - m_rA.y*Px);
vB.x += m_invMassB*Px;
vB.y += m_invMassB*Py;
wB += m_invIB*(m_rB.x*Py - m_rB.y*Px);
}
else
{
m_impulse = 0.0f;
}
pool.pushRot(2);
pool.pushVec2(1);
// data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
public override void solveVelocityConstraints(SolverData data)
{
Vec2 vA = data.velocities[m_indexA].v;
float wA = data.velocities[m_indexA].w;
Vec2 vB = data.velocities[m_indexB].v;
float wB = data.velocities[m_indexB].w;
// Cdot = dot(u, v + cross(w, r))
Vec2 vpA = pool.popVec2();
Vec2 vpB = pool.popVec2();
Vec2 temp = pool.popVec2();
Vec2.crossToOutUnsafe(wA, m_rA, ref vpA);
vpA.addLocal(vA);
Vec2.crossToOutUnsafe(wB, m_rB, ref vpB);
vpB.addLocal(vB);
float C = m_length - m_maxLength;
temp.set(vpB);
temp.subLocal(vpA);
float Cdot = Vec2.dot(m_u, temp);
// Predictive constraint.
if (C < 0.0f)
{
Cdot += data.step.inv_dt*C;
}
float impulse = -m_mass*Cdot;
float oldImpulse = m_impulse;
m_impulse = MathUtils.min(0.0f, m_impulse + impulse);
impulse = m_impulse - oldImpulse;
float Px = impulse*m_u.x;
float Py = impulse*m_u.y;
vA.x -= m_invMassA*Px;
vA.y -= m_invMassA*Py;
wA -= m_invIA*(m_rA.x*Py - m_rA.y*Px);
vB.x += m_invMassB*Px;
vB.y += m_invMassB*Py;
wB += m_invIB*(m_rB.x*Py - m_rB.y*Px);
pool.pushVec2(3);
// data.velocities[m_indexA].v = vA;
data.velocities[m_indexA].w = wA;
// data.velocities[m_indexB].v = vB;
data.velocities[m_indexB].w = wB;
}
public override bool solvePositionConstraints(SolverData data)
{
Vec2 cA = data.positions[m_indexA].c;
float aA = data.positions[m_indexA].a;
Vec2 cB = data.positions[m_indexB].c;
float aB = data.positions[m_indexB].a;
Rot qA = pool.popRot();
Rot qB = pool.popRot();
Vec2 u = pool.popVec2();
Vec2 rA = pool.popVec2();
Vec2 rB = pool.popVec2();
Vec2 temp = pool.popVec2();
qA.set(aA);
qB.set(aB);
// Compute the effective masses.
temp.set(m_localAnchorA);
temp.subLocal(m_localCenterA);
Rot.mulToOutUnsafe(qA, temp , ref rA);
temp.set(m_localAnchorB);
temp.subLocal(m_localCenterB);
Rot.mulToOutUnsafe(qB, temp, ref rB);
u.set(cB);
u.addLocal(rB);
u.subLocal(cA);
u.subLocal(rA);
float length = u.normalize();
float C = length - m_maxLength;
C = MathUtils.clamp(C, 0.0f, Settings.maxLinearCorrection);
float impulse = -m_mass*C;
float Px = impulse*u.x;
float Py = impulse*u.y;
cA.x -= m_invMassA*Px;
cA.y -= m_invMassA*Py;
aA -= m_invIA*(rA.x*Py - rA.y*Px);
cB.x += m_invMassB*Px;
cB.y += m_invMassB*Py;
aB += m_invIB*(rB.x*Py - rB.y*Px);
pool.pushRot(2);
pool.pushVec2(4);
// data.positions[m_indexA].c = cA;
data.positions[m_indexA].a = aA;
// data.positions[m_indexB].c = cB;
data.positions[m_indexB].a = aB;
return length - m_maxLength < Settings.linearSlop;
}
public override void getAnchorA(ref Vec2 argOut)
{
m_bodyA.getWorldPointToOut(m_localAnchorA, ref argOut);
}
public override void getAnchorB(ref Vec2 argOut)
{
m_bodyB.getWorldPointToOut(m_localAnchorB, ref argOut);
}
public override void getReactionForce(float inv_dt, ref Vec2 argOut)
{
argOut.set(m_u);
argOut.mulLocal(inv_dt);
argOut.mulLocal(m_impulse);
}
public override float getReactionTorque(float inv_dt)
{
return 0f;
}
public Vec2 getLocalAnchorA()
{
return m_localAnchorA;
}
public Vec2 getLocalAnchorB()
{
return m_localAnchorB;
}
public float getMaxLength()
{
return m_maxLength;
}
public void setMaxLength(float maxLength)
{
this.m_maxLength = maxLength;
}
public LimitState getLimitState()
{
return m_state;
}
}
}
| |
/*
* 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 copyrightD
* 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.Text;
using OMV = OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.PhysicsModules.SharedBase;
namespace OpenSim.Region.PhysicsModule.BulletS
{
public sealed class BSShapeCollection : IDisposable
{
#pragma warning disable 414
private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]";
#pragma warning restore 414
private BSScene m_physicsScene { get; set; }
private Object m_collectionActivityLock = new Object();
private bool DDetail = false;
public BSShapeCollection(BSScene physScene)
{
m_physicsScene = physScene;
// Set the next to 'true' for very detailed shape update detailed logging (detailed details?)
// While detailed debugging is still active, this is better than commenting out all the
// DetailLog statements. When debugging slows down, this and the protected logging
// statements can be commented/removed.
DDetail = true;
}
public void Dispose()
{
// TODO!!!!!!!!!
}
// Callbacks called just before either the body or shape is destroyed.
// Mostly used for changing bodies out from under Linksets.
// Useful for other cases where parameters need saving.
// Passing 'null' says no callback.
public delegate void PhysicalDestructionCallback(BulletBody pBody, BulletShape pShape);
// Called to update/change the body and shape for an object.
// The object has some shape and body on it. Here we decide if that is the correct shape
// for the current state of the object (static/dynamic/...).
// If bodyCallback is not null, it is called if either the body or the shape are changed
// so dependencies (like constraints) can be removed before the physical object is dereferenced.
// Return 'true' if either the body or the shape changed.
// Called at taint-time.
public bool GetBodyAndShape(bool forceRebuild, BulletWorld sim, BSPhysObject prim, PhysicalDestructionCallback bodyCallback)
{
bool ret = false;
// This lock could probably be pushed down lower but building shouldn't take long
lock (m_collectionActivityLock)
{
// Do we have the correct geometry for this type of object?
// Updates prim.BSShape with information/pointers to shape.
// Returns 'true' of BSShape is changed to a new shape.
bool newGeom = CreateGeom(forceRebuild, prim, bodyCallback);
// If we had to select a new shape geometry for the object,
// rebuild the body around it.
// Updates prim.BSBody with information/pointers to requested body
// Returns 'true' if BSBody was changed.
bool newBody = CreateBody((newGeom || forceRebuild), prim, m_physicsScene.World, bodyCallback);
ret = newGeom || newBody;
}
DetailLog("{0},BSShapeCollection.GetBodyAndShape,taintExit,force={1},ret={2},body={3},shape={4}",
prim.LocalID, forceRebuild, ret, prim.PhysBody, prim.PhysShape);
return ret;
}
public bool GetBodyAndShape(bool forceRebuild, BulletWorld sim, BSPhysObject prim)
{
return GetBodyAndShape(forceRebuild, sim, prim, null);
}
// If the existing prim's shape is to be replaced, remove the tie to the existing shape
// before replacing it.
private void DereferenceExistingShape(BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
{
if (prim.PhysShape.HasPhysicalShape)
{
if (shapeCallback != null)
shapeCallback(prim.PhysBody, prim.PhysShape.physShapeInfo);
prim.PhysShape.Dereference(m_physicsScene);
}
prim.PhysShape = new BSShapeNull();
}
// Create the geometry information in Bullet for later use.
// The objects needs a hull if it's physical otherwise a mesh is enough.
// if 'forceRebuild' is true, the geometry is unconditionally rebuilt. For meshes and hulls,
// shared geometries will be used. If the parameters of the existing shape are the same
// as this request, the shape is not rebuilt.
// Info in prim.BSShape is updated to the new shape.
// Returns 'true' if the geometry was rebuilt.
// Called at taint-time!
public const int AvatarShapeCapsule = 0;
public const int AvatarShapeCube = 1;
public const int AvatarShapeOvoid = 2;
public const int AvatarShapeMesh = 3;
private bool CreateGeom(bool forceRebuild, BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
{
bool ret = false;
bool haveShape = false;
bool nativeShapePossible = true;
PrimitiveBaseShape pbs = prim.BaseShape;
// Kludge to create the capsule for the avatar.
// TDOD: Remove/redo this when BSShapeAvatar is working!!
BSCharacter theChar = prim as BSCharacter;
if (theChar != null)
{
DereferenceExistingShape(prim, shapeCallback);
switch (BSParam.AvatarShape)
{
case AvatarShapeCapsule:
prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
BSPhysicsShapeType.SHAPE_CAPSULE, FixedShapeKey.KEY_CAPSULE);
ret = true;
haveShape = true;
break;
case AvatarShapeCube:
prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_CAPSULE);
ret = true;
haveShape = true;
break;
case AvatarShapeOvoid:
// Saddly, Bullet doesn't scale spheres so this doesn't work as an avatar shape
prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
BSPhysicsShapeType.SHAPE_SPHERE, FixedShapeKey.KEY_CAPSULE);
ret = true;
haveShape = true;
break;
case AvatarShapeMesh:
break;
default:
break;
}
}
// If the prim attributes are simple, this could be a simple Bullet native shape
// Native shapes work whether to object is static or physical.
if (!haveShape
&& nativeShapePossible
&& pbs != null
&& PrimHasNoCuts(pbs)
&& ( !pbs.SculptEntry || (pbs.SculptEntry && !BSParam.ShouldMeshSculptedPrim) )
)
{
// Get the scale of any existing shape so we can see if the new shape is same native type and same size.
OMV.Vector3 scaleOfExistingShape = OMV.Vector3.Zero;
if (prim.PhysShape.HasPhysicalShape)
scaleOfExistingShape = m_physicsScene.PE.GetLocalScaling(prim.PhysShape.physShapeInfo);
if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,maybeNative,force={1},primScale={2},primSize={3},primShape={4}",
prim.LocalID, forceRebuild, prim.Scale, prim.Size, prim.PhysShape.physShapeInfo.shapeType);
// It doesn't look like Bullet scales native spheres so make sure the scales are all equal
if ((pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1)
&& pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z)
{
haveShape = true;
if (forceRebuild
|| prim.PhysShape.ShapeType != BSPhysicsShapeType.SHAPE_SPHERE
)
{
DereferenceExistingShape(prim, shapeCallback);
prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
BSPhysicsShapeType.SHAPE_SPHERE, FixedShapeKey.KEY_SPHERE);
ret = true;
}
if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},rebuilt={2},shape={3}",
prim.LocalID, forceRebuild, ret, prim.PhysShape);
}
// If we didn't make a sphere, maybe a box will work.
if (!haveShape && pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
{
haveShape = true;
if (forceRebuild
|| prim.Scale != scaleOfExistingShape
|| prim.PhysShape.ShapeType != BSPhysicsShapeType.SHAPE_BOX
)
{
DereferenceExistingShape(prim, shapeCallback);
prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX);
ret = true;
}
if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},rebuilt={2},shape={3}",
prim.LocalID, forceRebuild, ret, prim.PhysShape);
}
}
// If a simple shape is not happening, create a mesh and possibly a hull.
if (!haveShape && pbs != null)
{
ret = CreateGeomMeshOrHull(prim, shapeCallback);
}
m_physicsScene.PE.ResetBroadphasePool(m_physicsScene.World); // DEBUG DEBUG
return ret;
}
// return 'true' if this shape description does not include any cutting or twisting.
public static bool PrimHasNoCuts(PrimitiveBaseShape pbs)
{
return pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
&& pbs.ProfileHollow == 0
&& pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
&& pbs.PathBegin == 0 && pbs.PathEnd == 0
&& pbs.PathTaperX == 0 && pbs.PathTaperY == 0
&& pbs.PathScaleX == 100 && pbs.PathScaleY == 100
&& pbs.PathShearX == 0 && pbs.PathShearY == 0;
}
// return 'true' if the prim's shape was changed.
private bool CreateGeomMeshOrHull(BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
{
bool ret = false;
// Note that if it's a native shape, the check for physical/non-physical is not
// made. Native shapes work in either case.
if (prim.IsPhysical && BSParam.ShouldUseHullsForPhysicalObjects)
{
// Use a simple, single mesh convex hull shape if the object is simple enough
BSShape potentialHull = null;
PrimitiveBaseShape pbs = prim.BaseShape;
// Use a simple, one section convex shape for prims that are probably convex (no cuts or twists)
if (BSParam.ShouldUseSingleConvexHullForPrims
&& pbs != null
&& !pbs.SculptEntry
&& PrimHasNoCuts(pbs)
)
{
potentialHull = BSShapeConvexHull.GetReference(m_physicsScene, false /* forceRebuild */, prim);
}
// Use the GImpact shape if it is a prim that has some concaveness
if (potentialHull == null
&& BSParam.ShouldUseGImpactShapeForPrims
&& pbs != null
&& !pbs.SculptEntry
)
{
potentialHull = BSShapeGImpact.GetReference(m_physicsScene, false /* forceRebuild */, prim);
}
// If not any of the simple cases, just make a hull
if (potentialHull == null)
{
potentialHull = BSShapeHull.GetReference(m_physicsScene, false /*forceRebuild*/, prim);
}
// If the current shape is not what is on the prim at the moment, time to change.
if (!prim.PhysShape.HasPhysicalShape
|| potentialHull.ShapeType != prim.PhysShape.ShapeType
|| potentialHull.physShapeInfo.shapeKey != prim.PhysShape.physShapeInfo.shapeKey)
{
DereferenceExistingShape(prim, shapeCallback);
prim.PhysShape = potentialHull;
ret = true;
}
else
{
// The current shape on the prim is the correct one. We don't need the potential reference.
potentialHull.Dereference(m_physicsScene);
}
if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1}", prim.LocalID, prim.PhysShape);
}
else
{
// Non-physical objects should be just meshes.
BSShape potentialMesh = BSShapeMesh.GetReference(m_physicsScene, false /*forceRebuild*/, prim);
// If the current shape is not what is on the prim at the moment, time to change.
if (!prim.PhysShape.HasPhysicalShape
|| potentialMesh.ShapeType != prim.PhysShape.ShapeType
|| potentialMesh.physShapeInfo.shapeKey != prim.PhysShape.physShapeInfo.shapeKey)
{
DereferenceExistingShape(prim, shapeCallback);
prim.PhysShape = potentialMesh;
ret = true;
}
else
{
// We don't need this reference to the mesh that is already being using.
potentialMesh.Dereference(m_physicsScene);
}
if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1}", prim.LocalID, prim.PhysShape);
}
return ret;
}
// Track another user of a body.
// We presume the caller has allocated the body.
// Bodies only have one user so the body is just put into the world if not already there.
private void ReferenceBody(BulletBody body)
{
lock (m_collectionActivityLock)
{
if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,body={1}", body.ID, body);
if (!m_physicsScene.PE.IsInWorld(m_physicsScene.World, body))
{
m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, body);
if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,addedToWorld,ref={1}", body.ID, body);
}
}
}
// Release the usage of a body.
// Called when releasing use of a BSBody. BSShape is handled separately.
// Called in taint time.
public void DereferenceBody(BulletBody body, PhysicalDestructionCallback bodyCallback )
{
if (!body.HasPhysicalBody)
return;
lock (m_collectionActivityLock)
{
if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody,body={1}", body.ID, body);
// If the caller needs to know the old body is going away, pass the event up.
if (bodyCallback != null)
bodyCallback(body, null);
// Removing an object not in the world is a NOOP
m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, body);
// Zero any reference to the shape so it is not freed when the body is deleted.
m_physicsScene.PE.SetCollisionShape(m_physicsScene.World, body, null);
m_physicsScene.PE.DestroyObject(m_physicsScene.World, body);
}
}
// Create a body object in Bullet.
// Updates prim.BSBody with the information about the new body if one is created.
// Returns 'true' if an object was actually created.
// Called at taint-time.
private bool CreateBody(bool forceRebuild, BSPhysObject prim, BulletWorld sim, PhysicalDestructionCallback bodyCallback)
{
bool ret = false;
// the mesh, hull or native shape must have already been created in Bullet
bool mustRebuild = !prim.PhysBody.HasPhysicalBody;
// If there is an existing body, verify it's of an acceptable type.
// If not a solid object, body is a GhostObject. Otherwise a RigidBody.
if (!mustRebuild)
{
CollisionObjectTypes bodyType = (CollisionObjectTypes)m_physicsScene.PE.GetBodyType(prim.PhysBody);
if (prim.IsSolid && bodyType != CollisionObjectTypes.CO_RIGID_BODY
|| !prim.IsSolid && bodyType != CollisionObjectTypes.CO_GHOST_OBJECT)
{
// If the collisionObject is not the correct type for solidness, rebuild what's there
mustRebuild = true;
if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,forceRebuildBecauseChangingBodyType,bodyType={1}", prim.LocalID, bodyType);
}
}
if (mustRebuild || forceRebuild)
{
// Free any old body
DereferenceBody(prim.PhysBody, bodyCallback);
BulletBody aBody;
if (prim.IsSolid)
{
aBody = m_physicsScene.PE.CreateBodyFromShape(sim, prim.PhysShape.physShapeInfo, prim.LocalID, prim.RawPosition, prim.RawOrientation);
if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,rigid,body={1}", prim.LocalID, aBody);
}
else
{
aBody = m_physicsScene.PE.CreateGhostFromShape(sim, prim.PhysShape.physShapeInfo, prim.LocalID, prim.RawPosition, prim.RawOrientation);
if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,ghost,body={1}", prim.LocalID, aBody);
}
ReferenceBody(aBody);
prim.PhysBody = aBody;
ret = true;
}
return ret;
}
private void DetailLog(string msg, params Object[] args)
{
if (m_physicsScene.PhysicsLogging.Enabled)
m_physicsScene.DetailLog(msg, args);
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections;
using System.Reflection;
using Common.Logging;
using Spring.Util;
using Spring.Core.TypeResolution;
using Spring.Core;
#endregion
namespace Spring.Transaction.Interceptor
{
/// <summary>
/// Simple implementation of the <see cref="Spring.Transaction.Interceptor.ITransactionAttributeSource"/>
/// interface that allows attributes to be stored per method in a map.
/// </summary>
/// <author>Rod Johnson</author>
/// <author>Juergen Hoeller</author>
/// <author>Griffin Caprio (.NET)</author>
public class MethodMapTransactionAttributeSource : ITransactionAttributeSource
{
private IDictionary _methodMap;
private IDictionary _nameMap;
#region Logging Definition
private static readonly ILog LOG = LogManager.GetLogger(typeof (MethodMapTransactionAttributeSource));
#endregion
/// <summary>
/// Creates a new instance of the
/// <see cref="Spring.Transaction.Interceptor.MethodMapTransactionAttributeSource"/> class.
/// </summary>
public MethodMapTransactionAttributeSource()
{
_methodMap = new Hashtable();
_nameMap = new Hashtable();
}
/// <summary>
/// Set a name/attribute map, consisting of "FQCN.method, AssemblyName" method names
/// (e.g. "MyNameSpace.MyClass.MyMethod, MyAssembly") and ITransactionAttribute
/// instances (or Strings to be converted to <see cref="ITransactionAttribute"/> instances).
/// </summary>
/// <remarks>
/// <p>
/// The key values of the supplied <see cref="System.Collections.IDictionary"/>
/// must adhere to the following form:<br/>
/// <code>FQCN.methodName, Assembly</code>.
/// </p>
/// <example>
/// <code>MyNameSpace.MyClass.MyMethod, MyAssembly</code>
/// </example>
/// </remarks>
public IDictionary MethodMap
{
set
{
foreach (DictionaryEntry entry in value)
{
string name = entry.Key as string;
ITransactionAttribute attribute = null;
//Check if we need to convert from a string to ITransactionAttribute
if (entry.Value is ITransactionAttribute)
{
attribute = entry.Value as ITransactionAttribute;
}
else
{
TransactionAttributeEditor editor = new TransactionAttributeEditor();
editor.SetAsText(entry.Value.ToString());
attribute = editor.Value;
}
AddTransactionalMethod( name, attribute );
}
}
}
/// <summary>
/// Add an attribute for a transactional method.
/// </summary>
/// <remarks>
/// Method names can end or start with "*" for matching multiple methods.
/// </remarks>
/// <param name="name">The class and method name, separated by a dot.</param>
/// <param name="attribute">The attribute to be associated with the method.</param>
public void AddTransactionalMethod( string name, ITransactionAttribute attribute )
{
AssertUtils.ArgumentNotNull(name, "name");
int lastCommaIndex = name.LastIndexOf( "," );
if (lastCommaIndex == -1)
{
throw new ArgumentException("'" + name + "'" +
" is not a valid method name, missing AssemblyName. Format is FQN.MethodName, AssemblyName.");
}
string fqnWithMethod = name.Substring(0, lastCommaIndex);
int lastDotIndex = fqnWithMethod.LastIndexOf( "." );
if ( lastDotIndex == -1 )
{
throw new TransactionUsageException("'" + fqnWithMethod + "' is not a valid method name: format is FQN.methodName");
}
string className = fqnWithMethod.Substring(0, lastDotIndex );
string assemblyName = name.Substring(lastCommaIndex + 1);
string methodName = fqnWithMethod.Substring(lastDotIndex + 1 );
string fqnClassName = className + ", " + assemblyName;
try
{
Type type = TypeResolutionUtils.ResolveType(fqnClassName);
AddTransactionalMethod( type, methodName, attribute );
} catch ( TypeLoadException exception )
{
throw new TransactionUsageException( "Type '" + fqnClassName + "' not found.", exception );
}
}
/// <summary>
/// Add an attribute for a transactional method.
/// </summary>
/// <remarks>
/// Method names can end or start with "*" for matching multiple methods.
/// </remarks>
/// <param name="type">The target interface or class.</param>
/// <param name="mappedName">The mapped method name.</param>
/// <param name="transactionAttribute">
/// The attribute to be associated with the method.
/// </param>
public void AddTransactionalMethod(
Type type, string mappedName, ITransactionAttribute transactionAttribute )
{
// TODO address method overloading? At present this will
// simply match all methods that have the given name.
string name = type.Name + "." + mappedName;
MethodInfo[] methods = type.GetMethods();
IList matchingMethods = new ArrayList();
for ( int i = 0; i < methods.Length; i++ )
{
if ( methods[i].Name.Equals( mappedName ) || IsMatch(methods[i].Name, mappedName ))
{
matchingMethods.Add( methods[i] );
}
}
if ( matchingMethods.Count == 0 )
{
throw new TransactionUsageException("Couldn't find method '" + mappedName + "' on Type [" + type.Name + "]");
}
// register all matching methods
foreach ( MethodInfo currentMethod in matchingMethods )
{
string regularMethodName = (string)_nameMap[currentMethod];
if ( regularMethodName == null || ( !regularMethodName.Equals(name) && regularMethodName.Length <= name.Length))
{
// No already registered method name, or more specific
// method name specification now -> (re-)register method.
if (LOG.IsDebugEnabled && regularMethodName != null)
{
LOG.Debug("Replacing attribute for transactional method [" + currentMethod + "]: current name '" +
name + "' is more specific than '" + regularMethodName + "'");
}
_nameMap.Add( currentMethod, name );
AddTransactionalMethod( currentMethod, transactionAttribute );
}
else
{
if (LOG.IsDebugEnabled && regularMethodName != null)
{
LOG.Debug("Keeping attribute for transactional method [" + currentMethod + "]: current name '" +
name + "' is not more specific than '" + regularMethodName + "'");
}
}
}
}
/// <summary>
/// Add an attribute for a transactional method.
/// </summary>
/// <param name="method">The transactional method.</param>
/// <param name="transactionAttribute">
/// The attribute to be associated with the method.
/// </param>
public void AddTransactionalMethod( MethodInfo method, ITransactionAttribute transactionAttribute )
{
_methodMap.Add( method, transactionAttribute );
}
/// <summary>
/// Does the supplied <paramref name="methodName"/> match the supplied <paramref name="mappedName"/>?
/// </summary>
/// <remarks>
/// The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches,
/// as well as direct equality. This behaviour can (of course) be overridden in
/// derived classes.
/// </remarks>
/// <param name="methodName">The method name of the class.</param>
/// <param name="mappedName">The name in the descriptor.</param>
/// <returns><b>True</b> if the names match.</returns>
protected virtual bool IsMatch( string methodName, string mappedName )
{
return PatternMatchUtils.SimpleMatch(mappedName, methodName);
}
#region ITransactionAttributeSource Members
/// <summary>
/// Return the <see cref="Spring.Transaction.Interceptor.ITransactionAttribute"/> for this
/// method.
/// </summary>
/// <param name="method">The method to check.</param>
/// <param name="targetType">
/// The target <see cref="System.Type"/>. May be null, in which case the declaring
/// class of the supplied <paramref name="method"/> must be used.
/// </param>
/// <returns>
/// A <see cref="Spring.Transaction.Interceptor.ITransactionAttribute"/> or
/// null if the method is non-transactional.
/// </returns>
public ITransactionAttribute ReturnTransactionAttribute(MethodInfo method, Type targetType)
{
//Might have registered MethodInfo objects whose declaring type is the interface, so 'downcast'
//to the most specific method which is typically what is passed in as the first method argument.
foreach (DictionaryEntry dictionaryEntry in _methodMap)
{
MethodInfo currentMethod = (MethodInfo)dictionaryEntry.Key;
MethodInfo specificMethod;
if (targetType == null)
{
specificMethod = currentMethod;
}
else
{
ParameterInfo[] parameters = currentMethod.GetParameters();
ComposedCriteria searchCriteria = new ComposedCriteria();
searchCriteria.Add(new MethodNameMatchCriteria(currentMethod.Name));
searchCriteria.Add(new MethodParametersCountCriteria(parameters.Length));
#if NET_2_0
searchCriteria.Add(new MethodGenericArgumentsCountCriteria(
currentMethod.GetGenericArguments().Length));
#endif
searchCriteria.Add(new MethodParametersCriteria(ReflectionUtils.GetParameterTypes(parameters)));
MemberInfo[] matchingMethods = targetType.FindMembers(
MemberTypes.Method,
BindingFlags.Instance | BindingFlags.Public,
new MemberFilter(new CriteriaMemberFilter().FilterMemberByCriteria),
searchCriteria);
if (matchingMethods != null && matchingMethods.Length == 1)
{
specificMethod = matchingMethods[0] as MethodInfo;
}
else
{
specificMethod = currentMethod;
}
}
if (method == specificMethod)
{
return (ITransactionAttribute)dictionaryEntry.Value;
}
}
return (ITransactionAttribute)_methodMap[method];
}
#endregion
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using Xunit;
namespace Moq.Tests
{
public class PropertiesFixture
{
public interface IFoo
{
IIndexedFoo Indexed { get; set; }
}
public interface IIndexedFoo
{
string this[int key] { get; set; }
string this[int key1, string key2, bool key3, DateTime key4] { get; set; }
IBar this[int key1, string key2, DateTime key4] { get; set; }
}
public interface IBar
{
string Value { get; set; }
}
[Fact]
public void ShouldSupportMultipleIndexerGettersInFluentMock()
{
var foo = new Mock<IFoo>();
foo.SetupGet(x => x.Indexed[It.IsAny<int>(), "foo", It.IsAny<DateTime>()].Value).Returns("bar");
var result = foo.Object.Indexed[1, "foo", DateTime.Now].Value;
Assert.Equal("bar", result);
}
[Fact]
public void ShouldSupportMultipleIndexerGetters()
{
var foo = new Mock<IIndexedFoo>();
foo.SetupGet(x => x[It.IsAny<int>(), "foo", true, It.IsAny<DateTime>()]).Returns("bar");
var result = foo.Object[1, "foo", true, DateTime.Now];
Assert.Equal("bar", result);
}
[Fact]
public void ShouldSetIndexer()
{
var foo = new Mock<IIndexedFoo>(MockBehavior.Strict);
foo.SetupSet(f => f[0] = "foo");
foo.Object[0] = "foo";
}
[Fact]
public void ShouldSetIndexerWithValueMatcher()
{
var foo = new Mock<IIndexedFoo>(MockBehavior.Strict);
foo.SetupSet(f => f[0] = It.IsAny<string>());
foo.Object[0] = "foo";
}
[Fact]
public void ShouldSetIndexerWithIndexMatcher()
{
var foo = new Mock<IIndexedFoo>(MockBehavior.Strict);
foo.SetupSet(f => f[It.IsAny<int>()] = "foo");
foo.Object[18] = "foo";
}
[Fact]
public void ShouldSetIndexerWithBothMatcher()
{
var foo = new Mock<IIndexedFoo>(MockBehavior.Strict);
foo.SetupSet(f => f[It.IsAny<int>()] = It.IsAny<string>());
foo.Object[18] = "foo";
}
[Fact]
public void Can_Setup_virtual_property()
{
// verify our assumptions that A is indeed virtual (and non-sealed):
var propertyGetter = typeof(Foo).GetProperty("A").GetGetMethod();
Assert.True(propertyGetter.IsVirtual);
Assert.False(propertyGetter.IsFinal);
var mock = new Mock<Foo>();
mock.Setup(m => m.A).Returns("mocked A");
var a = mock.Object.A;
Assert.Equal("mocked A", a);
}
[Fact]
public void Can_Setup_virtual_property_that_implicitly_implements_a_property_from_inaccessible_interface()
{
// verify our assumptions that C is indeed virtual (and non-sealed):
var propertyGetter = typeof(Foo).GetProperty("C").GetGetMethod();
Assert.True(propertyGetter.IsVirtual);
Assert.False(propertyGetter.IsFinal);
var mock = new Mock<Foo>();
mock.Setup(m => m.C).Returns("mocked C");
var c = mock.Object.C;
Assert.Equal("mocked C", c);
}
[Fact]
public void Cannot_Setup_virtual_but_sealed_property()
{
// verify our assumptions that B is indeed virtual and sealed:
var propertyGetter = typeof(Foo).GetProperty("B").GetGetMethod();
Assert.True(propertyGetter.IsVirtual);
Assert.True(propertyGetter.IsFinal);
var mock = new Mock<Foo>();
var exception = Record.Exception(() =>
{
mock.Setup(m => m.B).Returns("mocked B");
});
var b = mock.Object.B;
Assert.NotEqual("mocked B", b); // it simply shouldn't be possible for Moq to intercept a sealed property;
Assert.NotNull(exception); // and Moq should tell us by throwing an exception.
}
[Fact]
public void Cannot_Setup_virtual_but_sealed_property_that_implicitly_implements_a_property_from_inaccessible_interface()
{
// verify our assumptions that D is indeed virtual and sealed:
var propertyGetter = typeof(Foo).GetProperty("D").GetGetMethod();
Assert.True(propertyGetter.IsVirtual);
Assert.True(propertyGetter.IsFinal);
var mock = new Mock<Foo>();
var exception = Record.Exception(() =>
{
mock.Setup(m => m.D).Returns("mocked D");
});
var d = mock.Object.D;
Assert.NotEqual("mocked D", d); // it simply shouldn't be possible for Moq to intercept a sealed property;
Assert.NotNull(exception); // and Moq should tell us by throwing an exception.
}
[Fact]
public void SetupAllProperties_does_not_throw_when_it_encounters_properties_that_cannot_be_setup()
{
var mock = new Mock<Foo>();
var exception = Record.Exception(() =>
{
mock.SetupAllProperties();
});
Assert.Null(exception);
}
[Fact]
public void SetupAllProperties_should_not_reset_indexer_setups()
{
var mock = new Mock<IIndexedFoo>();
mock.SetupGet(m => m[1]).Returns("value from setup");
Assert.Equal("value from setup", mock.Object[1]);
mock.SetupAllProperties();
Assert.Equal("value from setup", mock.Object[1]);
}
public abstract class FooBase
{
public abstract object A { get; }
public abstract object B { get; }
}
internal interface IFooInternals
{
object C { get; }
object D { get; }
}
public abstract class Foo : FooBase, IFooInternals
{
public override object A => "A";
public sealed override object B => "B";
public virtual object C => "C";
public object D => "D";
}
}
}
| |
/*
* Copyright 2015 Software Freedom Conservancy.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Collections;
using System.Text;
namespace Selenium
{
/// <summary>
/// Sends commands and retrieves results via HTTP.
/// </summary>
public class HttpCommandProcessor : ICommandProcessor
{
private readonly string url;
private string sessionId;
private string browserStartCommand;
private string browserURL;
private string extensionJs;
/// <summary>
/// The server URL, to whom we send command requests
/// </summary>
public string Url
{
get { return url; }
}
/// <summary>
/// Specifies a server host/port, a command to launch the browser, and a starting URL for the browser.
/// </summary>
/// <param name="serverHost">the host name on which the Selenium Server resides</param>
/// <param name="serverPort">the port on which the Selenium Server is listening</param>
/// <param name="browserStartCommand">the command string used to launch the browser, e.g. "*firefox" or "c:\\program files\\internet explorer\\iexplore.exe"</param>
/// <param name="browserURL">the starting URL including just a domain name. We'll start the browser pointing at the Selenium resources on this URL,
/// e.g. "http://www.google.com" would send the browser to "http://www.google.com/selenium-server/RemoteRunner.html"</param>
public HttpCommandProcessor(string serverHost, int serverPort, string browserStartCommand, string browserURL)
{
this.url = "http://" + serverHost +
":"+ serverPort + "/selenium-server/driver/";
this.browserStartCommand = browserStartCommand;
this.browserURL = browserURL;
this.extensionJs = "";
}
/// <summary>
/// Specifies the URL to the server, a command to launch the browser, and a starting URL for the browser.
/// </summary>
/// <param name="serverURL">the URL of the Selenium Server Driver, e.g. "http://localhost:4444/selenium-server/driver/" (don't forget the final slash!)</param>
/// <param name="browserStartCommand">the command string used to launch the browser, e.g. "*firefox" or "c:\\program files\\internet explorer\\iexplore.exe"</param>
/// <param name="browserURL">the starting URL including just a domain name. We'll start the browser pointing at the Selenium resources on this URL,
/// e.g. "http://www.google.com" would send the browser to "http://www.google.com/selenium-server/RemoteRunner.html"</param>
public HttpCommandProcessor(string serverURL, string browserStartCommand, string browserURL)
{
this.url = serverURL;
this.browserStartCommand = browserStartCommand;
this.browserURL = browserURL;
this.extensionJs = "";
}
/// <summary>
/// Send the specified remote command to the browser to be performed
/// </summary>
/// <param name="command">the remote command verb</param>
/// <param name="args">the arguments to the remote command (depends on the verb)</param>
/// <returns>the command result, defined by the remote JavaScript. "getX" style
/// commands may return data from the browser</returns>
public string DoCommand(string command, string[] args)
{
IRemoteCommand remoteCommand = new DefaultRemoteCommand(command, args);
using (HttpWebResponse response = (HttpWebResponse) CreateWebRequest(remoteCommand).GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new SeleniumException(response.StatusDescription);
}
string resultBody = ReadResponse(response);
if (!resultBody.StartsWith("OK"))
{
throw new SeleniumException(resultBody);
}
return resultBody;
}
}
/// <summary>
/// Retrieves the body of the HTTP response
/// </summary>
/// <param name="response">the response object to read</param>
/// <returns>the body of the HTTP response</returns>
public virtual string ReadResponse(HttpWebResponse response)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
/// <summary>
/// Builds an HTTP request based on the specified remote Command
/// </summary>
/// <param name="command">the command we'll send to the server</param>
/// <returns>an HTTP request, which will perform this command</returns>
public virtual WebRequest CreateWebRequest(IRemoteCommand command)
{
byte[] data = BuildCommandPostData(command.CommandString);
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
request.Timeout = Timeout.Infinite;
request.ServicePoint.ConnectionLimit = 2000;
Stream rs = request.GetRequestStream();
rs.Write(data, 0, data.Length);
rs.Close();
return request;
}
private byte[] BuildCommandPostData(string commandString)
{
string data = commandString;
if (sessionId != null)
{
data += "&sessionId=" + sessionId;
}
return (new UTF8Encoding()).GetBytes(data);
}
/// <summary>
/// Sets the extension Javascript to be used in the created session
/// </summary>
/// <param name="extensionJs">The extension JavaScript to use.</param>
public void SetExtensionJs(string extensionJs)
{
this.extensionJs = extensionJs;
}
/// <summary>
/// Creates a new browser session
/// </summary>
public void Start()
{
string result = GetString("getNewBrowserSession", new String[] {browserStartCommand, browserURL, extensionJs});
sessionId = result;
}
/// <summary>
/// Take any extra options that may be needed when creating a browser session
/// </summary>
/// <param name="optionString">Browser Options</param>
public void Start(string optionString)
{
string result = GetString("getNewBrowserSession", new String[] { browserStartCommand, browserURL, extensionJs, optionString });
sessionId = result;
}
/// <summary>
/// Wraps the version of start() that takes a string parameter, sending it the result
/// of calling ToString() on optionsObject, which will likey be a BrowserConfigurationOptions instan
/// </summary>
/// <param name="optionsObject">Contains BrowserConfigurationOptions </param>
public void Start(Object optionsObject)
{
Start(optionsObject.ToString());
}
/// <summary>
/// Stops the previous browser session, killing the browser
/// </summary>
public void Stop()
{
DoCommand("testComplete", null);
sessionId = null;
}
/// <summary>
/// Runs the specified remote accessor (getter) command and returns the retrieved result
/// </summary>
/// <param name="commandName">the remote Command verb</param>
/// <param name="args">the arguments to the remote Command (depends on the verb)</param>
/// <returns>the result of running the accessor on the browser</returns>
public String GetString(String commandName, String[] args)
{
return DoCommand(commandName, args).Substring(3); // skip "OK,"
}
/// <summary>
/// Runs the specified remote accessor (getter) command and returns the retrieved result
/// </summary>
/// <param name="commandName">the remote Command verb</param>
/// <param name="args">the arguments to the remote Command (depends on the verb)</param>
/// <returns>the result of running the accessor on the browser</returns>
public String[] GetStringArray(String commandName, String[] args)
{
String result = GetString(commandName, args);
return parseCSV(result);
}
/// <summary>
/// Parse Selenium comma separated values.
/// </summary>
/// <param name="input">the comma delimited string to parse</param>
/// <returns>the parsed comma-separated entries</returns>
public static String[] parseCSV(String input)
{
ArrayList output = new ArrayList();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < input.Length; i++)
{
char c = input.ToCharArray()[i];
switch (c)
{
case ',':
output.Add(sb.ToString());
sb = new StringBuilder();
continue;
case '\\':
i++;
c = input.ToCharArray()[i];
sb.Append(c);
continue;
default:
sb.Append(c);
break;
}
}
output.Add(sb.ToString());
return (String[]) output.ToArray(typeof(String));
}
/// <summary>
/// Runs the specified remote accessor (getter) command and returns the retrieved result
/// </summary>
/// <param name="commandName">the remote Command verb</param>
/// <param name="args">the arguments to the remote Command (depends on the verb)</param>
/// <returns>the result of running the accessor on the browser</returns>
public Decimal GetNumber(String commandName, String[] args)
{
String result = GetString(commandName, args);
Decimal d = Decimal.Parse(result);
return d;
}
/// <summary>
/// Runs the specified remote accessor (getter) command and returns the retrieved result
/// </summary>
/// <param name="commandName">the remote Command verb</param>
/// <param name="args">the arguments to the remote Command (depends on the verb)</param>
/// <returns>the result of running the accessor on the browser</returns>
public Decimal[] GetNumberArray(String commandName, String[] args)
{
String[] result = GetStringArray(commandName, args);
Decimal[] d = new Decimal[result.Length];
for (int i = 0; i < result.Length; i++)
{
d[i] = Decimal.Parse(result[i]);
}
return d;
}
/// <summary>
/// Runs the specified remote accessor (getter) command and returns the retrieved result
/// </summary>
/// <param name="commandName">the remote Command verb</param>
/// <param name="args">the arguments to the remote Command (depends on the verb)</param>
/// <returns>the result of running the accessor on the browser</returns>
public bool GetBoolean(String commandName, String[] args)
{
String result = GetString(commandName, args);
bool b;
if ("true".Equals(result))
{
b = true;
return b;
}
if ("false".Equals(result))
{
b = false;
return b;
}
throw new Exception("result was neither 'true' nor 'false': " + result);
}
/// <summary>
/// Runs the specified remote accessor (getter) command and returns the retrieved result
/// </summary>
/// <param name="commandName">the remote Command verb</param>
/// <param name="args">the arguments to the remote Command (depends on the verb)</param>
/// <returns>the result of running the accessor on the browser</returns>
public bool[] GetBooleanArray(String commandName, String[] args)
{
String[] result = GetStringArray(commandName, args);
bool[] b = new bool[result.Length];
for (int i = 0; i < result.Length; i++)
{
if ("true".Equals(result))
{
b[i] = true;
continue;
}
if ("false".Equals(result))
{
b[i] = false;
continue;
}
throw new Exception("result was neither 'true' nor 'false': " + result);
}
return b;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Security.Cryptography
{
using Microsoft.Win32;
using System.IO;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if FEATURE_MACL
using System.Security.AccessControl;
#endif // FEATURE_MACL
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
#if FEATURE_IMPERSONATION
using System.Security.Principal;
#endif // FEATURE_IMPERSONATION
using System.Text;
using System.Threading;
using System.Diagnostics.Contracts;
using System.Runtime.Versioning;
[Serializable]
internal enum CspAlgorithmType {
Rsa = 0,
Dss = 1
}
internal static class Constants {
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
internal const int S_OK = 0;
internal const int NTE_FILENOTFOUND = unchecked((int) 0x80070002); // The system cannot find the file specified.
internal const int NTE_NO_KEY = unchecked((int) 0x8009000D); // Key does not exist.
internal const int NTE_BAD_KEYSET = unchecked((int) 0x80090016); // Keyset does not exist.
internal const int NTE_KEYSET_NOT_DEF = unchecked((int) 0x80090019); // The keyset is not defined.
internal const int KP_IV = 1;
internal const int KP_MODE = 4;
internal const int KP_MODE_BITS = 5;
internal const int KP_EFFECTIVE_KEYLEN = 19;
internal const int ALG_CLASS_SIGNATURE = (1 << 13);
internal const int ALG_CLASS_DATA_ENCRYPT = (3 << 13);
internal const int ALG_CLASS_HASH = (4 << 13);
internal const int ALG_CLASS_KEY_EXCHANGE = (5 << 13);
internal const int ALG_TYPE_DSS = (1 << 9);
internal const int ALG_TYPE_RSA = (2 << 9);
internal const int ALG_TYPE_BLOCK = (3 << 9);
internal const int ALG_TYPE_STREAM = (4 << 9);
internal const int ALG_TYPE_ANY = (0);
internal const int CALG_MD5 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 3);
internal const int CALG_SHA1 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 4);
internal const int CALG_SHA_256 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 12);
internal const int CALG_SHA_384 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 13);
internal const int CALG_SHA_512 = (ALG_CLASS_HASH | ALG_TYPE_ANY | 14);
internal const int CALG_RSA_KEYX = (ALG_CLASS_KEY_EXCHANGE | ALG_TYPE_RSA | 0);
internal const int CALG_RSA_SIGN = (ALG_CLASS_SIGNATURE | ALG_TYPE_RSA | 0);
internal const int CALG_DSS_SIGN = (ALG_CLASS_SIGNATURE | ALG_TYPE_DSS | 0);
internal const int CALG_DES = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 1);
internal const int CALG_RC2 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 2);
internal const int CALG_3DES = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 3);
internal const int CALG_3DES_112 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 9);
internal const int CALG_AES_128 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 14);
internal const int CALG_AES_192 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 15);
internal const int CALG_AES_256 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | 16);
internal const int CALG_RC4 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_STREAM | 1);
#endif // FEATURE_CRYPTO
internal const int PROV_RSA_FULL = 1;
internal const int PROV_DSS_DH = 13;
internal const int PROV_RSA_AES = 24;
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
internal const int AT_KEYEXCHANGE = 1;
#endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
internal const int AT_SIGNATURE = 2;
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
internal const int PUBLICKEYBLOB = 0x6;
internal const int PRIVATEKEYBLOB = 0x7;
internal const int CRYPT_OAEP = 0x40;
internal const uint CRYPT_VERIFYCONTEXT = 0xF0000000;
internal const uint CRYPT_NEWKEYSET = 0x00000008;
internal const uint CRYPT_DELETEKEYSET = 0x00000010;
internal const uint CRYPT_MACHINE_KEYSET = 0x00000020;
internal const uint CRYPT_SILENT = 0x00000040;
internal const uint CRYPT_EXPORTABLE = 0x00000001;
internal const uint CLR_KEYLEN = 1;
internal const uint CLR_PUBLICKEYONLY = 2;
internal const uint CLR_EXPORTABLE = 3;
internal const uint CLR_REMOVABLE = 4;
internal const uint CLR_HARDWARE = 5;
internal const uint CLR_ACCESSIBLE = 6;
internal const uint CLR_PROTECTED = 7;
internal const uint CLR_UNIQUE_CONTAINER = 8;
internal const uint CLR_ALGID = 9;
internal const uint CLR_PP_CLIENT_HWND = 10;
internal const uint CLR_PP_PIN = 11;
internal const string OID_RSA_SMIMEalgCMS3DESwrap = "1.2.840.113549.1.9.16.3.6";
internal const string OID_RSA_MD5 = "1.2.840.113549.2.5";
internal const string OID_RSA_RC2CBC = "1.2.840.113549.3.2";
internal const string OID_RSA_DES_EDE3_CBC = "1.2.840.113549.3.7";
internal const string OID_OIWSEC_desCBC = "1.3.14.3.2.7";
internal const string OID_OIWSEC_SHA1 = "1.3.14.3.2.26";
internal const string OID_OIWSEC_SHA256 = "2.16.840.1.101.3.4.2.1";
internal const string OID_OIWSEC_SHA384 = "2.16.840.1.101.3.4.2.2";
internal const string OID_OIWSEC_SHA512 = "2.16.840.1.101.3.4.2.3";
internal const string OID_OIWSEC_RIPEMD160 = "1.3.36.3.2.1";
#endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
}
internal static class Utils {
#if FEATURE_CRYPTO
[SecuritySafeCritical]
#endif
static Utils()
{
}
// Provider type to use by default for RSA operations. We want to use RSA-AES CSP
// since it enables access to SHA-2 operations. All currently supported OSes support RSA-AES.
internal const int DefaultRsaProviderType = Constants.PROV_RSA_AES;
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject = new Object();
private static Object InternalSyncObject {
get { return s_InternalSyncObject; }
}
[System.Security.SecurityCritical] // auto-generated
private static volatile SafeProvHandle _safeProvHandle;
internal static SafeProvHandle StaticProvHandle {
[System.Security.SecurityCritical] // auto-generated
get {
if (_safeProvHandle == null) {
lock (InternalSyncObject) {
if (_safeProvHandle == null) {
_safeProvHandle = AcquireProvHandle(new CspParameters(DefaultRsaProviderType));
}
}
}
return _safeProvHandle;
}
}
[System.Security.SecurityCritical] // auto-generated
private static volatile SafeProvHandle _safeDssProvHandle;
internal static SafeProvHandle StaticDssProvHandle {
[System.Security.SecurityCritical] // auto-generated
get {
if (_safeDssProvHandle == null) {
lock (InternalSyncObject) {
if (_safeDssProvHandle == null) {
_safeDssProvHandle = CreateProvHandle(new CspParameters(Constants.PROV_DSS_DH), true);
}
}
}
return _safeDssProvHandle;
}
}
[System.Security.SecurityCritical] // auto-generated
internal static SafeProvHandle AcquireProvHandle (CspParameters parameters) {
if (parameters == null)
parameters = new CspParameters(DefaultRsaProviderType);
SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle;
Utils._AcquireCSP(parameters, ref safeProvHandle);
return safeProvHandle;
}
[System.Security.SecurityCritical] // auto-generated
internal static SafeProvHandle CreateProvHandle (CspParameters parameters, bool randomKeyContainer) {
SafeProvHandle safeProvHandle = SafeProvHandle.InvalidHandle;
int hr = Utils._OpenCSP(parameters, 0, ref safeProvHandle);
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
if (hr != Constants.S_OK) {
// If UseExistingKey flag is used and the key container does not exist
// throw an exception without attempting to create the container.
if ((parameters.Flags & CspProviderFlags.UseExistingKey) != 0 || (hr != Constants.NTE_KEYSET_NOT_DEF && hr != Constants.NTE_BAD_KEYSET && hr != Constants.NTE_FILENOTFOUND))
throw new CryptographicException(hr);
if (!randomKeyContainer) {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Create);
kp.AccessEntries.Add(entry);
kp.Demand();
}
}
Utils._CreateCSP(parameters, randomKeyContainer, ref safeProvHandle);
} else {
if (!randomKeyContainer) {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Open);
kp.AccessEntries.Add(entry);
kp.Demand();
}
}
}
return safeProvHandle;
}
#if FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
internal static CryptoKeySecurity GetKeySetSecurityInfo (SafeProvHandle hProv, AccessControlSections accessControlSections) {
SecurityInfos securityInfo = 0;
Privilege privilege = null;
if ((accessControlSections & AccessControlSections.Owner) != 0)
securityInfo |= SecurityInfos.Owner;
if ((accessControlSections & AccessControlSections.Group) != 0)
securityInfo |= SecurityInfos.Group;
if ((accessControlSections & AccessControlSections.Access) != 0)
securityInfo |= SecurityInfos.DiscretionaryAcl;
byte[] rawSecurityDescriptor = null;
int error;
RuntimeHelpers.PrepareConstrainedRegions();
try {
if ((accessControlSections & AccessControlSections.Audit) != 0) {
securityInfo |= SecurityInfos.SystemAcl;
privilege = new Privilege("SeSecurityPrivilege");
privilege.Enable();
}
rawSecurityDescriptor = _GetKeySetSecurityInfo(hProv, securityInfo, out error);
}
finally {
if (privilege != null)
privilege.Revert();
}
// This means that the object doesn't have a security descriptor. And thus we throw
// a specific exception for the caller to catch and handle properly.
if (error == Win32Native.ERROR_SUCCESS && (rawSecurityDescriptor == null || rawSecurityDescriptor.Length == 0))
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoSecurityDescriptor"));
if (error == Win32Native.ERROR_NOT_ENOUGH_MEMORY)
throw new OutOfMemoryException();
if (error == Win32Native.ERROR_ACCESS_DENIED)
throw new UnauthorizedAccessException();
if (error == Win32Native.ERROR_PRIVILEGE_NOT_HELD)
throw new PrivilegeNotHeldException( "SeSecurityPrivilege" );
if (error != Win32Native.ERROR_SUCCESS)
throw new CryptographicException(error);
CommonSecurityDescriptor sd = new CommonSecurityDescriptor(false /* isContainer */,
false /* isDS */,
new RawSecurityDescriptor(rawSecurityDescriptor, 0),
true);
return new CryptoKeySecurity(sd);
}
[System.Security.SecurityCritical] // auto-generated
internal static void SetKeySetSecurityInfo (SafeProvHandle hProv, CryptoKeySecurity cryptoKeySecurity, AccessControlSections accessControlSections) {
SecurityInfos securityInfo = 0;
Privilege privilege = null;
if ((accessControlSections & AccessControlSections.Owner) != 0 && cryptoKeySecurity._securityDescriptor.Owner != null)
securityInfo |= SecurityInfos.Owner;
if ((accessControlSections & AccessControlSections.Group) != 0 && cryptoKeySecurity._securityDescriptor.Group != null)
securityInfo |= SecurityInfos.Group;
if ((accessControlSections & AccessControlSections.Audit) != 0)
securityInfo |= SecurityInfos.SystemAcl;
if ((accessControlSections & AccessControlSections.Access) != 0 && cryptoKeySecurity._securityDescriptor.IsDiscretionaryAclPresent)
securityInfo |= SecurityInfos.DiscretionaryAcl;
if (securityInfo == 0) {
// Nothing to persist
return;
}
int error = 0;
RuntimeHelpers.PrepareConstrainedRegions();
try {
if ((securityInfo & SecurityInfos.SystemAcl) != 0) {
privilege = new Privilege("SeSecurityPrivilege");
privilege.Enable();
}
byte[] sd = cryptoKeySecurity.GetSecurityDescriptorBinaryForm();
if (sd != null && sd.Length > 0)
error = SetKeySetSecurityInfo (hProv, securityInfo, sd);
}
finally {
if (privilege != null)
privilege.Revert();
}
if (error == Win32Native.ERROR_ACCESS_DENIED || error == Win32Native.ERROR_INVALID_OWNER || error == Win32Native.ERROR_INVALID_PRIMARY_GROUP)
throw new UnauthorizedAccessException();
else if (error == Win32Native.ERROR_PRIVILEGE_NOT_HELD)
throw new PrivilegeNotHeldException("SeSecurityPrivilege");
else if (error == Win32Native.ERROR_INVALID_HANDLE)
throw new NotSupportedException(Environment.GetResourceString("AccessControl_InvalidHandle"));
else if (error != Win32Native.ERROR_SUCCESS)
throw new CryptographicException(error);
}
#endif //FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
internal static byte[] ExportCspBlobHelper (bool includePrivateParameters, CspParameters parameters, SafeKeyHandle safeKeyHandle) {
if (includePrivateParameters) {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Export);
kp.AccessEntries.Add(entry);
kp.Demand();
}
}
byte[] blob = null;
Utils.ExportCspBlob(safeKeyHandle, includePrivateParameters ? Constants.PRIVATEKEYBLOB : Constants.PUBLICKEYBLOB, JitHelpers.GetObjectHandleOnStack(ref blob));
return blob;
}
[System.Security.SecuritySafeCritical] // auto-generated
internal static void GetKeyPairHelper (CspAlgorithmType keyType, CspParameters parameters, bool randomKeyContainer, int dwKeySize, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) {
SafeProvHandle TempFetchedProvHandle = Utils.CreateProvHandle(parameters, randomKeyContainer);
#if FEATURE_MACL
// If the user wanted to set the security descriptor on the provider context, apply it now.
if (parameters.CryptoKeySecurity != null) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.ChangeAcl);
kp.AccessEntries.Add(entry);
kp.Demand();
SetKeySetSecurityInfo(TempFetchedProvHandle, parameters.CryptoKeySecurity, parameters.CryptoKeySecurity.ChangedAccessControlSections);
}
#endif //FEATURE_MACL
#if FEATURE_X509_SECURESTRINGS
// If the user wanted to specify a PIN or HWND for a smart card CSP, apply those settings now.
if (parameters.ParentWindowHandle != IntPtr.Zero)
SetProviderParameter(TempFetchedProvHandle, parameters.KeyNumber, Constants.CLR_PP_CLIENT_HWND, parameters.ParentWindowHandle);
else if (parameters.KeyPassword != null) {
IntPtr szPassword = Marshal.SecureStringToCoTaskMemAnsi(parameters.KeyPassword);
try {
SetProviderParameter(TempFetchedProvHandle, parameters.KeyNumber, Constants.CLR_PP_PIN, szPassword);
}
finally {
if (szPassword != IntPtr.Zero)
Marshal.ZeroFreeCoTaskMemAnsi(szPassword);
}
}
#endif //FEATURE_X509_SECURESTRINGS
safeProvHandle = TempFetchedProvHandle;
// If the key already exists, use it, else generate a new one
SafeKeyHandle TempFetchedKeyHandle = SafeKeyHandle.InvalidHandle;
int hr = Utils._GetUserKey(safeProvHandle, parameters.KeyNumber, ref TempFetchedKeyHandle);
if (hr != Constants.S_OK) {
if ((parameters.Flags & CspProviderFlags.UseExistingKey) != 0 || hr != Constants.NTE_NO_KEY)
throw new CryptographicException(hr);
// _GenerateKey will check for failures and throw an exception
Utils._GenerateKey(safeProvHandle, parameters.KeyNumber, parameters.Flags, dwKeySize, ref TempFetchedKeyHandle);
}
// check that this is indeed an RSA/DSS key.
byte[] algid = (byte[]) Utils._GetKeyParameter(TempFetchedKeyHandle, Constants.CLR_ALGID);
int dwAlgId = (algid[0] | (algid[1] << 8) | (algid[2] << 16) | (algid[3] << 24));
if ((keyType == CspAlgorithmType.Rsa && dwAlgId != Constants.CALG_RSA_KEYX && dwAlgId != Constants.CALG_RSA_SIGN) ||
(keyType == CspAlgorithmType.Dss && dwAlgId != Constants.CALG_DSS_SIGN)) {
TempFetchedKeyHandle.Dispose();
throw new CryptographicException(Environment.GetResourceString("Cryptography_CSP_WrongKeySpec"));
}
safeKeyHandle = TempFetchedKeyHandle;
}
[System.Security.SecurityCritical] // auto-generated
internal static void ImportCspBlobHelper (CspAlgorithmType keyType, byte[] keyBlob, bool publicOnly, ref CspParameters parameters, bool randomKeyContainer, ref SafeProvHandle safeProvHandle, ref SafeKeyHandle safeKeyHandle) {
// Free the current key handle
if (safeKeyHandle != null && !safeKeyHandle.IsClosed)
safeKeyHandle.Dispose();
safeKeyHandle = SafeKeyHandle.InvalidHandle;
if (publicOnly) {
parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, keyType == CspAlgorithmType.Dss ? Utils.StaticDssProvHandle : Utils.StaticProvHandle, (CspProviderFlags) 0, ref safeKeyHandle);
} else {
if (!CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
KeyContainerPermission kp = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
KeyContainerPermissionAccessEntry entry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Import);
kp.AccessEntries.Add(entry);
kp.Demand();
}
if (safeProvHandle == null)
safeProvHandle = Utils.CreateProvHandle(parameters, randomKeyContainer);
parameters.KeyNumber = Utils._ImportCspBlob(keyBlob, safeProvHandle, parameters.Flags, ref safeKeyHandle);
}
}
#endif // FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
[System.Security.SecurityCritical] // auto-generated
internal static CspParameters SaveCspParameters (CspAlgorithmType keyType, CspParameters userParameters, CspProviderFlags defaultFlags, ref bool randomKeyContainer) {
CspParameters parameters;
if (userParameters == null) {
parameters = new CspParameters(keyType == CspAlgorithmType.Dss ? Constants.PROV_DSS_DH : DefaultRsaProviderType, null, null, defaultFlags);
} else {
ValidateCspFlags(userParameters.Flags);
parameters = new CspParameters(userParameters);
}
if (parameters.KeyNumber == -1)
parameters.KeyNumber = keyType == CspAlgorithmType.Dss ? Constants.AT_SIGNATURE : Constants.AT_KEYEXCHANGE;
else if (parameters.KeyNumber == Constants.CALG_DSS_SIGN || parameters.KeyNumber == Constants.CALG_RSA_SIGN)
parameters.KeyNumber = Constants.AT_SIGNATURE;
else if (parameters.KeyNumber == Constants.CALG_RSA_KEYX)
parameters.KeyNumber = Constants.AT_KEYEXCHANGE;
// If no key container was specified and UseDefaultKeyContainer is not used, then use CRYPT_VERIFYCONTEXT
// to generate an ephemeral key
randomKeyContainer = (parameters.Flags & CspProviderFlags.CreateEphemeralKey) == CspProviderFlags.CreateEphemeralKey;
if (parameters.KeyContainerName == null && (parameters.Flags & CspProviderFlags.UseDefaultKeyContainer) == 0) {
parameters.Flags |= CspProviderFlags.CreateEphemeralKey;
randomKeyContainer = true;
}
return parameters;
}
[System.Security.SecurityCritical] // auto-generated
private static void ValidateCspFlags (CspProviderFlags flags) {
// check that the flags are consistent.
if ((flags & CspProviderFlags.UseExistingKey) != 0) {
CspProviderFlags keyFlags = (CspProviderFlags.UseNonExportableKey | CspProviderFlags.UseArchivableKey | CspProviderFlags.UseUserProtectedKey);
if ((flags & keyFlags) != CspProviderFlags.NoFlags)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"));
}
// make sure we are allowed to display the key protection UI if a user protected key is requested.
if ((flags & CspProviderFlags.UseUserProtectedKey) != 0) {
// UI only allowed in interactive session.
if (!System.Environment.UserInteractive)
throw new InvalidOperationException(Environment.GetResourceString("Cryptography_NotInteractive"));
// we need to demand UI permission here.
UIPermission uiPermission = new UIPermission(UIPermissionWindow.SafeTopLevelWindows);
uiPermission.Demand();
}
}
#endif // FEATURE_CRYPTO
private static volatile RNGCryptoServiceProvider _rng;
internal static RNGCryptoServiceProvider StaticRandomNumberGenerator {
get {
if (_rng == null)
_rng = new RNGCryptoServiceProvider();
return _rng;
}
}
//
// internal static methods
//
internal static byte[] GenerateRandom (int keySize) {
byte[] key = new byte[keySize];
StaticRandomNumberGenerator.GetBytes(key);
return key;
}
#if FEATURE_CRYPTO
/// <summary>
/// Read the FIPS policy from the pre-Vista registry key
/// </summary>
/// <returns>
/// True if the FIPS policy is enabled, false otherwise. An error reading the policy key is
/// interpreted as if the policy is enabled, and a missing key is interpreted as the policy being
/// disabled.
/// </returns>
[System.Security.SecurityCritical] // auto-generated
#pragma warning disable 618
[RegistryPermissionAttribute(SecurityAction.Assert, Read="HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Lsa")]
#pragma warning restore 618
internal static bool ReadLegacyFipsPolicy()
{
Contract.Assert(Environment.OSVersion.Version.Major < 6, "CryptGetFIPSAlgorithmMode should be used on Vista+");
try
{
using (RegistryKey fipsAlgorithmPolicyKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Lsa", false))
{
if (fipsAlgorithmPolicyKey == null)
return false;
object data = fipsAlgorithmPolicyKey.GetValue("FIPSAlgorithmPolicy");
if (data == null)
{
return false;
}
else if (fipsAlgorithmPolicyKey.GetValueKind("FIPSAlgorithmPolicy") != RegistryValueKind.DWord)
{
return true;
}
else
{
return ((int)data != 0);
}
}
}
catch (SecurityException)
{
// If we could not open the registry key, we'll assume the setting is to enforce FIPS policy.
return true;
}
}
#endif //FEATURE_CRYPTO
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
// dwKeySize = 0 means the default key size
[System.Security.SecurityCritical] // auto-generated
internal static bool HasAlgorithm (int dwCalg, int dwKeySize) {
bool r = false;
// We need to take a lock here since we are querying the provider handle in a loop.
// If multiple threads are racing in this code, not all algorithms/key sizes combinations
// will be examined; which may lead to a situation where false is wrongfully returned.
lock (InternalSyncObject) {
r = SearchForAlgorithm(StaticProvHandle, dwCalg, dwKeySize);
}
return r;
}
internal static int ObjToAlgId(object hashAlg, OidGroup group) {
if (hashAlg == null)
throw new ArgumentNullException("hashAlg");
Contract.EndContractBlock();
string oidValue = null;
string hashAlgString = hashAlg as string;
if (hashAlgString != null) {
oidValue = CryptoConfig.MapNameToOID(hashAlgString, group);
if (oidValue == null)
oidValue = hashAlgString; // maybe we were passed the OID value
}
else if (hashAlg is HashAlgorithm) {
oidValue = CryptoConfig.MapNameToOID(hashAlg.GetType().ToString(), group);
}
else if (hashAlg is Type) {
oidValue = CryptoConfig.MapNameToOID(hashAlg.ToString(), group);
}
if (oidValue == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
return X509Utils.GetAlgIdFromOid(oidValue, group);
}
internal static HashAlgorithm ObjToHashAlgorithm (Object hashAlg) {
if (hashAlg == null)
throw new ArgumentNullException("hashAlg");
Contract.EndContractBlock();
HashAlgorithm hash = null;
if (hashAlg is String) {
hash = (HashAlgorithm) CryptoConfig.CreateFromName((string) hashAlg);
if (hash == null) {
string oidFriendlyName = X509Utils.GetFriendlyNameFromOid((string) hashAlg, OidGroup.HashAlgorithm);
if (oidFriendlyName != null)
hash = (HashAlgorithm) CryptoConfig.CreateFromName(oidFriendlyName);
}
}
else if (hashAlg is HashAlgorithm) {
hash = (HashAlgorithm) hashAlg;
}
else if (hashAlg is Type) {
hash = (HashAlgorithm) CryptoConfig.CreateFromName(hashAlg.ToString());
}
if (hash == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidValue"));
return hash;
}
internal static String DiscardWhiteSpaces (string inputBuffer) {
return DiscardWhiteSpaces(inputBuffer, 0, inputBuffer.Length);
}
internal static String DiscardWhiteSpaces (string inputBuffer, int inputOffset, int inputCount) {
int i, iCount = 0;
for (i=0; i<inputCount; i++)
if (Char.IsWhiteSpace(inputBuffer[inputOffset + i])) iCount++;
char[] output = new char[inputCount - iCount];
iCount = 0;
for (i=0; i<inputCount; i++) {
if (!Char.IsWhiteSpace(inputBuffer[inputOffset + i]))
output[iCount++] = inputBuffer[inputOffset + i];
}
return new String(output);
}
internal static int ConvertByteArrayToInt (byte[] input) {
// Input to this routine is always big endian
int dwOutput = 0;
for (int i = 0; i < input.Length; i++) {
dwOutput *= 256;
dwOutput += input[i];
}
return(dwOutput);
}
// output of this routine is always big endian
internal static byte[] ConvertIntToByteArray (int dwInput) {
byte[] temp = new byte[8]; // int can never be greater than Int64
int t1; // t1 is remaining value to account for
int t2; // t2 is t1 % 256
int i = 0;
if (dwInput == 0) return new byte[1];
t1 = dwInput;
while (t1 > 0) {
Contract.Assert(i < 8, "Got too big an int here!");
t2 = t1 % 256;
temp[i] = (byte) t2;
t1 = (t1 - t2)/256;
i++;
}
// Now, copy only the non-zero part of temp and reverse
byte[] output = new byte[i];
// copy and reverse in one pass
for (int j = 0; j < i; j++) {
output[j] = temp[i-j-1];
}
return output;
}
// output is little endian
internal static void ConvertIntToByteArray (uint dwInput, ref byte[] counter) {
uint t1 = dwInput; // t1 is remaining value to account for
uint t2; // t2 is t1 % 256
int i = 0;
// clear the array first
Array.Clear(counter, 0, counter.Length);
if (dwInput == 0) return;
while (t1 > 0) {
Contract.Assert(i < 4, "Got too big an int here!");
t2 = t1 % 256;
counter[3 - i] = (byte) t2;
t1 = (t1 - t2)/256;
i++;
}
}
internal static byte[] FixupKeyParity (byte[] key) {
byte[] oddParityKey = new byte[key.Length];
for (int index=0; index < key.Length; index++) {
// Get the bits we are interested in
oddParityKey[index] = (byte) (key[index] & 0xfe);
// Get the parity of the sum of the previous bits
byte tmp1 = (byte)((oddParityKey[index] & 0xF) ^ (oddParityKey[index] >> 4));
byte tmp2 = (byte)((tmp1 & 0x3) ^ (tmp1 >> 2));
byte sumBitsMod2 = (byte)((tmp2 & 0x1) ^ (tmp2 >> 1));
// We need to set the last bit in oddParityKey[index] to the negation
// of the last bit in sumBitsMod2
if (sumBitsMod2 == 0)
oddParityKey[index] |= 1;
}
return oddParityKey;
}
// digits == number of DWORDs
[System.Security.SecurityCritical] // auto-generated
internal unsafe static void DWORDFromLittleEndian (uint* x, int digits, byte* block) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 4)
x[i] = (uint) (block[j] | (block[j+1] << 8) | (block[j+2] << 16) | (block[j+3] << 24));
}
// encodes x (DWORD) into block (unsigned char), least significant byte first.
// digits == number of DWORDs
internal static void DWORDToLittleEndian (byte[] block, uint[] x, int digits) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 4) {
block[j] = (byte)(x[i] & 0xff);
block[j+1] = (byte)((x[i] >> 8) & 0xff);
block[j+2] = (byte)((x[i] >> 16) & 0xff);
block[j+3] = (byte)((x[i] >> 24) & 0xff);
}
}
#endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
// digits == number of DWORDs
[System.Security.SecurityCritical] // auto-generated
internal unsafe static void DWORDFromBigEndian (uint* x, int digits, byte* block) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 4)
x[i] = (uint)((block[j] << 24) | (block[j + 1] << 16) | (block[j + 2] << 8) | block[j + 3]);
}
// encodes x (DWORD) into block (unsigned char), most significant byte first.
// digits == number of DWORDs
internal static void DWORDToBigEndian (byte[] block, uint[] x, int digits) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 4) {
block[j] = (byte)((x[i] >> 24) & 0xff);
block[j+1] = (byte)((x[i] >> 16) & 0xff);
block[j+2] = (byte)((x[i] >> 8) & 0xff);
block[j+3] = (byte)(x[i] & 0xff);
}
}
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
// digits == number of QWORDs
[System.Security.SecurityCritical] // auto-generated
internal unsafe static void QuadWordFromBigEndian (UInt64* x, int digits, byte* block) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 8)
x[i] = (
(((UInt64)block[j]) << 56) | (((UInt64)block[j+1]) << 48) |
(((UInt64)block[j+2]) << 40) | (((UInt64)block[j+3]) << 32) |
(((UInt64)block[j+4]) << 24) | (((UInt64)block[j+5]) << 16) |
(((UInt64)block[j+6]) << 8) | ((UInt64)block[j+7])
);
}
// encodes x (DWORD) into block (unsigned char), most significant byte first.
// digits = number of QWORDS
internal static void QuadWordToBigEndian (byte[] block, UInt64[] x, int digits) {
int i;
int j;
for (i = 0, j = 0; i < digits; i++, j += 8) {
block[j] = (byte)((x[i] >> 56) & 0xff);
block[j+1] = (byte)((x[i] >> 48) & 0xff);
block[j+2] = (byte)((x[i] >> 40) & 0xff);
block[j+3] = (byte)((x[i] >> 32) & 0xff);
block[j+4] = (byte)((x[i] >> 24) & 0xff);
block[j+5] = (byte)((x[i] >> 16) & 0xff);
block[j+6] = (byte)((x[i] >> 8) & 0xff);
block[j+7] = (byte)(x[i] & 0xff);
}
}
#endif // FEATURE_CRYPTO
// encodes the integer i into a 4-byte array, in big endian.
internal static byte[] Int(uint i) {
return unchecked(new byte[] { (byte)(i >> 24), (byte)(i >> 16), (byte)(i >> 8), (byte)i });
}
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
[System.Security.SecurityCritical] // auto-generated
internal static byte[] RsaOaepEncrypt (RSA rsa, HashAlgorithm hash, PKCS1MaskGenerationMethod mgf, RandomNumberGenerator rng, byte[] data) {
int cb = rsa.KeySize / 8;
// 1. Hash the parameters to get PHash
int cbHash = hash.HashSize / 8;
if ((data.Length + 2 + 2*cbHash) > cb)
throw new CryptographicException(String.Format(null, Environment.GetResourceString("Cryptography_Padding_EncDataTooBig"), cb-2-2*cbHash));
hash.ComputeHash(EmptyArray<Byte>.Value); // Use an empty octet string
// 2. Create DB object
byte[] DB = new byte[cb - cbHash];
// Structure is as follows:
// pHash || PS || 01 || M
// PS consists of all zeros
Buffer.InternalBlockCopy(hash.Hash, 0, DB, 0, cbHash);
DB[DB.Length - data.Length - 1] = 1;
Buffer.InternalBlockCopy(data, 0, DB, DB.Length-data.Length, data.Length);
// 3. Create a random value of size hLen
byte[] seed = new byte[cbHash];
rng.GetBytes(seed);
// 4. Compute the mask value
byte[] mask = mgf.GenerateMask(seed, DB.Length);
// 5. Xor maskDB into DB
for (int i=0; i < DB.Length; i++) {
DB[i] = (byte) (DB[i] ^ mask[i]);
}
// 6. Compute seed mask value
mask = mgf.GenerateMask(DB, cbHash);
// 7. Xor mask into seed
for (int i=0; i < seed.Length; i++) {
seed[i] ^= mask[i];
}
// 8. Concatenate seed and DB to form value to encrypt
byte[] pad = new byte[cb];
Buffer.InternalBlockCopy(seed, 0, pad, 0, seed.Length);
Buffer.InternalBlockCopy(DB, 0, pad, seed.Length, DB.Length);
return rsa.EncryptValue(pad);
}
[System.Security.SecurityCritical] // auto-generated
internal static byte[] RsaOaepDecrypt (RSA rsa, HashAlgorithm hash, PKCS1MaskGenerationMethod mgf, byte[] encryptedData) {
int cb = rsa.KeySize / 8;
// 1. Decode the input data
// It is important that the Integer to Octet String conversion errors be indistinguishable from the other decoding
// errors to protect against chosen cipher text attacks
// A lecture given by James Manger during Crypto 2001 explains the issue in details
byte[] data = null;
try {
data = rsa.DecryptValue(encryptedData);
}
catch (CryptographicException) {
throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding"));
}
// 2. Create the hash object so we can get its size info.
int cbHash = hash.HashSize / 8;
// 3. Let maskedSeed be the first hLen octects and maskedDB
// be the remaining bytes.
int zeros = cb - data.Length;
if (zeros < 0 || zeros >= cbHash)
throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding"));
byte[] seed = new byte[cbHash];
Buffer.InternalBlockCopy(data, 0, seed, zeros, seed.Length - zeros);
byte[] DB = new byte[data.Length - seed.Length + zeros];
Buffer.InternalBlockCopy(data, seed.Length - zeros, DB, 0, DB.Length);
// 4. seedMask = MGF(maskedDB, hLen);
byte[] mask = mgf.GenerateMask(DB, seed.Length);
// 5. seed = seedMask XOR maskedSeed
int i = 0;
for (i=0; i < seed.Length; i++) {
seed[i] ^= mask[i];
}
// 6. dbMask = MGF(seed, |EM| - hLen);
mask = mgf.GenerateMask(seed, DB.Length);
// 7. DB = maskedDB xor dbMask
for (i=0; i < DB.Length; i++) {
DB[i] = (byte) (DB[i] ^ mask[i]);
}
// 8. pHash = HASH(P)
hash.ComputeHash(EmptyArray<Byte>.Value);
// 9. DB = pHash' || PS || 01 || M
// 10. Check that pHash = pHash'
byte[] hashValue = hash.Hash;
for (i=0; i < cbHash; i++) {
if (DB[i] != hashValue[i])
throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding"));
}
// Check that PS is all zeros
for (; i<DB.Length; i++) {
if (DB[i] == 1)
break;
else if (DB[i] != 0)
throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding"));
}
if (i == DB.Length)
throw new CryptographicException(Environment.GetResourceString("Cryptography_OAEPDecoding"));
i++; // skip over the one
// 11. Output M.
byte[] output = new byte[DB.Length - i];
Buffer.InternalBlockCopy(DB, i, output, 0, output.Length);
return output;
}
[System.Security.SecurityCritical] // auto-generated
internal static byte[] RsaPkcs1Padding (RSA rsa, byte[] oid, byte[] hash) {
int cb = rsa.KeySize/8;
byte[] pad = new byte[cb];
//
// We want to pad this to the following format:
//
// 00 || 01 || FF ... FF || 00 || prefix || Data
//
// We want basically to ASN 1 encode the OID + hash:
// STRUCTURE {
// STRUCTURE {
// OID <hash algorithm OID>
// NULL (0x05 0x00) // this is actually an ANY and contains the parameters of the algorithm specified by the OID, I think
// }
// OCTET STRING <hashvalue>
// }
//
// Get the correct prefix
byte[] data = new byte[oid.Length + 8 + hash.Length];
data[0] = 0x30; // a structure follows
int tmp = data.Length - 2;
data[1] = (byte) tmp;
data[2] = 0x30;
tmp = oid.Length + 2;
data[3] = (byte) tmp;
Buffer.InternalBlockCopy(oid, 0, data, 4, oid.Length);
data[4 + oid.Length] = 0x05;
data[4 + oid.Length + 1] = 0x00;
data[4 + oid.Length + 2] = 0x04; // an octet string follows
data[4 + oid.Length + 3] = (byte) hash.Length;
Buffer.InternalBlockCopy(hash, 0, data, oid.Length + 8, hash.Length);
// Construct the whole array
int cb1 = cb - data.Length;
if (cb1 <= 2)
throw new CryptographicUnexpectedOperationException(Environment.GetResourceString("Cryptography_InvalidOID"));
pad[0] = 0;
pad[1] = 1;
for (int i=2; i<cb1-1; i++) {
pad[i] = 0xff;
}
pad[cb1-1] = 0;
Buffer.InternalBlockCopy(data, 0, pad, cb1, data.Length);
return pad;
}
// This routine compares 2 big ints; ignoring any leading zeros
internal static bool CompareBigIntArrays (byte[] lhs, byte[] rhs) {
if (lhs == null)
return (rhs == null);
int i = 0, j = 0;
while (i < lhs.Length && lhs[i] == 0) i++;
while (j < rhs.Length && rhs[j] == 0) j++;
int count = (lhs.Length - i);
if ((rhs.Length - j) != count)
return false;
for (int k = 0; k < count; k++) {
if (lhs[i + k] != rhs[j + k])
return false;
}
return true;
}
#if !FEATURE_CORECLR
internal static HashAlgorithmName OidToHashAlgorithmName(string oid)
{
switch (oid)
{
case Constants.OID_OIWSEC_SHA1:
return HashAlgorithmName.SHA1;
case Constants.OID_OIWSEC_SHA256:
return HashAlgorithmName.SHA256;
case Constants.OID_OIWSEC_SHA384:
return HashAlgorithmName.SHA384;
case Constants.OID_OIWSEC_SHA512:
return HashAlgorithmName.SHA512;
default:
throw new NotSupportedException();
}
}
#endif // FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern SafeHashHandle CreateHash(SafeProvHandle hProv, int algid);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void EndHash(SafeHashHandle hHash, ObjectHandleOnStack retHash);
[System.Security.SecurityCritical] // auto-generated
internal static byte[] EndHash(SafeHashHandle hHash)
{
byte[] hash = null;
EndHash(hHash, JitHelpers.GetObjectHandleOnStack(ref hash));
return hash;
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void ExportCspBlob(SafeKeyHandle hKey, int blobType, ObjectHandleOnStack retBlob);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern bool GetPersistKeyInCsp(SafeProvHandle hProv);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void HashData(SafeHashHandle hHash, byte[] data, int cbData, int ibStart, int cbSize);
[System.Security.SecurityCritical] // auto-generated
internal static void HashData(SafeHashHandle hHash, byte[] data, int ibStart, int cbSize)
{
HashData(hHash, data, data.Length, ibStart, cbSize);
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern bool SearchForAlgorithm(SafeProvHandle hProv, int algID, int keyLength);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern void SetKeyParamDw(SafeKeyHandle hKey, int param, int dwValue);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern void SetKeyParamRgb(SafeKeyHandle hKey, int param, byte[] value, int cbValue);
#if FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern int SetKeySetSecurityInfo(SafeProvHandle hProv, SecurityInfos securityInfo, byte[] sd);
#endif //FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern void SetPersistKeyInCsp(SafeProvHandle hProv, bool fPersistKeyInCsp);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern void SetProviderParameter(SafeProvHandle hProv, int keyNumber, uint paramID, IntPtr pbData);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void SignValue(SafeKeyHandle hKey, int keyNumber, int calgKey, int calgHash, byte[] hash, int cbHash, ObjectHandleOnStack retSignature);
[System.Security.SecurityCritical] // auto-generated
internal static byte[] SignValue(SafeKeyHandle hKey, int keyNumber, int calgKey, int calgHash, byte[] hash)
{
byte[] signature = null;
SignValue(hKey, keyNumber, calgKey, calgHash, hash, hash.Length, JitHelpers.GetObjectHandleOnStack(ref signature));
return signature;
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern bool VerifySign(SafeKeyHandle hKey, int calgKey, int calgHash, byte[] hash, int cbHash, byte[] signature, int cbSignature);
[System.Security.SecurityCritical] // auto-generated
internal static bool VerifySign(SafeKeyHandle hKey, int calgKey, int calgHash, byte[] hash, byte[] signature)
{
return VerifySign(hKey, calgKey, calgHash, hash, hash.Length, signature, signature.Length);
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _CreateCSP(CspParameters param, bool randomKeyContainer, ref SafeProvHandle hProv);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int _DecryptData(SafeKeyHandle hKey, byte[] data, int ib, int cb, ref byte[] outputBuffer, int outputOffset, PaddingMode PaddingMode, bool fDone);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int _EncryptData(SafeKeyHandle hKey, byte[] data, int ib, int cb, ref byte[] outputBuffer, int outputOffset, PaddingMode PaddingMode, bool fDone);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _ExportKey(SafeKeyHandle hKey, int blobType, object cspObject);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _GenerateKey(SafeProvHandle hProv, int algid, CspProviderFlags flags, int keySize, ref SafeKeyHandle hKey);
#endif // FEATURE_CRYPTO
[System.Security.SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern bool _GetEnforceFipsPolicySetting();
#if FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern byte[] _GetKeyParameter(SafeKeyHandle hKey, uint paramID);
#if FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern byte[] _GetKeySetSecurityInfo(SafeProvHandle hProv, SecurityInfos securityInfo, out int error);
#endif //FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern object _GetProviderParameter(SafeProvHandle hProv, int keyNumber, uint paramID);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int _GetUserKey(SafeProvHandle hProv, int keyNumber, ref SafeKeyHandle hKey);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _ImportBulkKey(SafeProvHandle hProv, int algid, bool useSalt, byte[] key, ref SafeKeyHandle hKey);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int _ImportCspBlob(byte[] keyBlob, SafeProvHandle hProv, CspProviderFlags flags, ref SafeKeyHandle hKey);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _ImportKey(SafeProvHandle hCSP, int keyNumber, CspProviderFlags flags, object cspObject, ref SafeKeyHandle hKey);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool _ProduceLegacyHmacValues();
#endif // FEATURE_CRYPTO || FEATURE_LEGACYNETCFCRYPTO
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int _OpenCSP(CspParameters param, uint flags, ref SafeProvHandle hProv);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void _AcquireCSP(CspParameters param, ref SafeProvHandle hProv);
}
}
| |
// Copyright (c) 2006, ComponentAce
// http://www.componentace.com
// 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 ComponentAce 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.
/*
Copyright (c) 2001 Lapo Luchini.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHORS
OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
using System;
using System.IO;
namespace Cocos2D.Compression.Zlib
{
public class ZOutputStream : Stream
{
protected internal byte[] buf, buf1 = new byte[1];
protected internal int bufsize = 4096;
protected internal bool compress;
protected internal int flush_Renamed_Field;
private Stream out_Renamed;
protected internal ZStream z = new ZStream();
public ZOutputStream(Stream out_Renamed)
{
InitBlock();
this.out_Renamed = out_Renamed;
z.InflateInit();
compress = false;
}
public ZOutputStream(Stream out_Renamed, int level)
{
InitBlock();
this.out_Renamed = out_Renamed;
z.DeflateInit(level);
compress = true;
}
public virtual int FlushMode
{
get { return (flush_Renamed_Field); }
set { flush_Renamed_Field = value; }
}
/// <summary> Returns the total number of bytes input so far.</summary>
public virtual long TotalIn
{
get { return z.total_in; }
}
/// <summary> Returns the total number of bytes output so far.</summary>
public virtual long TotalOut
{
get { return z.total_out; }
}
public override Boolean CanRead
{
get { return false; }
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Boolean CanSeek
{
get { return false; }
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Boolean CanWrite
{
get { return false; }
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Int64 Length
{
get { return 0; }
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Int64 Position
{
get { return 0; }
set { }
}
private void InitBlock()
{
flush_Renamed_Field = zlibConst.Z_NO_FLUSH;
buf = new byte[bufsize];
}
public void WriteByte(int b)
{
buf1[0] = (byte) b;
Write(buf1, 0, 1);
}
//UPGRADE_TODO: The differences in the Expected value of parameters for method 'WriteByte' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092_3"'
public override void WriteByte(byte b)
{
WriteByte(b);
}
public override void Write(Byte[] b1, int off, int len)
{
if (len == 0)
return;
int err;
var b = new byte[b1.Length];
Array.Copy(b1, 0, b, 0, b1.Length);
z.next_in = b;
z.next_in_index = off;
z.avail_in = len;
do
{
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = bufsize;
if (compress)
err = z.Deflate(flush_Renamed_Field);
else
err = z.Inflate(flush_Renamed_Field);
if (err != zlibConst.Z_OK && err != zlibConst.Z_STREAM_END)
throw new ZStreamException((compress ? "de" : "in") + "flating: " + z.msg);
out_Renamed.Write(buf, 0, bufsize - z.avail_out);
} while (z.avail_in > 0 || z.avail_out == 0);
}
public virtual void Finish()
{
int err;
do
{
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = bufsize;
if (compress)
{
err = z.Deflate(zlibConst.Z_FINISH);
}
else
{
err = z.Inflate(zlibConst.Z_FINISH);
}
if (err != zlibConst.Z_STREAM_END && err != zlibConst.Z_OK)
throw new ZStreamException((compress ? "de" : "in") + "flating: " + z.msg);
if (bufsize - z.avail_out > 0)
{
out_Renamed.Write(buf, 0, bufsize - z.avail_out);
}
} while (z.avail_in > 0 || z.avail_out == 0);
try
{
Flush();
}
catch
{
}
}
public virtual void End()
{
if (compress)
{
z.DeflateEnd();
}
else
{
z.InflateEnd();
}
z.Free();
z = null;
}
#if NETFX_CORE
public void Close()
#else
public override void Close()
#endif
{
try
{
try
{
Finish();
}
catch
{
}
}
finally
{
End();
out_Renamed.Close();
out_Renamed = null;
}
}
public override void Flush()
{
out_Renamed.Flush();
}
//UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count)
{
return 0;
}
//UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override void SetLength(Int64 value)
{
}
//UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Int64 Seek(Int64 offset, SeekOrigin origin)
{
return 0;
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
}
}
| |
//
// WindowBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
// Andres G. Aragoneses <andres.aragoneses@7digital.com>
// Konrad M. Kruczynski <kkruczynski@antmicro.com>
//
// Copyright (c) 2011 Xamarin Inc
// Copyright (c) 2012 7Digital Media Ltd
// Copyright (c) 2016 Antmicro Ltd
//
// 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 AppKit;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.Mac
{
public class WindowBackend: NSWindow, IWindowBackend, IMacWindowBackend
{
WindowBackendController controller;
IWindowFrameEventSink eventSink;
Window frontend;
ViewBackend child;
NSView childView;
bool sensitive = true;
public WindowBackend (IntPtr ptr): base (ptr)
{
this.WillEnterFullScreen += HandleWindowStateChanging;
this.WillMiniaturize += HandleWindowStateChanging;
this.WillStartLiveResize += HandleWindowStateChanging;
}
private void HandleWindowStateChanging(object sender, EventArgs e) {
if(this.WindowState == WindowState.Normal) {
Rectangle restoreBounds = new Rectangle(this.Frame.X, this.Frame.Y, this.Frame.Width, this.Frame.Height);
restoreBounds.Y = Desktop.Bounds.Height - (restoreBounds.Y + restoreBounds.Height); //Invert Y
cachedRestoreBounds = restoreBounds;
}
}
public WindowBackend ()
{
this.WillEnterFullScreen += HandleWindowStateChanging;
this.WillMiniaturize += HandleWindowStateChanging;
this.WillStartLiveResize += HandleWindowStateChanging;
this.controller = new WindowBackendController ();
controller.Window = this;
StyleMask |= NSWindowStyle.Resizable | NSWindowStyle.Closable | NSWindowStyle.Miniaturizable;
AutorecalculatesKeyViewLoop = true;
ContentView.AutoresizesSubviews = true;
ContentView.Hidden = true;
// TODO: do it only if mouse move events are enabled in a widget
AcceptsMouseMovedEvents = true;
WillClose += delegate {
OnClosed ();
};
Center ();
}
object IWindowFrameBackend.Window {
get { return this; }
}
public IntPtr NativeHandle {
get { return Handle; }
}
public IWindowFrameEventSink EventSink {
get { return (IWindowFrameEventSink)eventSink; }
}
public virtual void InitializeBackend (object frontend, ApplicationContext context)
{
this.ApplicationContext = context;
this.frontend = (Window) frontend;
}
public void Initialize (IWindowFrameEventSink eventSink)
{
this.eventSink = eventSink;
}
public ApplicationContext ApplicationContext {
get;
private set;
}
public object NativeWidget {
get {
return this;
}
}
public string Name { get; set; }
void IMacWindowBackend.InternalShow ()
{
InternalShow ();
}
internal void InternalShow ()
{
MakeKeyAndOrderFront (MacEngine.App);
if (ParentWindow != null)
{
if (!ParentWindow.ChildWindows.Contains(this))
ParentWindow.AddChildWindow(this, NSWindowOrderingMode.Above);
// always use NSWindow for alignment when running in guest mode and
// don't rely on AddChildWindow to position the window correctly
if (frontend.InitialLocation == WindowLocation.CenterParent && !(ParentWindow is WindowBackend))
{
var parentBounds = MacDesktopBackend.ToDesktopRect(ParentWindow.ContentRectFor(ParentWindow.Frame));
var bounds = ((IWindowFrameBackend)this).Bounds;
bounds.X = parentBounds.Center.X - (Frame.Width / 2);
bounds.Y = parentBounds.Center.Y - (Frame.Height / 2);
((IWindowFrameBackend)this).Bounds = bounds;
}
}
}
public void Present ()
{
InternalShow();
}
public bool Visible {
get {
return IsVisible;
}
set {
if (value)
MacEngine.App.ShowWindow(this);
ContentView.Hidden = !value; // handle shown/hidden events
IsVisible = value;
}
}
public double Opacity {
get { return AlphaValue; }
set { AlphaValue = (float)value; }
}
Color IWindowBackend.BackgroundColor {
get {
return BackgroundColor.ToXwtColor ();
}
set {
BackgroundColor = value.ToNSColor ();
}
}
public bool Sensitive {
get {
return sensitive;
}
set {
sensitive = value;
if (child != null)
child.UpdateSensitiveStatus (child.Widget, sensitive);
}
}
public override bool CanBecomeKeyWindow {
get {
// must be overriden or borderless windows will not be able to become key
return frontend.CanBecomeKey;
}
}
public bool HasFocus {
get {
return IsKeyWindow;
}
}
public bool FullScreen {
get {
if (MacSystemInformation.OsVersion < MacSystemInformation.Lion)
return false;
return (StyleMask & NSWindowStyle.FullScreenWindow) != 0;
}
set {
if (MacSystemInformation.OsVersion < MacSystemInformation.Lion)
return;
if (value != ((StyleMask & NSWindowStyle.FullScreenWindow) != 0))
ToggleFullScreen (null);
}
}
object IWindowFrameBackend.Screen {
get {
return Screen;
}
}
private Rectangle cachedRestoreBounds;
public WindowState WindowState {
get {
if(this.IsMiniaturized) {
return WindowState.Minimized;
} else if(this.StyleMask.HasFlag(NSWindowStyle.FullScreenWindow)) {
return WindowState.FullScreen;
} else if(this.IsZoomed) {
return WindowState.Maximized;
} else {
return WindowState.Normal;
}
}
set {
if(value == WindowState) { return; }
switch(value) {
case WindowState.Minimized:
if(this.StyleMask.HasFlag(NSWindowStyle.FullScreenWindow)) {
this.ToggleFullScreen(this);
}
this.Miniaturize(this);
break;
case WindowState.FullScreen:
if(this.IsMiniaturized) {
this.Deminiaturize(this);
}
if(!this.StyleMask.HasFlag(NSWindowStyle.FullScreenWindow)) {
this.ToggleFullScreen(this);
}
break;
case WindowState.Maximized:
if(this.StyleMask.HasFlag(NSWindowStyle.FullScreenWindow)) {
this.ToggleFullScreen(this);
}
if(this.IsMiniaturized) {
this.Deminiaturize(this);
}
if(!this.IsZoomed) {
this.Zoom(this);
}
break;
case WindowState.Normal:
if(this.StyleMask.HasFlag(NSWindowStyle.FullScreenWindow)) {
this.ToggleFullScreen(this);
}
if(IsZoomed) {
this.Zoom(this);
}
if(this.IsMiniaturized) {
this.Deminiaturize(this);
}
break;
default:
throw new InvalidOperationException("Invalid window state: " + value);
}
}
}
public Rectangle RestoreBounds {
get {
return cachedRestoreBounds;
}
}
#region IWindowBackend implementation
void IBackend.EnableEvent (object eventId)
{
if (eventId is WindowFrameEvent) {
var @event = (WindowFrameEvent)eventId;
switch (@event) {
case WindowFrameEvent.BoundsChanged:
DidResize += HandleDidResize;
DidMove += HandleDidResize;
break;
case WindowFrameEvent.Hidden:
EnableVisibilityEvent (@event);
this.WillClose += OnWillClose;
break;
case WindowFrameEvent.Shown:
EnableVisibilityEvent (@event);
break;
case WindowFrameEvent.CloseRequested:
WindowShouldClose = OnShouldClose;
break;
}
}
}
void OnWillClose (object sender, EventArgs args) {
OnHidden ();
}
bool OnShouldClose (NSObject ob)
{
return closePerformed = RequestClose ();
}
internal bool RequestClose ()
{
bool res = true;
ApplicationContext.InvokeUserCode (() => res = eventSink.OnCloseRequested ());
return res;
}
protected virtual void OnClosed ()
{
if (!disposing)
ApplicationContext.InvokeUserCode (eventSink.OnClosed);
}
bool closePerformed;
bool IWindowFrameBackend.Close ()
{
closePerformed = true;
if ((StyleMask & NSWindowStyle.Titled) != 0 && (StyleMask & NSWindowStyle.Closable) != 0)
PerformClose(this);
else
Close ();
if (ParentWindow != null)
ParentWindow.RemoveChildWindow(this);
return closePerformed;
}
bool VisibilityEventsEnabled ()
{
return eventsEnabled != WindowFrameEvent.BoundsChanged;
}
WindowFrameEvent eventsEnabled = WindowFrameEvent.BoundsChanged;
NSString HiddenProperty {
get { return new NSString ("hidden"); }
}
void EnableVisibilityEvent (WindowFrameEvent ev)
{
if (!VisibilityEventsEnabled ()) {
ContentView.AddObserver (this, HiddenProperty, NSKeyValueObservingOptions.New, IntPtr.Zero);
}
if (!eventsEnabled.HasFlag (ev)) {
eventsEnabled |= ev;
}
}
public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
{
if (keyPath.ToString () == HiddenProperty.ToString () && ofObject.Equals (ContentView)) {
if (ContentView.Hidden) {
if (eventsEnabled.HasFlag (WindowFrameEvent.Hidden)) {
OnHidden ();
}
} else {
if (eventsEnabled.HasFlag (WindowFrameEvent.Shown)) {
OnShown ();
}
}
}
}
void OnHidden () {
ApplicationContext.InvokeUserCode (delegate ()
{
eventSink.OnHidden ();
});
}
void OnShown () {
ApplicationContext.InvokeUserCode (delegate ()
{
eventSink.OnShown ();
});
}
void DisableVisibilityEvent (WindowFrameEvent ev)
{
if (eventsEnabled.HasFlag (ev)) {
eventsEnabled ^= ev;
if (!VisibilityEventsEnabled ()) {
ContentView.RemoveObserver (this, HiddenProperty);
}
}
}
void IBackend.DisableEvent (object eventId)
{
if (eventId is WindowFrameEvent) {
var @event = (WindowFrameEvent)eventId;
switch (@event) {
case WindowFrameEvent.BoundsChanged:
DidResize -= HandleDidResize;
DidMove -= HandleDidResize;
break;
case WindowFrameEvent.Hidden:
this.WillClose -= OnWillClose;
DisableVisibilityEvent (@event);
break;
case WindowFrameEvent.Shown:
DisableVisibilityEvent (@event);
break;
}
}
}
void HandleDidResize (object sender, EventArgs e)
{
OnBoundsChanged ();
}
protected virtual void OnBoundsChanged ()
{
LayoutWindow ();
ApplicationContext.InvokeUserCode (delegate {
eventSink.OnBoundsChanged (((IWindowBackend)this).Bounds);
});
}
public override void BecomeMainWindow ()
{
base.BecomeMainWindow ();
eventSink.OnBecomeMain ();
}
public override void BecomeKeyWindow ()
{
base.BecomeKeyWindow ();
eventSink.OnBecomeKey ();
}
void IWindowBackend.SetChild (IWidgetBackend child)
{
if (this.child != null) {
ViewBackend.RemoveChildPlacement (this.child.Widget);
this.child.Widget.RemoveFromSuperview ();
childView = null;
}
this.child = (ViewBackend) child;
if (child != null) {
childView = ViewBackend.GetWidgetWithPlacement (child);
ContentView.AddSubview (childView);
LayoutWindow ();
childView.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable;
}
}
public virtual void UpdateChildPlacement (IWidgetBackend childBackend)
{
var w = ViewBackend.SetChildPlacement (childBackend);
LayoutWindow ();
w.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable;
}
bool IWindowFrameBackend.Decorated {
get {
return (StyleMask & NSWindowStyle.Titled) != 0;
}
set {
if (value)
StyleMask |= NSWindowStyle.Titled;
else
StyleMask &= ~(NSWindowStyle.Titled | NSWindowStyle.Borderless);
}
}
bool IWindowFrameBackend.ShowInTaskbar {
get {
return false;
}
set {
}
}
void IWindowFrameBackend.SetTransientFor (IWindowFrameBackend window)
{
if (!((IWindowFrameBackend)this).ShowInTaskbar)
StyleMask &= ~NSWindowStyle.Miniaturizable;
var win = window as NSWindow ?? ApplicationContext.Toolkit.GetNativeWindow(window) as NSWindow;
if (ParentWindow != win) {
// remove from the previous parent
if (ParentWindow != null)
ParentWindow.RemoveChildWindow(this);
ParentWindow = win;
// A window must be visible to be added to a parent. See InternalShow().
if (Visible)
ParentWindow.AddChildWindow(this, NSWindowOrderingMode.Above);
}
}
bool IWindowFrameBackend.Resizable {
get {
return (StyleMask & NSWindowStyle.Resizable) != 0;
}
set {
if (value)
StyleMask |= NSWindowStyle.Resizable;
else
StyleMask &= ~NSWindowStyle.Resizable;
}
}
public void SetPadding (double left, double top, double right, double bottom)
{
LayoutWindow ();
}
void IWindowFrameBackend.Move (double x, double y)
{
var r = FrameRectFor (new CGRect ((nfloat)x, (nfloat)y, Frame.Width, Frame.Height));
var dr = MacDesktopBackend.ToDesktopRect(r);
SetFrame (new CGRect((nfloat)dr.X, (nfloat)dr.Y, (nfloat)dr.Width, (nfloat)dr.Height), true);
}
void IWindowFrameBackend.SetSize (double width, double height)
{
var cr = ContentRectFor (Frame);
if (width == -1)
width = cr.Width;
if (height == -1)
height = cr.Height;
var r = FrameRectFor (new CGRect ((nfloat)cr.X, (nfloat)(cr.Y - height + cr.Height), (nfloat)width, (nfloat)height));
SetFrame (r, true);
LayoutWindow ();
}
Rectangle IWindowFrameBackend.Bounds {
get {
var b = ContentRectFor (Frame);
var r = MacDesktopBackend.ToDesktopRect (b);
return new Rectangle ((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height);
}
set {
CGRect cgr = MacDesktopBackend.FromDesktopRect(value);
CGRect fr = FrameRectFor (cgr);
SetFrame (fr, true);
}
}
public void SetMainMenu (IMenuBackend menu)
{
var m = (MenuBackend) menu;
m.SetMainMenuMode ();
NSApplication.SharedApplication.Menu = m;
// base.Menu = m;
}
#endregion
static Selector closeSel = new Selector ("close");
static readonly bool XamMacDangerousDispose = Version.Parse(Constants.Version) < new Version(5, 6);
public static bool SetReleasedWhenClosed = true;
bool disposing, disposed;
protected override void Dispose(bool disposing)
{
if (!disposed && disposing)
{
this.disposing = true;
try
{
if(VisibilityEventsEnabled() && ContentView != null)
ContentView.RemoveObserver(this, HiddenProperty);
// Disable the following hack - not really sure what it is supposed to accomplish but when it is here,
// some dialog windows cause a crash when they are disposed. Exclusion list avoids this problem. WIN-5549
if(SetReleasedWhenClosed) {
if(XamMacDangerousDispose) {
// HACK: Xamarin.Mac/MonoMac limitation: no direct way to release a window manually
// A NSWindow instance will be removed from NSApplication.SharedApplication.Windows
// only if it is being closed with ReleasedWhenClosed set to true but not on Dispose
// and there is no managed way to tell Cocoa to release the window manually (and to
// remove it from the active window list).
// see also: https://bugzilla.xamarin.com/show_bug.cgi?id=45298
// WORKAROUND:
// bump native reference count by calling DangerousRetain()
// base.Dispose will now unref the window correctly without crashing
DangerousRetain();
}
// tell Cocoa to release the window on Close
ReleasedWhenClosed = true;
}
// Close the window (Cocoa will do its job even if the window is already closed)
Messaging.void_objc_msgSend (this.Handle, closeSel.Handle);
} finally {
this.disposing = false;
this.disposed = true;
}
}
if (controller != null) {
controller.Dispose ();
controller = null;
}
base.Dispose (disposing);
}
public void DragStart (TransferDataSource data, DragDropAction dragAction, object dragImage, double xhot, double yhot)
{
throw new NotImplementedException ();
}
public void SetDragSource (string[] types, DragDropAction dragAction)
{
}
public void SetDragTarget (string[] types, DragDropAction dragAction)
{
}
public virtual void SetMinSize (Size s)
{
var b = ((IWindowBackend)this).Bounds;
if (b.Size.Width < s.Width)
b.Width = s.Width;
if (b.Size.Height < s.Height)
b.Height = s.Height;
if (b != ((IWindowBackend)this).Bounds)
((IWindowBackend)this).Bounds = b;
var r = FrameRectFor (new CGRect (0, 0, (nfloat)s.Width, (nfloat)s.Height));
MinSize = r.Size;
}
public void SetIcon (ImageDescription icon)
{
}
public virtual void GetMetrics (out Size minSize, out Size decorationSize)
{
minSize = decorationSize = Size.Zero;
}
public virtual void LayoutWindow ()
{
LayoutContent (ContentView.Frame);
}
public void LayoutContent (CGRect frame)
{
if (child != null) {
frame.X += (nfloat) frontend.Padding.Left;
frame.Width -= (nfloat) (frontend.Padding.HorizontalSpacing);
frame.Y += (nfloat) (childView.IsFlipped ? frontend.Padding.Bottom : frontend.Padding.Top);
frame.Height -= (nfloat) (frontend.Padding.VerticalSpacing);
childView.Frame = frame;
}
}
}
public partial class WindowBackendController : NSWindowController
{
public WindowBackendController ()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentNHibernate.Automapping.Alterations;
using FluentNHibernate.Cfg;
using FluentNHibernate.Mapping;
using FluentNHibernate.Mapping.Providers;
using FluentNHibernate.MappingModel;
using FluentNHibernate.MappingModel.ClassBased;
using FluentNHibernate.Utils;
using FluentNHibernate.Utils.Reflection;
using FluentNHibernate.Visitors;
namespace FluentNHibernate.Automapping
{
public class AutoPersistenceModel : PersistenceModel
{
readonly IAutomappingConfiguration cfg;
readonly AutoMappingExpressions expressions;
readonly AutoMapper autoMapper;
readonly List<ITypeSource> sources = new List<ITypeSource>();
Func<Type, bool> whereClause;
readonly List<AutoMapType> mappingTypes = new List<AutoMapType>();
bool autoMappingsCreated;
readonly AutoMappingAlterationCollection alterations = new AutoMappingAlterationCollection();
readonly List<InlineOverride> inlineOverrides = new List<InlineOverride>();
readonly List<Type> ignoredTypes = new List<Type>();
readonly List<Type> includedTypes = new List<Type>();
public AutoPersistenceModel()
{
expressions = new AutoMappingExpressions();
cfg = new ExpressionBasedAutomappingConfiguration(expressions);
autoMapper = new AutoMapper(cfg, Conventions, inlineOverrides);
componentResolvers.Add(new AutomappedComponentResolver(autoMapper, cfg));
}
public AutoPersistenceModel(IAutomappingConfiguration cfg)
{
this.cfg = cfg;
autoMapper = new AutoMapper(cfg, Conventions, inlineOverrides);
componentResolvers.Add(new AutomappedComponentResolver(autoMapper, cfg));
}
public AutoPersistenceModel AddMappingsFromAssemblyOf<T>()
{
return AddMappingsFromAssembly(typeof(T).Assembly);
}
public new AutoPersistenceModel AddMappingsFromAssembly(Assembly assembly)
{
AddMappingsFromSource(new AssemblyTypeSource(assembly));
return this;
}
public new AutoPersistenceModel AddMappingsFromSource(ITypeSource source)
{
base.AddMappingsFromSource(source);
return this;
}
/// <summary>
/// Specify alterations to be used with this AutoPersisteceModel
/// </summary>
/// <param name="alterationDelegate">Lambda to declare alterations</param>
/// <returns>AutoPersistenceModel</returns>
public AutoPersistenceModel Alterations(Action<AutoMappingAlterationCollection> alterationDelegate)
{
alterationDelegate(alterations);
return this;
}
/// <summary>
/// Use auto mapping overrides defined in the assembly of T.
/// </summary>
/// <typeparam name="T">Type to get assembly from</typeparam>
/// <returns>AutoPersistenceModel</returns>
public AutoPersistenceModel UseOverridesFromAssemblyOf<T>()
{
return UseOverridesFromAssembly(typeof(T).Assembly);
}
/// <summary>
/// Use auto mapping overrides defined in the assembly of T.
/// </summary>
/// <param name="assembly">Assembly to scan</param>
/// <returns>AutoPersistenceModel</returns>
public AutoPersistenceModel UseOverridesFromAssembly(Assembly assembly)
{
alterations.Add(new AutoMappingOverrideAlteration(assembly));
return this;
}
/// <summary>
/// Alter convention discovery
/// </summary>
public new SetupConventionFinder<AutoPersistenceModel> Conventions
{
get { return new SetupConventionFinder<AutoPersistenceModel>(this, base.Conventions); }
}
/// <summary>
/// Alter some of the configuration options that control how the automapper works.
/// Depreciated in favour of supplying your own IAutomappingConfiguration instance to AutoMap: <see cref="AutoMap.AssemblyOf{T}(FluentNHibernate.Automapping.IAutomappingConfiguration)"/>.
/// Cannot be used in combination with a user-defined configuration.
/// </summary>
[Obsolete("Depreciated in favour of supplying your own IAutomappingConfiguration instance to AutoMap: AutoMap.AssemblyOf<T>(your_configuration_instance)")]
public AutoPersistenceModel Setup(Action<AutoMappingExpressions> expressionsAction)
{
if (HasUserDefinedConfiguration)
throw new InvalidOperationException("Cannot use Setup method when using a user-defined IAutomappingConfiguration instance.");
expressionsAction(expressions);
return this;
}
/// <summary>
/// Supply a criteria for which types will be mapped.
/// Cannot be used in combination with a user-defined configuration.
/// </summary>
/// <param name="where">Where clause</param>
public AutoPersistenceModel Where(Func<Type, bool> where)
{
if (HasUserDefinedConfiguration)
throw new InvalidOperationException("Cannot use Where method when using a user-defined IAutomappingConfiguration instance.");
whereClause = where;
return this;
}
public override IEnumerable<HibernateMapping> BuildMappings()
{
CompileMappings();
return base.BuildMappings();
}
private void CompileMappings()
{
if (autoMappingsCreated)
return;
alterations.Apply(this);
var types = sources
.SelectMany(x => x.GetTypes())
.OrderBy(x => InheritanceHierarchyDepth(x));
foreach (var type in types)
{
// skipped by user-defined configuration criteria
if (!cfg.ShouldMap(type))
{
log.AutomappingSkippedType(type, "Skipped by result of IAutomappingConfiguration.ShouldMap(Type)");
continue;
}
// skipped by inline where clause
if (whereClause != null && !whereClause(type))
{
log.AutomappingSkippedType(type, "Skipped by Where clause");
continue;
}
// skipped because either already mapped elsewhere, or not valid for mapping
if (!ShouldMap(type))
continue;
mappingTypes.Add(new AutoMapType(type));
}
log.AutomappingCandidateTypes(mappingTypes.Select(x => x.Type));
foreach (var type in mappingTypes)
{
if (type.IsMapped) continue;
AddMapping(type.Type);
}
autoMappingsCreated = true;
}
private int InheritanceHierarchyDepth(Type type)
{
var depth = 0;
var parent = type;
while (parent != null && parent != typeof(object))
{
parent = parent.BaseType;
depth++;
}
return depth;
}
public override void Configure(NHibernate.Cfg.Configuration configuration)
{
CompileMappings();
base.Configure(configuration);
}
private void AddMapping(Type type)
{
Type typeToMap = GetTypeToMap(type);
if (typeToMap != type)
{
log.BeginAutomappingType(type);
var derivedMapping = autoMapper.Map(type, mappingTypes);
Add(new PassThroughMappingProvider(derivedMapping));
}
log.BeginAutomappingType(typeToMap);
var mapping = autoMapper.Map(typeToMap, mappingTypes);
Add(new PassThroughMappingProvider(mapping));
}
private Type GetTypeToMap(Type type)
{
while (ShouldMapParent(type))
{
type = type.BaseType;
}
return type;
}
private bool ShouldMapParent(Type type)
{
return ShouldMap(type.BaseType) && !cfg.IsConcreteBaseType(type.BaseType);
}
private bool ShouldMap(Type type)
{
if (includedTypes.Contains(type))
return true; // inclusions take precedence over everything
if (ignoredTypes.Contains(type))
{
log.AutomappingSkippedType(type, "Skipped by IgnoreBase");
return false; // excluded
}
if (type.IsGenericType && ignoredTypes.Contains(type.GetGenericTypeDefinition()))
{
log.AutomappingSkippedType(type, "Skipped by IgnoreBase");
return false; // generic definition is excluded
}
if (type.IsAbstract && cfg.AbstractClassIsLayerSupertype(type))
{
log.AutomappingSkippedType(type, "Skipped by IAutomappingConfiguration.AbstractClassIsLayerSupertype(Type)");
return false; // is abstract and a layer supertype
}
if (cfg.IsComponent(type))
{
log.AutomappingSkippedType(type, "Skipped by IAutomappingConfiguration.IsComponent(Type)");
return false; // skipped because we don't want to map components as entities
}
if (type == typeof(object))
return false;
return true;
}
public IMappingProvider FindMapping<T>()
{
return FindMapping(typeof(T));
}
public IMappingProvider FindMapping(Type type)
{
Func<IMappingProvider, Type, bool> finder = (provider, expectedType) =>
{
var mappingType = provider.GetType();
if (mappingType.IsGenericType)
{
// instance of a generic type (probably AutoMapping<T>)
return mappingType.GetGenericArguments()[0] == expectedType;
}
if (mappingType.BaseType.IsGenericType &&
mappingType.BaseType.GetGenericTypeDefinition() == typeof(ClassMap<>))
{
// base type is a generic type of ClassMap<T>, so we've got a XXXMap instance
return mappingType.BaseType.GetGenericArguments()[0] == expectedType;
}
if (provider is PassThroughMappingProvider)
return provider.GetClassMapping().Type == expectedType;
return false;
};
var mapping = classProviders.FirstOrDefault(t => finder(t, type));
if (mapping != null) return mapping;
// if we haven't found a map yet then try to find a map of the
// base type to merge if not a concrete base type
if (type.BaseType != typeof(object) && !cfg.IsConcreteBaseType(type.BaseType))
{
return FindMapping(type.BaseType);
}
return null;
}
/// <summary>
/// Adds all entities from a specific assembly.
/// </summary>
/// <param name="assembly">Assembly to load from</param>
public AutoPersistenceModel AddEntityAssembly(Assembly assembly)
{
return AddTypeSource(new AssemblyTypeSource(assembly));
}
/// <summary>
/// Adds all entities from the <see cref="ITypeSource"/>.
/// </summary>
/// <param name="source"><see cref="ITypeSource"/> to load from</param>
public AutoPersistenceModel AddTypeSource(ITypeSource source)
{
sources.Add(source);
return this;
}
public AutoPersistenceModel AddFilter<TFilter>() where TFilter : IFilterDefinition
{
Add(typeof(TFilter));
return this;
}
internal void AddOverride(Type type, Action<object> action)
{
inlineOverrides.Add(new InlineOverride(type, action));
}
/// <summary>
/// Override the mapping of a specific entity.
/// </summary>
/// <remarks>This may affect subclasses, depending on the alterations you do.</remarks>
/// <typeparam name="T">Entity who's mapping to override</typeparam>
/// <param name="populateMap">Lambda performing alterations</param>
public AutoPersistenceModel Override<T>(Action<AutoMapping<T>> populateMap)
{
inlineOverrides.Add(new InlineOverride(typeof(T), x =>
{
if (x is AutoMapping<T>)
populateMap((AutoMapping<T>)x);
}));
return this;
}
static bool IsAutomappingForType(object o, Type entityType)
{
var autoMappingType = ReflectionHelper.AutomappingTypeForEntityType(entityType);
return o.GetType().IsAssignableFrom(autoMappingType);
}
/// <summary>
/// Adds an IAutoMappingOverride reflectively
/// </summary>
/// <param name="overrideType">Override type, expected to be an IAutoMappingOverride</param>
public void Override(Type overrideType)
{
var overrideInterfaces = overrideType.GetInterfaces().Where(x => x.IsAutoMappingOverrideType()).ToList();
foreach (var overrideInterface in overrideInterfaces)
{
var entityType = overrideInterface.GetGenericArguments().First();
AddOverride(entityType, instance =>
{
if (!IsAutomappingForType(instance, entityType)) return;
var overrideInstance = Activator.CreateInstance(overrideType);
MethodInfo overrideHelperMethod = typeof(AutoPersistenceModel)
.GetMethod("OverrideHelper", BindingFlags.NonPublic | BindingFlags.Instance);
if (overrideHelperMethod == null) return;
overrideHelperMethod
.MakeGenericMethod(entityType)
.Invoke(this, new[] { instance, overrideInstance });
});
}
}
//called reflectively from method above
private void OverrideHelper<T>(AutoMapping<T> x, IAutoMappingOverride<T> mappingOverride)
{
mappingOverride.Override(x);
}
/// <summary>
/// Override all mappings.
/// </summary>
/// <remarks>Currently only supports ignoring properties on all entities.</remarks>
/// <param name="alteration">Lambda performing alterations</param>
public AutoPersistenceModel OverrideAll(Action<IPropertyIgnorer> alteration)
{
inlineOverrides.Add(new InlineOverride(typeof(object), x =>
{
if (x is IPropertyIgnorer)
alteration((IPropertyIgnorer)x);
}));
return this;
}
/// <summary>
/// Ignore a base type. This removes it from any mapped inheritance hierarchies, good for non-abstract layer
/// supertypes.
/// </summary>
/// <typeparam name="T">Type to ignore</typeparam>
public AutoPersistenceModel IgnoreBase<T>()
{
return IgnoreBase(typeof(T));
}
/// <summary>
/// Ignore a base type. This removes it from any mapped inheritance hierarchies, good for non-abstract layer
/// supertypes.
/// </summary>
/// <param name="baseType">Type to ignore</param>
public AutoPersistenceModel IgnoreBase(Type baseType)
{
ignoredTypes.Add(baseType);
return this;
}
/// <summary>
/// Explicitly includes a type to be used as part of a mapped inheritance hierarchy.
/// </summary>
/// <remarks>
/// Abstract classes are probably what you'll be using this method with. Fluent NHibernate considers abstract
/// classes to be layer supertypes, so doesn't automatically map them as part of an inheritance hierarchy. You
/// can use this method to override that behavior for a specific type; otherwise you should consider using the
/// <see cref="IAutomappingConfiguration.AbstractClassIsLayerSupertype"/> setting.
/// </remarks>
/// <typeparam name="T">Type to include</typeparam>
public AutoPersistenceModel IncludeBase<T>()
{
return IncludeBase(typeof(T));
}
/// <summary>
/// Explicitly includes a type to be used as part of a mapped inheritance hierarchy.
/// </summary>
/// <remarks>
/// Abstract classes are probably what you'll be using this method with. Fluent NHibernate considers abstract
/// classes to be layer supertypes, so doesn't automatically map them as part of an inheritance hierarchy. You
/// can use this method to override that behavior for a specific type; otherwise you should consider using the
/// <see cref="AutoMappingExpressions.AbstractClassIsLayerSupertype"/> setting.
/// </remarks>
/// <param name="baseType">Type to include</param>
public AutoPersistenceModel IncludeBase(Type baseType)
{
includedTypes.Add(baseType);
return this;
}
protected override string GetMappingFileName()
{
return "AutoMappings.hbm.xml";
}
bool HasUserDefinedConfiguration
{
get { return !(cfg is ExpressionBasedAutomappingConfiguration); }
}
}
public class AutomappedComponentResolver : IComponentReferenceResolver
{
readonly AutoMapper mapper;
IAutomappingConfiguration cfg;
public AutomappedComponentResolver(AutoMapper mapper, IAutomappingConfiguration cfg)
{
this.mapper = mapper;
this.cfg = cfg;
}
public ExternalComponentMapping Resolve(ComponentResolutionContext context, IEnumerable<IExternalComponentMappingProvider> componentProviders)
{
// this will only be called if there was no ComponentMap found
var mapping = new ExternalComponentMapping(ComponentType.Component)
{
Member = context.ComponentMember,
ContainingEntityType = context.EntityType,
};
mapping.Set(x => x.Name, Layer.Defaults, context.ComponentMember.Name);
mapping.Set(x => x.Type, Layer.Defaults, context.ComponentType);
if (context.ComponentMember.IsProperty && !context.ComponentMember.CanWrite)
mapping.Set(x => x.Access, Layer.Defaults, cfg.GetAccessStrategyForReadOnlyProperty(context.ComponentMember).ToString());
mapper.FlagAsMapped(context.ComponentType);
mapper.MergeMap(context.ComponentType, mapping, new List<Member>());
return mapping;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
namespace CleanSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2003 January 11
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the sqlite3_set_authorizer()
** API. This facility is an optional feature of the library. Embedded
** systems that do not need this facility may omit it by recompiling
** the library with -DSQLITE_OMIT_AUTHORIZATION=1
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** All of the code in this file may be omitted by defining a single
** macro.
*/
#if !SQLITE_OMIT_AUTHORIZATION
/*
** Set or clear the access authorization function.
**
** The access authorization function is be called during the compilation
** phase to verify that the user has read and/or write access permission on
** various fields of the database. The first argument to the auth function
** is a copy of the 3rd argument to this routine. The second argument
** to the auth function is one of these constants:
**
** SQLITE_CREATE_INDEX
** SQLITE_CREATE_TABLE
** SQLITE_CREATE_TEMP_INDEX
** SQLITE_CREATE_TEMP_TABLE
** SQLITE_CREATE_TEMP_TRIGGER
** SQLITE_CREATE_TEMP_VIEW
** SQLITE_CREATE_TRIGGER
** SQLITE_CREATE_VIEW
** SQLITE_DELETE
** SQLITE_DROP_INDEX
** SQLITE_DROP_TABLE
** SQLITE_DROP_TEMP_INDEX
** SQLITE_DROP_TEMP_TABLE
** SQLITE_DROP_TEMP_TRIGGER
** SQLITE_DROP_TEMP_VIEW
** SQLITE_DROP_TRIGGER
** SQLITE_DROP_VIEW
** SQLITE_INSERT
** SQLITE_PRAGMA
** SQLITE_READ
** SQLITE_SELECT
** SQLITE_TRANSACTION
** SQLITE_UPDATE
**
** The third and fourth arguments to the auth function are the name of
** the table and the column that are being accessed. The auth function
** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
** means that the SQL statement will never-run - the sqlite3_exec() call
** will return with an error. SQLITE_IGNORE means that the SQL statement
** should run but attempts to read the specified column will return NULL
** and attempts to write the column will be ignored.
**
** Setting the auth function to NULL disables this hook. The default
** setting of the auth function is NULL.
*/
int sqlite3_set_authorizer(
sqlite3 db,
int (*xAuth)(void*,int,const char*,const char*,const char*,const char),
void *pArg
){
sqlite3_mutex_enter(db->mutex);
db->xAuth = xAuth;
db->pAuthArg = pArg;
sqlite3ExpirePreparedStatements(db);
sqlite3_mutex_leave(db->mutex);
return SQLITE_OK;
}
/*
** Write an error message into pParse->zErrMsg that explains that the
** user-supplied authorization function returned an illegal value.
*/
static void sqliteAuthBadReturnCode(Parse *pParse){
sqlite3ErrorMsg(pParse, "authorizer malfunction");
pParse->rc = SQLITE_ERROR;
}
/*
** Invoke the authorization callback for permission to read column zCol from
** table zTab in database zDb. This function assumes that an authorization
** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
**
** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
** is treated as SQLITE_DENY. In this case an error is left in pParse.
*/
int sqlite3AuthReadCol(
Parse *pParse, /* The parser context */
string zTab, /* Table name */
string zCol, /* Column name */
int iDb /* Index of containing database. */
){
sqlite3 db = pParse->db; /* Database handle */
string zDb = db->aDb[iDb].zName; /* Name of attached database */
int rc; /* Auth callback return code */
rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
if( rc==SQLITE_DENY ){
if( db->nDb>2 || iDb!=0 ){
sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
}else{
sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
}
pParse->rc = SQLITE_AUTH;
}else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
sqliteAuthBadReturnCode(pParse);
}
return rc;
}
/*
** The pExpr should be a TK_COLUMN expression. The table referred to
** is in pTabList or else it is the NEW or OLD table of a trigger.
** Check to see if it is OK to read this particular column.
**
** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
** then generate an error.
*/
void sqlite3AuthRead(
Parse *pParse, /* The parser context */
Expr *pExpr, /* The expression to check authorization on */
Schema *pSchema, /* The schema of the expression */
SrcList *pTabList /* All table that pExpr might refer to */
){
sqlite3 db = pParse->db;
Table *pTab = 0; /* The table being read */
string zCol; /* Name of the column of the table */
int iSrc; /* Index in pTabList->a[] of table being read */
int iDb; /* The index of the database the expression refers to */
int iCol; /* Index of column in table */
if( db->xAuth==0 ) return;
iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
if( iDb<0 ){
/* An attempt to read a column out of a subquery or other
** temporary table. */
return;
}
Debug.Assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
if( pExpr->op==TK_TRIGGER ){
pTab = pParse->pTriggerTab;
}else{
Debug.Assert( pTabList );
for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
pTab = pTabList->a[iSrc].pTab;
break;
}
}
}
iCol = pExpr->iColumn;
if( NEVER(pTab==0) ) return;
if( iCol>=0 ){
Debug.Assert( iCol<pTab->nCol );
zCol = pTab->aCol[iCol].zName;
}else if( pTab->iPKey>=0 ){
Debug.Assert( pTab->iPKey<pTab->nCol );
zCol = pTab->aCol[pTab->iPKey].zName;
}else{
zCol = "ROWID";
}
Debug.Assert( iDb>=0 && iDb<db->nDb );
if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
pExpr->op = TK_NULL;
}
}
/*
** Do an authorization check using the code and arguments given. Return
** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
** is returned, then the error count and error message in pParse are
** modified appropriately.
*/
int sqlite3AuthCheck(
Parse *pParse,
int code,
string zArg1,
string zArg2,
string zArg3
){
sqlite3 db = pParse->db;
int rc;
/* Don't do any authorization checks if the database is initialising
** or if the parser is being invoked from within sqlite3_declare_vtab.
*/
if( db->init.busy || IN_DECLARE_VTAB ){
return SQLITE_OK;
}
if( db->xAuth==0 ){
return SQLITE_OK;
}
rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
if( rc==SQLITE_DENY ){
sqlite3ErrorMsg(pParse, "not authorized");
pParse->rc = SQLITE_AUTH;
}else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
rc = SQLITE_DENY;
sqliteAuthBadReturnCode(pParse);
}
return rc;
}
/*
** Push an authorization context. After this routine is called, the
** zArg3 argument to authorization callbacks will be zContext until
** popped. Or if pParse==0, this routine is a no-op.
*/
void sqlite3AuthContextPush(
Parse *pParse,
AuthContext *pContext,
string zContext
){
Debug.Assert( pParse );
pContext->pParse = pParse;
pContext->zAuthContext = pParse->zAuthContext;
pParse->zAuthContext = zContext;
}
/*
** Pop an authorization context that was previously pushed
** by sqlite3AuthContextPush
*/
void sqlite3AuthContextPop(AuthContext *pContext){
if( pContext->pParse ){
pContext->pParse->zAuthContext = pContext->zAuthContext;
pContext->pParse = 0;
}
}
#endif //* SQLITE_OMIT_AUTHORIZATION */
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;
namespace ILRuntime.Runtime.Generated
{
unsafe class System_Runtime_CompilerServices_AsyncTaskMethodBuilder_1_String_Binding
{
public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
{
BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
MethodBase method;
Type[] args;
Type type = typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>);
args = new Type[]{};
method = type.GetMethod("Create", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, Create_0);
Dictionary<string, List<MethodInfo>> genericMethods = new Dictionary<string, List<MethodInfo>>();
List<MethodInfo> lst = null;
foreach(var m in type.GetMethods())
{
if(m.IsGenericMethodDefinition)
{
if (!genericMethods.TryGetValue(m.Name, out lst))
{
lst = new List<MethodInfo>();
genericMethods[m.Name] = lst;
}
lst.Add(m);
}
}
args = new Type[]{typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)};
if (genericMethods.TryGetValue("Start", out lst))
{
foreach(var m in lst)
{
if(m.MatchGenericParameters(args, typeof(void), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType()))
{
method = m.MakeGenericMethod(args);
app.RegisterCLRMethodRedirection(method, Start_1);
break;
}
}
}
args = new Type[]{};
method = type.GetMethod("get_Task", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, get_Task_2);
args = new Type[]{typeof(System.Runtime.CompilerServices.TaskAwaiter), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)};
if (genericMethods.TryGetValue("AwaitUnsafeOnCompleted", out lst))
{
foreach(var m in lst)
{
if(m.MatchGenericParameters(args, typeof(void), typeof(System.Runtime.CompilerServices.TaskAwaiter).MakeByRefType(), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType()))
{
method = m.MakeGenericMethod(args);
app.RegisterCLRMethodRedirection(method, AwaitUnsafeOnCompleted_3);
break;
}
}
}
args = new Type[]{typeof(System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)};
if (genericMethods.TryGetValue("AwaitUnsafeOnCompleted", out lst))
{
foreach(var m in lst)
{
if(m.MatchGenericParameters(args, typeof(void), typeof(System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>).MakeByRefType(), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType()))
{
method = m.MakeGenericMethod(args);
app.RegisterCLRMethodRedirection(method, AwaitUnsafeOnCompleted_4);
break;
}
}
}
args = new Type[]{typeof(System.Exception)};
method = type.GetMethod("SetException", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, SetException_5);
args = new Type[]{typeof(System.String)};
method = type.GetMethod("SetResult", flag, null, args, null);
app.RegisterCLRMethodRedirection(method, SetResult_6);
app.RegisterCLRCreateDefaultInstance(type, () => new System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>());
}
static void WriteBackInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack, ref System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String> instance_of_this_method)
{
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
switch(ptr_of_this_method->ObjectType)
{
case ObjectTypes.Object:
{
__mStack[ptr_of_this_method->Value] = instance_of_this_method;
}
break;
case ObjectTypes.FieldReference:
{
var ___obj = __mStack[ptr_of_this_method->Value];
if(___obj is ILTypeInstance)
{
((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method;
}
else
{
var t = __domain.GetType(___obj.GetType()) as CLRType;
t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, instance_of_this_method);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var t = __domain.GetType(ptr_of_this_method->Value);
if(t is ILType)
{
((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method;
}
else
{
((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, instance_of_this_method);
}
}
break;
case ObjectTypes.ArrayReference:
{
var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>[];
instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method;
}
break;
}
}
static StackObject* Create_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* __ret = ILIntepreter.Minus(__esp, 0);
var result_of_this_method = System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>.Create();
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* Start_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack));
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
instance_of_this_method.Start<Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @stateMachine);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
switch(ptr_of_this_method->ObjectType)
{
case ObjectTypes.StackObjectReference:
{
var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method);
object ___obj = @stateMachine;
if (___dst->ObjectType >= ObjectTypes.Object)
{
if (___obj is CrossBindingAdaptorType)
___obj = ((CrossBindingAdaptorType)___obj).ILInstance;
__mStack[___dst->Value] = ___obj;
}
else
{
ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain);
}
}
break;
case ObjectTypes.FieldReference:
{
var ___obj = __mStack[ptr_of_this_method->Value];
if(___obj is ILTypeInstance)
{
((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine;
}
else
{
var ___type = __domain.GetType(___obj.GetType()) as CLRType;
___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var ___type = __domain.GetType(ptr_of_this_method->Value);
if(___type is ILType)
{
((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine;
}
else
{
((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine);
}
}
break;
case ObjectTypes.ArrayReference:
{
var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[];
instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine;
}
break;
}
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);
__intp.Free(ptr_of_this_method);
return __ret;
}
static StackObject* get_Task_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
var result_of_this_method = instance_of_this_method.Task;
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);
__intp.Free(ptr_of_this_method);
object obj_result_of_this_method = result_of_this_method;
if(obj_result_of_this_method is CrossBindingAdaptorType)
{
return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance);
}
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
static StackObject* AwaitUnsafeOnCompleted_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 3);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack));
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Runtime.CompilerServices.TaskAwaiter @awaiter = (System.Runtime.CompilerServices.TaskAwaiter)typeof(System.Runtime.CompilerServices.TaskAwaiter).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack));
ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
instance_of_this_method.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @awaiter, ref @stateMachine);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
switch(ptr_of_this_method->ObjectType)
{
case ObjectTypes.StackObjectReference:
{
var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method);
object ___obj = @stateMachine;
if (___dst->ObjectType >= ObjectTypes.Object)
{
if (___obj is CrossBindingAdaptorType)
___obj = ((CrossBindingAdaptorType)___obj).ILInstance;
__mStack[___dst->Value] = ___obj;
}
else
{
ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain);
}
}
break;
case ObjectTypes.FieldReference:
{
var ___obj = __mStack[ptr_of_this_method->Value];
if(___obj is ILTypeInstance)
{
((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine;
}
else
{
var ___type = __domain.GetType(___obj.GetType()) as CLRType;
___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var ___type = __domain.GetType(ptr_of_this_method->Value);
if(___type is ILType)
{
((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine;
}
else
{
((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine);
}
}
break;
case ObjectTypes.ArrayReference:
{
var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[];
instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine;
}
break;
}
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
switch(ptr_of_this_method->ObjectType)
{
case ObjectTypes.StackObjectReference:
{
var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method);
object ___obj = @awaiter;
if (___dst->ObjectType >= ObjectTypes.Object)
{
if (___obj is CrossBindingAdaptorType)
___obj = ((CrossBindingAdaptorType)___obj).ILInstance;
__mStack[___dst->Value] = ___obj;
}
else
{
ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain);
}
}
break;
case ObjectTypes.FieldReference:
{
var ___obj = __mStack[ptr_of_this_method->Value];
if(___obj is ILTypeInstance)
{
((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @awaiter;
}
else
{
var ___type = __domain.GetType(___obj.GetType()) as CLRType;
___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @awaiter);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var ___type = __domain.GetType(ptr_of_this_method->Value);
if(___type is ILType)
{
((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @awaiter;
}
else
{
((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @awaiter);
}
}
break;
case ObjectTypes.ArrayReference:
{
var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Runtime.CompilerServices.TaskAwaiter[];
instance_of_arrayReference[ptr_of_this_method->ValueLow] = @awaiter;
}
break;
}
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);
__intp.Free(ptr_of_this_method);
return __ret;
}
static StackObject* AwaitUnsafeOnCompleted_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 3);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack));
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance> @awaiter = (System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack));
ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
instance_of_this_method.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>, Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @awaiter, ref @stateMachine);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
switch(ptr_of_this_method->ObjectType)
{
case ObjectTypes.StackObjectReference:
{
var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method);
object ___obj = @stateMachine;
if (___dst->ObjectType >= ObjectTypes.Object)
{
if (___obj is CrossBindingAdaptorType)
___obj = ((CrossBindingAdaptorType)___obj).ILInstance;
__mStack[___dst->Value] = ___obj;
}
else
{
ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain);
}
}
break;
case ObjectTypes.FieldReference:
{
var ___obj = __mStack[ptr_of_this_method->Value];
if(___obj is ILTypeInstance)
{
((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine;
}
else
{
var ___type = __domain.GetType(___obj.GetType()) as CLRType;
___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var ___type = __domain.GetType(ptr_of_this_method->Value);
if(___type is ILType)
{
((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine;
}
else
{
((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine);
}
}
break;
case ObjectTypes.ArrayReference:
{
var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[];
instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine;
}
break;
}
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
switch(ptr_of_this_method->ObjectType)
{
case ObjectTypes.StackObjectReference:
{
var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method);
object ___obj = @awaiter;
if (___dst->ObjectType >= ObjectTypes.Object)
{
if (___obj is CrossBindingAdaptorType)
___obj = ((CrossBindingAdaptorType)___obj).ILInstance;
__mStack[___dst->Value] = ___obj;
}
else
{
ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain);
}
}
break;
case ObjectTypes.FieldReference:
{
var ___obj = __mStack[ptr_of_this_method->Value];
if(___obj is ILTypeInstance)
{
((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @awaiter;
}
else
{
var ___type = __domain.GetType(___obj.GetType()) as CLRType;
___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @awaiter);
}
}
break;
case ObjectTypes.StaticFieldReference:
{
var ___type = __domain.GetType(ptr_of_this_method->Value);
if(___type is ILType)
{
((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @awaiter;
}
else
{
((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @awaiter);
}
}
break;
case ObjectTypes.ArrayReference:
{
var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>[];
instance_of_arrayReference[ptr_of_this_method->ValueLow] = @awaiter;
}
break;
}
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);
__intp.Free(ptr_of_this_method);
return __ret;
}
static StackObject* SetException_5(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.Exception @exception = (System.Exception)typeof(System.Exception).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
instance_of_this_method.SetException(@exception);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);
__intp.Free(ptr_of_this_method);
return __ret;
}
static StackObject* SetResult_6(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.String @result = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);
System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String> instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.String>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
instance_of_this_method.SetResult(@result);
ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);
__intp.Free(ptr_of_this_method);
return __ret;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents a constructor call.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.NewExpressionProxy))]
public class NewExpression : Expression, IArgumentProvider
{
private readonly ConstructorInfo _constructor;
private IList<Expression> _arguments;
private readonly ReadOnlyCollection<MemberInfo> _members;
internal NewExpression(ConstructorInfo constructor, IList<Expression> arguments, ReadOnlyCollection<MemberInfo> members)
{
_constructor = constructor;
_arguments = arguments;
_members = members;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public override Type Type
{
get { return _constructor.DeclaringType; }
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.New; }
}
/// <summary>
/// Gets the called constructor.
/// </summary>
public ConstructorInfo Constructor
{
get { return _constructor; }
}
/// <summary>
/// Gets the arguments to the constructor.
/// </summary>
public ReadOnlyCollection<Expression> Arguments
{
get { return ReturnReadOnly(ref _arguments); }
}
public Expression GetArgument(int index)
{
return _arguments[index];
}
public int ArgumentCount
{
get
{
return _arguments.Count;
}
}
/// <summary>
/// Gets the members that can retrieve the values of the fields that were initialized with constructor arguments.
/// </summary>
public ReadOnlyCollection<MemberInfo> Members
{
get { return _members; }
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitNew(this);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public NewExpression Update(IEnumerable<Expression> arguments)
{
if (arguments == Arguments)
{
return this;
}
if (Members != null)
{
return Expression.New(Constructor, arguments, Members);
}
return Expression.New(Constructor, arguments);
}
}
internal class NewValueTypeExpression : NewExpression
{
private readonly Type _valueType;
internal NewValueTypeExpression(Type type, ReadOnlyCollection<Expression> arguments, ReadOnlyCollection<MemberInfo> members)
: base(null, arguments, members)
{
_valueType = type;
}
public sealed override Type Type
{
get { return _valueType; }
}
}
public partial class Expression
{
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> property set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor)
{
return New(constructor, (IEnumerable<Expression>)null);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An array of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> and <see cref="P:Arguments"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, params Expression[] arguments)
{
return New(constructor, (IEnumerable<Expression>)arguments);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor that takes no arguments.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/> and <see cref="P:Arguments"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments)
{
ContractUtils.RequiresNotNull(constructor, "constructor");
ContractUtils.RequiresNotNull(constructor.DeclaringType, "constructor.DeclaringType");
TypeUtils.ValidateType(constructor.DeclaringType);
ValidateConstructor(constructor);
var argList = arguments.ToReadOnly();
ValidateArgumentTypes(constructor, ExpressionType.New, ref argList);
return new NewExpression(constructor, argList, null);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <param name="members">An <see cref="IEnumerable{T}"/> of <see cref="MemberInfo"/> objects to use to populate the Members collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/>, <see cref="P:Arguments"/> and <see cref="P:Members"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments, IEnumerable<MemberInfo> members)
{
ContractUtils.RequiresNotNull(constructor, "constructor");
ValidateConstructor(constructor);
var memberList = members.ToReadOnly();
var argList = arguments.ToReadOnly();
ValidateNewArgs(constructor, ref argList, ref memberList);
return new NewExpression(constructor, argList, memberList);
}
/// <summary>
/// Creates a new <see cref="NewExpression"/> that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified.
/// </summary>
/// <param name="constructor">The <see cref="ConstructorInfo"/> to set the <see cref="P:Constructor"/> property equal to.</param>
/// <param name="arguments">An <see cref="IEnumerable{T}"/> of <see cref="Expression"/> objects to use to populate the Arguments collection.</param>
/// <param name="members">An Array of <see cref="MemberInfo"/> objects to use to populate the Members collection.</param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="P:New"/> and the <see cref="P:Constructor"/>, <see cref="P:Arguments"/> and <see cref="P:Members"/> properties set to the specified value.</returns>
public static NewExpression New(ConstructorInfo constructor, IEnumerable<Expression> arguments, params MemberInfo[] members)
{
return New(constructor, arguments, (IEnumerable<MemberInfo>)members);
}
/// <summary>
/// Creates a <see cref="NewExpression"/> that represents calling the parameterless constructor of the specified type.
/// </summary>
/// <param name="type">A <see cref="Type"/> that has a constructor that takes no arguments. </param>
/// <returns>A <see cref="NewExpression"/> that has the <see cref="NodeType"/> property equal to New and the Constructor property set to the ConstructorInfo that represents the parameterless constructor of the specified type.</returns>
public static NewExpression New(Type type)
{
ContractUtils.RequiresNotNull(type, "type");
if (type == typeof(void))
{
throw Error.ArgumentCannotBeOfTypeVoid();
}
ConstructorInfo ci = null;
if (!type.GetTypeInfo().IsValueType)
{
ci = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.GetParameters().Length == 0).SingleOrDefault();
if (ci == null)
{
throw Error.TypeMissingDefaultConstructor(type);
}
return New(ci);
}
return new NewValueTypeExpression(type, EmptyReadOnlyCollection<Expression>.Instance, null);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static void ValidateNewArgs(ConstructorInfo constructor, ref ReadOnlyCollection<Expression> arguments, ref ReadOnlyCollection<MemberInfo> members)
{
ParameterInfo[] pis;
if ((pis = constructor.GetParametersCached()).Length > 0)
{
if (arguments.Count != pis.Length)
{
throw Error.IncorrectNumberOfConstructorArguments();
}
if (arguments.Count != members.Count)
{
throw Error.IncorrectNumberOfArgumentsForMembers();
}
Expression[] newArguments = null;
MemberInfo[] newMembers = null;
for (int i = 0, n = arguments.Count; i < n; i++)
{
Expression arg = arguments[i];
RequiresCanRead(arg, "argument");
MemberInfo member = members[i];
ContractUtils.RequiresNotNull(member, "member");
if (!TypeUtils.AreEquivalent(member.DeclaringType, constructor.DeclaringType))
{
throw Error.ArgumentMemberNotDeclOnType(member.Name, constructor.DeclaringType.Name);
}
Type memberType;
ValidateAnonymousTypeMember(ref member, out memberType);
if (!TypeUtils.AreReferenceAssignable(memberType, arg.Type))
{
if (!TryQuote(memberType, ref arg))
{
throw Error.ArgumentTypeDoesNotMatchMember(arg.Type, memberType);
}
}
ParameterInfo pi = pis[i];
Type pType = pi.ParameterType;
if (pType.IsByRef)
{
pType = pType.GetElementType();
}
if (!TypeUtils.AreReferenceAssignable(pType, arg.Type))
{
if (!TryQuote(pType, ref arg))
{
throw Error.ExpressionTypeDoesNotMatchConstructorParameter(arg.Type, pType);
}
}
if (newArguments == null && arg != arguments[i])
{
newArguments = new Expression[arguments.Count];
for (int j = 0; j < i; j++)
{
newArguments[j] = arguments[j];
}
}
if (newArguments != null)
{
newArguments[i] = arg;
}
if (newMembers == null && member != members[i])
{
newMembers = new MemberInfo[members.Count];
for (int j = 0; j < i; j++)
{
newMembers[j] = members[j];
}
}
if (newMembers != null)
{
newMembers[i] = member;
}
}
if (newArguments != null)
{
arguments = new TrueReadOnlyCollection<Expression>(newArguments);
}
if (newMembers != null)
{
members = new TrueReadOnlyCollection<MemberInfo>(newMembers);
}
}
else if (arguments != null && arguments.Count > 0)
{
throw Error.IncorrectNumberOfConstructorArguments();
}
else if (members != null && members.Count > 0)
{
throw Error.IncorrectNumberOfMembersForGivenConstructor();
}
}
private static void ValidateAnonymousTypeMember(ref MemberInfo member, out Type memberType)
{
FieldInfo field = member as FieldInfo;
if (field != null)
{
if (field.IsStatic)
{
throw Error.ArgumentMustBeInstanceMember();
}
memberType = field.FieldType;
return;
}
PropertyInfo pi = member as PropertyInfo;
if (pi != null)
{
if (!pi.CanRead)
{
throw Error.PropertyDoesNotHaveGetter(pi);
}
if (pi.GetGetMethod().IsStatic)
{
throw Error.ArgumentMustBeInstanceMember();
}
memberType = pi.PropertyType;
return;
}
MethodInfo method = member as MethodInfo;
if (method != null)
{
if (method.IsStatic)
{
throw Error.ArgumentMustBeInstanceMember();
}
PropertyInfo prop = GetProperty(method);
member = prop;
memberType = prop.PropertyType;
return;
}
throw Error.ArgumentMustBeFieldInfoOrPropertyInfoOrMethod();
}
private static void ValidateConstructor(ConstructorInfo constructor)
{
if (constructor.IsStatic)
throw Error.NonStaticConstructorRequired();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Services.Interfaces;
using OpenSim.Server.Base;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using log4net;
using Nini.Config;
namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{
public class HGInventoryAccessModule : BasicInventoryAccessModule, INonSharedRegionModule, IInventoryAccessModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static HGAssetMapper m_assMapper;
public static HGAssetMapper AssetMapper
{
get { return m_assMapper; }
}
private string m_ProfileServerURI;
private bool m_OutboundPermission;
// private bool m_Initialized = false;
#region INonSharedRegionModule
public override string Name
{
get { return "HGInventoryAccessModule"; }
}
public override void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryAccessModule", "");
if (name == Name)
{
m_Enabled = true;
InitialiseCommon(source);
m_log.InfoFormat("[HG INVENTORY ACCESS MODULE]: {0} enabled.", Name);
IConfig thisModuleConfig = source.Configs["HGInventoryAccessModule"];
if (thisModuleConfig != null)
{
m_ProfileServerURI = thisModuleConfig.GetString("ProfileServerURI", string.Empty);
m_OutboundPermission = thisModuleConfig.GetBoolean("OutboundPermission", true);
}
else
m_log.Warn("[HG INVENTORY ACCESS MODULE]: HGInventoryAccessModule configs not found. ProfileServerURI not set!");
}
}
}
public override void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
base.AddRegion(scene);
m_assMapper = new HGAssetMapper(scene, m_ProfileServerURI);
scene.EventManager.OnNewInventoryItemUploadComplete += UploadInventoryItem;
}
#endregion
#region Event handlers
public void UploadInventoryItem(UUID avatarID, UUID assetID, string name, int userlevel)
{
string userAssetServer = string.Empty;
if (IsForeignUser(avatarID, out userAssetServer) && m_OutboundPermission)
{
Util.FireAndForget(delegate { m_assMapper.Post(assetID, avatarID, userAssetServer); });
}
}
#endregion
#region Overrides of Basic Inventory Access methods
///
/// CapsUpdateInventoryItemAsset
///
public override UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data)
{
UUID newAssetID = base.CapsUpdateInventoryItemAsset(remoteClient, itemID, data);
UploadInventoryItem(remoteClient.AgentId, newAssetID, "", 0);
return newAssetID;
}
///
/// Used in DeleteToInventory
///
protected override void ExportAsset(UUID agentID, UUID assetID)
{
if (!assetID.Equals(UUID.Zero))
UploadInventoryItem(agentID, assetID, "", 0);
else
m_log.Debug("[HGScene]: Scene.Inventory did not create asset");
}
///
/// RezObject
///
public override SceneObjectGroup RezObject(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart,
UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment)
{
m_log.DebugFormat("[HGScene] RezObject itemID={0} fromTaskID={1}", itemID, fromTaskID);
//if (fromTaskID.Equals(UUID.Zero))
//{
InventoryItemBase item = new InventoryItemBase(itemID);
item.Owner = remoteClient.AgentId;
item = m_Scene.InventoryService.GetItem(item);
//if (item == null)
//{ // Fetch the item
// item = new InventoryItemBase();
// item.Owner = remoteClient.AgentId;
// item.ID = itemID;
// item = m_assMapper.Get(item, userInfo.RootFolder.ID, userInfo);
//}
string userAssetServer = string.Empty;
if (item != null && IsForeignUser(remoteClient.AgentId, out userAssetServer))
{
m_assMapper.Get(item.AssetID, remoteClient.AgentId, userAssetServer);
}
//}
// OK, we're done fetching. Pass it up to the default RezObject
return base.RezObject(remoteClient, itemID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection,
RezSelected, RemoveItem, fromTaskID, attachment);
}
public override void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver)
{
string userAssetServer = string.Empty;
if (IsForeignUser(sender, out userAssetServer))
m_assMapper.Get(item.AssetID, sender, userAssetServer);
if (IsForeignUser(receiver, out userAssetServer) && m_OutboundPermission)
m_assMapper.Post(item.AssetID, receiver, userAssetServer);
}
public override bool IsForeignUser(UUID userID, out string assetServerURL)
{
assetServerURL = string.Empty;
UserAccount account = null;
if (m_Scene.UserAccountService != null)
account = m_Scene.UserAccountService.GetUserAccount(m_Scene.RegionInfo.ScopeID, userID);
if (account == null) // foreign
{
ScenePresence sp = null;
if (m_Scene.TryGetScenePresence(userID, out sp))
{
AgentCircuitData aCircuit = m_Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
if (aCircuit.ServiceURLs.ContainsKey("AssetServerURI"))
{
assetServerURL = aCircuit.ServiceURLs["AssetServerURI"].ToString();
assetServerURL = assetServerURL.Trim(new char[] { '/' }); return true;
}
}
}
return false;
}
#endregion
protected override InventoryItemBase GetItem(UUID agentID, UUID itemID)
{
InventoryItemBase item = base.GetItem(agentID, itemID);
string userAssetServer = string.Empty;
if (IsForeignUser(agentID, out userAssetServer))
m_assMapper.Get(item.AssetID, agentID, userAssetServer);
return item;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.