context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Diagnostics;
using System.Text;
using u8 = System.Byte;
using u32 = System.UInt32;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2001 September 22
**
** 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 is the implementation of generic hash-tables
** used in SQLite.
*************************************************************************
** 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: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c
**
** $Header$
*************************************************************************
*/
//#include "sqliteInt.h"
//#include <assert.h>
/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
*/
static void sqlite3HashInit( Hash pNew )
{
Debug.Assert( pNew != null );
pNew.first = null;
pNew.count = 0;
pNew.htsize = 0;
pNew.ht = null;
}
/* Remove all entries from a hash table. Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
static void sqlite3HashClear( Hash pH )
{
HashElem elem; /* For looping over all elements of the table */
Debug.Assert( pH != null );
elem = pH.first;
pH.first = null;
//sqlite3_free( ref pH.ht );
pH.ht = null;
pH.htsize = 0;
while ( elem != null )
{
HashElem next_elem = elem.next;
////sqlite3_free(ref elem );
elem = next_elem;
}
pH.count = 0;
}
/*
** The hashing function.
*/
static u32 strHash( string z, int nKey )
{
int h = 0;
Debug.Assert( nKey >= 0 );
int _z = 0;
while ( nKey > 0 )
{
h = ( h << 3 ) ^ h ^ ( ( _z < z.Length ) ? (int)sqlite3UpperToLower[(byte)z[_z++]] : 0 );
nKey--;
}
return (u32)h;
}
/* Link pNew element into the hash table pH. If pEntry!=0 then also
** insert pNew into the pEntry hash bucket.
*/
static void insertElement(
Hash pH, /* The complete hash table */
_ht pEntry, /* The entry into which pNew is inserted */
HashElem pNew /* The element to be inserted */
)
{
HashElem pHead; /* First element already in pEntry */
if ( pEntry != null )
{
pHead = pEntry.count != 0 ? pEntry.chain : null;
pEntry.count++;
pEntry.chain = pNew;
}
else
{
pHead = null;
}
if ( pHead != null )
{
pNew.next = pHead;
pNew.prev = pHead.prev;
if ( pHead.prev != null ) { pHead.prev.next = pNew; }
else { pH.first = pNew; }
pHead.prev = pNew;
}
else
{
pNew.next = pH.first;
if ( pH.first != null ) { pH.first.prev = pNew; }
pNew.prev = null;
pH.first = pNew;
}
}
/* Resize the hash table so that it cantains "new_size" buckets.
**
** The hash table might fail to resize if sqlite3_malloc() fails or
** if the new size is the same as the prior size.
** Return TRUE if the resize occurs and false if not.
*/
static bool rehash( ref Hash pH, u32 new_size )
{
_ht[] new_ht; /* The new hash table */
HashElem elem;
HashElem next_elem; /* For looping over existing elements */
#if SQLITE_MALLOC_SOFT_LIMIT
if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
}
if( new_size==pH->htsize ) return false;
#endif
/* There is a call to sqlite3Malloc() inside rehash(). If there is
** already an allocation at pH.ht, then if this malloc() fails it
** is benign (since failing to resize a hash table is a performance
** hit only, not a fatal error).
*/
sqlite3BeginBenignMalloc();
new_ht = new _ht[new_size]; //(struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
for ( int i = 0; i < new_size; i++ ) new_ht[i] = new _ht();
sqlite3EndBenignMalloc();
if ( new_ht == null ) return false;
//sqlite3_free( ref pH.ht );
pH.ht = new_ht;
// pH.htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
//memset(new_ht, 0, new_size*sizeof(struct _ht));
pH.htsize = new_size;
for ( elem = pH.first, pH.first = null; elem != null; elem = next_elem )
{
u32 h = strHash( elem.pKey, elem.nKey ) % new_size;
next_elem = elem.next;
insertElement( pH, new_ht[h], elem );
}
return true;
}
/* This function (for internal use only) locates an element in an
** hash table that matches the given key. The hash for this key has
** already been computed and is passed as the 4th parameter.
*/
static HashElem findElementGivenHash(
Hash pH, /* The pH to be searched */
string pKey, /* The key we are searching for */
int nKey, /* Bytes in key (not counting zero terminator) */
u32 h /* The hash for this key. */
)
{
HashElem elem; /* Used to loop thru the element list */
int count; /* Number of elements left to test */
if ( pH.ht != null && pH.ht[h] != null )
{
_ht pEntry = pH.ht[h];
elem = pEntry.chain;
count = (int)pEntry.count;
}
else
{
elem = pH.first;
count = (int)pH.count;
}
while ( count-- > 0 && ALWAYS( elem ) )
{
if ( elem.nKey == nKey && sqlite3StrNICmp( elem.pKey, pKey, nKey ) == 0 )
{
return elem;
}
elem = elem.next;
}
return null;
}
/* Remove a single entry from the hash table given a pointer to that
** element and a hash on the element's key.
*/
static void removeElementGivenHash(
Hash pH, /* The pH containing "elem" */
ref HashElem elem, /* The element to be removed from the pH */
u32 h /* Hash value for the element */
)
{
_ht pEntry;
if ( elem.prev != null )
{
elem.prev.next = elem.next;
}
else
{
pH.first = elem.next;
}
if ( elem.next != null )
{
elem.next.prev = elem.prev;
}
if ( pH.ht != null && pH.ht[h] != null )
{
pEntry = pH.ht[h];
if ( pEntry.chain == elem )
{
pEntry.chain = elem.next;
}
pEntry.count--;
Debug.Assert( pEntry.count >= 0 );
}
//sqlite3_free( ref elem );
pH.count--;
if ( pH.count <= 0 )
{
Debug.Assert( pH.first == null );
Debug.Assert( pH.count == 0 );
sqlite3HashClear( pH );
}
}
/* Attempt to locate an element of the hash table pH with a key
** that matches pKey,nKey. Return the data for this element if it is
** found, or NULL if there is no match.
*/
static object sqlite3HashFind( Hash pH, string pKey, int nKey )
{
HashElem elem; /* The element that matches key */
u32 h; /* A hash on key */
Debug.Assert( pH != null );
Debug.Assert( pKey != null );
Debug.Assert( nKey >= 0 );
if ( pH.ht != null )
{
h = strHash( pKey, nKey ) % pH.htsize;
}
else
{
h = 0;
}
elem = findElementGivenHash( pH, pKey, nKey, h );
return elem != null ? elem.data : null;
}
/* Insert an element into the hash table pH. The key is pKey,nKey
** and the data is "data".
**
** If no element exists with a matching key, then a new
** element is created and NULL is returned.
**
** If another element already exists with the same key, then the
** new data replaces the old data and the old data is returned.
** The key is not copied in this instance. If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
static object sqlite3HashInsert( ref Hash pH, string pKey, int nKey, object data )
{
u32 h; /* the hash of the key modulo hash table size */
HashElem elem; /* Used to loop thru the element list */
HashElem new_elem; /* New element added to the pH */
Debug.Assert( pH != null );
Debug.Assert( pKey != null );
Debug.Assert( nKey >= 0 );
if ( pH.htsize != 0 )
{
h = strHash( pKey, nKey ) % pH.htsize;
}
else
{
h = 0;
}
elem = findElementGivenHash( pH, pKey, nKey, h );
if ( elem != null )
{
object old_data = elem.data;
if ( data == null )
{
removeElementGivenHash( pH, ref elem, h );
}
else
{
elem.data = data;
elem.pKey = pKey;
Debug.Assert( nKey == elem.nKey );
}
return old_data;
}
if ( data == null ) return null;
new_elem = new HashElem();//(HashElem*)sqlite3Malloc( sizeof(HashElem) );
if ( new_elem == null ) return data;
new_elem.pKey = pKey;
new_elem.nKey = nKey;
new_elem.data = data;
pH.count++;
if ( pH.count >= 10 && pH.count > 2 * pH.htsize )
{
if ( rehash( ref pH, pH.count * 2 ) )
{
Debug.Assert( pH.htsize > 0 );
h = strHash( pKey, nKey ) % pH.htsize;
}
}
if ( pH.ht != null )
{
insertElement( pH, pH.ht[h], new_elem );
}
else
{
insertElement( pH, null, new_elem );
}
return null;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Securities;
using QuantConnect.Util;
namespace QuantConnect.Lean.Engine.DataFeeds
{
/// <summary>
/// DataManager will manage the subscriptions for both the DataFeeds and the SubscriptionManager
/// </summary>
public class DataManager : IAlgorithmSubscriptionManager, IDataFeedSubscriptionManager, IDataManager
{
private readonly IAlgorithmSettings _algorithmSettings;
private readonly IDataFeed _dataFeed;
private readonly MarketHoursDatabase _marketHoursDatabase;
private readonly ITimeKeeper _timeKeeper;
private readonly bool _liveMode;
private readonly IRegisteredSecurityDataTypesProvider _registeredTypesProvider;
private readonly IDataPermissionManager _dataPermissionManager;
/// There is no ConcurrentHashSet collection in .NET,
/// so we use ConcurrentDictionary with byte value to minimize memory usage
private readonly ConcurrentDictionary<SubscriptionDataConfig, SubscriptionDataConfig> _subscriptionManagerSubscriptions
= new ConcurrentDictionary<SubscriptionDataConfig, SubscriptionDataConfig>();
/// <summary>
/// Event fired when a new subscription is added
/// </summary>
public event EventHandler<Subscription> SubscriptionAdded;
/// <summary>
/// Event fired when an existing subscription is removed
/// </summary>
public event EventHandler<Subscription> SubscriptionRemoved;
/// <summary>
/// Creates a new instance of the DataManager
/// </summary>
public DataManager(
IDataFeed dataFeed,
UniverseSelection universeSelection,
IAlgorithm algorithm,
ITimeKeeper timeKeeper,
MarketHoursDatabase marketHoursDatabase,
bool liveMode,
IRegisteredSecurityDataTypesProvider registeredTypesProvider,
IDataPermissionManager dataPermissionManager)
{
_dataFeed = dataFeed;
UniverseSelection = universeSelection;
UniverseSelection.SetDataManager(this);
_algorithmSettings = algorithm.Settings;
AvailableDataTypes = SubscriptionManager.DefaultDataTypes();
_timeKeeper = timeKeeper;
_marketHoursDatabase = marketHoursDatabase;
_liveMode = liveMode;
_registeredTypesProvider = registeredTypesProvider;
_dataPermissionManager = dataPermissionManager;
// wire ourselves up to receive notifications when universes are added/removed
algorithm.UniverseManager.CollectionChanged += (sender, args) =>
{
switch (args.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (var universe in args.NewItems.OfType<Universe>())
{
var config = universe.Configuration;
var start = algorithm.UtcTime;
var end = algorithm.LiveMode ? Time.EndOfTime
: algorithm.EndDate.ConvertToUtc(algorithm.TimeZone);
Security security;
if (!algorithm.Securities.TryGetValue(config.Symbol, out security))
{
// create a canonical security object if it doesn't exist
security = new Security(
_marketHoursDatabase.GetExchangeHours(config),
config,
algorithm.Portfolio.CashBook[algorithm.AccountCurrency],
SymbolProperties.GetDefault(algorithm.AccountCurrency),
algorithm.Portfolio.CashBook,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache()
);
}
AddSubscription(
new SubscriptionRequest(true,
universe,
security,
config,
start,
end));
}
break;
case NotifyCollectionChangedAction.Remove:
foreach (var universe in args.OldItems.OfType<Universe>())
{
// removing the subscription will be handled by the SubscriptionSynchronizer
// in the next loop as well as executing a UniverseSelection one last time.
if (!universe.DisposeRequested)
{
universe.Dispose();
}
}
break;
default:
throw new NotImplementedException("The specified action is not implemented: " + args.Action);
}
};
}
#region IDataFeedSubscriptionManager
/// <summary>
/// Gets the data feed subscription collection
/// </summary>
public SubscriptionCollection DataFeedSubscriptions { get; } = new SubscriptionCollection();
/// <summary>
/// Will remove all current <see cref="Subscription"/>
/// </summary>
public void RemoveAllSubscriptions()
{
// remove each subscription from our collection
foreach (var subscription in DataFeedSubscriptions)
{
try
{
RemoveSubscription(subscription.Configuration);
}
catch (Exception err)
{
Log.Error(err, "DataManager.RemoveAllSubscriptions():" +
$"Error removing: {subscription.Configuration}");
}
}
}
/// <summary>
/// Adds a new <see cref="Subscription"/> to provide data for the specified security.
/// </summary>
/// <param name="request">Defines the <see cref="SubscriptionRequest"/> to be added</param>
/// <returns>True if the subscription was created and added successfully, false otherwise</returns>
public bool AddSubscription(SubscriptionRequest request)
{
// guarantee the configuration is present in our config collection
// this is related to GH issue 3877: where we added a configuration which we also removed
_subscriptionManagerSubscriptions.TryAdd(request.Configuration, request.Configuration);
Subscription subscription;
if (DataFeedSubscriptions.TryGetValue(request.Configuration, out subscription))
{
// duplicate subscription request
subscription.AddSubscriptionRequest(request);
// only result true if the existing subscription is internal, we actually added something from the users perspective
return subscription.Configuration.IsInternalFeed;
}
// before adding the configuration to the data feed let's assert it's valid
_dataPermissionManager.AssertConfiguration(request.Configuration, request.StartTimeLocal, request.EndTimeLocal);
subscription = _dataFeed.CreateSubscription(request);
if (subscription == null)
{
Log.Trace($"DataManager.AddSubscription(): Unable to add subscription for: {request.Configuration}");
// subscription will be null when there's no tradeable dates for the security between the requested times, so
// don't even try to load the data
return false;
}
if (_liveMode)
{
OnSubscriptionAdded(subscription);
Log.Trace($"DataManager.AddSubscription(): Added {request.Configuration}." +
$" Start: {request.StartTimeUtc}. End: {request.EndTimeUtc}");
}
else if(Log.DebuggingEnabled)
{
// for performance lets not create the message string if debugging is not enabled
// this can be executed many times and its in the algorithm thread
Log.Debug($"DataManager.AddSubscription(): Added {request.Configuration}." +
$" Start: {request.StartTimeUtc}. End: {request.EndTimeUtc}");
}
return DataFeedSubscriptions.TryAdd(subscription);
}
/// <summary>
/// Removes the <see cref="Subscription"/>, if it exists
/// </summary>
/// <param name="configuration">The <see cref="SubscriptionDataConfig"/> of the subscription to remove</param>
/// <param name="universe">Universe requesting to remove <see cref="Subscription"/>.
/// Default value, null, will remove all universes</param>
/// <returns>True if the subscription was successfully removed, false otherwise</returns>
public bool RemoveSubscription(SubscriptionDataConfig configuration, Universe universe = null)
{
// remove the subscription from our collection, if it exists
Subscription subscription;
if (DataFeedSubscriptions.TryGetValue(configuration, out subscription))
{
// we remove the subscription when there are no other requests left
if (subscription.RemoveSubscriptionRequest(universe))
{
if (!DataFeedSubscriptions.TryRemove(configuration, out subscription))
{
Log.Error($"DataManager.RemoveSubscription(): Unable to remove {configuration}");
return false;
}
_dataFeed.RemoveSubscription(subscription);
if (_liveMode)
{
OnSubscriptionRemoved(subscription);
}
subscription.Dispose();
RemoveSubscriptionDataConfig(subscription);
if (_liveMode)
{
Log.Trace($"DataManager.RemoveSubscription(): Removed {configuration}");
}
else if(Log.DebuggingEnabled)
{
// for performance lets not create the message string if debugging is not enabled
// this can be executed many times and its in the algorithm thread
Log.Debug($"DataManager.RemoveSubscription(): Removed {configuration}");
}
return true;
}
}
else if (universe != null)
{
// a universe requested removal of a subscription which wasn't present anymore, this can happen when a subscription ends
// it will get removed from the data feed subscription list, but the configuration will remain until the universe removes it
// why? the effect I found is that the fill models are using these subscriptions to determine which data they could use
SubscriptionDataConfig config;
_subscriptionManagerSubscriptions.TryRemove(configuration, out config);
}
return false;
}
/// <summary>
/// Event invocator for the <see cref="SubscriptionAdded"/> event
/// </summary>
/// <param name="subscription">The added subscription</param>
private void OnSubscriptionAdded(Subscription subscription)
{
SubscriptionAdded?.Invoke(this, subscription);
}
/// <summary>
/// Event invocator for the <see cref="SubscriptionRemoved"/> event
/// </summary>
/// <param name="subscription">The removed subscription</param>
private void OnSubscriptionRemoved(Subscription subscription)
{
SubscriptionRemoved?.Invoke(this, subscription);
}
#endregion
#region IAlgorithmSubscriptionManager
/// <summary>
/// Gets all the current data config subscriptions that are being processed for the SubscriptionManager
/// </summary>
public IEnumerable<SubscriptionDataConfig> SubscriptionManagerSubscriptions =>
_subscriptionManagerSubscriptions.Select(x => x.Key);
/// <summary>
/// Gets existing or adds new <see cref="SubscriptionDataConfig" />
/// </summary>
/// <returns>Returns the SubscriptionDataConfig instance used</returns>
public SubscriptionDataConfig SubscriptionManagerGetOrAdd(SubscriptionDataConfig newConfig)
{
var config = _subscriptionManagerSubscriptions.GetOrAdd(newConfig, newConfig);
// if the reference is not the same, means it was already there and we did not add anything new
if (!ReferenceEquals(config, newConfig))
{
// for performance lets not create the message string if debugging is not enabled
// this can be executed many times and its in the algorithm thread
if (Log.DebuggingEnabled)
{
Log.Debug("DataManager.SubscriptionManagerGetOrAdd(): subscription already added: " + config);
}
}
else
{
// for performance, only count if we are above the limit
if (SubscriptionManagerCount() > _algorithmSettings.DataSubscriptionLimit)
{
// count data subscriptions by symbol, ignoring multiple data types.
// this limit was added due to the limits IB places on number of subscriptions
var uniqueCount = SubscriptionManagerSubscriptions
.Where(x => !x.Symbol.IsCanonical())
.DistinctBy(x => x.Symbol.Value)
.Count();
if (uniqueCount > _algorithmSettings.DataSubscriptionLimit)
{
throw new Exception(
$"The maximum number of concurrent market data subscriptions was exceeded ({_algorithmSettings.DataSubscriptionLimit})." +
"Please reduce the number of symbols requested or increase the limit using Settings.DataSubscriptionLimit.");
}
}
// add the time zone to our time keeper
_timeKeeper.AddTimeZone(newConfig.ExchangeTimeZone);
}
return config;
}
/// <summary>
/// Will try to remove a <see cref="SubscriptionDataConfig"/> and update the corresponding
/// consumers accordingly
/// </summary>
/// <param name="subscription">The <see cref="Subscription"/> owning the configuration to remove</param>
private void RemoveSubscriptionDataConfig(Subscription subscription)
{
// the subscription could of ended but might still be part of the universe
if (subscription.RemovedFromUniverse.Value)
{
SubscriptionDataConfig config;
_subscriptionManagerSubscriptions.TryRemove(subscription.Configuration, out config);
}
}
/// <summary>
/// Returns the amount of data config subscriptions processed for the SubscriptionManager
/// </summary>
public int SubscriptionManagerCount()
{
return _subscriptionManagerSubscriptions.Skip(0).Count();
}
#region ISubscriptionDataConfigService
/// <summary>
/// The different <see cref="TickType" /> each <see cref="SecurityType" /> supports
/// </summary>
public Dictionary<SecurityType, List<TickType>> AvailableDataTypes { get; }
/// <summary>
/// Creates and adds a list of <see cref="SubscriptionDataConfig" /> for a given symbol and configuration.
/// Can optionally pass in desired subscription data type to use.
/// If the config already existed will return existing instance instead
/// </summary>
public SubscriptionDataConfig Add(
Type dataType,
Symbol symbol,
Resolution? resolution = null,
bool fillForward = true,
bool extendedMarketHours = false,
bool isFilteredSubscription = true,
bool isInternalFeed = false,
bool isCustomData = false,
DataNormalizationMode dataNormalizationMode = DataNormalizationMode.Adjusted,
DataMappingMode dataMappingMode = DataMappingMode.OpenInterest,
uint contractDepthOffset = 0
)
{
return Add(symbol, resolution, fillForward, extendedMarketHours, isFilteredSubscription, isInternalFeed, isCustomData,
new List<Tuple<Type, TickType>> { new Tuple<Type, TickType>(dataType, LeanData.GetCommonTickTypeForCommonDataTypes(dataType, symbol.SecurityType))},
dataNormalizationMode, dataMappingMode, contractDepthOffset)
.First();
}
/// <summary>
/// Creates and adds a list of <see cref="SubscriptionDataConfig" /> for a given symbol and configuration.
/// Can optionally pass in desired subscription data types to use.
/// If the config already existed will return existing instance instead
/// </summary>
public List<SubscriptionDataConfig> Add(
Symbol symbol,
Resolution? resolution = null,
bool fillForward = true,
bool extendedMarketHours = false,
bool isFilteredSubscription = true,
bool isInternalFeed = false,
bool isCustomData = false,
List<Tuple<Type, TickType>> subscriptionDataTypes = null,
DataNormalizationMode dataNormalizationMode = DataNormalizationMode.Adjusted,
DataMappingMode dataMappingMode = DataMappingMode.OpenInterest,
uint contractDepthOffset = 0
)
{
var dataTypes = subscriptionDataTypes ??
LookupSubscriptionConfigDataTypes(symbol.SecurityType, resolution ?? Resolution.Minute, symbol.IsCanonical());
if (!dataTypes.Any())
{
throw new ArgumentNullException(nameof(dataTypes), "At least one type needed to create new subscriptions");
}
var resolutionWasProvided = resolution.HasValue;
foreach (var typeTuple in dataTypes)
{
var baseInstance = typeTuple.Item1.GetBaseDataInstance();
baseInstance.Symbol = symbol;
if (!resolutionWasProvided)
{
var defaultResolution = baseInstance.DefaultResolution();
if (resolution.HasValue && resolution != defaultResolution)
{
// we are here because there are multiple 'dataTypes'.
// if we get different default resolutions lets throw, this shouldn't happen
throw new InvalidOperationException(
$"Different data types ({string.Join(",", dataTypes.Select(tuple => tuple.Item1))})" +
$" provided different default resolutions {defaultResolution} and {resolution}, this is an unexpected invalid operation.");
}
resolution = defaultResolution;
}
else
{
// only assert resolution in backtesting, live can use other data source
// for example daily data for options
if (!_liveMode)
{
var supportedResolutions = baseInstance.SupportedResolutions();
if (supportedResolutions.Contains(resolution.Value))
{
continue;
}
throw new ArgumentException($"Sorry {resolution.ToStringInvariant()} is not a supported resolution for {typeTuple.Item1.Name}" +
$" and SecurityType.{symbol.SecurityType.ToStringInvariant()}." +
$" Please change your AddData to use one of the supported resolutions ({string.Join(",", supportedResolutions)}).");
}
}
}
var marketHoursDbEntry = _marketHoursDatabase.GetEntry(symbol, dataTypes.Select(tuple => tuple.Item1));
var exchangeHours = marketHoursDbEntry.ExchangeHours;
if (symbol.ID.SecurityType.IsOption() ||
symbol.ID.SecurityType == SecurityType.Index)
{
dataNormalizationMode = DataNormalizationMode.Raw;
}
if (marketHoursDbEntry.DataTimeZone == null)
{
throw new ArgumentNullException(nameof(marketHoursDbEntry.DataTimeZone),
"DataTimeZone is a required parameter for new subscriptions. Set to the time zone the raw data is time stamped in.");
}
if (exchangeHours.TimeZone == null)
{
throw new ArgumentNullException(nameof(exchangeHours.TimeZone),
"ExchangeTimeZone is a required parameter for new subscriptions. Set to the time zone the security exchange resides in.");
}
var result = (from subscriptionDataType in dataTypes
let dataType = subscriptionDataType.Item1
let tickType = subscriptionDataType.Item2
select new SubscriptionDataConfig(
dataType,
symbol,
resolution.Value,
marketHoursDbEntry.DataTimeZone,
exchangeHours.TimeZone,
fillForward,
extendedMarketHours,
// if the subscription data types were not provided and the tick type is OpenInterest we make it internal
subscriptionDataTypes == null && tickType == TickType.OpenInterest || isInternalFeed,
isCustomData,
isFilteredSubscription: isFilteredSubscription,
tickType: tickType,
dataNormalizationMode: dataNormalizationMode,
dataMappingMode: dataMappingMode,
contractDepthOffset: contractDepthOffset)).ToList();
for (int i = 0; i < result.Count; i++)
{
result[i] = SubscriptionManagerGetOrAdd(result[i]);
// track all registered data types
_registeredTypesProvider.RegisterType(result[i].Type);
}
return result;
}
/// <summary>
/// Get the data feed types for a given <see cref="SecurityType" /> <see cref="Resolution" />
/// </summary>
/// <param name="symbolSecurityType">The <see cref="SecurityType" /> used to determine the types</param>
/// <param name="resolution">The resolution of the data requested</param>
/// <param name="isCanonical">Indicates whether the security is Canonical (future and options)</param>
/// <returns>Types that should be added to the <see cref="SubscriptionDataConfig" /></returns>
public List<Tuple<Type, TickType>> LookupSubscriptionConfigDataTypes(
SecurityType symbolSecurityType,
Resolution resolution,
bool isCanonical
)
{
if (isCanonical)
{
return new List<Tuple<Type, TickType>> { new Tuple<Type, TickType>(typeof(ZipEntryName), TickType.Quote) };
}
IEnumerable<TickType> availableDataType = AvailableDataTypes[symbolSecurityType];
// Equities will only look for trades in case of low resolutions.
if (symbolSecurityType == SecurityType.Equity && (resolution == Resolution.Daily || resolution == Resolution.Hour))
{
// we filter out quote tick type
availableDataType = availableDataType.Where(t => t != TickType.Quote);
}
return availableDataType
.Select(tickType => new Tuple<Type, TickType>(LeanData.GetDataType(resolution, tickType), tickType)).ToList();
}
/// <summary>
/// Gets a list of all registered <see cref="SubscriptionDataConfig"/> for a given <see cref="Symbol"/>
/// </summary>
/// <remarks>Will not return internal subscriptions by default</remarks>
public List<SubscriptionDataConfig> GetSubscriptionDataConfigs(Symbol symbol, bool includeInternalConfigs = false)
{
return SubscriptionManagerSubscriptions.Where(x => x.Symbol == symbol
&& (includeInternalConfigs || !x.IsInternalFeed)).ToList();
}
#endregion
#endregion
#region IDataManager
/// <summary>
/// Get the universe selection instance
/// </summary>
public UniverseSelection UniverseSelection { get; }
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.Language.Components;
namespace Microsoft.CodeAnalysis.Razor
{
internal class EventHandlerTagHelperDescriptorProvider : ITagHelperDescriptorProvider
{
public int Order { get; set; }
public RazorEngine Engine { get; set; }
public void Execute(TagHelperDescriptorProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var compilation = context.GetCompilation();
if (compilation == null)
{
return;
}
if (compilation.GetTypeByMetadataName(ComponentsApi.EventHandlerAttribute.FullTypeName) is not INamedTypeSymbol eventHandlerAttribute)
{
// If we can't find EventHandlerAttribute, then just bail. We won't discover anything.
return;
}
var eventHandlerData = GetEventHandlerData(context, compilation, eventHandlerAttribute);
foreach (var tagHelper in CreateEventHandlerTagHelpers(eventHandlerData))
{
context.Results.Add(tagHelper);
}
}
private List<EventHandlerData> GetEventHandlerData(TagHelperDescriptorProviderContext context, Compilation compilation, INamedTypeSymbol eventHandlerAttribute)
{
var types = new List<INamedTypeSymbol>();
var visitor = new EventHandlerDataVisitor(types);
var targetAssembly = context.Items.GetTargetAssembly();
if (targetAssembly is not null)
{
visitor.Visit(targetAssembly.GlobalNamespace);
}
else
{
visitor.Visit(compilation.Assembly.GlobalNamespace);
foreach (var reference in compilation.References)
{
if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assembly)
{
visitor.Visit(assembly.GlobalNamespace);
}
}
}
var results = new List<EventHandlerData>();
for (var i = 0; i < types.Count; i++)
{
var type = types[i];
var attributes = type.GetAttributes();
// Not handling duplicates here for now since we're the primary ones extending this.
// If we see users adding to the set of event handler constructs we will want to add deduplication
// and potentially diagnostics.
for (var j = 0; j < attributes.Length; j++)
{
var attribute = attributes[j];
if (SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, eventHandlerAttribute))
{
var enablePreventDefault = false;
var enableStopPropagation = false;
if (attribute.ConstructorArguments.Length == 4)
{
enablePreventDefault = (bool)attribute.ConstructorArguments[2].Value;
enableStopPropagation = (bool)attribute.ConstructorArguments[3].Value;
}
results.Add(new EventHandlerData(
type.ContainingAssembly.Name,
type.ToDisplayString(),
(string)attribute.ConstructorArguments[0].Value,
(INamedTypeSymbol)attribute.ConstructorArguments[1].Value,
enablePreventDefault,
enableStopPropagation));
}
}
}
return results;
}
private List<TagHelperDescriptor> CreateEventHandlerTagHelpers(List<EventHandlerData> data)
{
var results = new List<TagHelperDescriptor>();
for (var i = 0; i < data.Count; i++)
{
var entry = data[i];
var attributeName = "@" + entry.Attribute;
var eventArgType = entry.EventArgsType.ToDisplayString();
var builder = TagHelperDescriptorBuilder.Create(ComponentMetadata.EventHandler.TagHelperKind, entry.Attribute, ComponentsApi.AssemblyName);
builder.CaseSensitive = true;
builder.Documentation = string.Format(
CultureInfo.CurrentCulture,
ComponentResources.EventHandlerTagHelper_Documentation,
attributeName,
eventArgType);
builder.Metadata.Add(ComponentMetadata.SpecialKindKey, ComponentMetadata.EventHandler.TagHelperKind);
builder.Metadata.Add(ComponentMetadata.EventHandler.EventArgsType, eventArgType);
builder.Metadata.Add(TagHelperMetadata.Common.ClassifyAttributesOnly, bool.TrueString);
builder.Metadata[TagHelperMetadata.Runtime.Name] = ComponentMetadata.EventHandler.RuntimeName;
// WTE has a bug in 15.7p1 where a Tag Helper without a display-name that looks like
// a C# property will crash trying to create the tooltips.
builder.SetTypeName(entry.TypeName);
builder.TagMatchingRule(rule =>
{
rule.TagName = "*";
rule.Attribute(a =>
{
a.Name = attributeName;
a.NameComparisonMode = RequiredAttributeDescriptor.NameComparisonMode.FullMatch;
a.Metadata[ComponentMetadata.Common.DirectiveAttribute] = bool.TrueString;
});
});
if (entry.EnablePreventDefault)
{
builder.TagMatchingRule(rule =>
{
rule.TagName = "*";
rule.Attribute(a =>
{
a.Name = attributeName + ":preventDefault";
a.NameComparisonMode = RequiredAttributeDescriptor.NameComparisonMode.FullMatch;
a.Metadata[ComponentMetadata.Common.DirectiveAttribute] = bool.TrueString;
});
});
}
if (entry.EnableStopPropagation)
{
builder.TagMatchingRule(rule =>
{
rule.TagName = "*";
rule.Attribute(a =>
{
a.Name = attributeName + ":stopPropagation";
a.NameComparisonMode = RequiredAttributeDescriptor.NameComparisonMode.FullMatch;
a.Metadata[ComponentMetadata.Common.DirectiveAttribute] = bool.TrueString;
});
});
}
builder.BindAttribute(a =>
{
a.Documentation = string.Format(
CultureInfo.CurrentCulture,
ComponentResources.EventHandlerTagHelper_Documentation,
attributeName,
eventArgType);
a.Name = attributeName;
// We want event handler directive attributes to default to C# context.
a.TypeName = $"Microsoft.AspNetCore.Components.EventCallback<{eventArgType}>";
// But make this weakly typed (don't type check) - delegates have their own type-checking
// logic that we don't want to interfere with.
a.Metadata.Add(ComponentMetadata.Component.WeaklyTypedKey, bool.TrueString);
a.Metadata[ComponentMetadata.Common.DirectiveAttribute] = bool.TrueString;
// WTE has a bug 15.7p1 where a Tag Helper without a display-name that looks like
// a C# property will crash trying to create the tooltips.
a.SetPropertyName(entry.Attribute);
if (entry.EnablePreventDefault)
{
a.BindAttributeParameter(parameter =>
{
parameter.Name = "preventDefault";
parameter.TypeName = typeof(bool).FullName;
parameter.Documentation = string.Format(
CultureInfo.CurrentCulture, ComponentResources.EventHandlerTagHelper_PreventDefault_Documentation, attributeName);
parameter.SetPropertyName("PreventDefault");
});
}
if (entry.EnableStopPropagation)
{
a.BindAttributeParameter(parameter =>
{
parameter.Name = "stopPropagation";
parameter.TypeName = typeof(bool).FullName;
parameter.Documentation = string.Format(
CultureInfo.CurrentCulture, ComponentResources.EventHandlerTagHelper_StopPropagation_Documentation, attributeName);
parameter.SetPropertyName("StopPropagation");
});
}
});
results.Add(builder.Build());
}
return results;
}
private struct EventHandlerData
{
public EventHandlerData(
string assembly,
string typeName,
string element,
INamedTypeSymbol eventArgsType,
bool enablePreventDefault,
bool enableStopPropagation)
{
Assembly = assembly;
TypeName = typeName;
Attribute = element;
EventArgsType = eventArgsType;
EnablePreventDefault = enablePreventDefault;
EnableStopPropagation = enableStopPropagation;
}
public string Assembly { get; }
public string TypeName { get; }
public string Attribute { get; }
public INamedTypeSymbol EventArgsType { get; }
public bool EnablePreventDefault { get; }
public bool EnableStopPropagation { get; }
}
private class EventHandlerDataVisitor : SymbolVisitor
{
private readonly List<INamedTypeSymbol> _results;
public EventHandlerDataVisitor(List<INamedTypeSymbol> results)
{
_results = results;
}
public override void VisitNamedType(INamedTypeSymbol symbol)
{
if (symbol.Name == "EventHandlers" && symbol.DeclaredAccessibility == Accessibility.Public)
{
_results.Add(symbol);
}
}
public override void VisitNamespace(INamespaceSymbol symbol)
{
foreach (var member in symbol.GetMembers())
{
Visit(member);
}
}
public override void VisitAssembly(IAssemblySymbol symbol)
{
// This as a simple yet high-value optimization that excludes the vast majority of
// assemblies that (by definition) can't contain a component.
if (symbol.Name != null && !symbol.Name.StartsWith("System.", StringComparison.Ordinal))
{
Visit(symbol.GlobalNamespace);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
namespace CommonTools.ColorPickerCtrl
{
public class ColorTable : LabelRotate
{
public event EventHandler SelectedIndexChanged;
public Color SelectedItem
{
get
{
if (m_selindex < 0 || m_selindex >= m_colors.Count)
return Color.White;
return m_colors[m_selindex];
}
set
{
if (m_selindex < m_colors.Count && value == m_colors[m_selindex])
return;
int index = m_colors.IndexOf(value);
if (index < 0)
return;
SetIndex(index);
}
}
public bool ColorExist(Color c)
{
int index = m_colors.IndexOf(c);
return index >= 0;
}
int m_cols = 0;
int m_rows = 0;
public int Cols
{
get { return m_cols; }
set
{
m_cols = value;
m_rows = m_colors.Count / m_cols;
if ((m_colors.Count % m_cols) != 0)
m_rows++;
}
}
Size m_fieldSize = new Size(12, 12);
public Size FieldSize
{
get { return m_fieldSize; }
set { m_fieldSize = value; }
}
int CompareColorByValue(Color c1, Color c2)
{
int color1 = c1.R << 16 | c1.G << 8 | c1.B;
int color2 = c2.R << 16 | c2.G << 8 | c2.B;
if (color1 > color2)
return -1;
if (color1 < color2)
return 1;
return 0;
}
int CompareColorByHue(Color c1, Color c2)
{
float h1 = c1.GetHue();
float h2 = c2.GetHue();
if (h1 < h2)
return -1;
if (h1 > h2)
return 1;
return 0;
}
int CompareColorByBrightness(Color c1, Color c2)
{
// bug, using float causes the sort to go into infinite loop in release,
// but only when run as standalone. If started from Visual Studio it works correct in release.
// other work around is to move float h1 and h2 out of the method
double h1 = c1.GetBrightness();
double h2 = c2.GetBrightness();
if (h1 < h2)
return -1;
if (h1 > h2)
return 1;
return 0;
}
public void SortColorByValue()
{
m_colors.Sort(CompareColorByValue);
Invalidate();
}
public void SortColorByHue()
{
m_colors.Sort(CompareColorByHue);
Invalidate();
}
public void SortColorByBrightness()
{
m_colors.Sort(CompareColorByBrightness);
Invalidate();
}
List<Color> m_colors = new List<Color>();
public ColorTable(Color[] colors)
{
this.DoubleBuffered = true;
if (colors != null)
m_colors = new List<Color>(colors);
Cols = 16;
m_initialColorCount = m_colors.Count;
Padding = new Padding(8,8,0,0);
}
public ColorTable()
{
this.DoubleBuffered = true;
PropertyInfo[] propinfos = typeof(Color).GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach (PropertyInfo info in propinfos)
{
if (info.PropertyType == typeof(Color))
{
Color c = (Color)info.GetValue(typeof(Color), null);
if (c.A == 0) // transparent
continue;
m_colors.Add(c);
}
}
m_colors.Sort(CompareColorByBrightness);
m_initialColorCount = m_colors.Count;
Cols = 16;
}
public void RemoveCustomColor()
{
if (m_colors.Count > m_initialColorCount)
m_colors.RemoveAt(m_colors.Count-1);
}
public void SetCustomColor(Color col)
{
RemoveCustomColor();
if (m_colors.Contains(col) == false)
{
int rows = m_rows;
m_colors.Add(col);
Cols = Cols;
if (m_rows != rows)
Invalidate();
else
Invalidate(GetRectangle(m_colors.Count-1));
}
}
public Color[] Colors
{
get { return m_colors.ToArray(); }
set
{
m_colors = new List<Color>(value);
Cols = 16;
m_initialColorCount = m_colors.Count;
}
}
int m_spacing = 3;
int m_selindex = 0;
int m_initialColorCount = 0;
Rectangle GetSelectedItemRect()
{
Rectangle rect = GetRectangle(m_selindex);
rect.Inflate(m_fieldSize.Width / 2, m_fieldSize.Height / 2);
return rect;
}
Rectangle GetRectangle(int index)
{
int row = 0;
int col = 0;
GetRowCol(index, ref row, ref col);
return GetRectangle(row, col);
}
void GetRowCol(int index, ref int row, ref int col)
{
row = index / m_cols;
col = index - (row * m_cols);
}
Rectangle GetRectangle(int row, int col)
{
int x = Padding.Left + (col * (m_fieldSize.Width + m_spacing));
int y = Padding.Top + (row * (m_fieldSize.Height + m_spacing));
return new Rectangle(x,y,m_fieldSize.Width, m_fieldSize.Height);
}
int GetIndexFromMousePos(int x, int y)
{
int col = (x-Padding.Left) / (m_fieldSize.Width + m_spacing);
int row = (y-Padding.Top) / (m_fieldSize.Height + m_spacing);
return GetIndex(row, col);
}
int GetIndex(int row, int col)
{
if (col < 0 || col >= m_cols)
return -1;
if (row < 0 || row >= m_rows)
return -1;
return row * m_cols + col;
}
void SetIndex(int index)
{
if (index == m_selindex)
return;
Invalidate(GetSelectedItemRect());
m_selindex = index;
if (SelectedIndexChanged != null)
SelectedIndexChanged(this, null);
Invalidate(GetSelectedItemRect());
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
Focus();
if (GetSelectedItemRect().Contains(new Point(e.X, e.Y)))
return;
int index = GetIndexFromMousePos(e.X, e.Y);
if (index != -1)
SetIndex(index);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
int index = 0;
int totalwidth = m_cols * (m_fieldSize.Width + m_spacing);
int totalheight = m_rows * (m_fieldSize.Height + m_spacing);
int offset = (m_spacing / 2 + 1);
Rectangle r = new Rectangle(0, 0, totalwidth, totalheight);
r.X += Padding.Left - offset;
r.Y += Padding.Top - offset;
e.Graphics.DrawRectangle(Pens.CadetBlue, r);
r.X++;
r.Y++;
r.Width--;
r.Height--;
e.Graphics.FillRectangle(Brushes.White, r);
for (int col = 1; col < m_cols; col++)
{
int x = Padding.Left - offset + (col * (m_fieldSize.Width + m_spacing));
e.Graphics.DrawLine(Pens.CadetBlue, x, r.Y, x, r.Bottom - 1);
}
for (int row = 1; row < m_rows; row++)
{
int y = Padding.Top - offset + (row * (m_fieldSize.Height + m_spacing));
e.Graphics.DrawLine(Pens.CadetBlue, r.X, y, r.Right - 1, y);
}
for (int row = 0; row < m_rows; row++)
{
for (int col = 0; col < m_cols; col++)
{
if (index >= m_colors.Count)
break;
Rectangle rect = GetRectangle(row, col);
using (SolidBrush brush = new SolidBrush(m_colors[index++]))
{
e.Graphics.FillRectangle(brush, rect);
}
}
}
if (m_selindex >= 0)
{
Rectangle rect = GetSelectedItemRect();
e.Graphics.FillRectangle(Brushes.White, rect);
rect.Inflate(-3, -3);
using (SolidBrush brush = new SolidBrush(SelectedItem))
{
e.Graphics.FillRectangle(brush, rect);
}
if (Focused)
{
rect.Inflate(2, 2);
ControlPaint.DrawFocusRectangle(e.Graphics, rect);
}
else
{
rect.X -= 2;
rect.Y -= 2;
rect.Width += 3;
rect.Height += 3;
e.Graphics.DrawRectangle(Pens.CadetBlue, rect);
}
}
}
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
Invalidate();
}
protected override void OnLostFocus(EventArgs e)
{
base.OnLostFocus(e);
Invalidate();
}
protected override bool ProcessDialogKey(Keys keyData)
{
bool processed = false;
int row = 0;
int col = 0;
GetRowCol(m_selindex, ref row, ref col);
switch (keyData)
{
case Keys.Down:
row++;
processed = true;
break;
case Keys.Up:
row--;
processed = true;
break;
case Keys.Left:
col--;
if (col < 0)
{
col = m_cols-1;
row--;
}
processed = true;
break;
case Keys.Right:
col++;
if (col >= m_cols)
{
col = 0;
row++;
}
processed = true;
break;
}
if (processed)
{
int index = GetIndex(row, col);
if (index != -1)
SetIndex(index);
return false;
}
return base.ProcessDialogKey(keyData);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Security;
using Xunit;
namespace System.Reflection.Tests
{
public class GetCustomAttributes_MemberInfo
{
private static readonly Type s_typeWithoutAttr = typeof(TestClassWithoutAttribute);
private static readonly Type s_typeBaseClass = typeof(TestBaseClass);
private static readonly Type s_typeTestClass = typeof(TestClass);
[Fact]
public void IsDefined_Inherit()
{
Assert.False(CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_Single_Inherited), false));
}
[Fact]
public void IsDefined()
{
Assert.True(CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_Single_M)));
Assert.Throws<ArgumentException>(() =>
{
CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), typeof(String));
});
Assert.Throws<ArgumentNullException>(() =>
{
CustomAttributeExtensions.IsDefined(s_typeTestClass.GetTypeInfo(), null);
});
}
[Fact]
public void GetCustomAttributeOfT_Single_NotInherited()
{
Attribute attribute = CustomAttributeExtensions.GetCustomAttribute<MyAttribute_Single_Inherited>(s_typeTestClass.GetTypeInfo(), false);
Assert.Null(attribute);
}
[Fact]
public void GetCustomAttributeOfT_Single()
{
Attribute attribute = CustomAttributeExtensions.GetCustomAttribute<MyAttribute_Single_Inherited>(s_typeTestClass.GetTypeInfo());
Assert.NotNull(attribute);
Assert.Throws<AmbiguousMatchException>(() =>
{
attribute = CustomAttributeExtensions.GetCustomAttribute<MyAttribute_AllowMultiple_Inherited>(s_typeTestClass.GetTypeInfo());
});
}
[Fact]
public void GetCustomAttributeT_Multiple_NoInheirit()
{
var attributes = CustomAttributeExtensions.GetCustomAttributes<MyAttribute_AllowMultiple_Inherited>(s_typeTestClass.GetTypeInfo(), false);
Assert.Equal(1, attributes.Count());
}
[Fact]
public void GetCustomAttributeOfT_Multiple()
{
IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes<MyAttribute_Single_Inherited>(s_typeTestClass.GetTypeInfo());
Assert.Equal(1, attributes.Count());
attributes = CustomAttributeExtensions.GetCustomAttributes<SecurityCriticalAttribute>(s_typeTestClass.GetTypeInfo());
Assert.Equal(0, attributes.Count());
}
[Fact]
public void GetCustomAttribute_Multiple_NotInherited()
{
var attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited), false);
Assert.NotNull(attribute);
var attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited), false);
Assert.Equal(1, attributes.Count());
}
[Fact]
public void GetCustomAttributeSingle()
{
Attribute attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_Single_M));
Assert.NotNull(attribute);
Assert.Throws<AmbiguousMatchException>(() =>
{
attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited));
});
Assert.Throws<ArgumentException>(() =>
{
attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), typeof(String));
});
Assert.Throws<ArgumentNullException>(() =>
{
attribute = CustomAttributeExtensions.GetCustomAttribute(s_typeTestClass.GetTypeInfo(), null);
});
}
[Fact]
public void GetCustomAttribute4()
{
IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(MyAttribute_AllowMultiple_Inherited));
Assert.Equal(2, attributes.Count());
attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(SecurityCriticalAttribute));
Assert.Equal(0, attributes.Count());
Assert.Throws<ArgumentException>(() =>
{
attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), typeof(String));
});
Assert.Throws<ArgumentNullException>(() =>
{
attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), null);
});
}
[Fact]
public void GetCustomAttribute5()
{
IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), false);
Assert.Equal(4, attributes.Count());
Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_Single_M single", StringComparison.Ordinal)));
Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple1", StringComparison.Ordinal)));
Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple2", StringComparison.Ordinal)));
Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_Inherited multiple", StringComparison.Ordinal)));
}
[Fact]
public void GetCustomAttributeAll()
{
IEnumerable<Attribute> attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeWithoutAttr.GetTypeInfo());
Assert.Equal(0, attributes.Count());
attributes = CustomAttributeExtensions.GetCustomAttributes(s_typeTestClass.GetTypeInfo(), true);
IEnumerator<Attribute> customAttrs = attributes.GetEnumerator();
Assert.Equal(6, attributes.Count());
Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_Single_M single", StringComparison.Ordinal)));
Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple1", StringComparison.Ordinal)));
Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_M multiple2", StringComparison.Ordinal)));
Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_Single_Inherited singleBase", StringComparison.Ordinal)));
Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_Inherited multiple", StringComparison.Ordinal)));
Assert.Equal(1, attributes.Count(attr => attr.ToString().Equals("System.Reflection.Tests.MyAttribute_AllowMultiple_Inherited multipleBase", StringComparison.Ordinal)));
IEnumerable<CustomAttributeData> attributeData = s_typeTestClass.GetTypeInfo().CustomAttributes;
IEnumerator<CustomAttributeData> customAttrsdata = attributeData.GetEnumerator();
Assert.Equal(4, attributeData.Count());
Assert.Equal(3, attributeData.Count(attr => attr.ToString().Contains("MyAttribute_AllowMultiple")));
Assert.Equal(1, attributeData.Count(attr => attr.ToString().Contains("MyAttribute_Single_M")));
}
}
public class MyAttributeBase_M : Attribute
{
private String _name;
public MyAttributeBase_M(String name)
{
_name = name;
}
public override String ToString() { return this.GetType() + " " + _name; }
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
public class MyAttribute_Single_M : MyAttributeBase_M
{
public MyAttribute_Single_M(String name) : base(name) { }
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
public class MyAttribute_AllowMultiple_M : MyAttributeBase_M
{
public MyAttribute_AllowMultiple_M(String name) : base(name) { }
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public class MyAttribute_Single_Inherited : MyAttributeBase_M
{
public MyAttribute_Single_Inherited(String name) : base(name) { }
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class MyAttribute_AllowMultiple_Inherited : MyAttributeBase_M
{
public MyAttribute_AllowMultiple_Inherited(String name) : base(name) { }
}
public class TestClassWithoutAttribute
{
}
[MyAttribute_Single_M("singleBase"),
MyAttribute_AllowMultiple_M("multiple1Base"),
MyAttribute_AllowMultiple_M("multiple2Base"),
MyAttribute_Single_Inherited("singleBase"),
MyAttribute_AllowMultiple_Inherited("multipleBase")]
public class TestBaseClass
{
}
[MyAttribute_Single_M("single"),
MyAttribute_AllowMultiple_M("multiple1"),
MyAttribute_AllowMultiple_M("multiple2"),
MyAttribute_AllowMultiple_Inherited("multiple")]
public class TestClass : TestBaseClass
{
}
}
| |
// 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.Text;
using Microsoft.VisualStudio.Debugger.Interop;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Threading;
using MICore;
using Microsoft.DebugEngineHost;
namespace Microsoft.MIDebugEngine
{
internal class EngineCallback : ISampleEngineCallback, MICore.IDeviceAppLauncherEventCallback
{
private readonly IDebugEventCallback2 _eventCallback;
private readonly AD7Engine _engine;
private int _sentProgramDestroy;
public EngineCallback(AD7Engine engine, IDebugEventCallback2 ad7Callback)
{
_engine = engine;
_eventCallback = HostMarshal.GetThreadSafeEventCallback(ad7Callback);
}
public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugProgram2 program, IDebugThread2 thread)
{
uint attributes;
Guid riidEvent = new Guid(iidEvent);
EngineUtils.RequireOk(eventObject.GetAttributes(out attributes));
EngineUtils.RequireOk(_eventCallback.Event(_engine, null, program, thread, eventObject, ref riidEvent, attributes));
}
public void Send(IDebugEvent2 eventObject, string iidEvent, IDebugThread2 thread)
{
IDebugProgram2 program = _engine;
if (!_engine.ProgramCreateEventSent)
{
// Any events before programe create shouldn't include the program
program = null;
}
Send(eventObject, iidEvent, program, thread);
}
public void OnError(string message)
{
SendMessage(message, OutputMessage.Severity.Error, isAsync: true);
}
/// <summary>
/// Sends an error to the user, blocking until the user dismisses the error
/// </summary>
/// <param name="message">string to display to the user</param>
public void OnErrorImmediate(string message)
{
SendMessage(message, OutputMessage.Severity.Error, isAsync: false);
}
public void OnWarning(string message)
{
SendMessage(message, OutputMessage.Severity.Warning, isAsync: true);
}
public void OnModuleLoad(DebuggedModule debuggedModule)
{
// This will get called when the entrypoint breakpoint is fired because the engine sends a mod-load event
// for the exe.
if (_engine.DebuggedProcess != null)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
}
AD7Module ad7Module = new AD7Module(debuggedModule, _engine.DebuggedProcess);
AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, true /* this is a module load */);
debuggedModule.Client = ad7Module;
// The sample engine does not support binding breakpoints as modules load since the primary exe is the only module
// symbols are loaded for. A production debugger will need to bind breakpoints when a new module is loaded.
Send(eventObject, AD7ModuleLoadEvent.IID, null);
}
public void OnModuleUnload(DebuggedModule debuggedModule)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Module ad7Module = (AD7Module)debuggedModule.Client;
Debug.Assert(ad7Module != null);
AD7ModuleLoadEvent eventObject = new AD7ModuleLoadEvent(ad7Module, false /* this is a module unload */);
Send(eventObject, AD7ModuleLoadEvent.IID, null);
}
public void OnOutputString(string outputString)
{
AD7OutputDebugStringEvent eventObject = new AD7OutputDebugStringEvent(outputString);
Send(eventObject, AD7OutputDebugStringEvent.IID, null);
}
public void OnOutputMessage(OutputMessage outputMessage)
{
try
{
if (outputMessage.ErrorCode == 0)
{
var eventObject = new AD7MessageEvent(outputMessage, isAsync: true);
Send(eventObject, AD7MessageEvent.IID, null);
}
else
{
var eventObject = new AD7ErrorEvent(outputMessage, isAsync: true);
Send(eventObject, AD7ErrorEvent.IID, null);
}
}
catch
{
// Since we are often trying to report an exception, if something goes wrong we don't want to take down the process,
// so ignore the failure.
}
}
public void OnProcessExit(uint exitCode)
{
if (Interlocked.Exchange(ref _sentProgramDestroy, 1) == 0)
{
AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode);
try
{
Send(eventObject, AD7ProgramDestroyEvent.IID, null);
}
catch (InvalidOperationException)
{
// If debugging has already stopped, this can throw
}
}
}
public void OnEntryPoint(DebuggedThread thread)
{
AD7EntryPointEvent eventObject = new AD7EntryPointEvent();
Send(eventObject, AD7EntryPointEvent.IID, (AD7Thread)thread.Client);
}
public void OnThreadExit(DebuggedThread debuggedThread, uint exitCode)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Thread ad7Thread = (AD7Thread)debuggedThread.Client;
Debug.Assert(ad7Thread != null);
AD7ThreadDestroyEvent eventObject = new AD7ThreadDestroyEvent(exitCode);
Send(eventObject, AD7ThreadDestroyEvent.IID, ad7Thread);
}
public void OnThreadStart(DebuggedThread debuggedThread)
{
// This will get called when the entrypoint breakpoint is fired because the engine sends a thread start event
// for the main thread of the application.
if (_engine.DebuggedProcess != null)
{
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
}
AD7ThreadCreateEvent eventObject = new AD7ThreadCreateEvent();
Send(eventObject, AD7ThreadCreateEvent.IID, (IDebugThread2)debuggedThread.Client);
}
public void OnBreakpoint(DebuggedThread thread, ReadOnlyCollection<object> clients)
{
IDebugBoundBreakpoint2[] boundBreakpoints = new IDebugBoundBreakpoint2[clients.Count];
int i = 0;
foreach (object objCurrentBreakpoint in clients)
{
boundBreakpoints[i] = (IDebugBoundBreakpoint2)objCurrentBreakpoint;
i++;
}
// An engine that supports more advanced breakpoint features such as hit counts, conditions and filters
// should notify each bound breakpoint that it has been hit and evaluate conditions here.
// The sample engine does not support these features.
AD7BoundBreakpointsEnum boundBreakpointsEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
AD7BreakpointEvent eventObject = new AD7BreakpointEvent(boundBreakpointsEnum);
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7BreakpointEvent.IID, ad7Thread);
}
// Exception events are sent when an exception occurs in the debuggee that the debugger was not expecting.
public void OnException(DebuggedThread thread, string name, string description, uint code, Guid? exceptionCategory = null, ExceptionBreakpointState state = ExceptionBreakpointState.None)
{
AD7ExceptionEvent eventObject = new AD7ExceptionEvent(name, description, code, exceptionCategory, state);
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7ExceptionEvent.IID, ad7Thread);
}
public void OnExpressionEvaluationComplete(IVariableInformation var, IDebugProperty2 prop = null)
{
AD7ExpressionCompleteEvent eventObject = new AD7ExpressionCompleteEvent(_engine, var, prop);
Send(eventObject, AD7ExpressionCompleteEvent.IID, var.Client);
}
public void OnStepComplete(DebuggedThread thread)
{
// Step complete is sent when a step has finished
AD7StepCompleteEvent eventObject = new AD7StepCompleteEvent();
AD7Thread ad7Thread = (AD7Thread)thread.Client;
Send(eventObject, AD7StepCompleteEvent.IID, ad7Thread);
}
public void OnAsyncBreakComplete(DebuggedThread thread)
{
// This will get called when the engine receives the breakpoint event that is created when the user
// hits the pause button in vs.
Debug.Assert(_engine.DebuggedProcess.WorkerThread.IsPollThread());
AD7Thread ad7Thread = (AD7Thread)thread.Client;
AD7AsyncBreakCompleteEvent eventObject = new AD7AsyncBreakCompleteEvent();
Send(eventObject, AD7AsyncBreakCompleteEvent.IID, ad7Thread);
}
public void OnLoadComplete(DebuggedThread thread)
{
AD7Thread ad7Thread = (AD7Thread)thread.Client;
AD7LoadCompleteEvent eventObject = new AD7LoadCompleteEvent();
Send(eventObject, AD7LoadCompleteEvent.IID, ad7Thread);
}
public void OnProgramDestroy(uint exitCode)
{
AD7ProgramDestroyEvent eventObject = new AD7ProgramDestroyEvent(exitCode);
Send(eventObject, AD7ProgramDestroyEvent.IID, null);
}
// Engines notify the debugger that a breakpoint has bound through the breakpoint bound event.
public void OnBreakpointBound(object objBoundBreakpoint)
{
AD7BoundBreakpoint boundBreakpoint = (AD7BoundBreakpoint)objBoundBreakpoint;
IDebugPendingBreakpoint2 pendingBreakpoint;
((IDebugBoundBreakpoint2)boundBreakpoint).GetPendingBreakpoint(out pendingBreakpoint);
AD7BreakpointBoundEvent eventObject = new AD7BreakpointBoundEvent((AD7PendingBreakpoint)pendingBreakpoint, boundBreakpoint);
Send(eventObject, AD7BreakpointBoundEvent.IID, null);
}
// Engines notify the SDM that a pending breakpoint failed to bind through the breakpoint error event
public void OnBreakpointError(AD7ErrorBreakpoint bperr)
{
AD7BreakpointErrorEvent eventObject = new AD7BreakpointErrorEvent(bperr);
Send(eventObject, AD7BreakpointErrorEvent.IID, null);
}
// Engines notify the SDM that a bound breakpoint change resulted in an error
public void OnBreakpointUnbound(AD7BoundBreakpoint bp, enum_BP_UNBOUND_REASON reason)
{
AD7BreakpointUnboundEvent eventObject = new AD7BreakpointUnboundEvent(bp, reason);
Send(eventObject, AD7BreakpointUnboundEvent.IID, null);
}
public void OnCustomDebugEvent(Guid guidVSService, Guid sourceId, int messageCode, object parameter1, object parameter2)
{
var eventObject = new AD7CustomDebugEvent(guidVSService, sourceId, messageCode, parameter1, parameter2);
Send(eventObject, AD7CustomDebugEvent.IID, null);
}
public void OnStopComplete(DebuggedThread thread)
{
var eventObject = new AD7StopCompleteEvent();
Send(eventObject, AD7StopCompleteEvent.IID, (AD7Thread)thread.Client);
}
private void SendMessage(string message, OutputMessage.Severity severity, bool isAsync)
{
try
{
// IDebugErrorEvent2 is used to report error messages to the user when something goes wrong in the debug engine.
// The sample engine doesn't take advantage of this.
AD7MessageEvent eventObject = new AD7MessageEvent(new OutputMessage(message, enum_MESSAGETYPE.MT_MESSAGEBOX, severity), isAsync);
Send(eventObject, AD7MessageEvent.IID, null);
}
catch
{
// Since we are often trying to report an exception, if something goes wrong we don't want to take down the process,
// so ignore the failure.
}
}
}
}
| |
namespace VRTK
{
using UnityEngine;
using Valve.VR;
public class VRTK_SDK_Bridge : MonoBehaviour
{
private static SteamVR_ControllerManager cachedControllerManager;
private static Transform cachedHeadset;
private static Transform cachedHeadsetCamera;
private static Transform cachedPlayArea;
public static string defaultAttachPointPath = "Model/tip/attach";
public static string defaultTriggerModelPath = "Model/trigger";
public static string defaultGripLeftModelPath = "Model/lgrip";
public static string defaultGripRightModelPath = "Model/rgrip";
public static string defaultTouchpadModelPath = "Model/trackpad";
public static string defaultApplicationMenuModelPath = "Model/button";
public static string defaultSystemModelPath = "Model/sys_button";
public static string defaultBodyModelPath = "Model/body";
public static GameObject GetTrackedObject(GameObject obj, out uint index)
{
var trackedObject = obj.GetComponent<SteamVR_TrackedObject>();
index = 0;
if (trackedObject)
{
index = (uint)trackedObject.index;
return trackedObject.gameObject;
}
return null;
}
public static GameObject GetTrackedObjectByIndex(uint index)
{
//attempt to get from cache first
if (VRTK_ObjectCache.trackedControllers.ContainsKey(index))
{
return VRTK_ObjectCache.trackedControllers[index];
}
//if not found in cache then brute force check
foreach (SteamVR_TrackedObject trackedObject in FindObjectsOfType<SteamVR_TrackedObject>())
{
if ((uint)trackedObject.index == index)
{
return trackedObject.gameObject;
}
}
return null;
}
public static uint GetIndexOfTrackedObject(GameObject trackedObject)
{
uint index = 0;
GetTrackedObject(trackedObject, out index);
return index;
}
public static Transform GetTrackedObjectOrigin(GameObject obj)
{
var trackedObject = obj.GetComponent<SteamVR_TrackedObject>();
if (trackedObject)
{
return trackedObject.origin ? trackedObject.origin : trackedObject.transform.parent;
}
return null;
}
public static bool TrackedIndexIsController(uint index)
{
var system = OpenVR.System;
if (system != null && system.GetTrackedDeviceClass(index) == ETrackedDeviceClass.Controller)
{
return true;
}
return false;
}
public static GameObject GetControllerLeftHand()
{
var controllerManager = GetControllerManager();
if (controllerManager)
{
return controllerManager.left;
}
return null;
}
public static GameObject GetControllerRightHand()
{
var controllerManager = GetControllerManager();
if (controllerManager)
{
return controllerManager.right;
}
return null;
}
public static bool IsControllerLeftHand(GameObject controller)
{
var controllerManager = GetControllerManager();
if (controllerManager && controller == controllerManager.left)
{
return true;
}
return false;
}
public static bool IsControllerRightHand(GameObject controller)
{
var controllerManager = GetControllerManager();
if (controllerManager && controller == controllerManager.right)
{
return true;
}
return false;
}
public static Transform GetHeadset()
{
if (cachedHeadset == null)
{
#if (UNITY_5_4_OR_NEWER)
cachedHeadset = FindObjectOfType<SteamVR_Camera>().transform;
#else
cachedHeadset = FindObjectOfType<SteamVR_GameView>().transform;
#endif
}
return cachedHeadset;
}
public static Transform GetHeadsetCamera()
{
if (cachedHeadsetCamera == null)
{
cachedHeadsetCamera = FindObjectOfType<SteamVR_Camera>().transform;
}
return cachedHeadsetCamera;
}
public static Transform GetPlayArea()
{
if (cachedPlayArea == null)
{
cachedPlayArea = FindObjectOfType<SteamVR_PlayArea>().transform;
}
return cachedPlayArea;
}
public static Vector3[] GetPlayAreaVertices(GameObject playArea)
{
var area = playArea.GetComponent<SteamVR_PlayArea>();
if (area)
{
return area.vertices;
}
return null;
}
public static float GetPlayAreaBorderThickness(GameObject playArea)
{
var area = playArea.GetComponent<SteamVR_PlayArea>();
if (area)
{
return area.borderThickness;
}
return 0f;
}
public static bool IsPlayAreaSizeCalibrated(GameObject playArea)
{
var area = playArea.GetComponent<SteamVR_PlayArea>();
return (area.size == SteamVR_PlayArea.Size.Calibrated);
}
public static bool IsDisplayOnDesktop()
{
return (OpenVR.System == null || OpenVR.System.IsDisplayOnDesktop());
}
public static bool ShouldAppRenderWithLowResources()
{
return (OpenVR.Compositor != null && OpenVR.Compositor.ShouldAppRenderWithLowResources());
}
public static void ForceInterleavedReprojectionOn(bool force)
{
if (OpenVR.Compositor != null)
{
OpenVR.Compositor.ForceInterleavedReprojectionOn(force);
}
}
public static GameObject GetControllerRenderModel(GameObject controller)
{
var renderModel = (controller.GetComponent<SteamVR_RenderModel>() ? controller.GetComponent<SteamVR_RenderModel>() : controller.GetComponentInChildren<SteamVR_RenderModel>());
return renderModel.gameObject;
}
public static void SetControllerRenderModelWheel(GameObject renderModel, bool state)
{
var model = renderModel.GetComponent<SteamVR_RenderModel>();
if (model)
{
model.controllerModeState.bScrollWheelVisible = state;
}
}
public static void HeadsetFade(Color color, float duration, bool fadeOverlay = false)
{
SteamVR_Fade.Start(color, duration, fadeOverlay);
}
public static bool HasHeadsetFade(GameObject obj)
{
if (obj.GetComponentInChildren<SteamVR_Fade>())
{
return true;
}
return false;
}
public static void AddHeadsetFade(Transform camera)
{
if (camera && !camera.gameObject.GetComponent<SteamVR_Fade>())
{
camera.gameObject.AddComponent<SteamVR_Fade>();
}
}
public static void HapticPulseOnIndex(uint index, ushort durationMicroSec = 500)
{
if (index < uint.MaxValue)
{
var device = SteamVR_Controller.Input((int)index);
device.TriggerHapticPulse(durationMicroSec, EVRButtonId.k_EButton_Axis0);
}
}
public static Vector3 GetVelocityOnIndex(uint index)
{
if (index >= uint.MaxValue)
{
return Vector3.zero;
}
var device = SteamVR_Controller.Input((int)index);
return device.velocity;
}
public static Vector3 GetAngularVelocityOnIndex(uint index)
{
if (index >= uint.MaxValue)
{
return Vector3.zero;
}
var device = SteamVR_Controller.Input((int)index);
return device.angularVelocity;
}
public static Vector2 GetTouchpadAxisOnIndex(uint index)
{
if (index >= uint.MaxValue)
{
return Vector2.zero;
}
var device = SteamVR_Controller.Input((int)index);
return device.GetAxis();
}
public static Vector2 GetTriggerAxisOnIndex(uint index)
{
if (index >= uint.MaxValue)
{
return Vector2.zero;
}
var device = SteamVR_Controller.Input((int)index);
return device.GetAxis(EVRButtonId.k_EButton_SteamVR_Trigger);
}
public static float GetTriggerHairlineDeltaOnIndex(uint index)
{
if (index >= uint.MaxValue)
{
return 0f;
}
var device = SteamVR_Controller.Input((int)index);
return device.hairTriggerDelta;
}
//Trigger
public static bool IsTriggerPressedOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.Press, SteamVR_Controller.ButtonMask.Trigger);
}
public static bool IsTriggerPressedDownOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.PressDown, SteamVR_Controller.ButtonMask.Trigger);
}
public static bool IsTriggerPressedUpOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.PressUp, SteamVR_Controller.ButtonMask.Trigger);
}
public static bool IsTriggerTouchedOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.Touch, SteamVR_Controller.ButtonMask.Trigger);
}
public static bool IsTriggerTouchedDownOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.TouchDown, SteamVR_Controller.ButtonMask.Trigger);
}
public static bool IsTriggerTouchedUpOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.TouchUp, SteamVR_Controller.ButtonMask.Trigger);
}
public static bool IsHairTriggerDownOnIndex(uint index)
{
if (index >= uint.MaxValue)
{
return false;
}
var device = SteamVR_Controller.Input((int)index);
return device.GetHairTriggerDown();
}
public static bool IsHairTriggerUpOnIndex(uint index)
{
if (index >= uint.MaxValue)
{
return false;
}
var device = SteamVR_Controller.Input((int)index);
return device.GetHairTriggerUp();
}
//Grip
public static bool IsGripPressedOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.Press, SteamVR_Controller.ButtonMask.Grip);
}
public static bool IsGripPressedDownOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.PressDown, SteamVR_Controller.ButtonMask.Grip);
}
public static bool IsGripPressedUpOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.PressUp, SteamVR_Controller.ButtonMask.Grip);
}
public static bool IsGripTouchedOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.Touch, SteamVR_Controller.ButtonMask.Grip);
}
public static bool IsGripTouchedDownOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.TouchDown, SteamVR_Controller.ButtonMask.Grip);
}
public static bool IsGripTouchedUpOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.TouchUp, SteamVR_Controller.ButtonMask.Grip);
}
//Touchpad
public static bool IsTouchpadPressedOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.Press, SteamVR_Controller.ButtonMask.Touchpad);
}
public static bool IsTouchpadPressedDownOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.PressDown, SteamVR_Controller.ButtonMask.Touchpad);
}
public static bool IsTouchpadPressedUpOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.PressUp, SteamVR_Controller.ButtonMask.Touchpad);
}
public static bool IsTouchpadTouchedOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.Touch, SteamVR_Controller.ButtonMask.Touchpad);
}
public static bool IsTouchpadTouchedDownOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.TouchDown, SteamVR_Controller.ButtonMask.Touchpad);
}
public static bool IsTouchpadTouchedUpOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.TouchUp, SteamVR_Controller.ButtonMask.Touchpad);
}
//Application Menu
public static bool IsApplicationMenuPressedOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.Press, SteamVR_Controller.ButtonMask.ApplicationMenu);
}
public static bool IsApplicationMenuPressedDownOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.PressDown, SteamVR_Controller.ButtonMask.ApplicationMenu);
}
public static bool IsApplicationMenuPressedUpOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.PressUp, SteamVR_Controller.ButtonMask.ApplicationMenu);
}
public static bool IsApplicationMenuTouchedOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.Touch, SteamVR_Controller.ButtonMask.ApplicationMenu);
}
public static bool IsApplicationMenuTouchedDownOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.TouchDown, SteamVR_Controller.ButtonMask.ApplicationMenu);
}
public static bool IsApplicationMenuTouchedUpOnIndex(uint index)
{
return IsButtonPressed(index, ButtonPressTypes.TouchUp, SteamVR_Controller.ButtonMask.ApplicationMenu);
}
private static SteamVR_ControllerManager GetControllerManager()
{
if (cachedControllerManager == null)
{
cachedControllerManager = FindObjectOfType<SteamVR_ControllerManager>();
}
return cachedControllerManager;
}
private enum ButtonPressTypes
{
Press,
PressDown,
PressUp,
Touch,
TouchDown,
TouchUp
}
private static bool IsButtonPressed(uint index, ButtonPressTypes type, ulong button)
{
if (index >= uint.MaxValue)
{
return false;
}
var device = SteamVR_Controller.Input((int)index);
switch (type)
{
case ButtonPressTypes.Press:
return device.GetPress(button);
case ButtonPressTypes.PressDown:
return device.GetPressDown(button);
case ButtonPressTypes.PressUp:
return device.GetPressUp(button);
case ButtonPressTypes.Touch:
return device.GetTouch(button);
case ButtonPressTypes.TouchDown:
return device.GetTouchDown(button);
case ButtonPressTypes.TouchUp:
return device.GetTouchUp(button);
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
public sealed class DataContractSerializer : XmlObjectSerializer
{
private Type _rootType;
private DataContract _rootContract; // post-surrogate
private bool _needsContractNsAtRoot;
private XmlDictionaryString _rootName;
private XmlDictionaryString _rootNamespace;
private int _maxItemsInObjectGraph;
private bool _ignoreExtensionDataObject;
private bool _preserveObjectReferences;
private ReadOnlyCollection<Type> _knownTypeCollection;
internal IList<Type> knownTypeList;
internal DataContractDictionary knownDataContracts;
private DataContractResolver _dataContractResolver;
private ISerializationSurrogateProvider _serializationSurrogateProvider;
private bool _serializeReadOnlyTypes;
private static SerializationOption _option = IsReflectionBackupAllowed() ? SerializationOption.ReflectionAsBackup : SerializationOption.CodeGenOnly;
private static bool _optionAlreadySet;
internal static SerializationOption Option
{
get { return _option; }
set
{
if (_optionAlreadySet)
{
throw new InvalidOperationException("Can only set once");
}
_optionAlreadySet = true;
_option = value;
}
}
#if uapaot
[RemovableFeature(ReflectionBasedSerializationFeature.Name, UseNopBody = true)]
#endif
private static bool IsReflectionBackupAllowed()
{
// The RemovableFeature annotation above is going to replace this with
// "return false" if reflection based serialization feature was removed
// at publishing time.
return true;
}
public DataContractSerializer(Type type)
: this(type, (IEnumerable<Type>)null)
{
}
public DataContractSerializer(Type type, IEnumerable<Type> knownTypes)
{
Initialize(type, knownTypes, int.MaxValue, false, false, null, false);
}
public DataContractSerializer(Type type, string rootName, string rootNamespace)
: this(type, rootName, rootNamespace, null)
{
}
public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable<Type> knownTypes)
{
XmlDictionary dictionary = new XmlDictionary(2);
Initialize(type, dictionary.Add(rootName), dictionary.Add(DataContract.GetNamespace(rootNamespace)), knownTypes, int.MaxValue, false, false, null, false);
}
public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace)
: this(type, rootName, rootNamespace, null)
{
}
public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes)
{
Initialize(type, rootName, rootNamespace, knownTypes, int.MaxValue, false, false, null, false);
}
#if uapaot
public DataContractSerializer(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences)
#else
internal DataContractSerializer(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences)
#endif
{
Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, null, false);
}
public DataContractSerializer(Type type, DataContractSerializerSettings settings)
{
if (settings == null)
{
settings = new DataContractSerializerSettings();
}
Initialize(type, settings.RootName, settings.RootNamespace, settings.KnownTypes, settings.MaxItemsInObjectGraph, false,
settings.PreserveObjectReferences, settings.DataContractResolver, settings.SerializeReadOnlyTypes);
}
private void Initialize(Type type,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
DataContractResolver dataContractResolver,
bool serializeReadOnlyTypes)
{
CheckNull(type, nameof(type));
_rootType = type;
if (knownTypes != null)
{
this.knownTypeList = new List<Type>();
foreach (Type knownType in knownTypes)
{
this.knownTypeList.Add(knownType);
}
}
if (maxItemsInObjectGraph < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(maxItemsInObjectGraph), SR.ValueMustBeNonNegative));
_maxItemsInObjectGraph = maxItemsInObjectGraph;
_ignoreExtensionDataObject = ignoreExtensionDataObject;
_preserveObjectReferences = preserveObjectReferences;
_dataContractResolver = dataContractResolver;
_serializeReadOnlyTypes = serializeReadOnlyTypes;
}
private void Initialize(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
DataContractResolver dataContractResolver,
bool serializeReadOnlyTypes)
{
Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractResolver, serializeReadOnlyTypes);
// validate root name and namespace are both non-null
_rootName = rootName;
_rootNamespace = rootNamespace;
}
public ReadOnlyCollection<Type> KnownTypes
{
get
{
if (_knownTypeCollection == null)
{
if (knownTypeList != null)
{
_knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList);
}
else
{
_knownTypeCollection = new ReadOnlyCollection<Type>(Array.Empty<Type>());
}
}
return _knownTypeCollection;
}
}
internal override DataContractDictionary KnownDataContracts
{
get
{
if (this.knownDataContracts == null && this.knownTypeList != null)
{
// This assignment may be performed concurrently and thus is a race condition.
// It's safe, however, because at worse a new (and identical) dictionary of
// data contracts will be created and re-assigned to this field. Introduction
// of a lock here could lead to deadlocks.
this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList);
}
return this.knownDataContracts;
}
}
public int MaxItemsInObjectGraph
{
get { return _maxItemsInObjectGraph; }
}
internal ISerializationSurrogateProvider SerializationSurrogateProvider
{
get { return _serializationSurrogateProvider; }
set { _serializationSurrogateProvider = value; }
}
public bool PreserveObjectReferences
{
get { return _preserveObjectReferences; }
}
public bool IgnoreExtensionDataObject
{
get { return _ignoreExtensionDataObject; }
}
public DataContractResolver DataContractResolver
{
get { return _dataContractResolver; }
}
public bool SerializeReadOnlyTypes
{
get { return _serializeReadOnlyTypes; }
}
private DataContract RootContract
{
get
{
if (_rootContract == null)
{
_rootContract = DataContract.GetDataContract((_serializationSurrogateProvider == null) ? _rootType : GetSurrogatedType(_serializationSurrogateProvider, _rootType));
_needsContractNsAtRoot = CheckIfNeedsContractNsAtRoot(_rootName, _rootNamespace, _rootContract);
}
return _rootContract;
}
}
internal override void InternalWriteObject(XmlWriterDelegator writer, object graph)
{
InternalWriteObject(writer, graph, null);
}
internal override void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
{
InternalWriteStartObject(writer, graph);
InternalWriteObjectContent(writer, graph, dataContractResolver);
InternalWriteEndObject(writer);
}
public override void WriteObject(XmlWriter writer, object graph)
{
WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteStartObject(XmlWriter writer, object graph)
{
WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteObjectContent(XmlWriter writer, object graph)
{
WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteEndObject(XmlWriter writer)
{
WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer));
}
public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
{
WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
{
WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteEndObject(XmlDictionaryWriter writer)
{
WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer));
}
public void WriteObject(XmlDictionaryWriter writer, object graph, DataContractResolver dataContractResolver)
{
WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph, dataContractResolver);
}
public override object ReadObject(XmlReader reader)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/);
}
public override object ReadObject(XmlReader reader, bool verifyObjectName)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName);
}
public override bool IsStartObject(XmlReader reader)
{
return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader));
}
public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName);
}
public override bool IsStartObject(XmlDictionaryReader reader)
{
return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader));
}
public object ReadObject(XmlDictionaryReader reader, bool verifyObjectName, DataContractResolver dataContractResolver)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName, dataContractResolver);
}
internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph)
{
WriteRootElement(writer, RootContract, _rootName, _rootNamespace, _needsContractNsAtRoot);
}
internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph)
{
InternalWriteObjectContent(writer, graph, null);
}
internal void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
{
if (MaxItemsInObjectGraph == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
DataContract contract = RootContract;
Type declaredType = contract.UnderlyingType;
Type graphType = (graph == null) ? declaredType : graph.GetType();
if (_serializationSurrogateProvider != null)
{
graph = SurrogateToDataContractType(_serializationSurrogateProvider, graph, declaredType, ref graphType);
}
if (dataContractResolver == null)
dataContractResolver = this.DataContractResolver;
if (graph == null)
{
if (IsRootXmlAny(_rootName, contract))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeNull, declaredType)));
WriteNull(writer);
}
else
{
if (declaredType == graphType)
{
if (contract.CanContainReferences)
{
XmlObjectSerializerWriteContext context = XmlObjectSerializerWriteContext.CreateContext(this, contract
, dataContractResolver
);
context.HandleGraphAtTopLevel(writer, graph, contract);
context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
}
else
{
contract.WriteXmlValue(writer, graph, null);
}
}
else
{
XmlObjectSerializerWriteContext context = null;
if (IsRootXmlAny(_rootName, contract))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeSerializedAsDerivedType, graphType, contract.UnderlyingType)));
contract = GetDataContract(contract, declaredType, graphType);
context = XmlObjectSerializerWriteContext.CreateContext(this, RootContract
, dataContractResolver
);
if (contract.CanContainReferences)
{
context.HandleGraphAtTopLevel(writer, graph, contract);
}
context.OnHandleIsReference(writer, contract, graph);
context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType);
}
}
}
internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType)
{
if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
return declaredTypeContract;
}
else if (declaredType.IsArray)//Array covariance is not supported in XSD
{
return declaredTypeContract;
}
else
{
return DataContract.GetDataContract(objectType.TypeHandle, objectType, SerializationMode.SharedContract);
}
}
internal override void InternalWriteEndObject(XmlWriterDelegator writer)
{
if (!IsRootXmlAny(_rootName, RootContract))
{
writer.WriteEndElement();
}
}
internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName)
{
return InternalReadObject(xmlReader, verifyObjectName, null);
}
internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName, DataContractResolver dataContractResolver)
{
if (MaxItemsInObjectGraph == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
if (dataContractResolver == null)
dataContractResolver = this.DataContractResolver;
#if uapaot
// Give the root contract a chance to initialize or pre-verify the read
RootContract.PrepareToRead(xmlReader);
#endif
if (verifyObjectName)
{
if (!InternalIsStartObject(xmlReader))
{
XmlDictionaryString expectedName;
XmlDictionaryString expectedNs;
if (_rootName == null)
{
expectedName = RootContract.TopLevelElementName;
expectedNs = RootContract.TopLevelElementNamespace;
}
else
{
expectedName = _rootName;
expectedNs = _rootNamespace;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElement, expectedNs, expectedName), xmlReader));
}
}
else if (!IsStartElement(xmlReader))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingElementAtDeserialize, XmlNodeType.Element), xmlReader));
}
DataContract contract = RootContract;
if (contract.IsPrimitive && object.ReferenceEquals(contract.UnderlyingType, _rootType) /*handle Nullable<T> differently*/)
{
return contract.ReadXmlValue(xmlReader, null);
}
if (IsRootXmlAny(_rootName, contract))
{
return XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, contract as XmlDataContract, false /*isMemberType*/);
}
XmlObjectSerializerReadContext context = XmlObjectSerializerReadContext.CreateContext(this, contract, dataContractResolver);
return context.InternalDeserialize(xmlReader, _rootType, contract, null, null);
}
internal override bool InternalIsStartObject(XmlReaderDelegator reader)
{
return IsRootElement(reader, RootContract, _rootName, _rootNamespace);
}
internal override Type GetSerializeType(object graph)
{
return (graph == null) ? _rootType : graph.GetType();
}
internal override Type GetDeserializeType()
{
return _rootType;
}
internal static object SurrogateToDataContractType(ISerializationSurrogateProvider serializationSurrogateProvider, object oldObj, Type surrogatedDeclaredType, ref Type objType)
{
object obj = DataContractSurrogateCaller.GetObjectToSerialize(serializationSurrogateProvider, oldObj, objType, surrogatedDeclaredType);
if (obj != oldObj)
{
objType = obj != null ? obj.GetType() : Globals.TypeOfObject;
}
return obj;
}
internal static Type GetSurrogatedType(ISerializationSurrogateProvider serializationSurrogateProvider, Type type)
{
return DataContractSurrogateCaller.GetDataContractType(serializationSurrogateProvider, DataContract.UnwrapNullableType(type));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization
{
/// <summary>
/// This class implements the Julian calendar. In 48 B.C. Julius Caesar
/// ordered a calendar reform, and this calendar is called Julian calendar.
/// It consisted of a solar year of twelve months and of 365 days with an
/// extra day every fourth year.
/// </summary>
/// <remarks>
/// Calendar support range:
/// Calendar Minimum Maximum
/// ========== ========== ==========
/// Gregorian 0001/01/01 9999/12/31
/// Julia 0001/01/03 9999/10/19
/// </remarks>
public class JulianCalendar : Calendar
{
public static readonly int JulianEra = 1;
private const int DatePartYear = 0;
private const int DatePartDayOfYear = 1;
private const int DatePartMonth = 2;
private const int DatePartDay = 3;
// Number of days in a non-leap year
private const int JulianDaysPerYear = 365;
// Number of days in 4 years
private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1;
private static readonly int[] s_daysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
private static readonly int[] s_daysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
// Gregorian Calendar 9999/12/31 = Julian Calendar 9999/10/19
// keep it as variable field for serialization compat.
internal int MaxYear = 9999;
public override DateTime MinSupportedDateTime => DateTime.MinValue;
public override DateTime MaxSupportedDateTime => DateTime.MaxValue;
public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar;
public JulianCalendar()
{
// There is no system setting of TwoDigitYear max, so set the value here.
_twoDigitYearMax = 2029;
}
internal override CalendarId ID => CalendarId.JULIAN;
internal static void CheckEraRange(int era)
{
if (era != CurrentEra && era != JulianEra)
{
throw new ArgumentOutOfRangeException(nameof(era), era, SR.ArgumentOutOfRange_InvalidEraValue);
}
}
internal void CheckYearEraRange(int year, int era)
{
CheckEraRange(era);
if (year <= 0 || year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
year,
SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
}
internal static void CheckMonthRange(int month)
{
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException(nameof(month), month, SR.ArgumentOutOfRange_Month);
}
}
/// <summary>
/// Check for if the day value is valid.
/// </summary>
/// <remarks>
/// Before calling this method, call CheckYearEraRange()/CheckMonthRange() to make
/// sure year/month values are correct.
/// </remarks>
internal static void CheckDayRange(int year, int month, int day)
{
if (year == 1 && month == 1)
{
// The minimum supported Julia date is Julian 0001/01/03.
if (day < 3)
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
bool isLeapYear = (year % 4) == 0;
int[] days = isLeapYear ? s_daysToMonth366 : s_daysToMonth365;
int monthDays = days[month] - days[month - 1];
if (day < 1 || day > monthDays)
{
throw new ArgumentOutOfRangeException(
nameof(day),
day,
SR.Format(SR.ArgumentOutOfRange_Range, 1, monthDays));
}
}
/// <summary>
/// Returns a given date part of this DateTime. This method is used
/// to compute the year, day-of-year, month, or day part.
/// </summary>
internal static int GetDatePart(long ticks, int part)
{
// Gregorian 1/1/0001 is Julian 1/3/0001. Remember DateTime(0) is refered to Gregorian 1/1/0001.
// The following line convert Gregorian ticks to Julian ticks.
long julianTicks = ticks + TicksPerDay * 2;
// n = number of days since 1/1/0001
int n = (int)(julianTicks / TicksPerDay);
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / JulianDaysPer4Years;
// n = day number within 4-year period
n -= y4 * JulianDaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / JulianDaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return y4 * 4 + y1 + 1;
}
// n = day number within year
n -= y1 * JulianDaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return n + 1;
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3);
int[] days = leapYear ? s_daysToMonth366 : s_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++;
}
// If month was requested, return it
if (part == DatePartMonth)
{
return m;
}
// Return 1-based day-of-month
return n - days[m - 1] + 1;
}
/// <summary>
/// Returns the tick count corresponding to the given year, month, and day.
/// </summary>
internal static long DateToTicks(int year, int month, int day)
{
int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365;
int y = year - 1;
int n = y * 365 + y / 4 + days[month - 1] + day - 1;
// Gregorian 1/1/0001 is Julian 1/3/0001. n * TicksPerDay is the ticks in JulianCalendar.
// Therefore, we subtract two days in the following to convert the ticks in JulianCalendar
// to ticks in Gregorian calendar.
return (n - 2) * TicksPerDay;
}
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000)
{
throw new ArgumentOutOfRangeException(
nameof(months),
months,
SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000));
}
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? s_daysToMonth366 : s_daysToMonth365;
int days = daysArray[m] - daysArray[m - 1];
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return new DateTime(ticks);
}
public override DateTime AddYears(DateTime time, int years)
{
return AddMonths(time, years * 12);
}
public override int GetDayOfMonth(DateTime time)
{
return GetDatePart(time.Ticks, DatePartDay);
}
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return (DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7);
}
public override int GetDayOfYear(DateTime time)
{
return GetDatePart(time.Ticks, DatePartDayOfYear);
}
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
int[] days = (year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365;
return days[month] - days[month - 1];
}
public override int GetDaysInYear(int year, int era)
{
// Year/Era range is done in IsLeapYear().
return IsLeapYear(year, era) ? 366 : 365;
}
public override int GetEra(DateTime time) => JulianEra;
public override int GetMonth(DateTime time)
{
return GetDatePart(time.Ticks, DatePartMonth);
}
public override int[] Eras => new int[] { JulianEra };
public override int GetMonthsInYear(int year, int era)
{
CheckYearEraRange(year, era);
return 12;
}
public override int GetYear(DateTime time)
{
return GetDatePart(time.Ticks, DatePartYear);
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
CheckMonthRange(month);
// Year/Era range check is done in IsLeapYear().
if (IsLeapYear(year, era))
{
CheckDayRange(year, month, day);
return month == 2 && day == 29;
}
CheckDayRange(year, month, day);
return false;
}
public override int GetLeapMonth(int year, int era)
{
CheckYearEraRange(year, era);
return 0;
}
public override bool IsLeapMonth(int year, int month, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
return false;
}
public override bool IsLeapYear(int year, int era)
{
CheckYearEraRange(year, era);
return (year % 4 == 0);
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
CheckYearEraRange(year, era);
CheckMonthRange(month);
CheckDayRange(year, month, day);
if (millisecond < 0 || millisecond >= MillisPerSecond)
{
throw new ArgumentOutOfRangeException(
nameof(millisecond),
millisecond,
SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1));
}
if (hour < 0 || hour >= 24 || minute < 0 || minute >= 60 || second < 0 || second >= 60)
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks);
}
public override int TwoDigitYearMax
{
get => _twoDigitYearMax;
set
{
VerifyWritable();
if (value < 99 || value > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(value),
value,
SR.Format(SR.ArgumentOutOfRange_Range, 99, MaxYear));
}
_twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException(nameof(year), year, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (year > MaxYear)
{
throw new ArgumentOutOfRangeException(
nameof(year),
year,
SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, MaxYear));
}
return base.ToFourDigitYear(year);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ActionButton.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TQVaultAE.GUI
{
using Properties;
using System;
using System.Drawing;
using System.Globalization;
using System.Timers;
using System.Windows.Forms;
using TQVaultData;
/// <summary>
/// Class for displaying the action panel which has the animation of
/// removing a relic from an item or splitting a stack.
/// </summary>
public class ActionButton : Panel
{
/// <summary>
/// Bitmap for left door
/// </summary>
private Bitmap leftDoor;
/// <summary>
/// Bitmap for right door
/// </summary>
private Bitmap rightDoor;
/// <summary>
/// DragInfo for current dragged item
/// </summary>
private ItemDragInfo dragInfo;
/// <summary>
/// Brush for the normal background
/// </summary>
private Brush normalBackground;
/// <summary>
/// Brush for the active background
/// </summary>
private Brush activeBackground;
/// <summary>
/// Brush for the background flash
/// </summary>
private Brush flashBackground;
/// <summary>
/// Font for displaying quantity
/// </summary>
private Font numberFont;
/// <summary>
/// Brush for numbers
/// </summary>
private Brush numberBrush;
/// <summary>
/// Format for numbers
/// </summary>
private StringFormat numberFormat;
/// <summary>
/// Location of the dragged item
/// </summary>
private Point dragLocation;
/// <summary>
/// Bool for determining if the animation is active.
/// </summary>
private bool isActive;
/// <summary>
/// Flag for paint completion.
/// </summary>
private bool havePaintedOnce;
/// <summary>
/// Animation timer
/// </summary>
private System.Timers.Timer timer;
/// <summary>
/// The current tick
/// </summary>
private int tick;
/// <summary>
/// Door animation maximum position
/// </summary>
private int maxDoorPositions;
/// <summary>
/// Door animation current position.
/// 0 == closed, maxDoorPositions-1 == open
/// </summary>
private int doorPosition;
/// <summary>
/// stack animation - number of ticks to move the stack to the center
/// </summary>
private int stackTicksToCenter;
/// <summary>
/// stack animation - number of ticks to flash
/// </summary>
private int stackFlashTicks;
/// <summary>
/// stack animation - number of ticks to move the 2 items out
/// </summary>
private int stackSplitTicks;
/// <summary>
/// stack animation - number of ticks to pause before repeat.
/// </summary>
private int stackPauseTicks;
/// <summary>
/// Initializes a new instance of the ActionButton class.
/// </summary>
/// <param name="width">Width of the panel</param>
/// <param name="height">Height of the panel</param>
/// <param name="dragInfo">Info for dragged item</param>
public ActionButton(int width, int height, ItemDragInfo dragInfo)
{
this.dragInfo = dragInfo;
this.dragLocation.X = -1;
this.dragLocation.Y = -1;
Width = width;
Height = height;
this.CreateDoors();
this.CreateBrushes();
this.InitializeAnimationParams();
this.InitializeTimer();
BackColor = ((SolidBrush)this.normalBackground).Color;
// set up event handlers
this.Paint += new PaintEventHandler(this.PaintCallback);
this.MouseMove += new MouseEventHandler(this.MouseMoveCallback);
this.MouseLeave += new EventHandler(this.MouseLeaveCallback);
this.MouseEnter += new EventHandler(this.MouseEnterCallback);
this.MouseDown += new MouseEventHandler(this.MouseDownCallback);
// Da_FileServer: Some small paint optimizations.
this.SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
}
/// <summary>
/// Gets a value indicating whether the doors are closed.
/// </summary>
public bool AreDoorsClosed
{
get
{
return this.doorPosition == 0;
}
}
/// <summary>
/// Gets a value indicating whether the doors are fully open
/// </summary>
public bool AreDoorsFullyOpen
{
get
{
return this.doorPosition == (this.maxDoorPositions - 1);
}
}
/// <summary>
/// Gets a value indicating whether a stack is being dragged
/// </summary>
public bool IsStackBeingDragged
{
get
{
return this.dragInfo.IsActive && this.dragInfo.CanBeModified && this.dragInfo.Item.DoesStack && this.dragInfo.Item.Number > 1;
}
}
/// <summary>
/// Gets a value indicating whether an item with a relic is being dragged
/// </summary>
public bool IsItemWithRelicBeingDragged
{
get
{
return this.dragInfo.IsActive && this.dragInfo.CanBeModified && this.dragInfo.Item.HasRelic;
}
}
/// <summary>
/// Gets the total stack animation ticks
/// </summary>
public int StackTotalAnimationTicks
{
get
{
return this.stackTicksToCenter + this.stackFlashTicks + this.stackSplitTicks + this.stackPauseTicks;
}
}
/// <summary>
/// Handler for mouse button clicks
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">MouseEventArgs data</param>
private void MouseDownCallback(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (this.IsStackBeingDragged)
{
this.SplitStack();
}
else if (this.IsItemWithRelicBeingDragged)
{
this.SplitItemAndRelic();
}
}
else if (e.Button == MouseButtons.Right)
{
if (this.dragInfo.IsActive && this.dragInfo.CanBeCanceled)
{
this.dragInfo.Cancel();
// Now redraw ourselves
Refresh();
}
}
}
/// <summary>
/// Splits a stack
/// </summary>
private void SplitStack()
{
if (this.dragInfo.IsModifiedItem)
{
// we have already been splitting this stack.
// Here is what we do:
// just increment the original stackSize and decrement the dragItem stackSize
this.dragInfo.Original.Item.StackSize++;
this.dragInfo.Item.StackSize--;
this.dragInfo.MarkModified(this.dragInfo.Item);
}
else
{
// We need to pop all but one item off the stack as a new item.
Item newStack = this.dragInfo.Item.PopAllButOneItem();
this.dragInfo.MarkModified(newStack);
}
Refresh();
}
/// <summary>
/// Removes a relic from the item
/// </summary>
private void SplitItemAndRelic()
{
// pull out the relic
Item relic = this.dragInfo.Item.RemoveRelic();
this.dragInfo.MarkModified(relic);
Refresh();
}
/// <summary>
/// Handler for mouse pointer leaving the action button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void MouseLeaveCallback(object sender, EventArgs e)
{
this.isActive = false;
BackColor = ((SolidBrush)this.normalBackground).Color;
this.dragLocation.X = -1;
this.dragLocation.Y = -1;
if (this.dragInfo.IsActive)
{
Refresh();
}
}
/// <summary>
/// Handler for mouse entering the action button.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
private void MouseEnterCallback(object sender, EventArgs e)
{
this.isActive = true;
BackColor = ((SolidBrush)this.activeBackground).Color;
if (this.dragInfo.IsActive)
{
Refresh();
}
}
/// <summary>
/// Handler for mouse moving within the action button.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">MouseEventArgs data</param>
private void MouseMoveCallback(object sender, MouseEventArgs e)
{
this.dragLocation = new Point(e.X, e.Y);
if (this.dragInfo.IsActive)
{
Refresh();
}
}
/// <summary>
/// Creates the brushes for drawing the background and numbers
/// </summary>
private void CreateBrushes()
{
this.normalBackground = new SolidBrush(Color.Black);
this.activeBackground = new SolidBrush(Color.FromArgb(23, 149, 15));
this.flashBackground = new SolidBrush(Color.White);
this.numberFont = new Font("Arial", 10F * Database.DB.Scale, GraphicsUnit.Pixel);
this.numberBrush = new SolidBrush(Color.White);
this.numberFormat = new StringFormat();
this.numberFormat.Alignment = StringAlignment.Far; // right-justify
this.isActive = false;
}
/// <summary>
/// Initializes the animation timer.
/// </summary>
private void InitializeTimer()
{
this.timer = new System.Timers.Timer();
((System.ComponentModel.ISupportInitialize)this.timer).BeginInit();
this.timer.Interval = 100; // 10x per second
this.timer.Enabled = true;
this.timer.SynchronizingObject = this;
this.timer.Elapsed += new ElapsedEventHandler(this.AnimationTick);
((System.ComponentModel.ISupportInitialize)this.timer).EndInit();
}
/// <summary>
/// Initalizes the animation parameters.
/// </summary>
private void InitializeAnimationParams()
{
this.maxDoorPositions = 10;
this.doorPosition = 0;
this.havePaintedOnce = false;
this.tick = 0;
this.stackTicksToCenter = 10; // 1 second to get to center
this.stackFlashTicks = 1; // 1/10ths of a second
this.stackSplitTicks = 10; // move 2 stacks out for 1s
this.stackPauseTicks = 5;
}
/// <summary>
/// Creates the doors
/// Loads the door bitmaps from the resources.
/// </summary>
private void CreateDoors()
{
// Take the medallion bitmap and split it in twain
Bitmap medallion = Resources.tqmedalliondoor;
RectangleF rect = new RectangleF(0.0F, 0.0F, (float)medallion.Width / 2.0F, (float)medallion.Height);
this.leftDoor = medallion.Clone(rect, medallion.PixelFormat);
rect.X = rect.Width;
this.rightDoor = medallion.Clone(rect, medallion.PixelFormat);
}
/// <summary>
/// Animation tick handler.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">ElapsedEventArgs data</param>
private void AnimationTick(object sender, ElapsedEventArgs e)
{
++this.tick;
if (!this.havePaintedOnce)
{
return;
}
// see if something is being dragged
if ((!this.IsStackBeingDragged && !this.IsItemWithRelicBeingDragged) || !this.dragInfo.CanBeModified)
{
// just close the doors if necessary
if (!this.AreDoorsClosed)
{
this.doorPosition--;
if (this.isActive)
{
this.isActive = false; // we cannot be active if we have no good drag item
BackColor = ((SolidBrush)this.normalBackground).Color;
}
Refresh();
}
else if (this.isActive)
{
this.isActive = false;
BackColor = ((SolidBrush)this.normalBackground).Color;
Refresh();
}
return; // nothing else to do.
}
// okay something is being dragged. open the doors
if (!this.AreDoorsFullyOpen)
{
this.doorPosition++;
}
// now redraw
Refresh();
}
/// <summary>
/// Draws the dragged item
/// </summary>
/// <param name="g">graphics instance</param>
/// <param name="item">item bitmap</param>
/// <param name="x">x location</param>
/// <param name="y">y location</param>
/// <param name="scale">item scale</param>
/// <param name="quantity">item quantity for stacks</param>
/// <param name="drawRelic">if item has a relic</param>
private void DrawItem(Graphics g, Bitmap item, float x, float y, float scale, int quantity, bool drawRelic)
{
// first draw the base item
g.DrawImage(item, x, y, item.Width * scale, item.Height * scale);
// Add the relic overlay if this item has a relic in it.
if (drawRelic)
{
Bitmap overlay = Database.DB.LoadRelicOverlayBitmap();
if (overlay != null)
{
// draw it in the bottom-right most cell of this item
float rx = x + ((item.Width - Database.DB.ItemUnitSize) * scale);
float ry = y + ((item.Height - Database.DB.ItemUnitSize) * scale);
g.DrawImage(overlay, rx, ry, overlay.Width * scale, overlay.Height * scale);
}
}
// Add any number we need to add.
if (quantity > 0)
{
string numberString = quantity.ToString(CultureInfo.CurrentCulture);
// Draw the number along the bottom of the item
float nx = x;
float ny = y + (Database.DB.ItemUnitSize * scale);
float height = (float)this.numberFont.Height;
float width = (float)Database.DB.ItemUnitSize * scale;
float yy = (float)(ny - (0.75 * this.numberFont.Height) - 1);
float xx = (float)nx;
RectangleF rect = new RectangleF(xx, yy, width, height);
g.DrawString(numberString, this.numberFont, this.numberBrush, rect, this.numberFormat);
}
}
/// <summary>
/// Draws the floating stack animation
/// </summary>
/// <param name="g">graphics instance</param>
private void DrawStackTick(Graphics g)
{
int tickNum = this.tick % this.StackTotalAnimationTicks;
int prevTick = 0;
int tickTotal = this.stackTicksToCenter;
if (tickNum < tickTotal)
{
Item item = this.dragInfo.Item;
// draw the single item moving towards the center
float scale = Database.DB.Scale;
// Figure out its offset
float pctComplete = (float)(tickNum - prevTick) / (float)(tickTotal - prevTick - 1);
// linear interpolate between off-screen and center
float xloc = ((1 - pctComplete) * (-1 * item.ItemBitmap.Width * scale)) + (pctComplete * ((Width / 2.0F) - (scale * item.ItemBitmap.Width / 2.0F)));
float yloc = ((1 - pctComplete) * (Height / 4.0F)) + (pctComplete * (Height / 2.0F));
yloc -= scale * item.ItemBitmap.Height / 2.0F;
// now draw it
this.DrawItem(g, item.ItemBitmap, xloc, yloc, scale, item.Number, false);
return;
}
prevTick = tickTotal;
tickTotal += this.stackFlashTicks;
if (tickNum < tickTotal)
{
// draw the flash
g.FillRectangle(this.flashBackground, 0, 0, Width, Height);
return;
}
prevTick = tickTotal;
tickTotal += this.stackSplitTicks;
if (tickNum < tickTotal)
{
// draw the split stack -- all but 1 going up and 1 going down
Item item = this.dragInfo.Item;
float scale = Database.DB.Scale;
// Figure out its offset
float pctComplete = (float)(tickNum - prevTick) / (float)(tickTotal - prevTick - 1);
float offset = pctComplete * item.ItemBitmap.Height * scale;
float x = (Width / 2.0F) - (scale * item.ItemBitmap.Width / 2.0F);
// Draw the stack
this.DrawItem(g, item.ItemBitmap, x, (Height / 2.0F) - offset, scale, item.Number - 1, false);
// Draw the single
this.DrawItem(g, item.ItemBitmap, x, (Height / 2.0F) + offset, scale, 1, false);
return;
}
prevTick = tickTotal;
tickTotal += this.stackPauseTicks;
{
// draw the pause
Item item = this.dragInfo.Item;
float scale = Database.DB.Scale;
// Just draw the 2 stack at a fixed offset
float offset = item.ItemBitmap.Height * scale;
float x = (Width / 2.0F) - (scale * item.ItemBitmap.Width / 2.0F);
// Draw the stack
this.DrawItem(g, item.ItemBitmap, x, (Height / 2.0F) - offset, scale, item.Number - 1, false);
// Draw the single
this.DrawItem(g, item.ItemBitmap, x, (Height / 2.0F) + offset, scale, 1, false);
}
}
/// <summary>
/// Draws the floating relic animation
/// </summary>
/// <param name="g">graphics instance</param>
private void DrawRelicTick(Graphics g)
{
// Just use the stack tick animation data!
int tickNum = this.tick % this.StackTotalAnimationTicks;
Item item = this.dragInfo.Item;
// We need to set the scale such that the item is no more than x% of the height or width
float maxPct = 0.50F;
float scale = Database.DB.Scale;
if (item.ItemBitmap.Width > maxPct * Width)
{
scale = (maxPct * Width * Database.DB.Scale) / item.ItemBitmap.Width;
}
if (item.ItemBitmap.Height > maxPct * Height)
{
float vscale = (maxPct * Height * Database.DB.Scale) / item.ItemBitmap.Height;
if (vscale < scale)
{
scale = vscale;
}
}
int prevTick = 0;
int tickTotal = this.stackTicksToCenter;
if (tickNum < tickTotal)
{
// draw the item moving towards the center
// Figure out its offset
float pctComplete = (float)(tickNum - prevTick) / (float)(tickTotal - prevTick - 1);
// linear interpolate between off-screen and center
float xloc = ((1 - pctComplete) * (-1 * item.ItemBitmap.Width * scale)) + (pctComplete * ((Width / 2.0F) - (scale * item.ItemBitmap.Width / 2.0F)));
float yloc = ((1 - pctComplete) * (Height / 4.0F)) + (pctComplete * (Height / 2.0F));
yloc -= scale * item.ItemBitmap.Height / 2.0F;
// now draw it
this.DrawItem(g, item.ItemBitmap, xloc, yloc, scale, 0, true);
return;
}
prevTick = tickTotal;
tickTotal += this.stackFlashTicks;
if (tickNum < tickTotal)
{
// draw the flash
g.FillRectangle(this.flashBackground, 0, 0, Width, Height);
return;
}
prevTick = tickTotal;
tickTotal += this.stackSplitTicks;
if (tickNum < tickTotal)
{
// draw the item going up and the relic going down
// Figure out the item offset
float pctComplete = (float)(tickNum - prevTick) / (float)(tickTotal - prevTick - 1);
float offset = pctComplete * item.ItemBitmap.Height * scale;
if (offset >= .75 * Height / 2.0F)
{
offset = .75F * Height / 2.0F;
}
float x = (Width / 2.0F) - (scale * item.ItemBitmap.Width / 2.0F);
// Draw the item
this.DrawItem(g, item.ItemBitmap, x, (Height / 2.0F) - offset, scale, 0, false);
// Draw the relic
// We need to figure out the bitmap to use
Bitmap relicBitmap = Database.DB.LoadRelicOverlayBitmap();
if (item.RelicInfo != null)
{
if (item.Var1 >= item.RelicInfo.CompletedRelicLevel)
{
relicBitmap = Database.DB.LoadBitmap(item.RelicInfo.Bitmap);
}
else
{
relicBitmap = Database.DB.LoadBitmap(item.RelicInfo.ShardBitmap);
}
}
// Draw the relic FULL SIZE
int num = item.Var1;
if (num == 0)
{
num = 1;
}
else if (item.RelicInfo != null && num >= item.RelicInfo.CompletedRelicLevel)
{
num = 0;
}
this.DrawItem(g, relicBitmap, x, (Height / 2.0F) + (offset * scale), Database.DB.Scale, num, false);
return;
}
prevTick = tickTotal;
tickTotal += this.stackPauseTicks;
{
// draw the pause
// Just draw the item and relic at a fixed offset
float offset = item.ItemBitmap.Height * scale;
if (offset >= .75 * Height / 2.0F)
{
offset = .75F * Height / 2.0F;
}
float x = (Width / 2.0F) - (scale * item.ItemBitmap.Width / 2.0F);
// Draw the item
this.DrawItem(g, item.ItemBitmap, x, (Height / 2.0F) - offset, scale, 0, false);
// Draw the relic
// We need to figure out the bitmap to use
Bitmap relicBitmap = Database.DB.LoadRelicOverlayBitmap();
if (item.RelicInfo != null)
{
if (item.Var1 >= item.RelicInfo.CompletedRelicLevel)
{
relicBitmap = Database.DB.LoadBitmap(item.RelicInfo.Bitmap);
}
else
{
relicBitmap = Database.DB.LoadBitmap(item.RelicInfo.ShardBitmap);
}
}
// Draw the relic FULL SIZE
int num = item.Var1;
if (num == 0)
{
num = 1;
}
else if (item.RelicInfo != null && num >= item.RelicInfo.CompletedRelicLevel)
{
num = 0;
}
this.DrawItem(g, relicBitmap, x, (Height / 2.0F) + (offset * scale), Database.DB.Scale, num, false);
}
}
/// <summary>
/// Paint callback handler
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">PaintEventArgs data</param>
private void PaintCallback(object sender, PaintEventArgs e)
{
this.havePaintedOnce = true;
// First draw the active background if we are active
if (this.isActive)
{
e.Graphics.FillRectangle(this.activeBackground, 0, 0, Width, Height);
}
// Now draw the animation
if (this.IsStackBeingDragged)
{
this.DrawStackTick(e.Graphics);
}
else if (this.IsItemWithRelicBeingDragged)
{
this.DrawRelicTick(e.Graphics);
}
// draw the doors
this.DrawDoors(e.Graphics);
// Last step is to draw the drag item
if (this.dragInfo.IsActive && (this.dragLocation.X >= 0))
{
this.DrawItem(
e.Graphics,
this.dragInfo.Item.ItemBitmap,
(float)this.dragLocation.X - this.dragInfo.MouseOffset.X,
(float)this.dragLocation.Y - this.dragInfo.MouseOffset.Y,
Database.DB.Scale,
this.dragInfo.Item.Number,
this.dragInfo.Item.HasRelic);
}
}
/// <summary>
/// Draws the doors
/// </summary>
/// <param name="g">graphics instance</param>
private void DrawDoors(Graphics g)
{
if (this.doorPosition == this.maxDoorPositions - 1)
{
// doors are completely open
return;
}
// figure out the offset to draw each door
float offset = (this.doorPosition / (float)(this.maxDoorPositions - 1)) * Width / 2;
// Now draw each door
g.DrawImage(this.leftDoor, 0.0F - offset, 0.0F, (float)Width / 2.0F, (float)Height);
g.DrawImage(this.rightDoor, (float)(Width / 2.0F) + offset, 0.0F, (float)Width / 2.0F, (float)Height);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NUnit.Framework;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Store;
using StringHelper = Lucene.Net.Util.StringHelper;
using TermQuery = Lucene.Net.Search.TermQuery;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using _TestUtil = Lucene.Net.Util._TestUtil;
namespace Lucene.Net.Index
{
[TestFixture]
public class TestStressIndexing2:LuceneTestCase
{
internal class AnonymousClassComparator : System.Collections.IComparer
{
public virtual int Compare(System.Object o1, System.Object o2)
{
return String.CompareOrdinal(((Fieldable) o1).Name(), ((Fieldable) o2).Name());
}
}
internal static int maxFields = 4;
internal static int bigFieldSize = 10;
internal static bool sameFieldOrder = false;
internal static bool autoCommit = false;
internal static int mergeFactor = 3;
internal static int maxBufferedDocs = 3;
new internal static int seed = 0;
internal System.Random r;
public class MockIndexWriter:IndexWriter
{
private void InitBlock(TestStressIndexing2 enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private TestStressIndexing2 enclosingInstance;
public TestStressIndexing2 Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public MockIndexWriter(TestStressIndexing2 enclosingInstance, Directory dir, bool autoCommit, Analyzer a, bool create):base(dir, autoCommit, a, create)
{
InitBlock(enclosingInstance);
}
public /*internal*/ override bool TestPoint(System.String name)
{
// if (name.equals("startCommit")) {
if (Enclosing_Instance.r.Next(4) == 2)
System.Threading.Thread.Sleep(0);
return true;
}
}
[Test]
public virtual void TestRandomIWReader()
{
this.r = NewRandom();
Directory dir = new MockRAMDirectory();
// TODO: verify equals using IW.getReader
DocsAndWriter dw = IndexRandomIWReader(10, 100, 100, dir);
IndexReader r = dw.writer.GetReader();
dw.writer.Commit();
VerifyEquals(r, dir, "id");
r.Close();
dw.writer.Close();
dir.Close();
}
[Test]
public virtual void TestRandom()
{
r = NewRandom();
Directory dir1 = new MockRAMDirectory();
// dir1 = FSDirectory.open("foofoofoo");
Directory dir2 = new MockRAMDirectory();
// mergeFactor=2; maxBufferedDocs=2; Map docs = indexRandom(1, 3, 2, dir1);
System.Collections.IDictionary docs = IndexRandom(10, 100, 100, dir1);
IndexSerial(docs, dir2);
// verifying verify
// verifyEquals(dir1, dir1, "id");
// verifyEquals(dir2, dir2, "id");
VerifyEquals(dir1, dir2, "id");
}
[Test]
public virtual void TestMultiConfig()
{
// test lots of smaller different params together
r = NewRandom();
for (int i = 0; i < 100; i++)
{
// increase iterations for better testing
sameFieldOrder = r.NextDouble() > 0.5;
autoCommit = r.NextDouble() > 0.5;
mergeFactor = r.Next(3) + 2;
maxBufferedDocs = r.Next(3) + 2;
seed++;
int nThreads = r.Next(5) + 1;
int iter = r.Next(10) + 1;
int range = r.Next(20) + 1;
Directory dir1 = new MockRAMDirectory();
Directory dir2 = new MockRAMDirectory();
System.Collections.IDictionary docs = IndexRandom(nThreads, iter, range, dir1);
IndexSerial(docs, dir2);
VerifyEquals(dir1, dir2, "id");
}
}
internal static Term idTerm = new Term("id", "");
internal IndexingThread[] threads;
internal static System.Collections.IComparer fieldNameComparator;
// This test avoids using any extra synchronization in the multiple
// indexing threads to test that IndexWriter does correctly synchronize
// everything.
public class DocsAndWriter
{
internal System.Collections.IDictionary docs;
internal IndexWriter writer;
}
public virtual DocsAndWriter IndexRandomIWReader(int nThreads, int iterations, int range, Directory dir)
{
System.Collections.Hashtable docs = new System.Collections.Hashtable();
IndexWriter w = new MockIndexWriter(this, dir, autoCommit, new WhitespaceAnalyzer(), true);
w.SetUseCompoundFile(false);
/***
w.setMaxMergeDocs(Integer.MAX_VALUE);
w.setMaxFieldLength(10000);
w.setRAMBufferSizeMB(1);
w.setMergeFactor(10);
***/
// force many merges
w.SetMergeFactor(mergeFactor);
w.SetRAMBufferSizeMB(.1);
w.SetMaxBufferedDocs(maxBufferedDocs);
threads = new IndexingThread[nThreads];
for (int i = 0; i < threads.Length; i++)
{
IndexingThread th = new IndexingThread();
th.w = w;
th.base_Renamed = 1000000 * i;
th.range = range;
th.iterations = iterations;
threads[i] = th;
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Start();
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Join();
}
// w.optimize();
//w.close();
for (int i = 0; i < threads.Length; i++)
{
IndexingThread th = threads[i];
lock (th)
{
SupportClass.CollectionsHelper.AddAllIfNotContains(docs, th.docs);
}
}
_TestUtil.CheckIndex(dir);
DocsAndWriter dw = new DocsAndWriter();
dw.docs = docs;
dw.writer = w;
return dw;
}
public virtual System.Collections.IDictionary IndexRandom(int nThreads, int iterations, int range, Directory dir)
{
System.Collections.IDictionary docs = new System.Collections.Hashtable();
for (int iter = 0; iter < 3; iter++)
{
IndexWriter w = new MockIndexWriter(this, dir, autoCommit, new WhitespaceAnalyzer(), true);
w.SetUseCompoundFile(false);
// force many merges
w.SetMergeFactor(mergeFactor);
w.SetRAMBufferSizeMB(.1);
w.SetMaxBufferedDocs(maxBufferedDocs);
threads = new IndexingThread[nThreads];
for (int i = 0; i < threads.Length; i++)
{
IndexingThread th = new IndexingThread();
th.w = w;
th.base_Renamed = 1000000 * i;
th.range = range;
th.iterations = iterations;
threads[i] = th;
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Start();
}
for (int i = 0; i < threads.Length; i++)
{
threads[i].Join();
}
// w.optimize();
w.Close();
for (int i = 0; i < threads.Length; i++)
{
IndexingThread th = threads[i];
lock (th)
{
System.Collections.IEnumerator e = th.docs.Keys.GetEnumerator();
while (e.MoveNext())
{
docs[e.Current] = th.docs[e.Current];
}
}
}
}
_TestUtil.CheckIndex(dir);
return docs;
}
public static void IndexSerial(System.Collections.IDictionary docs, Directory dir)
{
IndexWriter w = new IndexWriter(dir, new WhitespaceAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED);
// index all docs in a single thread
System.Collections.IEnumerator iter = docs.Values.GetEnumerator();
while (iter.MoveNext())
{
Document d = (Document) iter.Current;
System.Collections.ArrayList fields = new System.Collections.ArrayList();
fields.AddRange(d.GetFields());
// put fields in same order each time
//{{Lucene.Net-2.9.1}} No, don't change the order of the fields
//SupportClass.CollectionsHelper.Sort(fields, fieldNameComparator);
Document d1 = new Document();
d1.SetBoost(d.GetBoost());
for (int i = 0; i < fields.Count; i++)
{
d1.Add((Fieldable) fields[i]);
}
w.AddDocument(d1);
// System.out.println("indexing "+d1);
}
w.Close();
}
public static void VerifyEquals(IndexReader r1, Directory dir2, System.String idField)
{
IndexReader r2 = IndexReader.Open(dir2);
VerifyEquals(r1, r2, idField);
r2.Close();
}
public static void VerifyEquals(Directory dir1, Directory dir2, System.String idField)
{
IndexReader r1 = IndexReader.Open(dir1);
IndexReader r2 = IndexReader.Open(dir2);
VerifyEquals(r1, r2, idField);
r1.Close();
r2.Close();
}
public static void VerifyEquals(IndexReader r1, IndexReader r2, System.String idField)
{
Assert.AreEqual(r1.NumDocs(), r2.NumDocs());
bool hasDeletes = !(r1.MaxDoc() == r2.MaxDoc() && r1.NumDocs() == r1.MaxDoc());
int[] r2r1 = new int[r2.MaxDoc()]; // r2 id to r1 id mapping
TermDocs termDocs1 = r1.TermDocs();
TermDocs termDocs2 = r2.TermDocs();
// create mapping from id2 space to id2 based on idField
idField = StringHelper.Intern(idField);
TermEnum termEnum = r1.Terms(new Term(idField, ""));
do
{
Term term = termEnum.Term();
if (term == null || (System.Object) term.Field() != (System.Object) idField)
break;
termDocs1.Seek(termEnum);
if (!termDocs1.Next())
{
// This doc is deleted and wasn't replaced
termDocs2.Seek(termEnum);
Assert.IsFalse(termDocs2.Next());
continue;
}
int id1 = termDocs1.Doc();
Assert.IsFalse(termDocs1.Next());
termDocs2.Seek(termEnum);
Assert.IsTrue(termDocs2.Next());
int id2 = termDocs2.Doc();
Assert.IsFalse(termDocs2.Next());
r2r1[id2] = id1;
// verify stored fields are equivalent
try
{
VerifyEquals(r1.Document(id1), r2.Document(id2));
}
catch (System.Exception t)
{
System.Console.Out.WriteLine("FAILED id=" + term + " id1=" + id1 + " id2=" + id2 + " term=" + term);
System.Console.Out.WriteLine(" d1=" + r1.Document(id1));
System.Console.Out.WriteLine(" d2=" + r2.Document(id2));
throw t;
}
try
{
// verify term vectors are equivalent
VerifyEquals(r1.GetTermFreqVectors(id1), r2.GetTermFreqVectors(id2));
}
catch (System.Exception e)
{
System.Console.Out.WriteLine("FAILED id=" + term + " id1=" + id1 + " id2=" + id2);
TermFreqVector[] tv1 = r1.GetTermFreqVectors(id1);
System.Console.Out.WriteLine(" d1=" + tv1);
if (tv1 != null)
for (int i = 0; i < tv1.Length; i++)
{
System.Console.Out.WriteLine(" " + i + ": " + tv1[i]);
}
TermFreqVector[] tv2 = r2.GetTermFreqVectors(id2);
System.Console.Out.WriteLine(" d2=" + tv2);
if (tv2 != null)
for (int i = 0; i < tv2.Length; i++)
{
System.Console.Out.WriteLine(" " + i + ": " + tv2[i]);
}
throw e;
}
}
while (termEnum.Next());
termEnum.Close();
// Verify postings
TermEnum termEnum1 = r1.Terms(new Term("", ""));
TermEnum termEnum2 = r2.Terms(new Term("", ""));
// pack both doc and freq into single element for easy sorting
long[] info1 = new long[r1.NumDocs()];
long[] info2 = new long[r2.NumDocs()];
for (; ; )
{
Term term1, term2;
// iterate until we get some docs
int len1;
for (; ; )
{
len1 = 0;
term1 = termEnum1.Term();
if (term1 == null)
break;
termDocs1.Seek(termEnum1);
while (termDocs1.Next())
{
int d1 = termDocs1.Doc();
int f1 = termDocs1.Freq();
info1[len1] = (((long) d1) << 32) | f1;
len1++;
}
if (len1 > 0)
break;
if (!termEnum1.Next())
break;
}
// iterate until we get some docs
int len2;
for (; ; )
{
len2 = 0;
term2 = termEnum2.Term();
if (term2 == null)
break;
termDocs2.Seek(termEnum2);
while (termDocs2.Next())
{
int d2 = termDocs2.Doc();
int f2 = termDocs2.Freq();
info2[len2] = (((long) r2r1[d2]) << 32) | f2;
len2++;
}
if (len2 > 0)
break;
if (!termEnum2.Next())
break;
}
if (!hasDeletes)
Assert.AreEqual(termEnum1.DocFreq(), termEnum2.DocFreq());
Assert.AreEqual(len1, len2);
if (len1 == 0)
break; // no more terms
Assert.AreEqual(term1, term2);
// sort info2 to get it into ascending docid
System.Array.Sort(info2, 0, len2 - 0);
// now compare
for (int i = 0; i < len1; i++)
{
Assert.AreEqual(info1[i], info2[i]);
}
termEnum1.Next();
termEnum2.Next();
}
}
public static void VerifyEquals(Document d1, Document d2)
{
System.Collections.IList ff1 = d1.GetFields();
System.Collections.IList ff2 = d2.GetFields();
SupportClass.CollectionsHelper.Sort(ff1, fieldNameComparator);
SupportClass.CollectionsHelper.Sort(ff2, fieldNameComparator);
if (ff1.Count != ff2.Count)
{
System.Console.Out.WriteLine(SupportClass.CollectionsHelper.CollectionToString(ff1));
System.Console.Out.WriteLine(SupportClass.CollectionsHelper.CollectionToString(ff2));
Assert.AreEqual(ff1.Count, ff2.Count);
}
for (int i = 0; i < ff1.Count; i++)
{
Fieldable f1 = (Fieldable) ff1[i];
Fieldable f2 = (Fieldable) ff2[i];
if (f1.IsBinary())
{
System.Diagnostics.Debug.Assert(f2.IsBinary());
//TODO
}
else
{
System.String s1 = f1.StringValue();
System.String s2 = f2.StringValue();
if (!s1.Equals(s2))
{
// print out whole doc on error
System.Console.Out.WriteLine(SupportClass.CollectionsHelper.CollectionToString(ff1));
System.Console.Out.WriteLine(SupportClass.CollectionsHelper.CollectionToString(ff2));
Assert.AreEqual(s1, s2);
}
}
}
}
public static void VerifyEquals(TermFreqVector[] d1, TermFreqVector[] d2)
{
if (d1 == null)
{
Assert.IsTrue(d2 == null);
return ;
}
Assert.IsTrue(d2 != null);
Assert.AreEqual(d1.Length, d2.Length);
for (int i = 0; i < d1.Length; i++)
{
TermFreqVector v1 = d1[i];
TermFreqVector v2 = d2[i];
if (v1 == null || v2 == null)
{
System.Console.Out.WriteLine("v1=" + v1 + " v2=" + v2 + " i=" + i + " of " + d1.Length);
}
Assert.AreEqual(v1.Size(), v2.Size());
int numTerms = v1.Size();
System.String[] terms1 = v1.GetTerms();
System.String[] terms2 = v2.GetTerms();
int[] freq1 = v1.GetTermFrequencies();
int[] freq2 = v2.GetTermFrequencies();
for (int j = 0; j < numTerms; j++)
{
if (!terms1[j].Equals(terms2[j]))
Assert.AreEqual(terms1[j], terms2[j]);
Assert.AreEqual(freq1[j], freq2[j]);
}
if (v1 is TermPositionVector)
{
Assert.IsTrue(v2 is TermPositionVector);
TermPositionVector tpv1 = (TermPositionVector) v1;
TermPositionVector tpv2 = (TermPositionVector) v2;
for (int j = 0; j < numTerms; j++)
{
int[] pos1 = tpv1.GetTermPositions(j);
int[] pos2 = tpv2.GetTermPositions(j);
Assert.AreEqual(pos1.Length, pos2.Length);
TermVectorOffsetInfo[] offsets1 = tpv1.GetOffsets(j);
TermVectorOffsetInfo[] offsets2 = tpv2.GetOffsets(j);
if (offsets1 == null)
Assert.IsTrue(offsets2 == null);
else
Assert.IsTrue(offsets2 != null);
for (int k = 0; k < pos1.Length; k++)
{
Assert.AreEqual(pos1[k], pos2[k]);
if (offsets1 != null)
{
Assert.AreEqual(offsets1[k].GetStartOffset(), offsets2[k].GetStartOffset());
Assert.AreEqual(offsets1[k].GetEndOffset(), offsets2[k].GetEndOffset());
}
}
}
}
}
}
internal class IndexingThread:SupportClass.ThreadClass
{
internal IndexWriter w;
internal int base_Renamed;
internal int range;
internal int iterations;
internal System.Collections.IDictionary docs = new System.Collections.Hashtable(); // Map<String,Document>
internal System.Random r;
public virtual int NextInt(int lim)
{
return r.Next(lim);
}
// start is inclusive and end is exclusive
public virtual int NextInt(int start, int end)
{
return start + r.Next(end - start);
}
internal char[] buffer = new char[100];
private int AddUTF8Token(int start)
{
int end = start + NextInt(20);
if (buffer.Length < 1 + end)
{
char[] newBuffer = new char[(int) ((1 + end) * 1.25)];
Array.Copy(buffer, 0, newBuffer, 0, buffer.Length);
buffer = newBuffer;
}
for (int i = start; i < end; i++)
{
int t = NextInt(6);
if (0 == t && i < end - 1)
{
// Make a surrogate pair
// High surrogate
buffer[i++] = (char) NextInt(0xd800, 0xdc00);
// Low surrogate
buffer[i] = (char) NextInt(0xdc00, 0xe000);
}
else if (t <= 1)
buffer[i] = (char) NextInt(0x80);
else if (2 == t)
buffer[i] = (char) NextInt(0x80, 0x800);
else if (3 == t)
buffer[i] = (char) NextInt(0x800, 0xd800);
else if (4 == t)
buffer[i] = (char) NextInt(0xe000, 0xffff);
else if (5 == t)
{
// Illegal unpaired surrogate
if (r.NextDouble() > 0.5)
buffer[i] = (char) NextInt(0xd800, 0xdc00);
else
buffer[i] = (char) NextInt(0xdc00, 0xe000);
}
}
buffer[end] = ' ';
return 1 + end;
}
public virtual System.String GetString(int nTokens)
{
nTokens = nTokens != 0?nTokens:r.Next(4) + 1;
// Half the time make a random UTF8 string
if (r.NextDouble() > 0.5)
return GetUTF8String(nTokens);
// avoid StringBuffer because it adds extra synchronization.
char[] arr = new char[nTokens * 2];
for (int i = 0; i < nTokens; i++)
{
arr[i * 2] = (char) ('A' + r.Next(10));
arr[i * 2 + 1] = ' ';
}
return new System.String(arr);
}
public virtual System.String GetUTF8String(int nTokens)
{
int upto = 0;
SupportClass.CollectionsHelper.Fill(buffer, (char) 0);
for (int i = 0; i < nTokens; i++)
upto = AddUTF8Token(upto);
return new System.String(buffer, 0, upto);
}
public virtual System.String GetIdString()
{
return System.Convert.ToString(base_Renamed + NextInt(range));
}
public virtual void IndexDoc()
{
Document d = new Document();
System.Collections.ArrayList fields = new System.Collections.ArrayList();
System.String idString = GetIdString();
Field idField = new Field(Lucene.Net.Index.TestStressIndexing2.idTerm.Field(), idString, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS);
fields.Add(idField);
int nFields = NextInt(Lucene.Net.Index.TestStressIndexing2.maxFields);
for (int i = 0; i < nFields; i++)
{
Field.TermVector tvVal = Field.TermVector.NO;
switch (NextInt(4))
{
case 0:
tvVal = Field.TermVector.NO;
break;
case 1:
tvVal = Field.TermVector.YES;
break;
case 2:
tvVal = Field.TermVector.WITH_POSITIONS;
break;
case 3:
tvVal = Field.TermVector.WITH_POSITIONS_OFFSETS;
break;
}
switch (NextInt(4))
{
case 0:
fields.Add(new Field("f" + NextInt(100), GetString(1), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS, tvVal));
break;
case 1:
fields.Add(new Field("f" + NextInt(100), GetString(0), Field.Store.NO, Field.Index.ANALYZED, tvVal));
break;
case 2:
fields.Add(new Field("f" + NextInt(100), GetString(0), Field.Store.YES, Field.Index.NO, Field.TermVector.NO));
break;
case 3:
fields.Add(new Field("f" + NextInt(100), GetString(Lucene.Net.Index.TestStressIndexing2.bigFieldSize), Field.Store.YES, Field.Index.ANALYZED, tvVal));
break;
}
}
if (Lucene.Net.Index.TestStressIndexing2.sameFieldOrder)
{
SupportClass.CollectionsHelper.Sort(fields, Lucene.Net.Index.TestStressIndexing2.fieldNameComparator);
}
else
{
// random placement of id field also
int index = NextInt(fields.Count);
fields[0] = fields[index];
fields[index] = idField;
}
for (int i = 0; i < fields.Count; i++)
{
d.Add((Fieldable) fields[i]);
}
w.UpdateDocument(Lucene.Net.Index.TestStressIndexing2.idTerm.CreateTerm(idString), d);
// System.out.println("indexing "+d);
docs[idString] = d;
}
public virtual void DeleteDoc()
{
System.String idString = GetIdString();
w.DeleteDocuments(Lucene.Net.Index.TestStressIndexing2.idTerm.CreateTerm(idString));
docs.Remove(idString);
}
public virtual void DeleteByQuery()
{
System.String idString = GetIdString();
w.DeleteDocuments(new TermQuery(Lucene.Net.Index.TestStressIndexing2.idTerm.CreateTerm(idString)));
docs.Remove(idString);
}
override public void Run()
{
try
{
r = new System.Random((System.Int32) (base_Renamed + range + Lucene.Net.Index.TestStressIndexing2.seed));
for (int i = 0; i < iterations; i++)
{
int what = NextInt(100);
if (what < 5)
{
DeleteDoc();
}
else if (what < 10)
{
DeleteByQuery();
}
else
{
IndexDoc();
}
}
}
catch (System.Exception e)
{
System.Console.Error.WriteLine(e.StackTrace);
Assert.Fail(e.ToString()); // TestCase.fail(e.ToString());
}
lock (this)
{
int generatedAux = docs.Count;
}
}
}
static TestStressIndexing2()
{
fieldNameComparator = new AnonymousClassComparator();
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PSView2;
using ProcessTools;
using System.Resources;
using System.Threading;
namespace MemHack
{
/// <summary>
/// Summary description for MemDisplay.
/// </summary>
public class MemDisplay : Form
{
private Button btnFindFirst;
private Button btnFindNext;
private Button btnSet;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
private Label lblFound;
private System.Threading.TimerCallback m_cb = new System.Threading.TimerCallback(UpdateList);
private System.Threading.Timer m_timer = null;
private ListView lstAddresses;
private Label label2;
private TextBox txtMessages;
Type m_searchType = null;
ProcessModifier m_pm = null;
private Label lblSearchSize;
CAddressValue[] m_last = new CAddressValue[0];
long m_count = 0;
private delegate void UpdateListDelegate();
UpdateListDelegate updList = null;
public MemDisplay()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
lstAddresses.Columns.Add(Resources.Address, 80, HorizontalAlignment.Left);
lstAddresses.Columns.Add(Resources.Value, 140, HorizontalAlignment.Left);
MinimumSize = new Size(390, 288);
this.btnFindFirst.Text = Resources.FindFirst;
this.btnFindNext.Text = Resources.FindNext;
this.lblFound.Text = Resources.AddressesFoundLabel;
this.btnSet.Text = Resources.Set;
this.label2.Text = Resources.MessagesLabel;
this.txtMessages.Text = Resources.NoAddressesFound;
this.Text = Resources.MemoryHacker;
(new ToolTip()).SetToolTip(this, Resources.ToolTip_MemDisplayDlg);
(new ToolTip()).SetToolTip(this.btnFindFirst, Resources.ToolTip_FindFirst);
(new ToolTip()).SetToolTip(this.btnFindNext, Resources.ToolTip_FindNext);
(new ToolTip()).SetToolTip(this.btnSet, Resources.ToolTip_Set);
(new ToolTip()).SetToolTip(this.lstAddresses, Resources.ToolTip_AddressList);
(new ToolTip()).SetToolTip(this.txtMessages, Resources.ToolTip_Messages);
this.lstAddresses.DoubleClick += new EventHandler(lstAddresses_DoubleClick);
}
public bool Configure(ProcessInformation pinfo)
{
Text = System.String.Format(Resources.MemoryHackerFormatString, pinfo.ID, pinfo.Name, pinfo.FullPath);
m_pm = ProcessModifier.Open((uint) pinfo.ID);
if(m_pm == null)
return false;
UpdateList();
UpdateList(); // The second call is for debugging any problems in this function.
updList = new UpdateListDelegate(UpdateList);
m_timer = new System.Threading.Timer(m_cb, this, 2000, 2000);
return true;
}
// For a while I thought UpdateList was generating a memory leak but it turns out that the handle it
// allocates every interval just doesn't get garbage collected immediately. Ran it for 48 hours to
// ensure it was ok.
static protected void UpdateList(object obj)
{
MemDisplay m = (MemDisplay) obj;
bool noUpdates = false;
lock (m.m_lockobj)
{
noUpdates = m.m_noUpdates;
}
if (!noUpdates)
m.InvokeUpdate();
}
protected void InvokeUpdate()
{
Invoke(updList);
}
object m_lockobj = new object();
bool m_fRunning = false;
protected void UpdateList()
{
lock(m_lockobj)
{
if(m_fRunning)
return;
m_fRunning = true;
}
m_count = (long)m_pm.Count;
bool fRetrieved = false;
CAddressValue[] avs = new CAddressValue[0];
if(m_count > 2000)
{
lstAddresses.Items.Clear();
goto Done;
}
fRetrieved = true;
if(m_count == 0)
{
lstAddresses.Items.Clear();
lblSearchSize.Text = string.Empty;
goto Done;
}
avs = m_pm.AddressValues;
m_count = avs.LongLength;
if(m_count == 0)
{
lstAddresses.Items.Clear();
lblSearchSize.Text = string.Empty;
goto Done;
}
// txtMessages.Text = count.ToString() + " addresses found.";
// Remove old items
int pos = 0, pos2 = 0;
if(m_last == null)
m_last = new CAddressValue[0];
bool fWasEmpty = lstAddresses.Items.Count == 0;
foreach(CAddressValue inf in avs)
{
if(inf == null)
break;
while(pos2 < m_last.Length &&
inf.Address > m_last[pos2].Address)
{
if(!fWasEmpty)
lstAddresses.Items.RemoveAt(pos);
++pos2;
}
if(pos2 >= m_last.Length || fWasEmpty)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = inf.GetAddress();
lvi.SubItems.Add(inf.Value.ToString());
lstAddresses.Items.Add(lvi);
}
else if(inf.Address == m_last[pos2].Address &&
m_last[pos2].Value != inf.Value)
{
lstAddresses.Items[pos].SubItems[1].Text = inf.Value.ToString();
}
++pos;
++pos2;
}
while(pos < lstAddresses.Items.Count)
lstAddresses.Items.RemoveAt(lstAddresses.Items.Count - 1);
Done:
if(fRetrieved)
m_last = avs;
CheckButtons();
lblFound.Text = "Addresses Found: " + m_count.ToString() + ((m_count > 2000) ? " (hidden)" : string.Empty);
lock(m_lockobj)
{
m_fRunning = false;
}
}
protected void CheckButtons()
{
lock(m_lockobj)
{
if(m_count == 0)
{
btnFindNext.Enabled = false;
btnSet.Enabled = false;
}
else
{
btnFindNext.Enabled = true;
}
if(lstAddresses.SelectedItems.Count == 0)
{
btnSet.Enabled = false;
}
else
{
btnSet.Enabled = true;
}
}
}
bool m_noUpdates = false;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
lock (m_lockobj)
{
m_noUpdates = true;
}
if( disposing )
{
if(m_timer != null)
m_timer.Dispose();
m_timer = null;
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
ResourceManager resources = new ResourceManager(typeof(MemDisplay));
this.btnFindFirst = new Button();
this.btnFindNext = new Button();
this.lblFound = new Label();
this.btnSet = new Button();
this.lstAddresses = new ListView();
this.label2 = new Label();
this.txtMessages = new TextBox();
this.lblSearchSize = new Label();
this.SuspendLayout();
//
// btnFindFirst
//
this.btnFindFirst.AccessibleDescription = resources.GetString("btnFindFirst.AccessibleDescription");
this.btnFindFirst.AccessibleName = resources.GetString("btnFindFirst.AccessibleName");
this.btnFindFirst.Anchor = ((AnchorStyles)(resources.GetObject("btnFindFirst.Anchor")));
this.btnFindFirst.BackgroundImage = ((Image)(resources.GetObject("btnFindFirst.BackgroundImage")));
this.btnFindFirst.Dock = ((DockStyle)(resources.GetObject("btnFindFirst.Dock")));
this.btnFindFirst.Enabled = ((bool)(resources.GetObject("btnFindFirst.Enabled")));
this.btnFindFirst.FlatStyle = ((FlatStyle)(resources.GetObject("btnFindFirst.FlatStyle")));
this.btnFindFirst.Font = ((Font)(resources.GetObject("btnFindFirst.Font")));
this.btnFindFirst.Image = ((Image)(resources.GetObject("btnFindFirst.Image")));
this.btnFindFirst.ImageAlign = ((ContentAlignment)(resources.GetObject("btnFindFirst.ImageAlign")));
this.btnFindFirst.ImageIndex = ((int)(resources.GetObject("btnFindFirst.ImageIndex")));
this.btnFindFirst.ImeMode = ((ImeMode)(resources.GetObject("btnFindFirst.ImeMode")));
this.btnFindFirst.Location = ((Point)(resources.GetObject("btnFindFirst.Location")));
this.btnFindFirst.Name = "btnFindFirst";
this.btnFindFirst.RightToLeft = ((RightToLeft)(resources.GetObject("btnFindFirst.RightToLeft")));
this.btnFindFirst.Size = ((Size)(resources.GetObject("btnFindFirst.Size")));
this.btnFindFirst.TabIndex = ((int)(resources.GetObject("btnFindFirst.TabIndex")));
this.btnFindFirst.Text = resources.GetString("btnFindFirst.Text");
this.btnFindFirst.TextAlign = ((ContentAlignment)(resources.GetObject("btnFindFirst.TextAlign")));
this.btnFindFirst.Visible = ((bool)(resources.GetObject("btnFindFirst.Visible")));
this.btnFindFirst.Click += new System.EventHandler(this.btnFindFirst_Click);
//
// btnFindNext
//
this.btnFindNext.AccessibleDescription = resources.GetString("btnFindNext.AccessibleDescription");
this.btnFindNext.AccessibleName = resources.GetString("btnFindNext.AccessibleName");
this.btnFindNext.Anchor = ((AnchorStyles)(resources.GetObject("btnFindNext.Anchor")));
this.btnFindNext.BackgroundImage = ((Image)(resources.GetObject("btnFindNext.BackgroundImage")));
this.btnFindNext.Dock = ((DockStyle)(resources.GetObject("btnFindNext.Dock")));
this.btnFindNext.Enabled = ((bool)(resources.GetObject("btnFindNext.Enabled")));
this.btnFindNext.FlatStyle = ((FlatStyle)(resources.GetObject("btnFindNext.FlatStyle")));
this.btnFindNext.Font = ((Font)(resources.GetObject("btnFindNext.Font")));
this.btnFindNext.Image = ((Image)(resources.GetObject("btnFindNext.Image")));
this.btnFindNext.ImageAlign = ((ContentAlignment)(resources.GetObject("btnFindNext.ImageAlign")));
this.btnFindNext.ImageIndex = ((int)(resources.GetObject("btnFindNext.ImageIndex")));
this.btnFindNext.ImeMode = ((ImeMode)(resources.GetObject("btnFindNext.ImeMode")));
this.btnFindNext.Location = ((Point)(resources.GetObject("btnFindNext.Location")));
this.btnFindNext.Name = "btnFindNext";
this.btnFindNext.RightToLeft = ((RightToLeft)(resources.GetObject("btnFindNext.RightToLeft")));
this.btnFindNext.Size = ((Size)(resources.GetObject("btnFindNext.Size")));
this.btnFindNext.TabIndex = ((int)(resources.GetObject("btnFindNext.TabIndex")));
this.btnFindNext.Text = resources.GetString("btnFindNext.Text");
this.btnFindNext.TextAlign = ((ContentAlignment)(resources.GetObject("btnFindNext.TextAlign")));
this.btnFindNext.Visible = ((bool)(resources.GetObject("btnFindNext.Visible")));
this.btnFindNext.Click += new System.EventHandler(this.btnFindNext_Click);
//
// lblFound
//
this.lblFound.AccessibleDescription = resources.GetString("lblFound.AccessibleDescription");
this.lblFound.AccessibleName = resources.GetString("lblFound.AccessibleName");
this.lblFound.Anchor = ((AnchorStyles)(resources.GetObject("lblFound.Anchor")));
this.lblFound.AutoSize = ((bool)(resources.GetObject("lblFound.AutoSize")));
this.lblFound.Dock = ((DockStyle)(resources.GetObject("lblFound.Dock")));
this.lblFound.Enabled = ((bool)(resources.GetObject("lblFound.Enabled")));
this.lblFound.Font = ((Font)(resources.GetObject("lblFound.Font")));
this.lblFound.Image = ((Image)(resources.GetObject("lblFound.Image")));
this.lblFound.ImageAlign = ((ContentAlignment)(resources.GetObject("lblFound.ImageAlign")));
this.lblFound.ImageIndex = ((int)(resources.GetObject("lblFound.ImageIndex")));
this.lblFound.ImeMode = ((ImeMode)(resources.GetObject("lblFound.ImeMode")));
this.lblFound.Location = ((Point)(resources.GetObject("lblFound.Location")));
this.lblFound.Name = "lblFound";
this.lblFound.RightToLeft = ((RightToLeft)(resources.GetObject("lblFound.RightToLeft")));
this.lblFound.Size = ((Size)(resources.GetObject("lblFound.Size")));
this.lblFound.TabIndex = ((int)(resources.GetObject("lblFound.TabIndex")));
this.lblFound.Text = resources.GetString("lblFound.Text");
this.lblFound.TextAlign = ((ContentAlignment)(resources.GetObject("lblFound.TextAlign")));
this.lblFound.Visible = ((bool)(resources.GetObject("lblFound.Visible")));
//
// btnSet
//
this.btnSet.AccessibleDescription = resources.GetString("btnSet.AccessibleDescription");
this.btnSet.AccessibleName = resources.GetString("btnSet.AccessibleName");
this.btnSet.Anchor = ((AnchorStyles)(resources.GetObject("btnSet.Anchor")));
this.btnSet.BackgroundImage = ((Image)(resources.GetObject("btnSet.BackgroundImage")));
this.btnSet.Dock = ((DockStyle)(resources.GetObject("btnSet.Dock")));
this.btnSet.Enabled = ((bool)(resources.GetObject("btnSet.Enabled")));
this.btnSet.FlatStyle = ((FlatStyle)(resources.GetObject("btnSet.FlatStyle")));
this.btnSet.Font = ((Font)(resources.GetObject("btnSet.Font")));
this.btnSet.Image = ((Image)(resources.GetObject("btnSet.Image")));
this.btnSet.ImageAlign = ((ContentAlignment)(resources.GetObject("btnSet.ImageAlign")));
this.btnSet.ImageIndex = ((int)(resources.GetObject("btnSet.ImageIndex")));
this.btnSet.ImeMode = ((ImeMode)(resources.GetObject("btnSet.ImeMode")));
this.btnSet.Location = ((Point)(resources.GetObject("btnSet.Location")));
this.btnSet.Name = "btnSet";
this.btnSet.RightToLeft = ((RightToLeft)(resources.GetObject("btnSet.RightToLeft")));
this.btnSet.Size = ((Size)(resources.GetObject("btnSet.Size")));
this.btnSet.TabIndex = ((int)(resources.GetObject("btnSet.TabIndex")));
this.btnSet.Text = resources.GetString("btnSet.Text");
this.btnSet.TextAlign = ((ContentAlignment)(resources.GetObject("btnSet.TextAlign")));
this.btnSet.Visible = ((bool)(resources.GetObject("btnSet.Visible")));
this.btnSet.Click += new System.EventHandler(this.btnSet_Click);
//
// lstAddresses
//
this.lstAddresses.AccessibleDescription = resources.GetString("lstAddresses.AccessibleDescription");
this.lstAddresses.AccessibleName = resources.GetString("lstAddresses.AccessibleName");
this.lstAddresses.Alignment = ((ListViewAlignment)(resources.GetObject("lstAddresses.Alignment")));
this.lstAddresses.Anchor = ((AnchorStyles)(resources.GetObject("lstAddresses.Anchor")));
this.lstAddresses.BackgroundImage = ((Image)(resources.GetObject("lstAddresses.BackgroundImage")));
this.lstAddresses.Dock = ((DockStyle)(resources.GetObject("lstAddresses.Dock")));
this.lstAddresses.Enabled = ((bool)(resources.GetObject("lstAddresses.Enabled")));
this.lstAddresses.Font = ((Font)(resources.GetObject("lstAddresses.Font")));
this.lstAddresses.FullRowSelect = true;
this.lstAddresses.ImeMode = ((ImeMode)(resources.GetObject("lstAddresses.ImeMode")));
this.lstAddresses.LabelWrap = ((bool)(resources.GetObject("lstAddresses.LabelWrap")));
this.lstAddresses.Location = ((Point)(resources.GetObject("lstAddresses.Location")));
this.lstAddresses.MultiSelect = false;
this.lstAddresses.Name = "lstAddresses";
this.lstAddresses.RightToLeft = ((RightToLeft)(resources.GetObject("lstAddresses.RightToLeft")));
this.lstAddresses.Size = ((Size)(resources.GetObject("lstAddresses.Size")));
this.lstAddresses.TabIndex = ((int)(resources.GetObject("lstAddresses.TabIndex")));
this.lstAddresses.Text = resources.GetString("lstAddresses.Text");
this.lstAddresses.View = View.Details;
this.lstAddresses.Visible = ((bool)(resources.GetObject("lstAddresses.Visible")));
this.lstAddresses.SelectedIndexChanged += new System.EventHandler(this.lstAddresses_SelectedIndexChanged);
//
// label2
//
this.label2.AccessibleDescription = resources.GetString("label2.AccessibleDescription");
this.label2.AccessibleName = resources.GetString("label2.AccessibleName");
this.label2.Anchor = ((AnchorStyles)(resources.GetObject("label2.Anchor")));
this.label2.AutoSize = ((bool)(resources.GetObject("label2.AutoSize")));
this.label2.Dock = ((DockStyle)(resources.GetObject("label2.Dock")));
this.label2.Enabled = ((bool)(resources.GetObject("label2.Enabled")));
this.label2.Font = ((Font)(resources.GetObject("label2.Font")));
this.label2.Image = ((Image)(resources.GetObject("label2.Image")));
this.label2.ImageAlign = ((ContentAlignment)(resources.GetObject("label2.ImageAlign")));
this.label2.ImageIndex = ((int)(resources.GetObject("label2.ImageIndex")));
this.label2.ImeMode = ((ImeMode)(resources.GetObject("label2.ImeMode")));
this.label2.Location = ((Point)(resources.GetObject("label2.Location")));
this.label2.Name = "label2";
this.label2.RightToLeft = ((RightToLeft)(resources.GetObject("label2.RightToLeft")));
this.label2.Size = ((Size)(resources.GetObject("label2.Size")));
this.label2.TabIndex = ((int)(resources.GetObject("label2.TabIndex")));
this.label2.Text = resources.GetString("label2.Text");
this.label2.TextAlign = ((ContentAlignment)(resources.GetObject("label2.TextAlign")));
this.label2.Visible = ((bool)(resources.GetObject("label2.Visible")));
//
// txtMessages
//
this.txtMessages.AccessibleDescription = resources.GetString("txtMessages.AccessibleDescription");
this.txtMessages.AccessibleName = resources.GetString("txtMessages.AccessibleName");
this.txtMessages.Anchor = ((AnchorStyles)(resources.GetObject("txtMessages.Anchor")));
this.txtMessages.AutoSize = ((bool)(resources.GetObject("txtMessages.AutoSize")));
this.txtMessages.BackgroundImage = ((Image)(resources.GetObject("txtMessages.BackgroundImage")));
this.txtMessages.Dock = ((DockStyle)(resources.GetObject("txtMessages.Dock")));
this.txtMessages.Enabled = ((bool)(resources.GetObject("txtMessages.Enabled")));
this.txtMessages.Font = ((Font)(resources.GetObject("txtMessages.Font")));
this.txtMessages.ImeMode = ((ImeMode)(resources.GetObject("txtMessages.ImeMode")));
this.txtMessages.Location = ((Point)(resources.GetObject("txtMessages.Location")));
this.txtMessages.MaxLength = ((int)(resources.GetObject("txtMessages.MaxLength")));
this.txtMessages.Multiline = ((bool)(resources.GetObject("txtMessages.Multiline")));
this.txtMessages.Name = "txtMessages";
this.txtMessages.PasswordChar = ((char)(resources.GetObject("txtMessages.PasswordChar")));
this.txtMessages.ReadOnly = true;
this.txtMessages.RightToLeft = ((RightToLeft)(resources.GetObject("txtMessages.RightToLeft")));
this.txtMessages.ScrollBars = ((ScrollBars)(resources.GetObject("txtMessages.ScrollBars")));
this.txtMessages.Size = ((Size)(resources.GetObject("txtMessages.Size")));
this.txtMessages.TabIndex = ((int)(resources.GetObject("txtMessages.TabIndex")));
this.txtMessages.TabStop = false;
this.txtMessages.Text = resources.GetString("txtMessages.Text");
this.txtMessages.TextAlign = ((HorizontalAlignment)(resources.GetObject("txtMessages.TextAlign")));
this.txtMessages.Visible = ((bool)(resources.GetObject("txtMessages.Visible")));
this.txtMessages.WordWrap = ((bool)(resources.GetObject("txtMessages.WordWrap")));
//
// lblSearchSize
//
this.lblSearchSize.AccessibleDescription = resources.GetString("lblSearchSize.AccessibleDescription");
this.lblSearchSize.AccessibleName = resources.GetString("lblSearchSize.AccessibleName");
this.lblSearchSize.Anchor = ((AnchorStyles)(resources.GetObject("lblSearchSize.Anchor")));
this.lblSearchSize.AutoSize = ((bool)(resources.GetObject("lblSearchSize.AutoSize")));
this.lblSearchSize.Dock = ((DockStyle)(resources.GetObject("lblSearchSize.Dock")));
this.lblSearchSize.Enabled = ((bool)(resources.GetObject("lblSearchSize.Enabled")));
this.lblSearchSize.Font = ((Font)(resources.GetObject("lblSearchSize.Font")));
this.lblSearchSize.Image = ((Image)(resources.GetObject("lblSearchSize.Image")));
this.lblSearchSize.ImageAlign = ((ContentAlignment)(resources.GetObject("lblSearchSize.ImageAlign")));
this.lblSearchSize.ImageIndex = ((int)(resources.GetObject("lblSearchSize.ImageIndex")));
this.lblSearchSize.ImeMode = ((ImeMode)(resources.GetObject("lblSearchSize.ImeMode")));
this.lblSearchSize.Location = ((Point)(resources.GetObject("lblSearchSize.Location")));
this.lblSearchSize.Name = "lblSearchSize";
this.lblSearchSize.RightToLeft = ((RightToLeft)(resources.GetObject("lblSearchSize.RightToLeft")));
this.lblSearchSize.Size = ((Size)(resources.GetObject("lblSearchSize.Size")));
this.lblSearchSize.TabIndex = ((int)(resources.GetObject("lblSearchSize.TabIndex")));
this.lblSearchSize.Text = resources.GetString("lblSearchSize.Text");
this.lblSearchSize.TextAlign = ((ContentAlignment)(resources.GetObject("lblSearchSize.TextAlign")));
this.lblSearchSize.Visible = ((bool)(resources.GetObject("lblSearchSize.Visible")));
//
// MemDisplay
//
this.AccessibleDescription = resources.GetString("$this.AccessibleDescription");
this.AccessibleName = resources.GetString("$this.AccessibleName");
this.AutoScaleBaseSize = ((Size)(resources.GetObject("$this.AutoScaleBaseSize")));
this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll")));
this.AutoScrollMargin = ((Size)(resources.GetObject("$this.AutoScrollMargin")));
this.AutoScrollMinSize = ((Size)(resources.GetObject("$this.AutoScrollMinSize")));
this.BackgroundImage = ((Image)(resources.GetObject("$this.BackgroundImage")));
this.ClientSize = ((Size)(resources.GetObject("$this.ClientSize")));
this.Controls.Add(this.lblSearchSize);
this.Controls.Add(this.txtMessages);
this.Controls.Add(this.label2);
this.Controls.Add(this.lstAddresses);
this.Controls.Add(this.btnSet);
this.Controls.Add(this.lblFound);
this.Controls.Add(this.btnFindNext);
this.Controls.Add(this.btnFindFirst);
this.Enabled = ((bool)(resources.GetObject("$this.Enabled")));
this.Font = ((Font)(resources.GetObject("$this.Font")));
this.Icon = ((Icon)(resources.GetObject("$this.Icon")));
this.ImeMode = ((ImeMode)(resources.GetObject("$this.ImeMode")));
this.Location = ((Point)(resources.GetObject("$this.Location")));
this.MaximumSize = ((Size)(resources.GetObject("$this.MaximumSize")));
this.MinimumSize = ((Size)(resources.GetObject("$this.MinimumSize")));
this.Name = "MemDisplay";
this.RightToLeft = ((RightToLeft)(resources.GetObject("$this.RightToLeft")));
this.SizeGripStyle = SizeGripStyle.Show;
this.StartPosition = ((FormStartPosition)(resources.GetObject("$this.StartPosition")));
this.Text = resources.GetString("$this.Text");
this.Closed += new System.EventHandler(this.MemDisplay_Closed);
this.ResumeLayout(false);
}
#endregion
private object getValue(string s)
{
try
{
return Convert.ChangeType(s, m_searchType);
}
catch
{
return null;
}
}
private void btnFindFirst_Click(object sender, System.EventArgs e)
{
DisableUpdate();
FindFirst ff = new FindFirst();
if(ff.ShowDialog(this) != DialogResult.OK)
{
txtMessages.Text = Resources.FindFirstCanceled;
goto Done;
}
if(ff.radioByte.Checked)
{
m_searchType = typeof(Byte);
lblSearchSize.Text = Resources.SearchSize1Byte;
}
else if(ff.radioShort.Checked)
{
m_searchType = typeof(UInt16);
lblSearchSize.Text = Resources.SearchSize2Bytes;
}
else if(ff.radioInt.Checked)
{
m_searchType = typeof(UInt32);
lblSearchSize.Text = Resources.SearchSize4Bytes;
}
else if(ff.radioLong.Checked)
{
m_searchType = typeof(UInt64);
lblSearchSize.Text = Resources.SearchSize8Bytes;
}
else
m_searchType = null;
lock(m_lockobj)
{
object obj = getValue(ff.textValue.Text);
if(obj == null)
{
txtMessages.Text = Resources.ErrorFailedToConvert;
goto Done;
}
ProgressBarWindow pb = new ProgressBarWindow();
pb.Owner = this;
pb.Show();
txtMessages.Text = String.Format(Resources.SearchingForFormatString, ff.textValue.Text);
try
{
ulong count = m_pm.FindFirst(obj, pb);
txtMessages.Text = String.Format(Resources.FindFirstFoundFormatString, count);
}
catch(System.Exception f)
{
txtMessages.Text = String.Format(Resources.FindFirstFailedFormatString, f.Message);
}
Thread.Sleep(500);
pb.Hide();
pb.Close();
pb = null;
m_last = null;
lstAddresses.Items.Clear();
UpdateList();
}
Done:
EnableUpdate();
}
private void btnFindNext_Click(object sender, System.EventArgs e)
{
DisableUpdate();
SetNext sn = new SetNext(true, 0, 0);
if(sn.ShowDialog(this) == DialogResult.OK)
{
lock(m_lockobj)
{
object obj = getValue(sn.Value);
if(obj == null)
{
txtMessages.Text = Resources.ErrorFailedToConvert;
goto Done;
}
txtMessages.Text = String.Format(Resources.SearchingForFormatString, sn.Value);
ProgressBarWindow pb = new ProgressBarWindow();
pb.Owner = this;
pb.Show();
try
{
UInt64 count = m_pm.FindNext(obj, pb);
txtMessages.Text = String.Format(Resources.FindNextFoundFormatString, count);
}
catch(System.Exception f)
{
txtMessages.Text = String.Format(Resources.FindNextFailedFormatString, f.Message);
}
Thread.Sleep(500);
pb.Hide();
pb.Close();
pb = null;
UpdateList();
}
}
else
{
txtMessages.Text = Resources.FindNextCanceled;
}
Done:
EnableUpdate();
}
private void btnSet_Click(object sender, System.EventArgs e)
{
if(lstAddresses.SelectedItems.Count == 0)
return;
ulong addr = 0;
ulong val = 0;
lock(m_lockobj)
{
addr = Convert.ToUInt64(lstAddresses.SelectedItems[0].Text.Substring(2), 16);
val = Convert.ToUInt64(lstAddresses.SelectedItems[0].SubItems[1].Text);
}
if(addr == 0)
{
txtMessages.Text = String.Format(Resources.ErrorInvalidAddressFormatString, lstAddresses.SelectedItems[0].Text);;
return;
}
SetNext sn = new SetNext(false, addr, val);
if(sn.ShowDialog(this) == DialogResult.OK)
{
lock(m_lockobj)
{
object obj = getValue(sn.Value);
if(obj == null)
{
txtMessages.Text = Resources.ErrorFailedToConvert;
return;
}
try
{
if(m_pm.SetValue(addr, obj))
txtMessages.Text = String.Format(Resources.ValueAtAddressSetFormatString, addr.ToString("X16"), sn.Value);
else
txtMessages.Text = String.Format(Resources.ErrorValueNotSetFormatString, m_pm.LastError);
UpdateList();
}
catch(System.Exception f)
{
txtMessages.Text = String.Format(Resources.ErrorSetValueFailedFormatString, f.Message);
}
}
}
else
{
txtMessages.Text = Resources.SetValueCanceled;
}
}
private void lstAddresses_SelectedIndexChanged(object sender, System.EventArgs e)
{
CheckButtons();
}
private void DisableUpdate()
{
m_timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
}
private void EnableUpdate()
{
m_timer.Change(2000, 2000);
}
private void MemDisplay_Closed(object sender, System.EventArgs e)
{
DisableUpdate();
m_pm.Close();
}
private void lstAddresses_DoubleClick(object sender, EventArgs e)
{
btnSet_Click(null, 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.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
namespace System.Net.Sockets
{
internal partial class SafeCloseSocket :
#if DEBUG
DebugSafeHandleMinusOneIsInvalid
#else
SafeHandleMinusOneIsInvalid
#endif
{
private int _receiveTimeout = -1;
private int _sendTimeout = -1;
private bool _nonBlocking;
private SocketAsyncContext _asyncContext;
private TrackedSocketOptions _trackedOptions;
internal bool LastConnectFailed { get; set; }
internal bool DualMode { get; set; }
internal bool ExposedHandleOrUntrackedConfiguration { get; private set; }
public void RegisterConnectResult(SocketError error)
{
switch (error)
{
case SocketError.Success:
case SocketError.WouldBlock:
break;
default:
LastConnectFailed = true;
break;
}
}
public void TransferTrackedState(SafeCloseSocket target)
{
target._trackedOptions = _trackedOptions;
target.LastConnectFailed = LastConnectFailed;
target.DualMode = DualMode;
target.ExposedHandleOrUntrackedConfiguration = ExposedHandleOrUntrackedConfiguration;
}
public void SetExposed() => ExposedHandleOrUntrackedConfiguration = true;
public bool IsTrackedOption(TrackedSocketOptions option) => (_trackedOptions & option) != 0;
public void TrackOption(SocketOptionLevel level, SocketOptionName name)
{
// As long as only these options are set, we can support Connect{Async}(IPAddress[], ...).
switch (level)
{
case SocketOptionLevel.Tcp:
switch (name)
{
case SocketOptionName.NoDelay: _trackedOptions |= TrackedSocketOptions.NoDelay; return;
}
break;
case SocketOptionLevel.IP:
switch (name)
{
case SocketOptionName.DontFragment: _trackedOptions |= TrackedSocketOptions.DontFragment; return;
case SocketOptionName.IpTimeToLive: _trackedOptions |= TrackedSocketOptions.Ttl; return;
}
break;
case SocketOptionLevel.IPv6:
switch (name)
{
case SocketOptionName.IPv6Only: _trackedOptions |= TrackedSocketOptions.DualMode; return;
case SocketOptionName.IpTimeToLive: _trackedOptions |= TrackedSocketOptions.Ttl; return;
}
break;
case SocketOptionLevel.Socket:
switch (name)
{
case SocketOptionName.Broadcast: _trackedOptions |= TrackedSocketOptions.EnableBroadcast; return;
case SocketOptionName.Linger: _trackedOptions |= TrackedSocketOptions.LingerState; return;
case SocketOptionName.ReceiveBuffer: _trackedOptions |= TrackedSocketOptions.ReceiveBufferSize; return;
case SocketOptionName.ReceiveTimeout: _trackedOptions |= TrackedSocketOptions.ReceiveTimeout; return;
case SocketOptionName.SendBuffer: _trackedOptions |= TrackedSocketOptions.SendBufferSize; return;
case SocketOptionName.SendTimeout: _trackedOptions |= TrackedSocketOptions.SendTimeout; return;
}
break;
}
// For any other settings, we need to track that they were used so that we can error out
// if a Connect{Async}(IPAddress[],...) attempt is made.
ExposedHandleOrUntrackedConfiguration = true;
}
public SocketAsyncContext AsyncContext
{
get
{
if (Volatile.Read(ref _asyncContext) == null)
{
Interlocked.CompareExchange(ref _asyncContext, new SocketAsyncContext(this), null);
}
return _asyncContext;
}
}
public bool IsNonBlocking
{
get
{
return _nonBlocking;
}
set
{
_nonBlocking = value;
//
// If transitioning to non-blocking, we need to set the native socket to non-blocking mode.
// If we ever transition back to blocking, we keep the native socket in non-blocking mode, and emulate
// blocking. This avoids problems with switching to native blocking while there are pending async
// operations.
//
if (value)
{
AsyncContext.SetNonBlocking();
}
}
}
public int ReceiveTimeout
{
get
{
return _receiveTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}");
_receiveTimeout = value;;
}
}
public int SendTimeout
{
get
{
return _sendTimeout;
}
set
{
Debug.Assert(value == -1 || value > 0, $"Unexpected value: {value}");
_sendTimeout = value;
}
}
public static unsafe SafeCloseSocket CreateSocket(IntPtr fileDescriptor)
{
return CreateSocket(InnerSafeCloseSocket.CreateSocket(fileDescriptor));
}
public static unsafe SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.CreateSocket(addressFamily, socketType, protocolType, out errorCode));
return errorCode;
}
public static unsafe SocketError Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressSize, out SafeCloseSocket socket)
{
SocketError errorCode;
socket = CreateSocket(InnerSafeCloseSocket.Accept(socketHandle, socketAddress, ref socketAddressSize, out errorCode));
return errorCode;
}
private void InnerReleaseHandle()
{
if (_asyncContext != null)
{
_asyncContext.Close();
}
}
internal sealed partial class InnerSafeCloseSocket : SafeHandleMinusOneIsInvalid
{
private unsafe SocketError InnerReleaseHandle()
{
int errorCode;
// If _blockable was set in BlockingRelease, it's safe to block here, which means
// we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which
// case we need to do some recovery.
if (_blockable)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle} Following 'blockable' branch.");
errorCode = Interop.Sys.Close(handle);
if (errorCode == -1)
{
errorCode = (int)Interop.Sys.GetLastError();
}
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close()#1:{errorCode}");
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
// If it's not EWOULDBLOCK, there's no more recourse - we either succeeded or failed.
if (errorCode != (int)Interop.Error.EWOULDBLOCK)
{
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
// The socket must be non-blocking with a linger timeout set.
// We have to set the socket to blocking.
errorCode = Interop.Sys.Fcntl.DangerousSetIsNonBlocking(handle, 0);
if (errorCode == 0)
{
// The socket successfully made blocking; retry the close().
errorCode = Interop.Sys.Close(handle);
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close()#2:{errorCode}");
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
// The socket could not be made blocking; fall through to the regular abortive close.
}
// By default or if CloseAsIs() path failed, set linger timeout to zero to get an abortive close (RST).
var linger = new Interop.Sys.LingerOption {
OnOff = 1,
Seconds = 0
};
errorCode = (int)Interop.Sys.SetLingerOption(handle, &linger);
#if DEBUG
_closeSocketLinger = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, setsockopt():{errorCode}");
if (errorCode != 0 && errorCode != (int)Interop.Error.EINVAL && errorCode != (int)Interop.Error.ENOPROTOOPT)
{
// Too dangerous to try closesocket() - it might block!
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
errorCode = Interop.Sys.Close(handle);
#if DEBUG
_closeSocketHandle = handle;
_closeSocketResult = SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
#endif
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"handle:{handle}, close#3():{(errorCode == -1 ? (int)Interop.Sys.GetLastError() : errorCode)}");
return SocketPal.GetSocketErrorForErrorCode((Interop.Error)errorCode);
}
public static InnerSafeCloseSocket CreateSocket(IntPtr fileDescriptor)
{
var res = new InnerSafeCloseSocket();
res.SetHandle(fileDescriptor);
return res;
}
public static unsafe InnerSafeCloseSocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SocketError errorCode)
{
IntPtr fd;
Interop.Error error = Interop.Sys.Socket(addressFamily, socketType, protocolType, &fd);
if (error == Interop.Error.SUCCESS)
{
Debug.Assert(fd != (IntPtr)(-1), "fd should not be -1");
errorCode = SocketError.Success;
// The socket was created successfully; enable IPV6_V6ONLY by default for AF_INET6 sockets.
if (addressFamily == AddressFamily.InterNetworkV6)
{
int on = 1;
error = Interop.Sys.SetSockOpt(fd, SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, (byte*)&on, sizeof(int));
if (error != Interop.Error.SUCCESS)
{
Interop.Sys.Close(fd);
fd = (IntPtr)(-1);
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
}
}
else
{
Debug.Assert(fd == (IntPtr)(-1), $"Unexpected fd: {fd}");
errorCode = SocketPal.GetSocketErrorForErrorCode(error);
}
var res = new InnerSafeCloseSocket();
res.SetHandle(fd);
return res;
}
public static unsafe InnerSafeCloseSocket Accept(SafeCloseSocket socketHandle, byte[] socketAddress, ref int socketAddressLen, out SocketError errorCode)
{
IntPtr acceptedFd;
if (!socketHandle.IsNonBlocking)
{
errorCode = socketHandle.AsyncContext.Accept(socketAddress, ref socketAddressLen, -1, out acceptedFd);
}
else
{
bool completed = SocketPal.TryCompleteAccept(socketHandle, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode);
if (!completed)
{
errorCode = SocketError.WouldBlock;
}
}
var res = new InnerSafeCloseSocket();
res.SetHandle(acceptedFd);
return res;
}
}
}
/// <summary>Flags that correspond to exposed options on Socket.</summary>
[Flags]
internal enum TrackedSocketOptions : short
{
DontFragment = 0x1,
DualMode = 0x2,
EnableBroadcast = 0x4,
LingerState = 0x8,
NoDelay = 0x10,
ReceiveBufferSize = 0x20,
ReceiveTimeout = 0x40,
SendBufferSize = 0x80,
SendTimeout = 0x100,
Ttl = 0x200,
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class SplitGroupTargetTests : NLogTestBase
{
[Fact]
public void SplitGroupSyncTest1()
{
var myTarget1 = new MyTarget();
var myTarget2 = new MyTarget();
var myTarget3 = new MyTarget();
var wrapper = new SplitGroupTarget()
{
Targets = { myTarget1, myTarget2, myTarget3 },
};
myTarget1.Initialize(null);
myTarget2.Initialize(null);
myTarget3.Initialize(null);
wrapper.Initialize(null);
List<Exception> exceptions = new List<Exception>();
var inputEvents = new List<LogEventInfo>();
for (int i = 0; i < 10; ++i)
{
inputEvents.Add(LogEventInfo.CreateNullEvent());
}
int remaining = inputEvents.Count;
var allDone = new ManualResetEvent(false);
// no exceptions
for (int i = 0; i < inputEvents.Count; ++i)
{
wrapper.WriteAsyncLogEvent(inputEvents[i].WithContinuation(ex =>
{
lock (exceptions)
{
exceptions.Add(ex);
if (Interlocked.Decrement(ref remaining) == 0)
{
allDone.Set();
}
};
}));
}
allDone.WaitOne();
Assert.Equal(inputEvents.Count, exceptions.Count);
foreach (var e in exceptions)
{
Assert.Null(e);
}
Assert.Equal(inputEvents.Count, myTarget1.WriteCount);
Assert.Equal(inputEvents.Count, myTarget2.WriteCount);
Assert.Equal(inputEvents.Count, myTarget3.WriteCount);
for (int i = 0; i < inputEvents.Count; ++i)
{
Assert.Same(inputEvents[i], myTarget1.WrittenEvents[i]);
Assert.Same(inputEvents[i], myTarget2.WrittenEvents[i]);
Assert.Same(inputEvents[i], myTarget3.WrittenEvents[i]);
}
Exception flushException = null;
var flushHit = new ManualResetEvent(false);
wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });
flushHit.WaitOne();
if (flushException != null)
{
Assert.True(false, flushException.ToString());
}
Assert.Equal(1, myTarget1.FlushCount);
Assert.Equal(1, myTarget2.FlushCount);
Assert.Equal(1, myTarget3.FlushCount);
}
[Fact]
public void SplitGroupSyncTest2()
{
var wrapper = new SplitGroupTarget()
{
// no targets
};
wrapper.Initialize(null);
List<Exception> exceptions = new List<Exception>();
// no exceptions
for (int i = 0; i < 10; ++i)
{
wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
}
Assert.Equal(10, exceptions.Count);
foreach (var e in exceptions)
{
Assert.Null(e);
}
Exception flushException = new Exception("Flush not hit synchronously.");
wrapper.Flush(ex => flushException = ex);
if (flushException != null)
{
Assert.True(false, flushException.ToString());
}
}
public class MyAsyncTarget : Target
{
public int FlushCount { get; private set; }
public int WriteCount { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
this.WriteCount++;
ThreadPool.QueueUserWorkItem(
s =>
{
if (this.ThrowExceptions)
{
logEvent.Continuation(new InvalidOperationException("Some problem!"));
logEvent.Continuation(new InvalidOperationException("Some problem!"));
}
else
{
logEvent.Continuation(null);
logEvent.Continuation(null);
}
});
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.FlushCount++;
ThreadPool.QueueUserWorkItem(
s => asyncContinuation(null));
}
public bool ThrowExceptions { get; set; }
}
public class MyTarget : Target
{
public MyTarget()
{
this.WrittenEvents = new List<LogEventInfo>();
}
public int FlushCount { get; set; }
public int WriteCount { get; set; }
public int FailCounter { get; set; }
public List<LogEventInfo> WrittenEvents { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
Assert.True(this.FlushCount <= this.WriteCount);
lock (this)
{
this.WriteCount++;
this.WrittenEvents.Add(logEvent);
}
if (this.FailCounter > 0)
{
this.FailCounter--;
throw new InvalidOperationException("Some failure.");
}
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.FlushCount++;
asyncContinuation(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;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace System.Reflection
{
//
// Parses an assembly name.
//
[System.Runtime.CompilerServices.ReflectionBlocked]
public static class AssemblyNameParser
{
public static void Parse(AssemblyName blank, string s)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
RuntimeAssemblyName runtimeAssemblyName = Parse(s);
runtimeAssemblyName.CopyToAssemblyName(blank);
}
public static RuntimeAssemblyName Parse(string s)
{
Debug.Assert(s != null);
int indexOfNul = s.IndexOf((char)0);
if (indexOfNul != -1)
s = s.Substring(0, indexOfNul);
if (s.Length == 0)
throw new ArgumentException(SR.Format_StringZeroLength);
AssemblyNameLexer lexer = new AssemblyNameLexer(s);
// Name must come first.
string name;
AssemblyNameLexer.Token token = lexer.GetNext(out name);
if (token != AssemblyNameLexer.Token.String)
throw new FileLoadException(SR.InvalidAssemblyName);
if (name == string.Empty || name.IndexOfAny(s_illegalCharactersInSimpleName) != -1)
throw new FileLoadException(SR.InvalidAssemblyName);
Version version = null;
string cultureName = null;
byte[] pkt = null;
AssemblyNameFlags flags = 0;
LowLevelList<string> alreadySeen = new LowLevelList<string>();
token = lexer.GetNext();
while (token != AssemblyNameLexer.Token.End)
{
if (token != AssemblyNameLexer.Token.Comma)
throw new FileLoadException(SR.InvalidAssemblyName);
string attributeName;
token = lexer.GetNext(out attributeName);
if (token != AssemblyNameLexer.Token.String)
throw new FileLoadException(SR.InvalidAssemblyName);
token = lexer.GetNext();
// Compat note: Inside AppX apps, the desktop CLR's AssemblyName parser skips past any elements that don't follow the "<Something>=<Something>" pattern.
// (when running classic Windows apps, such an illegal construction throws an exception as expected.)
// Naturally, at least one app unwittingly takes advantage of this.
if (token == AssemblyNameLexer.Token.Comma || token == AssemblyNameLexer.Token.End)
continue;
if (token != AssemblyNameLexer.Token.Equals)
throw new FileLoadException(SR.InvalidAssemblyName);
string attributeValue;
token = lexer.GetNext(out attributeValue);
if (token != AssemblyNameLexer.Token.String)
throw new FileLoadException(SR.InvalidAssemblyName);
if (attributeName == string.Empty)
throw new FileLoadException(SR.InvalidAssemblyName);
for (int i = 0; i < alreadySeen.Count; i++)
{
if (alreadySeen[i].Equals(attributeName, StringComparison.OrdinalIgnoreCase))
throw new FileLoadException(SR.InvalidAssemblyName); // Cannot specify the same attribute twice.
}
alreadySeen.Add(attributeName);
if (attributeName.Equals("Version", StringComparison.OrdinalIgnoreCase))
{
version = ParseVersion(attributeValue);
}
if (attributeName.Equals("Culture", StringComparison.OrdinalIgnoreCase))
{
cultureName = ParseCulture(attributeValue);
}
if (attributeName.Equals("PublicKeyToken", StringComparison.OrdinalIgnoreCase))
{
pkt = ParsePKT(attributeValue);
}
if (attributeName.Equals("ProcessorArchitecture", StringComparison.OrdinalIgnoreCase))
{
flags |= (AssemblyNameFlags)(((int)ParseProcessorArchitecture(attributeValue)) << 4);
}
if (attributeName.Equals("Retargetable", StringComparison.OrdinalIgnoreCase))
{
if (attributeValue.Equals("Yes", StringComparison.OrdinalIgnoreCase))
flags |= AssemblyNameFlags.Retargetable;
else if (attributeValue.Equals("No", StringComparison.OrdinalIgnoreCase))
{
// nothing to do
}
else
throw new FileLoadException(SR.InvalidAssemblyName);
}
if (attributeName.Equals("ContentType", StringComparison.OrdinalIgnoreCase))
{
if (attributeValue.Equals("WindowsRuntime", StringComparison.OrdinalIgnoreCase))
flags |= (AssemblyNameFlags)(((int)AssemblyContentType.WindowsRuntime) << 9);
else
throw new FileLoadException(SR.InvalidAssemblyName);
}
// Desktop compat: If we got here, the attribute name is unknown to us. Ignore it (as long it's not duplicated.)
token = lexer.GetNext();
}
return new RuntimeAssemblyName(name, version, cultureName, flags, pkt);
}
private static Version ParseVersion(string attributeValue)
{
string[] parts = attributeValue.Split('.');
if (parts.Length > 4)
throw new FileLoadException(SR.InvalidAssemblyName);
ushort[] versionNumbers = new ushort[4];
for (int i = 0; i < versionNumbers.Length; i++)
{
if (i >= parts.Length)
versionNumbers[i] = ushort.MaxValue;
else
{
// Desktop compat: TryParse is a little more forgiving than Fusion.
for (int j = 0; j < parts[i].Length; j++)
{
if (!char.IsDigit(parts[i][j]))
throw new FileLoadException(SR.InvalidAssemblyName);
}
if (!(ushort.TryParse(parts[i], out versionNumbers[i])))
{
throw new FileLoadException(SR.InvalidAssemblyName);
}
}
}
if (versionNumbers[0] == ushort.MaxValue || versionNumbers[1] == ushort.MaxValue)
throw new FileLoadException(SR.InvalidAssemblyName);
if (versionNumbers[2] == ushort.MaxValue)
return new Version(versionNumbers[0], versionNumbers[1]);
if (versionNumbers[3] == ushort.MaxValue)
return new Version(versionNumbers[0], versionNumbers[1], versionNumbers[2]);
return new Version(versionNumbers[0], versionNumbers[1], versionNumbers[2], versionNumbers[3]);
}
private static string ParseCulture(string attributeValue)
{
if (attributeValue.Equals("Neutral", StringComparison.OrdinalIgnoreCase))
{
return "";
}
else
{
CultureInfo culture = new CultureInfo(attributeValue); // Force a CultureNotFoundException if not a valid culture.
return culture.Name;
}
}
private static byte[] ParsePKT(string attributeValue)
{
if (attributeValue.Equals("null", StringComparison.OrdinalIgnoreCase) || attributeValue == string.Empty)
return Array.Empty<byte>();
if (attributeValue.Length != 8 * 2)
throw new FileLoadException(SR.InvalidAssemblyName);
byte[] pkt = new byte[8];
int srcIndex = 0;
for (int i = 0; i < 8; i++)
{
char hi = attributeValue[srcIndex++];
char lo = attributeValue[srcIndex++];
pkt[i] = (byte)((ParseHexNybble(hi) << 4) | ParseHexNybble(lo));
}
return pkt;
}
private static ProcessorArchitecture ParseProcessorArchitecture(string attributeValue)
{
if (attributeValue.Equals("msil", StringComparison.OrdinalIgnoreCase))
return ProcessorArchitecture.MSIL;
if (attributeValue.Equals("x86", StringComparison.OrdinalIgnoreCase))
return ProcessorArchitecture.X86;
if (attributeValue.Equals("ia64", StringComparison.OrdinalIgnoreCase))
return ProcessorArchitecture.IA64;
if (attributeValue.Equals("amd64", StringComparison.OrdinalIgnoreCase))
return ProcessorArchitecture.Amd64;
if (attributeValue.Equals("arm", StringComparison.OrdinalIgnoreCase))
return ProcessorArchitecture.Arm;
throw new FileLoadException(SR.InvalidAssemblyName);
}
private static byte ParseHexNybble(char c)
{
if (c >= '0' && c <= '9')
return (byte)(c - '0');
if (c >= 'a' && c <= 'f')
return (byte)(c - 'a' + 10);
if (c >= 'A' && c <= 'F')
return (byte)(c - 'A' + 10);
throw new FileLoadException(SR.InvalidAssemblyName);
}
private static readonly char[] s_illegalCharactersInSimpleName = { '/', '\\', ':' };
}
}
| |
using BDSA2017.Lecture11.Common;
using BDSA2017.Lecture11.Entities;
using BDSA2017.Lecture11.Web.Models;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Moq;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace BDSA2017.Lecture11.Web.Tests.Models
{
public class EntityFrameworkCharacterRepositoryTests
{
[Fact]
public async Task CreateAsync_given_character_adds_it()
{
var entity = default(Character);
var context = new Mock<IFuturamaContext>();
context.Setup(c => c.Characters.Add(It.IsAny<Character>())).Callback<Character>(t => entity = t);
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterCreateDTO
{
ActorId = 1,
Name = "Name",
Species = "Species",
Planet = "Planet",
Image = "Image"
};
await repository.CreateAsync(character);
}
Assert.Equal(1, entity.ActorId);
Assert.Equal("Name", entity.Name);
Assert.Equal("Species", entity.Species);
Assert.Equal("Planet", entity.Planet);
Assert.Equal("Image", entity.Image);
}
[Fact]
public async Task Create_given_character_calls_SaveChangesAsync()
{
var context = new Mock<IFuturamaContext>();
context.Setup(c => c.Characters.Add(It.IsAny<Character>()));
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterCreateDTO
{
Name = "Name",
Species = "Species",
};
await repository.CreateAsync(character);
}
context.Verify(c => c.SaveChangesAsync(default(CancellationToken)));
}
[Fact]
public async Task Create_given_character_returns_new_Id()
{
var entity = default(Character);
var context = new Mock<IFuturamaContext>();
context.Setup(c => c.Characters.Add(It.IsAny<Character>()))
.Callback<Character>(t => entity = t);
context.Setup(c => c.SaveChangesAsync(default(CancellationToken)))
.Returns(Task.FromResult(0))
.Callback(() => entity.Id = 42);
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterCreateDTO
{
Name = "Name",
Species = "Species",
};
var id = await repository.CreateAsync(character);
Assert.Equal(42, id);
}
}
[Fact]
public async Task Find_given_non_existing_id_returns_null()
{
var builder = new DbContextOptionsBuilder<FuturamaContext>()
.UseInMemoryDatabase(nameof(Find_given_non_existing_id_returns_null));
using (var context = new FuturamaContext(builder.Options))
using (var repository = new CharacterRepository(context))
{
var character = await repository.FindAsync(42);
Assert.Null(character);
}
}
[Fact]
public async Task Find_given_existing_id_returns_mapped_CharacterDTO()
{
using (var connection = new SqliteConnection("DataSource=:memory:"))
{
connection.Open();
var builder = new DbContextOptionsBuilder<FuturamaContext>()
.UseSqlite(connection);
var context = new FuturamaContext(builder.Options);
await context.Database.EnsureCreatedAsync();
var entity = new Character
{
Name = "Name",
Species = "Species",
Planet = "Planet",
Image = "Image",
Actor = new Actor { Name = "Actor" },
Episodes = new[] { new EpisodeCharacter { Episode = new Episode { Title = "Episode 1" } }, new EpisodeCharacter { Episode = new Episode { Title = "Episode 2" } } }
};
context.Characters.Add(entity);
await context.SaveChangesAsync();
var id = entity.Id;
using (var repository = new CharacterRepository(context))
{
var character = await repository.FindAsync(id);
Assert.Equal("Name", character.Name);
Assert.Equal("Species", character.Species);
Assert.Equal("Planet", character.Planet);
Assert.Equal("Image", character.Image);
Assert.Equal("Actor", character.ActorName);
Assert.Equal(2, character.NumberOfEpisodes);
}
}
}
[Fact]
public async Task Read_returns_mapped_CharacterDTO()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var builder = new DbContextOptionsBuilder<FuturamaContext>()
.UseSqlite(connection);
var context = new FuturamaContext(builder.Options);
context.Database.EnsureCreated();
var entity = new Character
{
Name = "Name",
Species = "Species",
Actor = new Actor { Name = "Actor" }
};
context.Characters.Add(entity);
await context.SaveChangesAsync();
var id = entity.Id;
using (var repository = new CharacterRepository(context))
{
var characters = await repository.ReadAsync();
var character = characters.Single();
Assert.Equal("Name", character.Name);
Assert.Equal("Actor", character.ActorName);
}
}
[Fact]
public async Task Update_given_existing_character_Updates_properties()
{
var context = new Mock<IFuturamaContext>();
var entity = new Character { Id = 42 };
context.Setup(c => c.Characters.FindAsync(42)).ReturnsAsync(entity);
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterUpdateDTO
{
Id = 42,
ActorId = 12,
Name = "Name",
Species = "Species",
Planet = "Planet",
Image = "Image"
};
await repository.UpdateAsync(character);
}
Assert.Equal(12, entity.ActorId);
Assert.Equal("Name", entity.Name);
Assert.Equal("Species", entity.Species);
Assert.Equal("Planet", entity.Planet);
Assert.Equal("Image", entity.Image);
}
[Fact]
public async Task Update_given_existing_character_calls_SaveChangesAsync()
{
var context = new Mock<IFuturamaContext>();
var entity = new Character { Id = 42 };
context.Setup(c => c.Characters.FindAsync(42)).ReturnsAsync(entity);
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterUpdateDTO
{
Id = 42,
Name = "Name",
Species = "Species",
};
await repository.UpdateAsync(character);
}
context.Verify(c => c.SaveChangesAsync(default(CancellationToken)));
}
[Fact]
public async Task Update_given_existing_character_returns_true()
{
var context = new Mock<IFuturamaContext>();
var entity = new Character { Id = 42 };
context.Setup(c => c.Characters.FindAsync(42)).ReturnsAsync(entity);
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterUpdateDTO
{
Id = 42,
Name = "Name",
Species = "Species",
};
var result = await repository.UpdateAsync(character);
Assert.True(result);
}
}
[Fact]
public async Task Update_given_non_existing_character_returns_false()
{
var context = new Mock<IFuturamaContext>();
context.Setup(c => c.Characters.FindAsync(42)).ReturnsAsync(default(Character));
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterUpdateDTO
{
Id = 42,
Name = "Name",
Species = "Species",
};
var result = await repository.UpdateAsync(character);
Assert.False(result);
}
}
[Fact]
public async Task Update_given_non_existing_character_does_not_SaveChangesAsync()
{
var context = new Mock<IFuturamaContext>();
context.Setup(c => c.Characters.FindAsync(42)).ReturnsAsync(default(Character));
using (var repository = new CharacterRepository(context.Object))
{
var character = new CharacterUpdateDTO
{
Id = 42,
Name = "Name",
Species = "Species",
};
await repository.UpdateAsync(character);
}
context.Verify(c => c.SaveChangesAsync(default(CancellationToken)), Times.Never);
}
[Fact]
public async Task Delete_given_existing_character_removes_it()
{
var character = new Character();
var mock = new Mock<IFuturamaContext>();
mock.Setup(m => m.Characters.FindAsync(42)).ReturnsAsync(character);
using (var repository = new CharacterRepository(mock.Object))
{
await repository.DeleteAsync(42);
}
mock.Verify(m => m.Characters.Remove(character));
}
[Fact]
public async Task Delete_given_existing_character_calls_SaveChangesAsync()
{
var character = new Character();
var mock = new Mock<IFuturamaContext>();
mock.Setup(m => m.Characters.FindAsync(42)).ReturnsAsync(character);
using (var repository = new CharacterRepository(mock.Object))
{
await repository.DeleteAsync(42);
}
mock.Verify(m => m.SaveChangesAsync(default(CancellationToken)));
}
[Fact]
public async Task Delete_given_non_existing_character_does_not_remove_it()
{
var character = new Character();
var mock = new Mock<IFuturamaContext>();
mock.Setup(m => m.Characters.FindAsync(42)).ReturnsAsync(default(Character));
using (var repository = new CharacterRepository(mock.Object))
{
await repository.DeleteAsync(42);
}
mock.Verify(m => m.Characters.Remove(character), Times.Never);
}
[Fact]
public async Task Delete_given_non_existing_character_does_not_call_SaveChangesAsync()
{
var character = new Character();
var mock = new Mock<IFuturamaContext>();
mock.Setup(m => m.Characters.FindAsync(42)).ReturnsAsync(default(Character));
using (var repository = new CharacterRepository(mock.Object))
{
await repository.DeleteAsync(42);
}
mock.Verify(m => m.SaveChangesAsync(default(CancellationToken)), Times.Never);
}
[Fact]
public void Dispose_disposes_context()
{
var mock = new Mock<IFuturamaContext>();
using (var repository = new CharacterRepository(mock.Object))
{
}
mock.Verify(m => m.Dispose());
}
}
}
| |
#region License
// Copyright 2004-2010 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
namespace Framework.Windsor
{
using System;
using System.Configuration;
using System.IO;
using System.Reflection;
using NHibernate.Event;
using Configuration = NHibernate.Cfg.Configuration;
using Castle.Facilities.NHibernateIntegration;
using Castle.Core.Configuration;
using NHibernate.ByteCode.Castle;
using NHibernate.Cfg.Loquacious;
using NHibernate.Cfg.MappingSchema;
using Framework;
using Framework.HbmMapper;
using Castle.MicroKernel;
using Framework.NHibernateExt;
/// <summary>
/// Default imlementation of <see cref="IConfigurationBuilder"/>
/// </summary>
public class NHConfigurationBuilder : IConfigurationBuilder
{
private const String NHMappingAttributesAssemblyName = "NHibernate.Mapping.Attributes";
private IKernel kernel;
public NHConfigurationBuilder(IKernel kernel)
{
this.kernel = kernel;
}
/// <summary>
/// Builds the Configuration object from the specifed configuration
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
public virtual Configuration GetConfiguration(IConfiguration config)
{
Configuration cfg = ConfigureNHibernate();
AuditEventListener listener = kernel.Resolve<AuditEventListener>();
cfg.SetListener(ListenerType.PreInsert, listener);
cfg.SetListener(ListenerType.PreUpdate, listener);
ApplyConfigurationSettings(cfg, config.Children["settings"]);
RegisterAssemblies(cfg, config.Children["assemblies"]);
RegisterResources(cfg, config.Children["resources"]);
RegisterListeners(cfg, config.Children["listeners"]);
IHbmMapper[] mappers = this.kernel.ResolveAll<IHbmMapper>();
foreach (var mapper in mappers)
{
cfg.AddDeserializedMapping(mapper.GetMapping(), mapper.GetMapingName());
this.kernel.ReleaseComponent(mapper);
}
return cfg;
}
private Configuration ConfigureNHibernate()
{
Configuration cfg = new Configuration();
cfg.SessionFactory()
.Named("Demo")
.Proxy.Through<ProxyFactoryFactory>()
.Integrate
.Using<NHibernate.Dialect.MySQL5Dialect>()
.LogSqlInConsole()
.Schema
.Updating()
.BatchingQueries
.Each(100)
.Connected
.By<NHibernate.Driver.MySqlDataDriver>()
.Releasing(NHibernate.ConnectionReleaseMode.AfterTransaction)
.ByAppConfing("TestDb")
.CreateCommands
.AutoCommentingSql();
return cfg;
}
/// <summary>
/// Applies the configuration settings.
/// </summary>
/// <param name="cfg">The CFG.</param>
/// <param name="facilityConfig">The facility config.</param>
protected void ApplyConfigurationSettings(Configuration cfg, IConfiguration facilityConfig)
{
if (facilityConfig == null) return;
foreach (IConfiguration item in facilityConfig.Children)
{
String key = item.Attributes["key"];
String value = item.Value;
cfg.SetProperty(key, value);
}
}
/// <summary>
/// Registers the resources.
/// </summary>
/// <param name="cfg">The CFG.</param>
/// <param name="facilityConfig">The facility config.</param>
protected void RegisterResources(Configuration cfg, IConfiguration facilityConfig)
{
if (facilityConfig == null) return;
foreach (IConfiguration item in facilityConfig.Children)
{
String name = item.Attributes["name"];
String assembly = item.Attributes["assembly"];
if (assembly != null)
{
cfg.AddResource(name, ObtainAssembly(assembly));
}
else
{
cfg.AddXmlFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, name));
}
}
}
/// <summary>
/// Registers the listeners.
/// </summary>
/// <param name="cfg">The CFG.</param>
/// <param name="facilityConfig">The facility config.</param>
protected void RegisterListeners(Configuration cfg, IConfiguration facilityConfig)
{
if (facilityConfig == null) return;
foreach (IConfiguration item in facilityConfig.Children)
{
String eventName = item.Attributes["event"];
String typeName = item.Attributes["type"];
if (!Enum.IsDefined(typeof(ListenerType), eventName))
throw new ConfigurationErrorsException("An invalid listener type was specified.");
Type classType = Type.GetType(typeName);
//if (classType == null)
// throw new ConfigurationErrorsException("The full type name of the listener class must be specified.");
ListenerType listenerType = (ListenerType)Enum.Parse(typeof(ListenerType), eventName);
object listenerInstance = Activator.CreateInstance(classType);
cfg.SetListener(listenerType, listenerInstance);
}
}
/// <summary>
/// Registers the assemblies.
/// </summary>
/// <param name="cfg">The CFG.</param>
/// <param name="facilityConfig">The facility config.</param>
protected void RegisterAssemblies(Configuration cfg, IConfiguration facilityConfig)
{
if (facilityConfig == null) return;
foreach (IConfiguration item in facilityConfig.Children)
{
String assembly = item.Value;
cfg.AddAssembly(assembly);
GenerateMappingFromAttributesIfNeeded(cfg, assembly);
}
}
/// <summary>
/// If <paramref name="targetAssembly"/> has a reference on
/// <c>NHibernate.Mapping.Attributes</c> : use the NHibernate mapping
/// attributes contained in that assembly to update NHibernate
/// configuration (<paramref name="cfg"/>). Else do nothing
/// </summary>
/// <remarks>
/// To avoid an unnecessary dependency on the library
/// <c>NHibernate.Mapping.Attributes.dll</c> when using this
/// facility without NHibernate mapping attributes, all calls to that
/// library are made using reflexion.
/// </remarks>
/// <param name="cfg">NHibernate configuration</param>
/// <param name="targetAssembly">Target assembly name</param>
protected void GenerateMappingFromAttributesIfNeeded(Configuration cfg, String targetAssembly)
{
//Get an array of all assemblies referenced by targetAssembly
AssemblyName[] refAssemblies = Assembly.Load(targetAssembly).GetReferencedAssemblies();
//If assembly "NHibernate.Mapping.Attributes" is referenced in targetAssembly
if (Array.Exists(refAssemblies, delegate(AssemblyName an) { return an.Name.Equals(NHMappingAttributesAssemblyName); }))
{
//Obtains, by reflexion, the necessary tools to generate NH mapping from attributes
Type HbmSerializerType =
Type.GetType(String.Concat(NHMappingAttributesAssemblyName, ".HbmSerializer, ", NHMappingAttributesAssemblyName));
Object hbmSerializer = Activator.CreateInstance(HbmSerializerType);
PropertyInfo validate = HbmSerializerType.GetProperty("Validate");
MethodInfo serialize = HbmSerializerType.GetMethod("Serialize", new[] { typeof(Assembly) });
//Enable validation of mapping documents generated from the mapping attributes
validate.SetValue(hbmSerializer, true, null);
//Generates a stream of mapping documents from all decorated classes in targetAssembly and add it to NH config
cfg.AddInputStream((MemoryStream)serialize.Invoke(hbmSerializer, new object[] { Assembly.Load(targetAssembly) }));
}
}
private Assembly ObtainAssembly(String assembly)
{
try
{
return Assembly.Load(assembly);
}
catch (Exception ex)
{
String message = String.Format("The assembly {0} could not be loaded.", assembly);
throw new ConfigurationErrorsException(message, ex);
}
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// Common.cs
//
//
// Helper routines for the rest of the TPL Dataflow implementation.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Collections;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks.Dataflow.Internal.Threading;
namespace System.Threading.Tasks.Dataflow.Internal
{
/// <summary>Internal helper utilities.</summary>
internal static class Common
{
/// <summary>
/// An invalid ID to assign for reordering purposes. This value is chosen to be the last of the 64-bit integers that
/// could ever be assigned as a reordering ID.
/// </summary>
internal const long INVALID_REORDERING_ID = -1;
/// <summary>A well-known message ID for code that will send exactly one message or
/// where the exact message ID is not important.</summary>
internal const int SINGLE_MESSAGE_ID = 1;
/// <summary>A perf optimization for caching a well-known message header instead of
/// constructing one every time it is needed.</summary>
internal static readonly DataflowMessageHeader SingleMessageHeader = new DataflowMessageHeader(SINGLE_MESSAGE_ID);
/// <summary>The cached completed Task{bool} with a result of true.</summary>
internal static readonly Task<bool> CompletedTaskWithTrueResult = CreateCachedBooleanTask(true);
/// <summary>The cached completed Task{bool} with a result of false.</summary>
internal static readonly Task<bool> CompletedTaskWithFalseResult = CreateCachedBooleanTask(false);
/// <summary>The cached completed TaskCompletionSource{VoidResult}.</summary>
internal static readonly TaskCompletionSource<VoidResult> CompletedVoidResultTaskCompletionSource = CreateCachedTaskCompletionSource<VoidResult>();
/// <summary>Asserts that a given synchronization object is either held or not held.</summary>
/// <param name="syncObj">The monitor to check.</param>
/// <param name="held">Whether we want to assert that it's currently held or not held.</param>
[Conditional("DEBUG")]
internal static void ContractAssertMonitorStatus(object syncObj, bool held)
{
Debug.Assert(syncObj != null, "The monitor object to check must be provided.");
Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed.");
}
/// <summary>Keeping alive processing tasks: maximum number of processed messages.</summary>
internal const int KEEP_ALIVE_NUMBER_OF_MESSAGES_THRESHOLD = 1;
/// <summary>Keeping alive processing tasks: do not attempt this many times.</summary>
internal const int KEEP_ALIVE_BAN_COUNT = 1000;
/// <summary>A predicate type for TryKeepAliveUntil.</summary>
/// <param name="stateIn">Input state for the predicate in order to avoid closure allocations.</param>
/// <param name="stateOut">Output state for the predicate in order to avoid closure allocations.</param>
/// <returns>The state of the predicate.</returns>
internal delegate bool KeepAlivePredicate<TStateIn, TStateOut>(TStateIn stateIn, out TStateOut stateOut);
/// <summary>Actively waits for a predicate to become true.</summary>
/// <param name="predicate">The predicate to become true.</param>
/// <param name="stateIn">Input state for the predicate in order to avoid closure allocations.</param>
/// <param name="stateOut">Output state for the predicate in order to avoid closure allocations.</param>
/// <returns>True if the predicate was evaluated and it returned true. False otherwise.</returns>
internal static bool TryKeepAliveUntil<TStateIn, TStateOut>(KeepAlivePredicate<TStateIn, TStateOut> predicate,
TStateIn stateIn, out TStateOut stateOut)
{
Debug.Assert(predicate != null, "Non-null predicate to execute is required.");
const int ITERATION_LIMIT = 16;
for (int c = ITERATION_LIMIT; c > 0; c--)
{
if (!Thread.Yield())
{
// There was no other thread waiting.
// We may spend some more cycles to evaluate the predicate.
if (predicate(stateIn, out stateOut)) return true;
}
}
stateOut = default(TStateOut);
return false;
}
/// <summary>Unwraps an instance T from object state that is a WeakReference to that instance.</summary>
/// <typeparam name="T">The type of the data to be unwrapped.</typeparam>
/// <param name="state">The weak reference.</param>
/// <returns>The T instance.</returns>
internal static T UnwrapWeakReference<T>(object state) where T : class
{
var wr = state as WeakReference<T>;
Debug.Assert(wr != null, "Expected a WeakReference<T> as the state argument");
T item;
return wr.TryGetTarget(out item) ? item : null;
}
/// <summary>Gets an ID for the dataflow block.</summary>
/// <param name="block">The dataflow block.</param>
/// <returns>An ID for the dataflow block.</returns>
internal static int GetBlockId(IDataflowBlock block)
{
Debug.Assert(block != null, "Block required to extract an Id.");
const int NOTASKID = 0; // tasks don't have 0 as ids
Task t = Common.GetPotentiallyNotSupportedCompletionTask(block);
return t != null ? t.Id : NOTASKID;
}
/// <summary>Gets the name for the specified block, suitable to be rendered in a debugger window.</summary>
/// <param name="block">The block for which a name is needed.</param>
/// <param name="options">
/// The options to use when rendering the name. If no options are provided, the block's name is used directly.
/// </param>
/// <returns>The name of the object.</returns>
/// <remarks>This is used from DebuggerDisplay attributes.</remarks>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
[SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")]
internal static string GetNameForDebugger(
IDataflowBlock block, DataflowBlockOptions options = null)
{
Debug.Assert(block != null, "Should only be used with valid objects being displayed in the debugger.");
Debug.Assert(options == null || options.NameFormat != null, "If options are provided, NameFormat must be valid.");
if (block == null) return string.Empty;
string blockName = block.GetType().Name;
if (options == null) return blockName;
// {0} == block name
// {1} == block id
int blockId = GetBlockId(block);
// Since NameFormat is public, formatting may throw if the user has set
// a string that contains a reference to an argument higher than {1}.
// In the case of an exception, show the exception message.
try
{
return string.Format(options.NameFormat, blockName, blockId);
}
catch (Exception exception)
{
return exception.Message;
}
}
/// <summary>
/// Gets whether the exception represents a cooperative cancellation acknowledgment.
/// </summary>
/// <param name="exception">The exception to check.</param>
/// <returns>true if this exception represents a cooperative cancellation acknowledgment; otherwise, false.</returns>
internal static bool IsCooperativeCancellation(Exception exception)
{
Debug.Assert(exception != null, "An exception to check for cancellation must be provided.");
return exception is OperationCanceledException;
// Note that the behavior of this method does not exactly match that of Parallel.*, PLINQ, and Task.Factory.StartNew,
// in that it's more liberal and treats any OCE as acknowledgment of cancellation; in contrast, the other
// libraries only treat OCEs as such if they contain the same token that was provided by the user
// and if that token has cancellation requested. Such logic could be achieved here with:
// var oce = exception as OperationCanceledException;
// return oce != null &&
// oce.CancellationToken == dataflowBlockOptions.CancellationToken &&
// oce.CancellationToken.IsCancellationRequested;
// However, that leads to a discrepancy with the async processing case of dataflow blocks,
// where tasks are returned to represent the message processing, potentially in the Canceled state,
// and we simply ignore such tasks. Further, for blocks like TransformBlock, it's useful to be able
// to cancel an individual operation which must return a TOutput value, simply by throwing an OperationCanceledException.
// In such cases, you wouldn't want cancellation tied to the token, because you would only be able to
// cancel an individual message processing if the whole block was canceled.
}
/// <summary>Registers a block for cancellation by completing when cancellation is requested.</summary>
/// <param name="cancellationToken">The block's cancellation token.</param>
/// <param name="completionTask">The task that will complete when the block is completely done processing.</param>
/// <param name="completeAction">An action that will decline permanently on the state passed to it.</param>
/// <param name="completeState">The block on which to decline permanently.</param>
internal static void WireCancellationToComplete(
CancellationToken cancellationToken, Task completionTask, Action<object> completeAction, object completeState)
{
Debug.Assert(completionTask != null, "A task to wire up for completion is needed.");
Debug.Assert(completeAction != null, "An action to invoke upon cancellation is required.");
// If a cancellation request has already occurred, just invoke the declining action synchronously.
// CancellationToken would do this anyway but we can short-circuit it further and avoid a bunch of unnecessary checks.
if (cancellationToken.IsCancellationRequested)
{
completeAction(completeState);
}
// Otherwise, if a cancellation request occurs, we want to prevent the block from accepting additional
// data, and we also want to dispose of that registration when we complete so that we don't
// leak into a long-living cancellation token.
else if (cancellationToken.CanBeCanceled)
{
CancellationTokenRegistration reg = cancellationToken.Register(completeAction, completeState);
completionTask.ContinueWith((completed, state) => ((CancellationTokenRegistration)state).Dispose(),
reg, cancellationToken, Common.GetContinuationOptions(), TaskScheduler.Default);
}
}
/// <summary>Initializes the stack trace and watson bucket of an inactive exception.</summary>
/// <param name="exception">The exception to initialize.</param>
/// <returns>The initialized exception.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static Exception InitializeStackTrace(Exception exception)
{
Debug.Assert(exception != null && exception.StackTrace == null,
"A valid but uninitialized exception should be provided.");
try { throw exception; }
catch { return exception; }
}
/// <summary>The name of the key in an Exception's Data collection used to store information on a dataflow message.</summary>
internal const string EXCEPTIONDATAKEY_DATAFLOWMESSAGEVALUE = "DataflowMessageValue"; // should not be localized
/// <summary>Stores details on a dataflow message into an Exception's Data collection.</summary>
/// <typeparam name="T">Specifies the type of data stored in the message.</typeparam>
/// <param name="exc">The Exception whose Data collection should store message information.</param>
/// <param name="messageValue">The message information to be stored.</param>
/// <param name="targetInnerExceptions">Whether to store the data into the exception's inner exception(s) in addition to the exception itself.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static void StoreDataflowMessageValueIntoExceptionData<T>(Exception exc, T messageValue, bool targetInnerExceptions = false)
{
Debug.Assert(exc != null, "The exception into which data should be stored must be provided.");
// Get the string value to store
string strValue = messageValue as string;
if (strValue == null && messageValue != null)
{
try
{
strValue = messageValue.ToString();
}
catch { /* It's ok to eat all exceptions here. If ToString throws, we'll just ignore it. */ }
}
if (strValue == null) return;
// Store the data into the exception itself
StoreStringIntoExceptionData(exc, Common.EXCEPTIONDATAKEY_DATAFLOWMESSAGEVALUE, strValue);
// If we also want to target inner exceptions...
if (targetInnerExceptions)
{
// If this is an aggregate, store into all inner exceptions.
var aggregate = exc as AggregateException;
if (aggregate != null)
{
foreach (Exception innerException in aggregate.InnerExceptions)
{
StoreStringIntoExceptionData(innerException, Common.EXCEPTIONDATAKEY_DATAFLOWMESSAGEVALUE, strValue);
}
}
// Otherwise, if there's an Exception.InnerException, store into that.
else if (exc.InnerException != null)
{
StoreStringIntoExceptionData(exc.InnerException, Common.EXCEPTIONDATAKEY_DATAFLOWMESSAGEVALUE, strValue);
}
}
}
/// <summary>Stores the specified string value into the specified key slot of the specified exception's data dictionary.</summary>
/// <param name="exception">The exception into which the key/value should be stored.</param>
/// <param name="key">The key.</param>
/// <param name="value">The value to be serialized as a string and stored.</param>
/// <remarks>If the key is already present in the exception's data dictionary, the value is not overwritten.</remarks>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void StoreStringIntoExceptionData(Exception exception, string key, string value)
{
Debug.Assert(exception != null, "An exception is needed to store the data into.");
Debug.Assert(key != null, "A key into the exception's data collection is needed.");
Debug.Assert(value != null, "The value to store must be provided.");
try
{
IDictionary data = exception.Data;
if (data != null && !data.IsFixedSize && !data.IsReadOnly && data[key] == null)
{
data[key] = value;
}
}
catch
{
// It's ok to eat all exceptions here. This could throw if an Exception type
// has overridden Data to behave differently than we expect.
}
}
/// <summary>Throws an exception asynchronously on the thread pool.</summary>
/// <param name="error">The exception to throw.</param>
/// <remarks>
/// This function is used when an exception needs to be propagated from a thread
/// other than the current context. This could happen, for example, if the exception
/// should cause the standard CLR exception escalation behavior, but we're inside
/// of a task that will squirrel the exception away.
/// </remarks>
internal static void ThrowAsync(Exception error)
{
ExceptionDispatchInfo edi = ExceptionDispatchInfo.Capture(error);
ThreadPool.QueueUserWorkItem(state => { ((ExceptionDispatchInfo)state).Throw(); }, edi);
}
/// <summary>Adds the exception to the list, first initializing the list if the list is null.</summary>
/// <param name="list">The list to add the exception to, and initialize if null.</param>
/// <param name="exception">The exception to add or whose inner exception(s) should be added.</param>
/// <param name="unwrapInnerExceptions">Unwrap and add the inner exception(s) rather than the specified exception directly.</param>
/// <remarks>This method is not thread-safe, in that it manipulates <paramref name="list"/> without any synchronization.</remarks>
internal static void AddException(ref List<Exception> list, Exception exception, bool unwrapInnerExceptions = false)
{
Debug.Assert(exception != null, "An exception to add is required.");
Debug.Assert(!unwrapInnerExceptions || exception.InnerException != null,
"If unwrapping is requested, an inner exception is required.");
// Make sure the list of exceptions is initialized (lazily).
if (list == null) list = new List<Exception>();
if (unwrapInnerExceptions)
{
AggregateException aggregate = exception as AggregateException;
if (aggregate != null)
{
list.AddRange(aggregate.InnerExceptions);
}
else
{
list.Add(exception.InnerException);
}
}
else list.Add(exception);
}
/// <summary>Creates a task we can cache for the desired Boolean result.</summary>
/// <param name="value">The value of the Boolean.</param>
/// <returns>A task that may be cached.</returns>
private static Task<Boolean> CreateCachedBooleanTask(bool value)
{
// AsyncTaskMethodBuilder<Boolean> caches tasks that are non-disposable.
// By using these same tasks, we're a bit more robust against disposals,
// in that such a disposed task's ((IAsyncResult)task).AsyncWaitHandle
// is still valid.
var atmb = System.Runtime.CompilerServices.AsyncTaskMethodBuilder<Boolean>.Create();
atmb.SetResult(value);
return atmb.Task; // must be accessed after SetResult to get the cached task
}
/// <summary>Creates a TaskCompletionSource{T} completed with a value of default(T) that we can cache.</summary>
/// <returns>Completed TaskCompletionSource{T} that may be cached.</returns>
private static TaskCompletionSource<T> CreateCachedTaskCompletionSource<T>()
{
var tcs = new TaskCompletionSource<T>();
tcs.SetResult(default(T));
return tcs;
}
/// <summary>Creates a task faulted with the specified exception.</summary>
/// <typeparam name="TResult">Specifies the type of the result for this task.</typeparam>
/// <param name="exception">The exception with which to complete the task.</param>
/// <returns>The faulted task.</returns>
internal static Task<TResult> CreateTaskFromException<TResult>(Exception exception)
{
var atmb = System.Runtime.CompilerServices.AsyncTaskMethodBuilder<TResult>.Create();
atmb.SetException(exception);
return atmb.Task;
}
/// <summary>Creates a task canceled with the specified cancellation token.</summary>
/// <typeparam name="TResult">Specifies the type of the result for this task.</typeparam>
/// <returns>The canceled task.</returns>
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
internal static Task<TResult> CreateTaskFromCancellation<TResult>(CancellationToken cancellationToken)
{
Debug.Assert(cancellationToken.IsCancellationRequested,
"The task will only be immediately canceled if the token has cancellation requested already.");
var t = new Task<TResult>(CachedGenericDelegates<TResult>.DefaultTResultFunc, cancellationToken);
Debug.Assert(t.IsCanceled, "Task's constructor should cancel the task synchronously in the ctor.");
return t;
}
/// <summary>Gets the completion task of a block, and protects against common cases of the completion task not being implemented or supported.</summary>
/// <param name="block">The block.</param>
/// <returns>The completion task, or null if the block's completion task is not implemented or supported.</returns>
internal static Task GetPotentiallyNotSupportedCompletionTask(IDataflowBlock block)
{
Debug.Assert(block != null, "We need a block from which to retrieve a cancellation task.");
try
{
return block.Completion;
}
catch (NotImplementedException) { }
catch (NotSupportedException) { }
return null;
}
/// <summary>
/// Creates an IDisposable that, when disposed, will acquire the outgoing lock while removing
/// the target block from the target registry.
/// </summary>
/// <typeparam name="TOutput">Specifies the type of data in the block.</typeparam>
/// <param name="outgoingLock">The outgoing lock used to protect the target registry.</param>
/// <param name="targetRegistry">The target registry from which the target should be removed.</param>
/// <param name="targetBlock">The target to remove from the registry.</param>
/// <returns>An IDisposable that will unregister the target block from the registry while holding the outgoing lock.</returns>
internal static IDisposable CreateUnlinker<TOutput>(object outgoingLock, TargetRegistry<TOutput> targetRegistry, ITargetBlock<TOutput> targetBlock)
{
Debug.Assert(outgoingLock != null, "Monitor object needed to protect the operation.");
Debug.Assert(targetRegistry != null, "Registry from which to remove is required.");
Debug.Assert(targetBlock != null, "Target block to unlink is required.");
return Disposables.Create(CachedGenericDelegates<TOutput>.CreateUnlinkerShimAction,
outgoingLock, targetRegistry, targetBlock);
}
/// <summary>An infinite TimeSpan.</summary>
internal static readonly TimeSpan InfiniteTimeSpan = Timeout.InfiniteTimeSpan;
/// <summary>Validates that a timeout either is -1 or is non-negative and within the range of an Int32.</summary>
/// <param name="timeout">The timeout to validate.</param>
/// <returns>true if the timeout is valid; otherwise, false.</returns>
internal static bool IsValidTimeout(TimeSpan timeout)
{
long millisecondsTimeout = (long)timeout.TotalMilliseconds;
return millisecondsTimeout >= Timeout.Infinite && millisecondsTimeout <= Int32.MaxValue;
}
/// <summary>Gets the options to use for continuation tasks.</summary>
/// <param name="toInclude">Any options to include in the result.</param>
/// <returns>The options to use.</returns>
internal static TaskContinuationOptions GetContinuationOptions(TaskContinuationOptions toInclude = TaskContinuationOptions.None)
{
return toInclude | TaskContinuationOptions.DenyChildAttach;
}
/// <summary>Gets the options to use for tasks.</summary>
/// <param name="isReplacementReplica">If this task is being created to replace another.</param>
/// <remarks>
/// These options should be used for all tasks that have the potential to run user code or
/// that are repeatedly spawned and thus need a modicum of fair treatment.
/// </remarks>
/// <returns>The options to use.</returns>
internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false)
{
TaskCreationOptions options = TaskCreationOptions.DenyChildAttach;
if (isReplacementReplica) options |= TaskCreationOptions.PreferFairness;
return options;
}
/// <summary>Starts an already constructed task with handling and observing exceptions that may come from the scheduling process.</summary>
/// <param name="task">Task to be started.</param>
/// <param name="scheduler">TaskScheduler to schedule the task on.</param>
/// <returns>null on success, an exception reference on scheduling error. In the latter case, the task reference is nulled out.</returns>
internal static Exception StartTaskSafe(Task task, TaskScheduler scheduler)
{
Debug.Assert(task != null, "Task to start is required.");
Debug.Assert(scheduler != null, "Scheduler on which to start the task is required.");
if (scheduler == TaskScheduler.Default)
{
task.Start(scheduler);
return null; // We don't need to worry about scheduler exceptions from the default scheduler.
}
// Slow path with try/catch separated out so that StartTaskSafe may be inlined in the common case.
else return StartTaskSafeCore(task, scheduler);
}
/// <summary>Starts an already constructed task with handling and observing exceptions that may come from the scheduling process.</summary>
/// <param name="task">Task to be started.</param>
/// <param name="scheduler">TaskScheduler to schedule the task on.</param>
/// <returns>null on success, an exception reference on scheduling error. In the latter case, the task reference is nulled out.</returns>
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static Exception StartTaskSafeCore(Task task, TaskScheduler scheduler)
{
Debug.Assert(task != null, "Task to start is needed.");
Debug.Assert(scheduler != null, "Scheduler on which to start the task is required.");
Exception schedulingException = null;
try
{
task.Start(scheduler);
}
catch (Exception caughtException)
{
// Verify TPL has faulted the task
Debug.Assert(task.IsFaulted, "The task should have been faulted if it failed to start.");
// Observe the task's exception
AggregateException ignoredTaskException = task.Exception;
schedulingException = caughtException;
}
return schedulingException;
}
/// <summary>Pops and explicitly releases postponed messages after the block is done with processing.</summary>
/// <remarks>No locks should be held at this time. Unfortunately we cannot assert that.</remarks>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal static void ReleaseAllPostponedMessages<T>(ITargetBlock<T> target,
QueuedMap<ISourceBlock<T>, DataflowMessageHeader> postponedMessages,
ref List<Exception> exceptions)
{
Debug.Assert(target != null, "There must be a subject target.");
Debug.Assert(postponedMessages != null, "The stacked map of postponed messages must exist.");
// Note that we don't synchronize on lockObject for postponedMessages here,
// because no one should be adding to it at this time. We do a bit of
// checking just for sanity's sake.
int initialCount = postponedMessages.Count;
int processedCount = 0;
KeyValuePair<ISourceBlock<T>, DataflowMessageHeader> sourceAndMessage;
while (postponedMessages.TryPop(out sourceAndMessage))
{
// Loop through all postponed messages declining each messages.
// The only way we have to do this is by reserving and then immediately releasing each message.
// This is important for sources like SendAsyncSource, which keep state around until
// they get a response to a postponed message.
try
{
Debug.Assert(sourceAndMessage.Key != null, "Postponed messages must have an associated source.");
if (sourceAndMessage.Key.ReserveMessage(sourceAndMessage.Value, target))
{
sourceAndMessage.Key.ReleaseReservation(sourceAndMessage.Value, target);
}
}
catch (Exception exc)
{
Common.AddException(ref exceptions, exc);
}
processedCount++;
}
Debug.Assert(processedCount == initialCount,
"We should have processed the exact number of elements that were initially there.");
}
/// <summary>Cache ThrowAsync to avoid allocations when it is passed into PropagateCompletionXxx.</summary>
internal static readonly Action<Exception> AsyncExceptionHandler = ThrowAsync;
/// <summary>
/// Propagates completion of sourceCompletionTask to target synchronously.
/// </summary>
/// <param name="sourceCompletionTask">The task whose completion is to be propagated. It must be completed.</param>
/// <param name="target">The block where completion is propagated.</param>
/// <param name="exceptionHandler">Handler for exceptions from the target. May be null which would propagate the exception to the caller.</param>
internal static void PropagateCompletion(Task sourceCompletionTask, IDataflowBlock target, Action<Exception> exceptionHandler)
{
Debug.Assert(sourceCompletionTask != null, "sourceCompletionTask may not be null.");
Debug.Assert(target != null, "The target where completion is to be propagated may not be null.");
Debug.Assert(sourceCompletionTask.IsCompleted, "sourceCompletionTask must be completed in order to propagate its completion.");
AggregateException exception = sourceCompletionTask.IsFaulted ? sourceCompletionTask.Exception : null;
try
{
if (exception != null) target.Fault(exception);
else target.Complete();
}
catch (Exception exc)
{
if (exceptionHandler != null) exceptionHandler(exc);
else throw;
}
}
/// <summary>
/// Creates a continuation off sourceCompletionTask to complete target. See PropagateCompletion.
/// </summary>
private static void PropagateCompletionAsContinuation(Task sourceCompletionTask, IDataflowBlock target)
{
Debug.Assert(sourceCompletionTask != null, "sourceCompletionTask may not be null.");
Debug.Assert(target != null, "The target where completion is to be propagated may not be null.");
sourceCompletionTask.ContinueWith((task, state) => Common.PropagateCompletion(task, (IDataflowBlock)state, AsyncExceptionHandler),
target, CancellationToken.None, Common.GetContinuationOptions(), TaskScheduler.Default);
}
/// <summary>
/// Propagates completion of sourceCompletionTask to target based on sourceCompletionTask's current state. See PropagateCompletion.
/// </summary>
internal static void PropagateCompletionOnceCompleted(Task sourceCompletionTask, IDataflowBlock target)
{
Debug.Assert(sourceCompletionTask != null, "sourceCompletionTask may not be null.");
Debug.Assert(target != null, "The target where completion is to be propagated may not be null.");
// If sourceCompletionTask is completed, propagate completion synchronously.
// Otherwise hook up a continuation.
if (sourceCompletionTask.IsCompleted) PropagateCompletion(sourceCompletionTask, target, exceptionHandler: null);
else PropagateCompletionAsContinuation(sourceCompletionTask, target);
}
/// <summary>Static class used to cache generic delegates the C# compiler doesn't cache by default.</summary>
/// <remarks>Without this, we end up allocating the generic delegate each time the operation is used.</remarks>
static class CachedGenericDelegates<T>
{
/// <summary>A function that returns the default value of T.</summary>
internal static readonly Func<T> DefaultTResultFunc = () => default(T);
/// <summary>
/// A function to use as the body of ActionOnDispose in CreateUnlinkerShim.
/// Passed a tuple of the sync obj, the target registry, and the target block as the state parameter.
/// </summary>
internal static readonly Action<object, TargetRegistry<T>, ITargetBlock<T>> CreateUnlinkerShimAction =
(syncObj, registry, target) =>
{
lock (syncObj) registry.Remove(target);
};
}
}
/// <summary>State used only when bounding.</summary>
[DebuggerDisplay("BoundedCapacity={BoundedCapacity}}")]
internal class BoundingState
{
/// <summary>The maximum number of messages allowed to be buffered.</summary>
internal readonly int BoundedCapacity;
/// <summary>The number of messages currently stored.</summary>
/// <remarks>
/// This value may temporarily be higher than the actual number stored.
/// That's ok, we just can't accept any new messages if CurrentCount >= BoundedCapacity.
/// Worst case is that we may temporarily have fewer items in the block than our maximum allows,
/// but we'll never have more.
/// </remarks>
internal int CurrentCount;
/// <summary>Initializes the BoundingState.</summary>
/// <param name="boundedCapacity">The positive bounded capacity.</param>
internal BoundingState(int boundedCapacity)
{
Debug.Assert(boundedCapacity > 0, "Bounded is only supported with positive values.");
BoundedCapacity = boundedCapacity;
}
/// <summary>Gets whether there's room available to add another message.</summary>
internal bool CountIsLessThanBound { get { return CurrentCount < BoundedCapacity; } }
}
/// <summary>Stated used only when bounding and when postponed messages are stored.</summary>
/// <typeparam name="TInput">Specifies the type of input messages.</typeparam>
[DebuggerDisplay("BoundedCapacity={BoundedCapacity}, PostponedMessages={PostponedMessagesCountForDebugger}")]
internal class BoundingStateWithPostponed<TInput> : BoundingState
{
/// <summary>Queue of postponed messages.</summary>
internal readonly QueuedMap<ISourceBlock<TInput>, DataflowMessageHeader> PostponedMessages =
new QueuedMap<ISourceBlock<TInput>, DataflowMessageHeader>();
/// <summary>
/// The number of transfers from the postponement queue to the input queue currently being processed.
/// </summary>
/// <remarks>
/// Blocks that use TargetCore need to transfer messages from the postponed queue to the input messages
/// queue. While doing that, new incoming messages may arrive, and if they view the postponed queue
/// as being empty (after the block has removed the last postponed message and is consuming it, before
/// storing it into the input queue), they might go directly into the input queue... that will then mess
/// up the ordering between those postponed messages and the newly incoming messages. To address that,
/// OutstandingTransfers is used to track the number of transfers currently in progress. Incoming
/// messages must be postponed not only if there are already any postponed messages, but also if
/// there are any transfers in progress (i.e. this value is > 0). It's an integer because the DOP could
/// be greater than 1, and thus we need to ref count multiple transfers that might be in progress.
/// </remarks>
internal int OutstandingTransfers;
/// <summary>Initializes the BoundingState.</summary>
/// <param name="boundedCapacity">The positive bounded capacity.</param>
internal BoundingStateWithPostponed(int boundedCapacity) : base(boundedCapacity)
{
}
/// <summary>Gets the number of postponed messages for the debugger.</summary>
private int PostponedMessagesCountForDebugger { get { return PostponedMessages.Count; } }
}
/// <summary>Stated used only when bounding and when postponed messages and a task are stored.</summary>
/// <typeparam name="TInput">Specifies the type of input messages.</typeparam>
internal class BoundingStateWithPostponedAndTask<TInput> : BoundingStateWithPostponed<TInput>
{
/// <summary>The task used to process messages.</summary>
internal Task TaskForInputProcessing;
/// <summary>Initializes the BoundingState.</summary>
/// <param name="boundedCapacity">The positive bounded capacity.</param>
internal BoundingStateWithPostponedAndTask(int boundedCapacity) : base(boundedCapacity)
{
}
}
/// <summary>
/// Type used with TaskCompletionSource(Of TResult) as the TResult
/// to ensure that the resulting task can't be upcast to something
/// that in the future could lead to compat problems.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
[DebuggerNonUserCode]
internal struct VoidResult { }
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Globalization;
using Xunit;
namespace System.Net.Mime.Tests
{
public class ContentDispositionTest
{
private const string ValidDateGmt = "Sun, 17 May 2009 15:34:07 GMT";
private const string ValidDateGmtOffset = "Sun, 17 May 2009 15:34:07 +0000";
private const string ValidDateUnspecified = "Sun, 17 May 2009 15:34:07 -0000";
private const string ValidDateTimeLocal = "Sun, 17 May 2009 15:34:07 -0800";
private const string ValidDateTimeNotLocal = "Sun, 17 May 2009 15:34:07 -0200";
private const string InvalidDate = "Sun, 32 Say 2009 25:15:15 7m-gte";
private static readonly TimeSpan s_localTimeOffset = TimeZoneInfo.Local.GetUtcOffset(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local));
[Fact]
public static void DefaultCtor_ExpectedDefaultPropertyValues()
{
var cd = new ContentDisposition();
Assert.Equal(DateTime.MinValue, cd.CreationDate);
Assert.Equal("attachment", cd.DispositionType);
Assert.Null(cd.FileName);
Assert.False(cd.Inline);
Assert.Equal(DateTime.MinValue, cd.ModificationDate);
Assert.Empty(cd.Parameters);
Assert.Equal(DateTime.MinValue, cd.ReadDate);
Assert.Equal(-1, cd.Size);
Assert.Equal("attachment", cd.ToString());
}
[Fact]
public void ConstructorWithOtherPropertyValues_ShouldSetAppropriately()
{
var cd = new ContentDisposition("attachment;creation-date=\"" + ValidDateTimeLocal + "\";read-date=\"" +
ValidDateTimeLocal + "\";modification-date=\"" +
ValidDateTimeLocal + "\";filename=\"=?utf-8?B?dGVzdC50eHTnkIY=?=\";size=200");
Assert.Equal("attachment", cd.DispositionType);
Assert.False(cd.Inline);
Assert.Equal(200, cd.Size);
Assert.Equal("=?utf-8?B?dGVzdC50eHTnkIY=?=", cd.FileName);
cd.FileName = "test.txt\x7406";
Assert.Equal("test.txt\x7406", cd.FileName);
}
[Theory]
[InlineData(typeof(ArgumentNullException), null)]
[InlineData(typeof(FormatException), "inline; creation-date=\"" + InvalidDate + "\";")]
[InlineData(typeof(FormatException), "inline; size=\"notANumber\"")]
public static void Ctor_InvalidThrows(Type exceptionType, string contentDisposition)
{
Assert.Throws(exceptionType, () => new ContentDisposition(contentDisposition));
}
[Theory]
[InlineData(typeof(ArgumentNullException), null)]
[InlineData(typeof(ArgumentException), "")]
public static void DispositionType_SetValue_InvalidThrows(Type exceptionType, string contentDisposition)
{
Assert.Throws(exceptionType, () => new ContentDisposition().DispositionType = contentDisposition);
}
[Fact]
public static void Filename_Roundtrip()
{
var cd = new ContentDisposition();
Assert.Null(cd.FileName);
Assert.Empty(cd.Parameters);
cd.FileName = "hello";
Assert.Equal("hello", cd.FileName);
Assert.Equal(1, cd.Parameters.Count);
Assert.Equal("hello", cd.Parameters["filename"]);
Assert.Equal("attachment; filename=hello", cd.ToString());
cd.FileName = "world";
Assert.Equal("world", cd.FileName);
Assert.Equal(1, cd.Parameters.Count);
Assert.Equal("world", cd.Parameters["filename"]);
Assert.Equal("attachment; filename=world", cd.ToString());
cd.FileName = null;
Assert.Null(cd.FileName);
Assert.Empty(cd.Parameters);
cd.FileName = string.Empty;
Assert.Null(cd.FileName);
Assert.Empty(cd.Parameters);
}
[Fact]
public static void Inline_Roundtrip()
{
var cd = new ContentDisposition();
Assert.False(cd.Inline);
cd.Inline = true;
Assert.True(cd.Inline);
cd.Inline = false;
Assert.False(cd.Inline);
Assert.Empty(cd.Parameters);
}
[Fact]
public static void Dates_RoundtripWithoutImpactingOtherDates()
{
var cd = new ContentDisposition();
Assert.Equal(DateTime.MinValue, cd.CreationDate);
Assert.Equal(DateTime.MinValue, cd.ModificationDate);
Assert.Equal(DateTime.MinValue, cd.ReadDate);
Assert.Empty(cd.Parameters);
DateTime dt1 = DateTime.Now;
cd.CreationDate = dt1;
Assert.Equal(1, cd.Parameters.Count);
DateTime dt2 = DateTime.Now;
cd.ModificationDate = dt2;
Assert.Equal(2, cd.Parameters.Count);
DateTime dt3 = DateTime.Now;
cd.ReadDate = dt3;
Assert.Equal(3, cd.Parameters.Count);
Assert.Equal(dt1, cd.CreationDate);
Assert.Equal(dt2, cd.ModificationDate);
Assert.Equal(dt3, cd.ReadDate);
Assert.Equal(3, cd.Parameters.Count);
}
[Fact]
public void SetAndResetDateViaParameters_ShouldWorkCorrectly()
{
var cd = new ContentDisposition("inline");
cd.Parameters["creation-date"] = ValidDateUnspecified;
Assert.Equal(DateTimeKind.Unspecified, cd.CreationDate.Kind);
Assert.Equal(ValidDateUnspecified, cd.Parameters["creation-date"]);
cd.Parameters["creation-date"] = ValidDateTimeLocal;
Assert.Equal(ValidDateTimeLocal, cd.Parameters["creation-date"]);
Assert.Equal(ValidDateTimeLocal, cd.Parameters["Creation-Date"]);
}
[Fact]
public static void DispositionType_Roundtrip()
{
var cd = new ContentDisposition();
Assert.Equal("attachment", cd.DispositionType);
Assert.Empty(cd.Parameters);
cd.DispositionType = "hello";
Assert.Equal("hello", cd.DispositionType);
cd.DispositionType = "world";
Assert.Equal("world", cd.DispositionType);
Assert.Equal(0, cd.Parameters.Count);
}
[Fact]
public static void Size_Roundtrip()
{
var cd = new ContentDisposition();
Assert.Equal(-1, cd.Size);
Assert.Empty(cd.Parameters);
cd.Size = 42;
Assert.Equal(42, cd.Size);
Assert.Equal(1, cd.Parameters.Count);
}
[Fact]
public static void ConstructorWithDateTimesBefore10AM_DateTimesAreValidForReUse()
{
ContentDisposition contentDisposition =
new ContentDisposition("attachment; filename=\"image.jpg\"; size=461725;\tcreation-date=\"Sun, 15 Apr 2012 09:55:44 GMT\";\tmodification-date=\"Sun, 15 Apr 2012 06:30:20 GMT\"");
var contentDisposition2 = new ContentDisposition();
contentDisposition2.Parameters.Add("creation-date", contentDisposition.Parameters["creation-date"]);
contentDisposition2.Parameters.Add("modification-date", contentDisposition.Parameters["modification-date"]);
Assert.Equal(contentDisposition.CreationDate, contentDisposition2.CreationDate);
Assert.Equal(contentDisposition.ModificationDate, contentDisposition2.ModificationDate);
}
[Fact]
public static void UseDifferentCultureAndConstructorWithDateTimesBefore10AM_DateTimesAreValidForReUse()
{
ContentDisposition contentDisposition =
new ContentDisposition("attachment; filename=\"image.jpg\"; size=461725;\tcreation-date=\"Sun, 15 Apr 2012 09:55:44 GMT\";\tmodification-date=\"Sun, 15 Apr 2012 06:30:20 GMT\"");
CultureInfo origCulture = CultureInfo.CurrentCulture;
CultureInfo.CurrentCulture = new CultureInfo("zh-cn");
try
{
ContentDisposition contentDisposition2 = new ContentDisposition();
contentDisposition2.Parameters.Add("creation-date", contentDisposition.Parameters["creation-date"]);
contentDisposition2.Parameters.Add("modification-date", contentDisposition.Parameters["modification-date"]);
Assert.Equal(contentDisposition.CreationDate, contentDisposition2.CreationDate);
Assert.Equal(contentDisposition.ModificationDate, contentDisposition2.ModificationDate);
}
finally
{
CultureInfo.CurrentCulture = origCulture;
}
}
[Fact]
public void SetDateViaConstructor_ShouldPersistToPropertyAndPersistToParametersCollection()
{
string disposition = "inline; creation-date=\"" + ValidDateGmt + "\";";
string dispositionValue = "inline; creation-date=\"" + ValidDateGmtOffset + "\"";
var cd = new ContentDisposition(disposition);
Assert.Equal(ValidDateGmtOffset, cd.Parameters["creation-date"]);
Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate);
Assert.Equal("inline", cd.DispositionType);
Assert.Equal(dispositionValue, cd.ToString());
}
[Fact]
public static void SetDateViaProperty_ShouldPersistToProprtyAndParametersCollection_AndRespectKindProperty()
{
DateTime date = new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Unspecified);
var cd = new ContentDisposition("inline");
cd.CreationDate = date;
Assert.Equal(ValidDateUnspecified, cd.Parameters["creation-date"]);
Assert.Equal(date, cd.CreationDate);
}
[Fact]
public static void GetViaDateTimeProperty_WithUniversalTime_ShouldSetDateTimeKindAppropriately()
{
var cd = new ContentDisposition("inline");
cd.Parameters["creation-date"] = ValidDateGmt;
Assert.Equal(DateTimeKind.Local, cd.CreationDate.Kind);
Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate);
}
[Fact]
public void GetViaDateTimeProperty_WithLocalTime_ShouldSetDateTimeKindAppropriately()
{
var cd = new ContentDisposition("inline");
cd.Parameters["creation-date"] = ValidDateTimeLocal;
Assert.Equal(DateTimeKind.Local, cd.CreationDate.Kind);
Assert.Equal(cd.Parameters["creation-date"], ValidDateTimeLocal);
}
[Fact]
public void GetViaDateTimeProperty_WithOtherTime_ShouldSetDateTimeKindAppropriately()
{
var cd = new ContentDisposition("inline");
cd.Parameters["creation-date"] = ValidDateUnspecified;
Assert.Equal(DateTimeKind.Unspecified, cd.CreationDate.Kind);
}
[Fact]
public void GetViaDateTimeProperty_WithNonLocalTimeZone_ShouldWorkCorrectly()
{
var cd = new ContentDisposition("inline");
cd.Parameters["creation-date"] = ValidDateTimeNotLocal;
DateTime result = cd.CreationDate;
Assert.Equal(ValidDateTimeNotLocal, cd.Parameters["creation-date"]);
Assert.Equal(DateTimeKind.Local, result.Kind);
// be sure that the local offset isn't the same as the offset we're testing
// so that this comparison will be valid
if (s_localTimeOffset != new TimeSpan(-2, 0, 0))
{
Assert.NotEqual(ValidDateTimeNotLocal, result.ToString("ddd, dd MMM yyyy H:mm:ss"));
}
}
[Fact]
public void SetCreateDateViaParameters_WithInvalidDate_ShouldThrow()
{
var cd = new ContentDisposition("inline");
Assert.Throws<FormatException>(() =>
{
cd.Parameters["creation-date"] = InvalidDate;
//string date = cd.Parameters["creation-date"];
});
}
[Fact]
public void GetCustomerParameterThatIsNotSet_ShouldReturnNull()
{
var cd = new ContentDisposition("inline");
Assert.Null(cd.Parameters["doesnotexist"]);
Assert.Equal("inline", cd.DispositionType);
Assert.True(cd.Inline);
}
[Fact]
public void SetDispositionViaConstructor_ShouldSetCorrectly_AndRespectCustomValues()
{
var cd = new ContentDisposition("inline; creation-date=\"" + ValidDateGmtOffset + "\"; X-Test=\"value\"");
Assert.Equal("inline", cd.DispositionType);
Assert.Equal(ValidDateGmtOffset, cd.Parameters["creation-date"]);
Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07, DateTimeKind.Local) + s_localTimeOffset, cd.CreationDate);
}
[Fact]
public void CultureSensitiveSetDateViaProperty_ShouldPersistToProprtyAndParametersCollectionAndRespectKindProperty()
{
CultureInfo origCulture = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = new CultureInfo("zh");
var cd = new ContentDisposition("inline");
var date = new DateTime(2011, 6, 8, 15, 34, 07, DateTimeKind.Unspecified);
cd.CreationDate = date;
Assert.Equal("Wed, 08 Jun 2011 15:34:07 -0000", cd.Parameters["creation-date"]);
Assert.Equal(date, cd.CreationDate);
Assert.Equal("inline; creation-date=\"Wed, 08 Jun 2011 15:34:07 -0000\"", cd.ToString());
}
finally
{
CultureInfo.CurrentCulture = origCulture;
}
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
namespace Microsoft.Extensions.DependencyModel
{
public partial class DependencyContextWriter
{
private void WriteCore(DependencyContext context, UnifiedJsonWriter jsonWriter)
{
jsonWriter.WriteStartObject();
WriteRuntimeTargetInfo(context, ref jsonWriter);
WriteCompilationOptions(context.CompilationOptions, ref jsonWriter);
WriteTargets(context, ref jsonWriter);
WriteLibraries(context, ref jsonWriter);
if (context.RuntimeGraph.Any())
{
WriteRuntimeGraph(context, ref jsonWriter);
}
jsonWriter.WriteEndObject();
jsonWriter.Flush();
}
private void WriteRuntimeTargetInfo(DependencyContext context, ref UnifiedJsonWriter jsonWriter)
{
jsonWriter.WriteStartObject(DependencyContextStrings.RuntimeTargetPropertyName, escape: false);
if (context.Target.IsPortable)
{
jsonWriter.WriteString(DependencyContextStrings.RuntimeTargetNamePropertyName,
context.Target.Framework, escape: false);
}
else
{
jsonWriter.WriteString(DependencyContextStrings.RuntimeTargetNamePropertyName,
context.Target.Framework + DependencyContextStrings.VersionSeparator + context.Target.Runtime, escape: false);
}
jsonWriter.WriteString(DependencyContextStrings.RuntimeTargetSignaturePropertyName,
context.Target.RuntimeSignature, escape: false);
jsonWriter.WriteEndObject();
}
private void WriteRuntimeGraph(DependencyContext context, ref UnifiedJsonWriter jsonWriter)
{
jsonWriter.WriteStartObject(DependencyContextStrings.RuntimesPropertyName, escape: false);
foreach (RuntimeFallbacks runtimeFallback in context.RuntimeGraph)
{
jsonWriter.WriteStartArray(runtimeFallback.Runtime);
foreach (string fallback in runtimeFallback.Fallbacks)
{
jsonWriter.WriteStringValue(fallback);
}
jsonWriter.WriteEndArray();
}
jsonWriter.WriteEndObject();
}
private void WriteCompilationOptions(CompilationOptions compilationOptions, ref UnifiedJsonWriter jsonWriter)
{
jsonWriter.WriteStartObject(DependencyContextStrings.CompilationOptionsPropertName, escape: false);
if (compilationOptions.Defines?.Any() == true)
{
jsonWriter.WriteStartArray(DependencyContextStrings.DefinesPropertyName, escape: false);
foreach (string define in compilationOptions.Defines)
{
jsonWriter.WriteStringValue(define);
}
jsonWriter.WriteEndArray();
}
AddStringPropertyIfNotNull(DependencyContextStrings.LanguageVersionPropertyName, compilationOptions.LanguageVersion, ref jsonWriter);
AddStringPropertyIfNotNull(DependencyContextStrings.PlatformPropertyName, compilationOptions.Platform, ref jsonWriter);
AddBooleanPropertyIfNotNull(DependencyContextStrings.AllowUnsafePropertyName, compilationOptions.AllowUnsafe, ref jsonWriter);
AddBooleanPropertyIfNotNull(DependencyContextStrings.WarningsAsErrorsPropertyName, compilationOptions.WarningsAsErrors, ref jsonWriter);
AddBooleanPropertyIfNotNull(DependencyContextStrings.OptimizePropertyName, compilationOptions.Optimize, ref jsonWriter);
AddStringPropertyIfNotNull(DependencyContextStrings.KeyFilePropertyName, compilationOptions.KeyFile, ref jsonWriter);
AddBooleanPropertyIfNotNull(DependencyContextStrings.DelaySignPropertyName, compilationOptions.DelaySign, ref jsonWriter);
AddBooleanPropertyIfNotNull(DependencyContextStrings.PublicSignPropertyName, compilationOptions.PublicSign, ref jsonWriter);
AddBooleanPropertyIfNotNull(DependencyContextStrings.EmitEntryPointPropertyName, compilationOptions.EmitEntryPoint, ref jsonWriter);
AddBooleanPropertyIfNotNull(DependencyContextStrings.GenerateXmlDocumentationPropertyName, compilationOptions.GenerateXmlDocumentation, ref jsonWriter);
AddStringPropertyIfNotNull(DependencyContextStrings.DebugTypePropertyName, compilationOptions.DebugType, ref jsonWriter);
jsonWriter.WriteEndObject();
}
private void AddStringPropertyIfNotNull(string name, string value, ref UnifiedJsonWriter jsonWriter)
{
if (value != null)
{
jsonWriter.WriteString(name, value, escape: true);
}
}
private void AddBooleanPropertyIfNotNull(string name, bool? value, ref UnifiedJsonWriter jsonWriter)
{
if (value.HasValue)
{
jsonWriter.WriteBoolean(name, value.Value, escape: true);
}
}
private void WriteTargets(DependencyContext context, ref UnifiedJsonWriter jsonWriter)
{
jsonWriter.WriteStartObject(DependencyContextStrings.TargetsPropertyName, escape: false);
if (context.Target.IsPortable)
{
WritePortableTarget(context.Target.Framework, context.RuntimeLibraries, context.CompileLibraries, ref jsonWriter);
}
else
{
WriteTarget(context.Target.Framework, context.CompileLibraries, ref jsonWriter);
WriteTarget(context.Target.Framework + DependencyContextStrings.VersionSeparator + context.Target.Runtime,
context.RuntimeLibraries, ref jsonWriter);
}
jsonWriter.WriteEndObject();
}
private void WriteTarget(string key, IReadOnlyList<Library> libraries, ref UnifiedJsonWriter jsonWriter)
{
jsonWriter.WriteStartObject(key);
int count = libraries.Count;
for (int i = 0; i < count; i++)
{
Library library = libraries[i];
WriteTargetLibrary(library.Name + DependencyContextStrings.VersionSeparator + library.Version, library, ref jsonWriter);
}
jsonWriter.WriteEndObject();
}
private void WritePortableTarget(string key, IReadOnlyList<RuntimeLibrary> runtimeLibraries, IReadOnlyList<CompilationLibrary> compilationLibraries, ref UnifiedJsonWriter jsonWriter)
{
Dictionary<string, RuntimeLibrary> runtimeLookup = runtimeLibraries.ToDictionary(l => l.Name, StringComparer.OrdinalIgnoreCase);
Dictionary<string, CompilationLibrary> compileLookup = compilationLibraries.ToDictionary(l => l.Name, StringComparer.OrdinalIgnoreCase);
jsonWriter.WriteStartObject(key);
foreach (string packageName in runtimeLookup.Keys.Concat(compileLookup.Keys).Distinct())
{
runtimeLookup.TryGetValue(packageName, out RuntimeLibrary runtimeLibrary);
compileLookup.TryGetValue(packageName, out CompilationLibrary compilationLibrary);
if (compilationLibrary != null && runtimeLibrary != null)
{
Debug.Assert(compilationLibrary.Serviceable == runtimeLibrary.Serviceable);
Debug.Assert(compilationLibrary.Version == runtimeLibrary.Version);
Debug.Assert(compilationLibrary.Hash == runtimeLibrary.Hash);
Debug.Assert(compilationLibrary.Type == runtimeLibrary.Type);
Debug.Assert(compilationLibrary.Path == runtimeLibrary.Path);
Debug.Assert(compilationLibrary.HashPath == runtimeLibrary.HashPath);
Debug.Assert(compilationLibrary.RuntimeStoreManifestName == null);
}
Library library = (Library)compilationLibrary ?? (Library)runtimeLibrary;
WritePortableTargetLibrary(library.Name + DependencyContextStrings.VersionSeparator + library.Version,
runtimeLibrary, compilationLibrary, ref jsonWriter);
}
jsonWriter.WriteEndObject();
}
private void AddCompilationAssemblies(IEnumerable<string> compilationAssemblies, ref UnifiedJsonWriter jsonWriter)
{
if (!compilationAssemblies.Any())
{
return;
}
WriteAssetList(DependencyContextStrings.CompileTimeAssembliesKey, compilationAssemblies, ref jsonWriter);
}
private void AddAssets(string key, RuntimeAssetGroup group, ref UnifiedJsonWriter jsonWriter)
{
if (group == null || !group.RuntimeFiles.Any())
{
return;
}
WriteAssetList(key, group.RuntimeFiles, ref jsonWriter);
}
private void AddDependencies(IEnumerable<Dependency> dependencies, ref UnifiedJsonWriter jsonWriter)
{
if (!dependencies.Any())
{
return;
}
jsonWriter.WriteStartObject(DependencyContextStrings.DependenciesPropertyName, escape: false);
foreach (Dependency dependency in dependencies)
{
jsonWriter.WriteString(dependency.Name, dependency.Version);
}
jsonWriter.WriteEndObject();
}
private void AddResourceAssemblies(IEnumerable<ResourceAssembly> resourceAssemblies, ref UnifiedJsonWriter jsonWriter)
{
if (!resourceAssemblies.Any())
{
return;
}
jsonWriter.WriteStartObject(DependencyContextStrings.ResourceAssembliesPropertyName, escape: false);
foreach (ResourceAssembly resourceAssembly in resourceAssemblies)
{
jsonWriter.WriteStartObject(NormalizePath(resourceAssembly.Path));
jsonWriter.WriteString(DependencyContextStrings.LocalePropertyName, resourceAssembly.Locale, escape: false);
jsonWriter.WriteEndObject();
}
jsonWriter.WriteEndObject();
}
private void WriteTargetLibrary(string key, Library library, ref UnifiedJsonWriter jsonWriter)
{
if (library is RuntimeLibrary runtimeLibrary)
{
jsonWriter.WriteStartObject(key);
AddDependencies(runtimeLibrary.Dependencies, ref jsonWriter);
// Add runtime-agnostic assets
AddAssets(DependencyContextStrings.RuntimeAssembliesKey, runtimeLibrary.RuntimeAssemblyGroups.GetDefaultGroup(), ref jsonWriter);
AddAssets(DependencyContextStrings.NativeLibrariesKey, runtimeLibrary.NativeLibraryGroups.GetDefaultGroup(), ref jsonWriter);
AddResourceAssemblies(runtimeLibrary.ResourceAssemblies, ref jsonWriter);
jsonWriter.WriteEndObject();
}
else if (library is CompilationLibrary compilationLibrary)
{
jsonWriter.WriteStartObject(key);
AddDependencies(compilationLibrary.Dependencies, ref jsonWriter);
AddCompilationAssemblies(compilationLibrary.Assemblies, ref jsonWriter);
jsonWriter.WriteEndObject();
}
else
{
throw new NotSupportedException();
}
}
private void WritePortableTargetLibrary(string key, RuntimeLibrary runtimeLibrary, CompilationLibrary compilationLibrary, ref UnifiedJsonWriter jsonWriter)
{
jsonWriter.WriteStartObject(key);
var dependencies = new HashSet<Dependency>();
if (runtimeLibrary != null)
{
dependencies.UnionWith(runtimeLibrary.Dependencies);
}
if (compilationLibrary != null)
{
dependencies.UnionWith(compilationLibrary.Dependencies);
}
AddDependencies(dependencies, ref jsonWriter);
if (runtimeLibrary != null)
{
// Add runtime-agnostic assets
AddAssets(DependencyContextStrings.RuntimeAssembliesKey, runtimeLibrary.RuntimeAssemblyGroups.GetDefaultGroup(), ref jsonWriter);
AddAssets(DependencyContextStrings.NativeLibrariesKey, runtimeLibrary.NativeLibraryGroups.GetDefaultGroup(), ref jsonWriter);
AddResourceAssemblies(runtimeLibrary.ResourceAssemblies, ref jsonWriter);
// Add runtime-specific assets
bool wroteObjectStart = false;
wroteObjectStart = AddRuntimeSpecificAssetGroups(DependencyContextStrings.RuntimeAssetType, runtimeLibrary.RuntimeAssemblyGroups, wroteObjectStart, ref jsonWriter);
wroteObjectStart = AddRuntimeSpecificAssetGroups(DependencyContextStrings.NativeAssetType, runtimeLibrary.NativeLibraryGroups, wroteObjectStart, ref jsonWriter);
if (wroteObjectStart)
{
jsonWriter.WriteEndObject();
}
}
if (compilationLibrary != null)
{
AddCompilationAssemblies(compilationLibrary.Assemblies, ref jsonWriter);
}
if (compilationLibrary != null && runtimeLibrary == null)
{
jsonWriter.WriteBoolean(DependencyContextStrings.CompilationOnlyPropertyName, true, escape: false);
}
jsonWriter.WriteEndObject();
}
private bool AddRuntimeSpecificAssetGroups(string assetType, IEnumerable<RuntimeAssetGroup> assetGroups, bool wroteObjectStart, ref UnifiedJsonWriter jsonWriter)
{
IEnumerable<RuntimeAssetGroup> groups = assetGroups.Where(g => !string.IsNullOrEmpty(g.Runtime));
if (!wroteObjectStart && (groups.Count() > 0))
{
jsonWriter.WriteStartObject(DependencyContextStrings.RuntimeTargetsPropertyName, escape: false);
wroteObjectStart = true;
}
foreach (RuntimeAssetGroup group in groups)
{
if (group.RuntimeFiles.Any())
{
AddRuntimeSpecificAssets(group.RuntimeFiles, group.Runtime, assetType, ref jsonWriter);
}
else
{
// Add a placeholder item
// We need to generate a pseudo-path because there could be multiple different asset groups with placeholders
// Only the last path segment matters, the rest is basically just a GUID.
var pseudoPathFolder = assetType == DependencyContextStrings.RuntimeAssetType ?
"lib" :
"native";
jsonWriter.WriteStartObject($"runtime/{group.Runtime}/{pseudoPathFolder}/_._");
jsonWriter.WriteString(DependencyContextStrings.RidPropertyName, group.Runtime, escape: false);
jsonWriter.WriteString(DependencyContextStrings.AssetTypePropertyName, assetType, escape: false);
jsonWriter.WriteEndObject();
}
}
return wroteObjectStart;
}
private void AddRuntimeSpecificAssets(IEnumerable<RuntimeFile> assets, string runtime, string assetType, ref UnifiedJsonWriter jsonWriter)
{
foreach (RuntimeFile asset in assets)
{
jsonWriter.WriteStartObject(NormalizePath(asset.Path));
jsonWriter.WriteString(DependencyContextStrings.RidPropertyName, runtime, escape: false);
jsonWriter.WriteString(DependencyContextStrings.AssetTypePropertyName, assetType, escape: false);
if (asset.AssemblyVersion != null)
{
jsonWriter.WriteString(DependencyContextStrings.AssemblyVersionPropertyName, asset.AssemblyVersion, escape: false);
}
if (asset.FileVersion != null)
{
jsonWriter.WriteString(DependencyContextStrings.FileVersionPropertyName, asset.FileVersion, escape: false);
}
jsonWriter.WriteEndObject();
}
}
private void WriteAssetList(string key, IEnumerable<string> assetPaths, ref UnifiedJsonWriter jsonWriter)
{
jsonWriter.WriteStartObject(key, escape: false);
foreach (string assembly in assetPaths)
{
jsonWriter.WriteStartObject(NormalizePath(assembly));
jsonWriter.WriteEndObject();
}
jsonWriter.WriteEndObject();
}
private void WriteAssetList(string key, IEnumerable<RuntimeFile> runtimeFiles, ref UnifiedJsonWriter jsonWriter)
{
jsonWriter.WriteStartObject(key, escape: false);
foreach (RuntimeFile runtimeFile in runtimeFiles)
{
jsonWriter.WriteStartObject(NormalizePath(runtimeFile.Path));
if (runtimeFile.AssemblyVersion != null)
{
jsonWriter.WriteString(DependencyContextStrings.AssemblyVersionPropertyName, runtimeFile.AssemblyVersion, escape: false);
}
if (runtimeFile.FileVersion != null)
{
jsonWriter.WriteString(DependencyContextStrings.FileVersionPropertyName, runtimeFile.FileVersion, escape: false);
}
jsonWriter.WriteEndObject();
}
jsonWriter.WriteEndObject();
}
private void WriteLibraries(DependencyContext context, ref UnifiedJsonWriter jsonWriter)
{
IEnumerable<IGrouping<string, Library>> allLibraries =
context.RuntimeLibraries.Cast<Library>().Concat(context.CompileLibraries)
.GroupBy(library => library.Name + DependencyContextStrings.VersionSeparator + library.Version);
jsonWriter.WriteStartObject(DependencyContextStrings.LibrariesPropertyName, escape: false);
foreach (IGrouping<string, Library> libraryGroup in allLibraries)
{
WriteLibrary(libraryGroup.Key, libraryGroup.First(), ref jsonWriter);
}
jsonWriter.WriteEndObject();
}
private void WriteLibrary(string key, Library library, ref UnifiedJsonWriter jsonWriter)
{
jsonWriter.WriteStartObject(key);
jsonWriter.WriteString(DependencyContextStrings.TypePropertyName, library.Type, escape: false);
jsonWriter.WriteBoolean(DependencyContextStrings.ServiceablePropertyName, library.Serviceable, escape: false);
jsonWriter.WriteString(DependencyContextStrings.Sha512PropertyName, library.Hash, escape: false);
if (library.Path != null)
{
jsonWriter.WriteString(DependencyContextStrings.PathPropertyName, library.Path, escape: false);
}
if (library.HashPath != null)
{
jsonWriter.WriteString(DependencyContextStrings.HashPathPropertyName, library.HashPath, escape: false);
}
if (library.RuntimeStoreManifestName != null)
{
jsonWriter.WriteString(DependencyContextStrings.RuntimeStoreManifestPropertyName, library.RuntimeStoreManifestName, escape: false);
}
jsonWriter.WriteEndObject();
}
private static string NormalizePath(string path)
{
return path.Replace('\\', '/');
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagve = Google.Ads.GoogleAds.V8.Enums;
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V8.Services;
namespace Google.Ads.GoogleAds.Tests.V8.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCampaignExperimentServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCampaignExperimentRequestObject()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCampaignExperimentRequest request = new GetCampaignExperimentRequest
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
};
gagvr::CampaignExperiment expectedResponse = new gagvr::CampaignExperiment
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
TrafficSplitType = gagve::CampaignExperimentTrafficSplitTypeEnum.Types.CampaignExperimentTrafficSplitType.RandomQuery,
Status = gagve::CampaignExperimentStatusEnum.Types.CampaignExperimentStatus.Initializing,
Id = -6774108720365892680L,
CampaignDraftAsCampaignDraftName = gagvr::CampaignDraftName.FromCustomerBaseCampaignDraft("[CUSTOMER_ID]", "[BASE_CAMPAIGN_ID]", "[DRAFT_ID]"),
CampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
Description = "description2cf9da67",
TrafficSplitPercent = -7167375592409567671L,
ExperimentCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
LongRunningOperation = "long_running_operation0897bd41",
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetCampaignExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignExperiment response = client.GetCampaignExperiment(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignExperimentRequestObjectAsync()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCampaignExperimentRequest request = new GetCampaignExperimentRequest
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
};
gagvr::CampaignExperiment expectedResponse = new gagvr::CampaignExperiment
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
TrafficSplitType = gagve::CampaignExperimentTrafficSplitTypeEnum.Types.CampaignExperimentTrafficSplitType.RandomQuery,
Status = gagve::CampaignExperimentStatusEnum.Types.CampaignExperimentStatus.Initializing,
Id = -6774108720365892680L,
CampaignDraftAsCampaignDraftName = gagvr::CampaignDraftName.FromCustomerBaseCampaignDraft("[CUSTOMER_ID]", "[BASE_CAMPAIGN_ID]", "[DRAFT_ID]"),
CampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
Description = "description2cf9da67",
TrafficSplitPercent = -7167375592409567671L,
ExperimentCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
LongRunningOperation = "long_running_operation0897bd41",
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetCampaignExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignExperiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignExperiment responseCallSettings = await client.GetCampaignExperimentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignExperiment responseCancellationToken = await client.GetCampaignExperimentAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignExperiment()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCampaignExperimentRequest request = new GetCampaignExperimentRequest
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
};
gagvr::CampaignExperiment expectedResponse = new gagvr::CampaignExperiment
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
TrafficSplitType = gagve::CampaignExperimentTrafficSplitTypeEnum.Types.CampaignExperimentTrafficSplitType.RandomQuery,
Status = gagve::CampaignExperimentStatusEnum.Types.CampaignExperimentStatus.Initializing,
Id = -6774108720365892680L,
CampaignDraftAsCampaignDraftName = gagvr::CampaignDraftName.FromCustomerBaseCampaignDraft("[CUSTOMER_ID]", "[BASE_CAMPAIGN_ID]", "[DRAFT_ID]"),
CampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
Description = "description2cf9da67",
TrafficSplitPercent = -7167375592409567671L,
ExperimentCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
LongRunningOperation = "long_running_operation0897bd41",
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetCampaignExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignExperiment response = client.GetCampaignExperiment(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignExperimentAsync()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCampaignExperimentRequest request = new GetCampaignExperimentRequest
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
};
gagvr::CampaignExperiment expectedResponse = new gagvr::CampaignExperiment
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
TrafficSplitType = gagve::CampaignExperimentTrafficSplitTypeEnum.Types.CampaignExperimentTrafficSplitType.RandomQuery,
Status = gagve::CampaignExperimentStatusEnum.Types.CampaignExperimentStatus.Initializing,
Id = -6774108720365892680L,
CampaignDraftAsCampaignDraftName = gagvr::CampaignDraftName.FromCustomerBaseCampaignDraft("[CUSTOMER_ID]", "[BASE_CAMPAIGN_ID]", "[DRAFT_ID]"),
CampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
Description = "description2cf9da67",
TrafficSplitPercent = -7167375592409567671L,
ExperimentCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
LongRunningOperation = "long_running_operation0897bd41",
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetCampaignExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignExperiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignExperiment responseCallSettings = await client.GetCampaignExperimentAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignExperiment responseCancellationToken = await client.GetCampaignExperimentAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCampaignExperimentResourceNames()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCampaignExperimentRequest request = new GetCampaignExperimentRequest
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
};
gagvr::CampaignExperiment expectedResponse = new gagvr::CampaignExperiment
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
TrafficSplitType = gagve::CampaignExperimentTrafficSplitTypeEnum.Types.CampaignExperimentTrafficSplitType.RandomQuery,
Status = gagve::CampaignExperimentStatusEnum.Types.CampaignExperimentStatus.Initializing,
Id = -6774108720365892680L,
CampaignDraftAsCampaignDraftName = gagvr::CampaignDraftName.FromCustomerBaseCampaignDraft("[CUSTOMER_ID]", "[BASE_CAMPAIGN_ID]", "[DRAFT_ID]"),
CampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
Description = "description2cf9da67",
TrafficSplitPercent = -7167375592409567671L,
ExperimentCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
LongRunningOperation = "long_running_operation0897bd41",
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetCampaignExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignExperiment response = client.GetCampaignExperiment(request.ResourceNameAsCampaignExperimentName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCampaignExperimentResourceNamesAsync()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetCampaignExperimentRequest request = new GetCampaignExperimentRequest
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
};
gagvr::CampaignExperiment expectedResponse = new gagvr::CampaignExperiment
{
ResourceNameAsCampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
TrafficSplitType = gagve::CampaignExperimentTrafficSplitTypeEnum.Types.CampaignExperimentTrafficSplitType.RandomQuery,
Status = gagve::CampaignExperimentStatusEnum.Types.CampaignExperimentStatus.Initializing,
Id = -6774108720365892680L,
CampaignDraftAsCampaignDraftName = gagvr::CampaignDraftName.FromCustomerBaseCampaignDraft("[CUSTOMER_ID]", "[BASE_CAMPAIGN_ID]", "[DRAFT_ID]"),
CampaignExperimentName = gagvr::CampaignExperimentName.FromCustomerCampaignExperiment("[CUSTOMER_ID]", "[CAMPAIGN_EXPERIMENT_ID]"),
Description = "description2cf9da67",
TrafficSplitPercent = -7167375592409567671L,
ExperimentCampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"),
LongRunningOperation = "long_running_operation0897bd41",
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetCampaignExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignExperiment>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CampaignExperiment responseCallSettings = await client.GetCampaignExperimentAsync(request.ResourceNameAsCampaignExperimentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CampaignExperiment responseCancellationToken = await client.GetCampaignExperimentAsync(request.ResourceNameAsCampaignExperimentName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCampaignExperimentsRequestObject()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
MutateCampaignExperimentsRequest request = new MutateCampaignExperimentsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignExperimentOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCampaignExperimentsResponse expectedResponse = new MutateCampaignExperimentsResponse
{
Results =
{
new MutateCampaignExperimentResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignExperiments(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignExperimentsResponse response = client.MutateCampaignExperiments(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCampaignExperimentsRequestObjectAsync()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
MutateCampaignExperimentsRequest request = new MutateCampaignExperimentsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignExperimentOperation(),
},
PartialFailure = false,
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCampaignExperimentsResponse expectedResponse = new MutateCampaignExperimentsResponse
{
Results =
{
new MutateCampaignExperimentResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignExperimentsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignExperimentsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignExperimentsResponse responseCallSettings = await client.MutateCampaignExperimentsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCampaignExperimentsResponse responseCancellationToken = await client.MutateCampaignExperimentsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCampaignExperiments()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
MutateCampaignExperimentsRequest request = new MutateCampaignExperimentsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignExperimentOperation(),
},
};
MutateCampaignExperimentsResponse expectedResponse = new MutateCampaignExperimentsResponse
{
Results =
{
new MutateCampaignExperimentResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignExperiments(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignExperimentsResponse response = client.MutateCampaignExperiments(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCampaignExperimentsAsync()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
MutateCampaignExperimentsRequest request = new MutateCampaignExperimentsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CampaignExperimentOperation(),
},
};
MutateCampaignExperimentsResponse expectedResponse = new MutateCampaignExperimentsResponse
{
Results =
{
new MutateCampaignExperimentResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCampaignExperimentsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignExperimentsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
MutateCampaignExperimentsResponse responseCallSettings = await client.MutateCampaignExperimentsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCampaignExperimentsResponse responseCancellationToken = await client.MutateCampaignExperimentsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GraduateCampaignExperimentRequestObject()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GraduateCampaignExperimentRequest request = new GraduateCampaignExperimentRequest
{
CampaignExperiment = "campaign_experimente81fbe81",
CampaignBudget = "campaign_budgetc3f474d4",
ValidateOnly = true,
};
GraduateCampaignExperimentResponse expectedResponse = new GraduateCampaignExperimentResponse
{
GraduatedCampaign = "graduated_campaign1b91421c",
};
mockGrpcClient.Setup(x => x.GraduateCampaignExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
GraduateCampaignExperimentResponse response = client.GraduateCampaignExperiment(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GraduateCampaignExperimentRequestObjectAsync()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GraduateCampaignExperimentRequest request = new GraduateCampaignExperimentRequest
{
CampaignExperiment = "campaign_experimente81fbe81",
CampaignBudget = "campaign_budgetc3f474d4",
ValidateOnly = true,
};
GraduateCampaignExperimentResponse expectedResponse = new GraduateCampaignExperimentResponse
{
GraduatedCampaign = "graduated_campaign1b91421c",
};
mockGrpcClient.Setup(x => x.GraduateCampaignExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GraduateCampaignExperimentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
GraduateCampaignExperimentResponse responseCallSettings = await client.GraduateCampaignExperimentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
GraduateCampaignExperimentResponse responseCancellationToken = await client.GraduateCampaignExperimentAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GraduateCampaignExperiment()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GraduateCampaignExperimentRequest request = new GraduateCampaignExperimentRequest
{
CampaignExperiment = "campaign_experimente81fbe81",
CampaignBudget = "campaign_budgetc3f474d4",
};
GraduateCampaignExperimentResponse expectedResponse = new GraduateCampaignExperimentResponse
{
GraduatedCampaign = "graduated_campaign1b91421c",
};
mockGrpcClient.Setup(x => x.GraduateCampaignExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
GraduateCampaignExperimentResponse response = client.GraduateCampaignExperiment(request.CampaignExperiment, request.CampaignBudget);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GraduateCampaignExperimentAsync()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GraduateCampaignExperimentRequest request = new GraduateCampaignExperimentRequest
{
CampaignExperiment = "campaign_experimente81fbe81",
CampaignBudget = "campaign_budgetc3f474d4",
};
GraduateCampaignExperimentResponse expectedResponse = new GraduateCampaignExperimentResponse
{
GraduatedCampaign = "graduated_campaign1b91421c",
};
mockGrpcClient.Setup(x => x.GraduateCampaignExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GraduateCampaignExperimentResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
GraduateCampaignExperimentResponse responseCallSettings = await client.GraduateCampaignExperimentAsync(request.CampaignExperiment, request.CampaignBudget, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
GraduateCampaignExperimentResponse responseCancellationToken = await client.GraduateCampaignExperimentAsync(request.CampaignExperiment, request.CampaignBudget, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void EndCampaignExperimentRequestObject()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
EndCampaignExperimentRequest request = new EndCampaignExperimentRequest
{
CampaignExperiment = "campaign_experimente81fbe81",
ValidateOnly = true,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.EndCampaignExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
client.EndCampaignExperiment(request);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task EndCampaignExperimentRequestObjectAsync()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
EndCampaignExperimentRequest request = new EndCampaignExperimentRequest
{
CampaignExperiment = "campaign_experimente81fbe81",
ValidateOnly = true,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.EndCampaignExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
await client.EndCampaignExperimentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.EndCampaignExperimentAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void EndCampaignExperiment()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
EndCampaignExperimentRequest request = new EndCampaignExperimentRequest
{
CampaignExperiment = "campaign_experimente81fbe81",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.EndCampaignExperiment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
client.EndCampaignExperiment(request.CampaignExperiment);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task EndCampaignExperimentAsync()
{
moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient> mockGrpcClient = new moq::Mock<CampaignExperimentService.CampaignExperimentServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
EndCampaignExperimentRequest request = new EndCampaignExperimentRequest
{
CampaignExperiment = "campaign_experimente81fbe81",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.EndCampaignExperimentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CampaignExperimentServiceClient client = new CampaignExperimentServiceClientImpl(mockGrpcClient.Object, null);
await client.EndCampaignExperimentAsync(request.CampaignExperiment, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.EndCampaignExperimentAsync(request.CampaignExperiment, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Management.Automation.Runspaces;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
// Stops compiler from warning about unknown warnings
#pragma warning disable 1634, 1691
namespace System.Management.Automation
{
/// <summary>
/// Contains the definition of a job which is defined in a
/// job store.
/// </summary>
/// <remarks>The actual implementation of this class will
/// happen in M2</remarks>
[Serializable]
public class JobDefinition : ISerializable
{
private string _name;
/// <summary>
/// A friendly Name for this definition.
/// </summary>
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <summary>
/// The type that derives from JobSourceAdapter
/// that contains the logic for invocation and
/// management of this type of job.
/// </summary>
public Type JobSourceAdapterType { get; }
private string _moduleName;
/// <summary>
/// Module name for the module containing
/// the source adapter implementation.
/// </summary>
public string ModuleName
{
get { return _moduleName; }
set { _moduleName = value; }
}
private string _jobSourceAdapterTypeName;
/// <summary>
/// Job source adapter type name.
/// </summary>
public string JobSourceAdapterTypeName
{
get { return _jobSourceAdapterTypeName; }
set { _jobSourceAdapterTypeName = value; }
}
/// <summary>
/// Name of the job that needs to be loaded
/// from the specified module.
/// </summary>
public string Command { get; }
private Guid _instanceId;
/// <summary>
/// Unique Guid for this job definition.
/// </summary>
public Guid InstanceId
{
get
{
return _instanceId;
}
set
{
_instanceId = value;
}
}
/// <summary>
/// Save this definition to the specified
/// file on disk.
/// </summary>
/// <param name="stream">Stream to save to.</param>
public virtual void Save(Stream stream)
{
throw new NotImplementedException();
}
/// <summary>
/// Load this definition from the specified
/// file on disk.
/// </summary>
/// <param name="stream"></param>
public virtual void Load(Stream stream)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns information about this job like
/// name, definition, parameters etc.
/// </summary>
public CommandInfo CommandInfo
{
get
{
return null;
}
}
/// <summary>
/// Public constructor for testing.
/// </summary>
/// <param name="jobSourceAdapterType">Type of adapter to use to create a job.</param>
/// <param name="command">The command string.</param>
/// <param name="name">The job name.</param>
public JobDefinition(Type jobSourceAdapterType, string command, string name)
{
JobSourceAdapterType = jobSourceAdapterType;
if (jobSourceAdapterType != null)
{
_jobSourceAdapterTypeName = jobSourceAdapterType.Name;
}
Command = command;
_name = name;
_instanceId = Guid.NewGuid();
}
/// <summary>
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected JobDefinition(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Class that helps define the parameters to
/// be passed to a job so that the job can be
/// instantiated without having to specify
/// the parameters explicitly. Helps in
/// passing job parameters to disk.
/// </summary>
/// <remarks>This class is not required if
/// CommandParameterCollection adds a public
/// constructor.The actual implementation of
/// this class will happen in M2</remarks>
[Serializable]
public class JobInvocationInfo : ISerializable
{
/// <summary>
/// Friendly name associated with this specification.
/// </summary>
public string Name
{
get
{
return _name;
}
set
{
if (value == null)
throw new PSArgumentNullException("value");
_name = value;
}
}
private string _name = string.Empty;
private string _command;
/// <summary>
/// Command string to execute.
/// </summary>
public string Command
{
get
{
return _command ?? _definition.Command;
}
set
{
_command = value;
}
}
private JobDefinition _definition;
/// <summary>
/// Definition associated with the job.
/// </summary>
public JobDefinition Definition
{
get
{
return _definition;
}
set
{
_definition = value;
}
}
private List<CommandParameterCollection> _parameters;
/// <summary>
/// Parameters associated with this specification.
/// </summary>
public List<CommandParameterCollection> Parameters
{
get { return _parameters ?? (_parameters = new List<CommandParameterCollection>()); }
}
/// <summary>
/// Unique identifies for this specification.
/// </summary>
public Guid InstanceId { get; } = Guid.NewGuid();
/// <summary>
/// Save this specification to a file.
/// </summary>
/// <param name="stream">Stream to save to.</param>
public virtual void Save(Stream stream)
{
throw new NotImplementedException();
}
/// <summary>
/// Load this specification from a file.
/// </summary>
/// <param name="stream">Stream to load from.</param>
public virtual void Load(Stream stream)
{
throw new NotImplementedException();
}
/// <summary>
/// Constructor.
/// </summary>
protected JobInvocationInfo()
{ }
/// <summary>
/// Create a new job definition with a single set of parameters.
/// </summary>
/// <param name="definition">The job definition.</param>
/// <param name="parameters">The parameter collection to use.</param>
public JobInvocationInfo(JobDefinition definition, Dictionary<string, object> parameters)
{
_definition = definition;
var convertedCollection = ConvertDictionaryToParameterCollection(parameters);
if (convertedCollection != null)
{
Parameters.Add(convertedCollection);
}
}
/// <summary>
/// Create a new job definition with a multiple sets of parameters. This allows
/// different parameters for different machines.
/// </summary>
/// <param name="definition">The job definition.</param>
/// <param name="parameterCollectionList">Collection of sets of parameters to use for the child jobs.</param>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is forced by the interaction of PowerShell and Workflow.")]
public JobInvocationInfo(JobDefinition definition, IEnumerable<Dictionary<string, object>> parameterCollectionList)
{
_definition = definition;
if (parameterCollectionList == null) return;
foreach (var parameterCollection in parameterCollectionList)
{
if (parameterCollection == null) continue;
CommandParameterCollection convertedCollection = ConvertDictionaryToParameterCollection(parameterCollection);
if (convertedCollection != null)
{
Parameters.Add(convertedCollection);
}
}
}
/// <summary>
/// </summary>
/// <param name="definition"></param>
/// <param name="parameters"></param>
public JobInvocationInfo(JobDefinition definition, CommandParameterCollection parameters)
{
_definition = definition;
Parameters.Add(parameters ?? new CommandParameterCollection());
}
/// <summary>
/// </summary>
/// <param name="definition"></param>
/// <param name="parameters"></param>
public JobInvocationInfo(JobDefinition definition, IEnumerable<CommandParameterCollection> parameters)
{
_definition = definition;
if (parameters == null) return;
foreach (var parameter in parameters)
{
Parameters.Add(parameter);
}
}
/// <summary>
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected JobInvocationInfo(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Utility function to turn a dictionary of name/value pairs into a parameter collection.
/// </summary>
/// <param name="parameters">The dictionary to convert.</param>
/// <returns>The converted collection.</returns>
private static CommandParameterCollection ConvertDictionaryToParameterCollection(IEnumerable<KeyValuePair<string, object>> parameters)
{
if (parameters == null)
return null;
CommandParameterCollection paramCollection = new CommandParameterCollection();
foreach (CommandParameter paramItem in
parameters.Select(param => new CommandParameter(param.Key, param.Value)))
{
paramCollection.Add(paramItem);
}
return paramCollection;
}
}
/// <summary>
/// Abstract class for a job store which will
/// contain the jobs of a specific type.
/// </summary>
public abstract class JobSourceAdapter
{
/// <summary>
/// Name for this store.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// Get a token that allows for construction of a job with a previously assigned
/// Id and InstanceId. This is only possible if this JobSourceAdapter is the
/// creator of the original job.
/// The original job must have been saved using "SaveJobIdForReconstruction"
/// </summary>
/// <param name="instanceId">Instance Id of the job to recreate.</param>
/// <returns>JobIdentifier to be used in job construction.</returns>
protected JobIdentifier RetrieveJobIdForReuse(Guid instanceId)
{
return JobManager.GetJobIdentifier(instanceId, this.GetType().Name);
}
/// <summary>
/// Saves the Id information for a job so that it can be constructed at a later time.
/// This will only allow this job source adapter type to recreate the job.
/// </summary>
/// <param name="job">The job whose id information to store.</param>
/// <param name="recurse">Recurse to save child job Ids.</param>
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only jobs that derive from Job2 should have reusable IDs.")]
public void StoreJobIdForReuse(Job2 job, bool recurse)
{
if (job == null)
{
PSTraceSource.NewArgumentNullException("job", RemotingErrorIdStrings.JobSourceAdapterCannotSaveNullJob);
}
JobManager.SaveJobId(job.InstanceId, job.Id, this.GetType().Name);
if (recurse && job.ChildJobs != null && job.ChildJobs.Count > 0)
{
Hashtable duplicateDetector = new Hashtable();
duplicateDetector.Add(job.InstanceId, job.InstanceId);
foreach (Job child in job.ChildJobs)
{
Job2 childJob = child as Job2;
if (childJob == null) continue;
StoreJobIdForReuseHelper(duplicateDetector, childJob, true);
}
}
}
private void StoreJobIdForReuseHelper(Hashtable duplicateDetector, Job2 job, bool recurse)
{
if (duplicateDetector.ContainsKey(job.InstanceId)) return;
duplicateDetector.Add(job.InstanceId, job.InstanceId);
JobManager.SaveJobId(job.InstanceId, job.Id, this.GetType().Name);
if (!recurse || job.ChildJobs == null) return;
foreach (Job child in job.ChildJobs)
{
Job2 childJob = child as Job2;
if (childJob == null) continue;
StoreJobIdForReuseHelper(duplicateDetector, childJob, recurse);
}
}
/// <summary>
/// Create a new job with the specified definition.
/// </summary>
/// <param name="definition">Job definition to use.</param>
/// <returns>Job object.</returns>
public Job2 NewJob(JobDefinition definition)
{
return NewJob(new JobInvocationInfo(definition, new Dictionary<string, object>()));
}
/// <summary>
/// Creates a new job with the definition as specified by
/// the provided definition name and path. If path is null
/// then a default location will be used to find the job
/// definition by name.
/// </summary>
/// <param name="definitionName">Job definition name.</param>
/// <param name="definitionPath">Job definition file path.</param>
/// <returns>Job2 object.</returns>
public virtual Job2 NewJob(string definitionName, string definitionPath)
{
return null;
}
/// <summary>
/// Create a new job with the specified JobSpecification.
/// </summary>
/// <param name="specification">Specification.</param>
/// <returns>Job object.</returns>
public abstract Job2 NewJob(JobInvocationInfo specification);
/// <summary>
/// Get the list of jobs that are currently available in this
/// store.
/// </summary>
/// <returns>Collection of job objects.</returns>
public abstract IList<Job2> GetJobs();
/// <summary>
/// Get list of jobs that matches the specified names.
/// </summary>
/// <param name="name">names to match, can support
/// wildcard if the store supports</param>
/// <param name="recurse"></param>
/// <returns>Collection of jobs that match the specified
/// criteria.</returns>
public abstract IList<Job2> GetJobsByName(string name, bool recurse);
/// <summary>
/// Get list of jobs that run the specified command.
/// </summary>
/// <param name="command">Command to match.</param>
/// <param name="recurse"></param>
/// <returns>Collection of jobs that match the specified
/// criteria.</returns>
public abstract IList<Job2> GetJobsByCommand(string command, bool recurse);
/// <summary>
/// Get list of jobs that has the specified id.
/// </summary>
/// <param name="instanceId">Guid to match.</param>
/// <param name="recurse"></param>
/// <returns>Job with the specified guid.</returns>
public abstract Job2 GetJobByInstanceId(Guid instanceId, bool recurse);
/// <summary>
/// Get job that has specific session id.
/// </summary>
/// <param name="id">Id to match.</param>
/// <param name="recurse"></param>
/// <returns>Job with the specified id.</returns>
public abstract Job2 GetJobBySessionId(int id, bool recurse);
/// <summary>
/// Get list of jobs that are in the specified state.
/// </summary>
/// <param name="state">State to match.</param>
/// <param name="recurse"></param>
/// <returns>Collection of jobs with the specified
/// state.</returns>
public abstract IList<Job2> GetJobsByState(JobState state, bool recurse);
/// <summary>
/// Get list of jobs based on the adapter specific
/// filter parameters.
/// </summary>
/// <param name="filter">dictionary containing name value
/// pairs for adapter specific filters</param>
/// <param name="recurse"></param>
/// <returns>Collection of jobs that match the
/// specified criteria.</returns>
public abstract IList<Job2> GetJobsByFilter(Dictionary<string, object> filter, bool recurse);
/// <summary>
/// Remove a job from the store.
/// </summary>
/// <param name="job">Job object to remove.</param>
public abstract void RemoveJob(Job2 job);
/// <summary>
/// Saves the job to a persisted store.
/// </summary>
/// <param name="job">Job2 type job to persist.</param>
public virtual void PersistJob(Job2 job)
{
// Implemented only if job needs to be told when to persist.
}
}
}
| |
//
// PangoUtils.cs
//
// Author:
// Michael Hutchinson <mhutchinson@novell.com>
//
// Copyright (c) 2010 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Gtk;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using Xwt.Drawing;
namespace Xwt.GtkBackend
{
public static class GtkInterop
{
#if XWT_GTK3
internal const string LIBGTK = "libgtk-3-0.dll";
internal const string LIBATK = "libatk-1.0-0.dll";
internal const string LIBGLIB = "libglib-2.0-0.dll";
internal const string LIBGDK = "libgdk-3-0.dll";
internal const string LIBGOBJECT = "libgobject-2.0-0.dll";
internal const string LIBPANGO = "libpango-1.0-0.dll";
internal const string LIBPANGOCAIRO = "libpangocairo-1.0-0.dll";
internal const string LIBGTKGLUE = "gtksharpglue-3";
internal const string LIBGLIBGLUE = "glibsharpglue-3";
internal const string LIBWEBKIT = "libwebkitgtk-3.0-0.dll";
#else
internal const string LIBGTK = "libgtk-win32-2.0-0.dll";
internal const string LIBATK = "libatk-1.0-0.dll";
internal const string LIBGLIB = "libglib-2.0-0.dll";
internal const string LIBGDK = "libgdk-win32-2.0-0.dll";
internal const string LIBGOBJECT = "libgobject-2.0-0.dll";
internal const string LIBPANGO = "libpango-1.0-0.dll";
internal const string LIBPANGOCAIRO = "libpangocairo-1.0-0.dll";
internal const string LIBGTKGLUE = "gtksharpglue-2";
internal const string LIBGLIBGLUE = "glibsharpglue-2";
internal const string LIBWEBKIT = "libwebkitgtk-1.0-0.dll";
#endif
}
/// <summary>
/// This creates a Pango list and applies attributes to it with *much* less overhead than the GTK# version.
/// </summary>
internal class FastPangoAttrList : IDisposable
{
IntPtr list;
public FastPangoAttrList ()
{
list = pango_attr_list_new ();
}
public void AddAttributes (TextIndexer indexer, IEnumerable<TextAttribute> attrs)
{
foreach (var attr in attrs)
AddAttribute (indexer, attr);
}
public void AddAttribute (TextIndexer indexer, TextAttribute attr)
{
var start = (uint) indexer.IndexToByteIndex (attr.StartIndex);
var end = (uint) indexer.IndexToByteIndex (attr.StartIndex + attr.Count);
if (attr is BackgroundTextAttribute) {
var xa = (BackgroundTextAttribute)attr;
AddBackgroundAttribute (xa.Color.ToGtkValue (), start, end);
}
else if (attr is ColorTextAttribute) {
var xa = (ColorTextAttribute)attr;
AddForegroundAttribute (xa.Color.ToGtkValue (), start, end);
}
else if (attr is FontWeightTextAttribute) {
var xa = (FontWeightTextAttribute)attr;
AddWeightAttribute ((Pango.Weight)(int)xa.Weight, start, end);
}
else if (attr is FontStyleTextAttribute) {
var xa = (FontStyleTextAttribute)attr;
AddStyleAttribute ((Pango.Style)(int)xa.Style, start, end);
}
else if (attr is UnderlineTextAttribute) {
var xa = (UnderlineTextAttribute)attr;
AddUnderlineAttribute (xa.Underline ? Pango.Underline.Single : Pango.Underline.None, start, end);
}
else if (attr is StrikethroughTextAttribute) {
var xa = (StrikethroughTextAttribute)attr;
AddStrikethroughAttribute (xa.Strikethrough, start, end);
}
else if (attr is FontTextAttribute) {
var xa = (FontTextAttribute)attr;
AddFontAttribute ((Pango.FontDescription)Toolkit.GetBackend (xa.Font), start, end);
}
else if (attr is LinkTextAttribute) {
AddUnderlineAttribute (Pango.Underline.Single, start, end);
AddForegroundAttribute (Colors.Blue.ToGtkValue (), start, end);
}
}
public IntPtr Handle {
get { return list; }
}
public void AddStyleAttribute (Pango.Style style, uint start, uint end)
{
Add (pango_attr_style_new (style), start, end);
}
public void AddWeightAttribute (Pango.Weight weight, uint start, uint end)
{
Add (pango_attr_weight_new (weight), start, end);
}
public void AddForegroundAttribute (Gdk.Color color, uint start, uint end)
{
Add (pango_attr_foreground_new (color.Red, color.Green, color.Blue), start, end);
}
public void AddBackgroundAttribute (Gdk.Color color, uint start, uint end)
{
Add (pango_attr_background_new (color.Red, color.Green, color.Blue), start, end);
}
public void AddUnderlineAttribute (Pango.Underline underline, uint start, uint end)
{
Add (pango_attr_underline_new (underline), start, end);
}
public void AddStrikethroughAttribute (bool strikethrough, uint start, uint end)
{
Add (pango_attr_strikethrough_new (strikethrough), start, end);
}
public void AddFontAttribute (Pango.FontDescription font, uint start, uint end)
{
Add (pango_attr_font_desc_new (font.Handle), start, end);
}
void Add (IntPtr attribute, uint start, uint end)
{
unsafe {
PangoAttribute *attPtr = (PangoAttribute *) attribute;
attPtr->start_index = start;
attPtr->end_index = end;
}
pango_attr_list_insert (list, attribute);
}
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_style_new (Pango.Style style);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_stretch_new (Pango.Stretch stretch);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_weight_new (Pango.Weight weight);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_foreground_new (ushort red, ushort green, ushort blue);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_background_new (ushort red, ushort green, ushort blue);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_underline_new (Pango.Underline underline);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_strikethrough_new (bool strikethrough);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_font_desc_new (IntPtr desc);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr pango_attr_list_new ();
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern void pango_attr_list_unref (IntPtr list);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern void pango_attr_list_insert (IntPtr list, IntPtr attr);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern void pango_layout_set_attributes (IntPtr layout, IntPtr attrList);
[DllImport (GtkInterop.LIBPANGO, CallingConvention=CallingConvention.Cdecl)]
static extern void pango_attr_list_splice (IntPtr attr_list, IntPtr other, Int32 pos, Int32 len);
public void Splice (Pango.AttrList attrs, int pos, int len)
{
pango_attr_list_splice (list, attrs.Handle, pos, len);
}
public void AssignTo (Pango.Layout layout)
{
pango_layout_set_attributes (layout.Handle, list);
}
[StructLayout (LayoutKind.Sequential)]
struct PangoAttribute
{
public IntPtr klass;
public uint start_index;
public uint end_index;
}
public void Dispose ()
{
pango_attr_list_unref (list);
list = IntPtr.Zero;
}
}
internal class TextIndexer
{
int[] indexToByteIndex;
int[] byteIndexToIndex;
public TextIndexer (string text)
{
SetupTables (text);
}
public int IndexToByteIndex (int i)
{
if (i >= indexToByteIndex.Length)
return i;
return indexToByteIndex[i];
}
public int ByteIndexToIndex (int i)
{
return byteIndexToIndex[i];
}
public void SetupTables (string text)
{
if (text == null) {
this.indexToByteIndex = new int[0];
this.byteIndexToIndex = new int[0];
return;
}
var arr = text.ToCharArray ();
int byteIndex = 0;
int[] indexToByteIndex = new int[arr.Length];
var byteIndexToIndex = new List<int> ();
for (int i = 0; i < arr.Length; i++) {
indexToByteIndex[i] = byteIndex;
byteIndex += System.Text.Encoding.UTF8.GetByteCount (arr, i, 1);
while (byteIndexToIndex.Count < byteIndex)
byteIndexToIndex.Add (i);
}
this.indexToByteIndex = indexToByteIndex;
this.byteIndexToIndex = byteIndexToIndex.ToArray ();
}
}
}
| |
using System;
using System.Text;
using Newtonsoft.Json;
namespace DocDBAPIRest.Models
{
/// <summary>
/// Triggers are pieces of application logic that can executed before (pre-triggers) and after (post-triggers)
/// creation, deletion, and replacement of a document. Triggers are written in JavaScript. Both pre and post triggers
/// do no take parameters. Like stored procedures, triggers live within the confines of a collection, thus confining
/// the application logic to the collection
/// </summary>
public class Trigger : IEquatable<Trigger>
{
/// <summary>
/// Gets or Sets Id
/// </summary>
public string Id { get; set; }
/// <summary>
/// This is a user settable property. This is the body of the Trigger
/// </summary>
/// <value>This is a user settable property. This is the body of the Trigger</value>
public string Body { get; set; }
/// <summary>
/// This is the type of operation that will invoke the trigger. The acceptable values are: All, Insert, Replace and
/// Delete.
/// </summary>
/// <value>
/// This is the type of operation that will invoke the trigger. The acceptable values are: All, Insert, Replace and
/// Delete.
/// </value>
public string TriggerOperation { get; set; }
/// <summary>
/// This specifies when the trigger will be fired. The acceptable values are: Pre and Post. Pre triggers fire before an
/// operation while Post triggers after an operation.
/// </summary>
/// <value>
/// This specifies when the trigger will be fired. The acceptable values are: Pre and Post. Pre triggers fire before
/// an operation while Post triggers after an operation.
/// </value>
public string TriggerType { get; set; }
/// <summary>
/// Gets or Sets Rid
/// </summary>
public string Rid { get; set; }
/// <summary>
/// Gets or Sets Ts
/// </summary>
public string Ts { get; set; }
/// <summary>
/// Gets or Sets Self
/// </summary>
public string Self { get; set; }
/// <summary>
/// Gets or Sets Etag
/// </summary>
public string Etag { get; set; }
/// <summary>
/// Returns true if Trigger instances are equal
/// </summary>
/// <param name="other">Instance of Trigger to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Trigger other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
Id == other.Id ||
Id != null &&
Id.Equals(other.Id)
) &&
(
Body == other.Body ||
Body != null &&
Body.Equals(other.Body)
) &&
(
TriggerOperation == other.TriggerOperation ||
TriggerOperation != null &&
TriggerOperation.Equals(other.TriggerOperation)
) &&
(
TriggerType == other.TriggerType ||
TriggerType != null &&
TriggerType.Equals(other.TriggerType)
) &&
(
Rid == other.Rid ||
Rid != null &&
Rid.Equals(other.Rid)
) &&
(
Ts == other.Ts ||
Ts != null &&
Ts.Equals(other.Ts)
) &&
(
Self == other.Self ||
Self != null &&
Self.Equals(other.Self)
) &&
(
Etag == other.Etag ||
Etag != null &&
Etag.Equals(other.Etag)
);
}
/// <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 Trigger {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Body: ").Append(Body).Append("\n");
sb.Append(" TriggerOperation: ").Append(TriggerOperation).Append("\n");
sb.Append(" TriggerType: ").Append(TriggerType).Append("\n");
sb.Append(" Rid: ").Append(Rid).Append("\n");
sb.Append(" Ts: ").Append(Ts).Append("\n");
sb.Append(" Self: ").Append(Self).Append("\n");
sb.Append(" Etag: ").Append(Etag).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 Equals(obj as Trigger);
}
/// <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
{
var hash = 41;
// Suitable nullity checks etc, of course :)
if (Id != null)
hash = hash*57 + Id.GetHashCode();
if (Body != null)
hash = hash*57 + Body.GetHashCode();
if (TriggerOperation != null)
hash = hash*57 + TriggerOperation.GetHashCode();
if (TriggerType != null)
hash = hash*57 + TriggerType.GetHashCode();
if (Rid != null)
hash = hash*57 + Rid.GetHashCode();
if (Ts != null)
hash = hash*57 + Ts.GetHashCode();
if (Self != null)
hash = hash*57 + Self.GetHashCode();
if (Etag != null)
hash = hash*57 + Etag.GetHashCode();
return hash;
}
}
}
}
| |
// -------------------------------------------------------------------------------
//
// This file is part of the FluidKit project: http://www.codeplex.com/fluidkit
//
// Copyright (c) 2008, The FluidKit community
// 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 FluidKit 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.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
//namespace FluidKit.Shapes
namespace LionFire.Avalon
{
public class PolygonShape : Shape
{
#region ctr
#endregion
#region Properties
#region CornerPointsProperty
public static readonly DependencyProperty CornerPointsProperty =
DependencyProperty.Register(
"CornerPoints",
typeof (int),
typeof (PolygonShape),
new FrameworkPropertyMetadata(3, FrameworkPropertyMetadataOptions.AffectsRender, null,
OnCoerceCornerPoints));
public int CornerPoints
{
get { return (int) GetValue(CornerPointsProperty); }
set { SetValue(CornerPointsProperty, value); }
}
//Making sure that we have at minimum 3 CornerPoints;
private static object OnCoerceCornerPoints(DependencyObject obj, object baseValue)
{
PolygonShape shape = (PolygonShape) obj;
int value = (int) baseValue;
if (value < 3)
value = 3;
return value;
}
#endregion
#region RotationAngleProperty
public static readonly DependencyProperty RotationAngleProperty =
DependencyProperty.Register(
"RotationAngle",
typeof (double),
typeof (PolygonShape),
new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.AffectsRender, null,
OnCoerceRotationAngle));
public double RotationAngle
{
get { return (double) GetValue(RotationAngleProperty); }
set { SetValue(RotationAngleProperty, value); }
}
//Making sure that Rotation is between 0 and 360;
private static object OnCoerceRotationAngle(DependencyObject obj, object baseValue)
{
PolygonShape shape = (PolygonShape) obj;
double value = (double) baseValue;
if (value < 0)
value = 0;
if (value > 360)
value = 360;
return value;
}
#endregion
#region InnerRadiusOffsetProperty
public static readonly DependencyProperty InnerRadiusOffsetProperty =
DependencyProperty.Register(
"InnerRadiusOffset",
typeof (int),
typeof (PolygonShape),
new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsRender, null,
OnCoerceInnerRadiusOffset));
public int InnerRadiusOffset
{
get { return (int) GetValue(InnerRadiusOffsetProperty); }
set { SetValue(InnerRadiusOffsetProperty, value); }
}
//Restrict OffSetValue between 0 and 200 %;
private static object OnCoerceInnerRadiusOffset(DependencyObject obj, object baseValue)
{
PolygonShape shape = (PolygonShape) obj;
int value = (int) baseValue;
if (value < 0)
value = 0;
if (value > 200)
value = 200;
return value;
}
#endregion
#endregion
#region Overridden Methods
protected override Geometry DefiningGeometry
{
get { return CreateGeometry(); }
}
#endregion
#region Private HelperFunctions
private static float GetSin(double degAngle)
{
return (float) Math.Sin(Math.PI*degAngle/180);
}
private static float GetCos(double degAngle)
{
return (float) Math.Cos(Math.PI*degAngle/180);
}
private void Swap(ref float val1, ref float val2)
{
float temp = val1;
val1 = val2;
val2 = temp;
}
private StreamGeometry CreateGeometry()
{
// Twice as much points for the calculation of intermediate point between cornerpoints
int cornerPoints = CornerPoints*2;
// Incrementing angle based on amount of cornerpoints
float incrementingAngle = 360f/cornerPoints;
//Outer radius based on the minium widht or height of the shape
float outerRadius =
(float)
Math.Min(RenderSize.Width/2 - StrokeThickness/2, RenderSize.Height/2 - StrokeThickness/2);
//innerRadius calculation taking innerRadiusOffset as a percentage offset into account
float innerRadiusOffset = (1 - InnerRadiusOffset/100f);
float innerRadius = GetCos(incrementingAngle)*outerRadius*innerRadiusOffset;
float rotationAnle = (float) RotationAngle;
//Calculate and store points for geometry
float x, y, angle;
Point[] points = new Point[cornerPoints];
for (int i = 0; i < cornerPoints; i++)
{
//Alternating point on outer and inner radius
angle = i*incrementingAngle + rotationAnle;
x = GetCos(angle)*outerRadius;
y = GetSin(angle)*outerRadius;
points[i] = new Point(x, y);
Swap(ref outerRadius, ref innerRadius);
}
//Create the geometry
StreamGeometry geometry = new StreamGeometry();
using (StreamGeometryContext ctx = geometry.Open())
{
ctx.BeginFigure(points[0], true, true);
for (int i = 1; i < cornerPoints; i++)
{
ctx.LineTo(points[i], true, true);
}
}
//Translate into shape center
geometry.Transform = new TranslateTransform(outerRadius + StrokeThickness/2,
outerRadius + StrokeThickness/2);
return geometry;
}
#endregion
}
}
| |
using System;
using ChainUtils.BouncyCastle.Crypto.Utilities;
using ChainUtils.BouncyCastle.Utilities;
namespace ChainUtils.BouncyCastle.Crypto.Digests
{
/**
* Draft FIPS 180-2 implementation of SHA-256. <b>Note:</b> As this is
* based on a draft this implementation is subject to change.
*
* <pre>
* block word digest
* SHA-1 512 32 160
* SHA-256 512 32 256
* SHA-384 1024 64 384
* SHA-512 1024 64 512
* </pre>
*/
public class Sha256Digest
: GeneralDigest
{
private const int DigestLength = 32;
private uint H1, H2, H3, H4, H5, H6, H7, H8;
private uint[] X = new uint[64];
private int xOff;
public Sha256Digest()
{
initHs();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public Sha256Digest(Sha256Digest t) : base(t)
{
CopyIn(t);
}
private void CopyIn(Sha256Digest t)
{
base.CopyIn(t);
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
H6 = t.H6;
H7 = t.H7;
H8 = t.H8;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
public override string AlgorithmName
{
get { return "SHA-256"; }
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff] = Pack.BE_To_UInt32(input, inOff);
if (++xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(
long bitLength)
{
if (xOff > 14)
{
ProcessBlock();
}
X[14] = (uint)((ulong)bitLength >> 32);
X[15] = (uint)((ulong)bitLength);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
Pack.UInt32_To_BE((uint)H1, output, outOff);
Pack.UInt32_To_BE((uint)H2, output, outOff + 4);
Pack.UInt32_To_BE((uint)H3, output, outOff + 8);
Pack.UInt32_To_BE((uint)H4, output, outOff + 12);
Pack.UInt32_To_BE((uint)H5, output, outOff + 16);
Pack.UInt32_To_BE((uint)H6, output, outOff + 20);
Pack.UInt32_To_BE((uint)H7, output, outOff + 24);
Pack.UInt32_To_BE((uint)H8, output, outOff + 28);
Reset();
return DigestLength;
}
/**
* reset the chaining variables
*/
public override void Reset()
{
base.Reset();
initHs();
xOff = 0;
Array.Clear(X, 0, X.Length);
}
private void initHs()
{
/* SHA-256 initial hash value
* The first 32 bits of the fractional parts of the square roots
* of the first eight prime numbers
*/
H1 = 0x6a09e667;
H2 = 0xbb67ae85;
H3 = 0x3c6ef372;
H4 = 0xa54ff53a;
H5 = 0x510e527f;
H6 = 0x9b05688c;
H7 = 0x1f83d9ab;
H8 = 0x5be0cd19;
}
internal override void ProcessBlock()
{
//
// expand 16 word block into 64 word blocks.
//
for (var ti = 16; ti <= 63; ti++)
{
X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16];
}
//
// set up working variables.
//
var a = H1;
var b = H2;
var c = H3;
var d = H4;
var e = H5;
var f = H6;
var g = H7;
var h = H8;
var t = 0;
for(var i = 0; i < 8; ++i)
{
// t = 8 * i
h += Sum1Ch(e, f, g) + K[t] + X[t];
d += h;
h += Sum0Maj(a, b, c);
++t;
// t = 8 * i + 1
g += Sum1Ch(d, e, f) + K[t] + X[t];
c += g;
g += Sum0Maj(h, a, b);
++t;
// t = 8 * i + 2
f += Sum1Ch(c, d, e) + K[t] + X[t];
b += f;
f += Sum0Maj(g, h, a);
++t;
// t = 8 * i + 3
e += Sum1Ch(b, c, d) + K[t] + X[t];
a += e;
e += Sum0Maj(f, g, h);
++t;
// t = 8 * i + 4
d += Sum1Ch(a, b, c) + K[t] + X[t];
h += d;
d += Sum0Maj(e, f, g);
++t;
// t = 8 * i + 5
c += Sum1Ch(h, a, b) + K[t] + X[t];
g += c;
c += Sum0Maj(d, e, f);
++t;
// t = 8 * i + 6
b += Sum1Ch(g, h, a) + K[t] + X[t];
f += b;
b += Sum0Maj(c, d, e);
++t;
// t = 8 * i + 7
a += Sum1Ch(f, g, h) + K[t] + X[t];
e += a;
a += Sum0Maj(b, c, d);
++t;
}
H1 += a;
H2 += b;
H3 += c;
H4 += d;
H5 += e;
H6 += f;
H7 += g;
H8 += h;
//
// reset the offset and clean out the word buffer.
//
xOff = 0;
Array.Clear(X, 0, 16);
}
private static uint Sum1Ch(
uint x,
uint y,
uint z)
{
// return Sum1(x) + Ch(x, y, z);
return (((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)))
+ ((x & y) ^ ((~x) & z));
}
private static uint Sum0Maj(
uint x,
uint y,
uint z)
{
// return Sum0(x) + Maj(x, y, z);
return (((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)))
+ ((x & y) ^ (x & z) ^ (y & z));
}
// /* SHA-256 functions */
// private static uint Ch(
// uint x,
// uint y,
// uint z)
// {
// return ((x & y) ^ ((~x) & z));
// }
//
// private static uint Maj(
// uint x,
// uint y,
// uint z)
// {
// return ((x & y) ^ (x & z) ^ (y & z));
// }
//
// private static uint Sum0(
// uint x)
// {
// return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10));
// }
//
// private static uint Sum1(
// uint x)
// {
// return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7));
// }
private static uint Theta0(
uint x)
{
return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3);
}
private static uint Theta1(
uint x)
{
return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10);
}
/* SHA-256 Constants
* (represent the first 32 bits of the fractional parts of the
* cube roots of the first sixty-four prime numbers)
*/
private static readonly uint[] K = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
public override IMemoable Copy()
{
return new Sha256Digest(this);
}
public override void Reset(IMemoable other)
{
var d = (Sha256Digest)other;
CopyIn(d);
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Contoso.Core.AppPartPropertyUIOverrideWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System.Windows.Forms;
namespace Cosmos.Debug.GDB {
partial class FormRegisters {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.panel5 = new System.Windows.Forms.Panel();
this.label2 = new Label();
this.lablFlagsText = new Label();
this.label3 = new Label();
this.lablFlags = new Label();
this.label4 = new Label();
this.label11 = new Label();
this.lablALText = new Label();
this.lablGS = new Label();
this.lablEAX = new Label();
this.label32 = new Label();
this.lablAX = new Label();
this.lablFS = new Label();
this.lablAH = new Label();
this.label29 = new Label();
this.lablEBXLabel = new Label();
this.lablES = new Label();
this.lablBXLabel = new Label();
this.label17 = new Label();
this.label8 = new Label();
this.lablDS = new Label();
this.lablEBX = new Label();
this.label19 = new Label();
this.lablBX = new Label();
this.lablCS = new Label();
this.lablBH = new Label();
this.label22 = new Label();
this.lablECXLabel = new Label();
this.lablSS = new Label();
this.lablCXLabel = new Label();
this.label25 = new Label();
this.label14 = new Label();
this.lablEDI = new Label();
this.lablECX = new Label();
this.label7 = new Label();
this.lablCX = new Label();
this.lablESI = new Label();
this.lablCH = new Label();
this.label10 = new Label();
this.lablEDXLabel = new Label();
this.lablEBP = new Label();
this.lablDXLabel = new Label();
this.label12 = new Label();
this.label20 = new Label();
this.lablESP = new Label();
this.lablEDX = new Label();
this.label15 = new Label();
this.lablDX = new Label();
this.lablEIPText = new Label();
this.lablDH = new Label();
this.lablEIP = new Label();
this.label30 = new Label();
this.label6 = new Label();
this.lablAL = new Label();
this.lablDL = new Label();
this.label28 = new Label();
this.label24 = new Label();
this.lablBL = new Label();
this.lablCL = new Label();
this.label26 = new Label();
this.panel5.SuspendLayout();
this.SuspendLayout();
//
// panel5
//
this.panel5.Controls.Add(this.label2);
this.panel5.Controls.Add(this.lablFlagsText);
this.panel5.Controls.Add(this.label3);
this.panel5.Controls.Add(this.lablFlags);
this.panel5.Controls.Add(this.label4);
this.panel5.Controls.Add(this.label11);
this.panel5.Controls.Add(this.lablALText);
this.panel5.Controls.Add(this.lablGS);
this.panel5.Controls.Add(this.lablEAX);
this.panel5.Controls.Add(this.label32);
this.panel5.Controls.Add(this.lablAX);
this.panel5.Controls.Add(this.lablFS);
this.panel5.Controls.Add(this.lablAH);
this.panel5.Controls.Add(this.label29);
this.panel5.Controls.Add(this.lablEBXLabel);
this.panel5.Controls.Add(this.lablES);
this.panel5.Controls.Add(this.lablBXLabel);
this.panel5.Controls.Add(this.label17);
this.panel5.Controls.Add(this.label8);
this.panel5.Controls.Add(this.lablDS);
this.panel5.Controls.Add(this.lablEBX);
this.panel5.Controls.Add(this.label19);
this.panel5.Controls.Add(this.lablBX);
this.panel5.Controls.Add(this.lablCS);
this.panel5.Controls.Add(this.lablBH);
this.panel5.Controls.Add(this.label22);
this.panel5.Controls.Add(this.lablECXLabel);
this.panel5.Controls.Add(this.lablSS);
this.panel5.Controls.Add(this.lablCXLabel);
this.panel5.Controls.Add(this.label25);
this.panel5.Controls.Add(this.label14);
this.panel5.Controls.Add(this.lablEDI);
this.panel5.Controls.Add(this.lablECX);
this.panel5.Controls.Add(this.label7);
this.panel5.Controls.Add(this.lablCX);
this.panel5.Controls.Add(this.lablESI);
this.panel5.Controls.Add(this.lablCH);
this.panel5.Controls.Add(this.label10);
this.panel5.Controls.Add(this.lablEDXLabel);
this.panel5.Controls.Add(this.lablEBP);
this.panel5.Controls.Add(this.lablDXLabel);
this.panel5.Controls.Add(this.label12);
this.panel5.Controls.Add(this.label20);
this.panel5.Controls.Add(this.lablESP);
this.panel5.Controls.Add(this.lablEDX);
this.panel5.Controls.Add(this.label15);
this.panel5.Controls.Add(this.lablDX);
this.panel5.Controls.Add(this.lablEIPText);
this.panel5.Controls.Add(this.lablDH);
this.panel5.Controls.Add(this.lablEIP);
this.panel5.Controls.Add(this.label30);
this.panel5.Controls.Add(this.label6);
this.panel5.Controls.Add(this.lablAL);
this.panel5.Controls.Add(this.lablDL);
this.panel5.Controls.Add(this.label28);
this.panel5.Controls.Add(this.label24);
this.panel5.Controls.Add(this.lablBL);
this.panel5.Controls.Add(this.lablCL);
this.panel5.Controls.Add(this.label26);
this.panel5.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel5.Location = new System.Drawing.Point(0, 0);
this.panel5.Name = "panel5";
this.panel5.Size = new System.Drawing.Size(275, 263);
this.panel5.TabIndex = 62;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(6, 10);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(60, 13);
this.label2.TabIndex = 2;
this.label2.Text = "Registers";
//
// lablFlagsText
//
this.lablFlagsText.AutoSize = true;
this.lablFlagsText.Location = new System.Drawing.Point(36, 152);
this.lablFlagsText.Name = "lablFlagsText";
this.lablFlagsText.Size = new System.Drawing.Size(55, 13);
this.lablFlagsText.TabIndex = 60;
this.lablFlagsText.Text = "12345678";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 37);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(28, 13);
this.label3.TabIndex = 3;
this.label3.Text = "EAX";
//
// lablFlags
//
this.lablFlags.AutoSize = true;
this.lablFlags.Location = new System.Drawing.Point(36, 139);
this.lablFlags.Name = "lablFlags";
this.lablFlags.Size = new System.Drawing.Size(55, 13);
this.lablFlags.TabIndex = 59;
this.lablFlags.Text = "12345678";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(107, 37);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(21, 13);
this.label4.TabIndex = 4;
this.label4.Text = "AX";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(6, 139);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(32, 13);
this.label11.TabIndex = 58;
this.label11.Text = "Flags";
//
// lablALText
//
this.lablALText.AutoSize = true;
this.lablALText.Location = new System.Drawing.Point(176, 37);
this.lablALText.Name = "lablALText";
this.lablALText.Size = new System.Drawing.Size(22, 13);
this.lablALText.TabIndex = 5;
this.lablALText.Text = "AH";
//
// lablGS
//
this.lablGS.AutoSize = true;
this.lablGS.Location = new System.Drawing.Point(162, 240);
this.lablGS.Name = "lablGS";
this.lablGS.Size = new System.Drawing.Size(55, 13);
this.lablGS.TabIndex = 57;
this.lablGS.Text = "12345678";
//
// lablEAX
//
this.lablEAX.AutoSize = true;
this.lablEAX.Location = new System.Drawing.Point(36, 37);
this.lablEAX.Name = "lablEAX";
this.lablEAX.Size = new System.Drawing.Size(55, 13);
this.lablEAX.TabIndex = 6;
this.lablEAX.Text = "12345678";
this.lablEAX.Visible = false;
//
// label32
//
this.label32.AutoSize = true;
this.label32.Location = new System.Drawing.Point(132, 240);
this.label32.Name = "label32";
this.label32.Size = new System.Drawing.Size(22, 13);
this.label32.TabIndex = 56;
this.label32.Text = "GS";
//
// lablAX
//
this.lablAX.AutoSize = true;
this.lablAX.Location = new System.Drawing.Point(130, 37);
this.lablAX.Name = "lablAX";
this.lablAX.Size = new System.Drawing.Size(31, 13);
this.lablAX.TabIndex = 7;
this.lablAX.Text = "1234";
//
// lablFS
//
this.lablFS.AutoSize = true;
this.lablFS.Location = new System.Drawing.Point(162, 227);
this.lablFS.Name = "lablFS";
this.lablFS.Size = new System.Drawing.Size(55, 13);
this.lablFS.TabIndex = 55;
this.lablFS.Text = "12345678";
//
// lablAH
//
this.lablAH.AutoSize = true;
this.lablAH.Location = new System.Drawing.Point(196, 37);
this.lablAH.Name = "lablAH";
this.lablAH.Size = new System.Drawing.Size(19, 13);
this.lablAH.TabIndex = 8;
this.lablAH.Text = "12";
this.lablAH.Visible = false;
//
// label29
//
this.label29.AutoSize = true;
this.label29.Location = new System.Drawing.Point(132, 227);
this.label29.Name = "label29";
this.label29.Size = new System.Drawing.Size(20, 13);
this.label29.TabIndex = 54;
this.label29.Text = "FS";
//
// lablEBXLabel
//
this.lablEBXLabel.AutoSize = true;
this.lablEBXLabel.Location = new System.Drawing.Point(6, 50);
this.lablEBXLabel.Name = "lablEBXLabel";
this.lablEBXLabel.Size = new System.Drawing.Size(28, 13);
this.lablEBXLabel.TabIndex = 9;
this.lablEBXLabel.Text = "EBX";
//
// lablES
//
this.lablES.AutoSize = true;
this.lablES.Location = new System.Drawing.Point(162, 214);
this.lablES.Name = "lablES";
this.lablES.Size = new System.Drawing.Size(55, 13);
this.lablES.TabIndex = 53;
this.lablES.Text = "12345678";
//
// lablBXLabel
//
this.lablBXLabel.AutoSize = true;
this.lablBXLabel.Location = new System.Drawing.Point(107, 50);
this.lablBXLabel.Name = "lablBXLabel";
this.lablBXLabel.Size = new System.Drawing.Size(21, 13);
this.lablBXLabel.TabIndex = 10;
this.lablBXLabel.Text = "BX";
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(132, 214);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(21, 13);
this.label17.TabIndex = 52;
this.label17.Text = "ES";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(176, 50);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(22, 13);
this.label8.TabIndex = 11;
this.label8.Text = "BH";
//
// lablDS
//
this.lablDS.AutoSize = true;
this.lablDS.Location = new System.Drawing.Point(162, 201);
this.lablDS.Name = "lablDS";
this.lablDS.Size = new System.Drawing.Size(55, 13);
this.lablDS.TabIndex = 51;
this.lablDS.Text = "12345678";
//
// lablEBX
//
this.lablEBX.AutoSize = true;
this.lablEBX.Location = new System.Drawing.Point(36, 50);
this.lablEBX.Name = "lablEBX";
this.lablEBX.Size = new System.Drawing.Size(55, 13);
this.lablEBX.TabIndex = 12;
this.lablEBX.Text = "12345678";
this.lablEBX.Visible = false;
//
// label19
//
this.label19.AutoSize = true;
this.label19.Location = new System.Drawing.Point(132, 201);
this.label19.Name = "label19";
this.label19.Size = new System.Drawing.Size(22, 13);
this.label19.TabIndex = 50;
this.label19.Text = "DS";
//
// lablBX
//
this.lablBX.AutoSize = true;
this.lablBX.Location = new System.Drawing.Point(130, 50);
this.lablBX.Name = "lablBX";
this.lablBX.Size = new System.Drawing.Size(31, 13);
this.lablBX.TabIndex = 13;
this.lablBX.Text = "1234";
this.lablBX.Visible = false;
//
// lablCS
//
this.lablCS.AutoSize = true;
this.lablCS.Location = new System.Drawing.Point(162, 188);
this.lablCS.Name = "lablCS";
this.lablCS.Size = new System.Drawing.Size(55, 13);
this.lablCS.TabIndex = 49;
this.lablCS.Text = "12345678";
//
// lablBH
//
this.lablBH.AutoSize = true;
this.lablBH.Location = new System.Drawing.Point(196, 50);
this.lablBH.Name = "lablBH";
this.lablBH.Size = new System.Drawing.Size(19, 13);
this.lablBH.TabIndex = 14;
this.lablBH.Text = "12";
this.lablBH.Visible = false;
//
// label22
//
this.label22.AutoSize = true;
this.label22.Location = new System.Drawing.Point(132, 188);
this.label22.Name = "label22";
this.label22.Size = new System.Drawing.Size(21, 13);
this.label22.TabIndex = 48;
this.label22.Text = "CS";
//
// lablECXLabel
//
this.lablECXLabel.AutoSize = true;
this.lablECXLabel.Location = new System.Drawing.Point(6, 63);
this.lablECXLabel.Name = "lablECXLabel";
this.lablECXLabel.Size = new System.Drawing.Size(28, 13);
this.lablECXLabel.TabIndex = 15;
this.lablECXLabel.Text = "ECX";
//
// lablSS
//
this.lablSS.AutoSize = true;
this.lablSS.Location = new System.Drawing.Point(162, 175);
this.lablSS.Name = "lablSS";
this.lablSS.Size = new System.Drawing.Size(55, 13);
this.lablSS.TabIndex = 47;
this.lablSS.Text = "12345678";
//
// lablCXLabel
//
this.lablCXLabel.AutoSize = true;
this.lablCXLabel.Location = new System.Drawing.Point(107, 63);
this.lablCXLabel.Name = "lablCXLabel";
this.lablCXLabel.Size = new System.Drawing.Size(21, 13);
this.lablCXLabel.TabIndex = 16;
this.lablCXLabel.Text = "CX";
//
// label25
//
this.label25.AutoSize = true;
this.label25.Location = new System.Drawing.Point(132, 175);
this.label25.Name = "label25";
this.label25.Size = new System.Drawing.Size(21, 13);
this.label25.TabIndex = 46;
this.label25.Text = "SS";
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(176, 63);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(22, 13);
this.label14.TabIndex = 17;
this.label14.Text = "CH";
//
// lablEDI
//
this.lablEDI.AutoSize = true;
this.lablEDI.Location = new System.Drawing.Point(36, 214);
this.lablEDI.Name = "lablEDI";
this.lablEDI.Size = new System.Drawing.Size(55, 13);
this.lablEDI.TabIndex = 45;
this.lablEDI.Text = "12345678";
//
// lablECX
//
this.lablECX.AutoSize = true;
this.lablECX.Location = new System.Drawing.Point(36, 63);
this.lablECX.Name = "lablECX";
this.lablECX.Size = new System.Drawing.Size(55, 13);
this.lablECX.TabIndex = 18;
this.lablECX.Text = "12345678";
this.lablECX.Visible = false;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(6, 214);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(25, 13);
this.label7.TabIndex = 44;
this.label7.Text = "EDI";
//
// lablCX
//
this.lablCX.AutoSize = true;
this.lablCX.Location = new System.Drawing.Point(130, 63);
this.lablCX.Name = "lablCX";
this.lablCX.Size = new System.Drawing.Size(31, 13);
this.lablCX.TabIndex = 19;
this.lablCX.Text = "1234";
this.lablCX.Visible = false;
//
// lablESI
//
this.lablESI.AutoSize = true;
this.lablESI.Location = new System.Drawing.Point(36, 201);
this.lablESI.Name = "lablESI";
this.lablESI.Size = new System.Drawing.Size(55, 13);
this.lablESI.TabIndex = 43;
this.lablESI.Text = "12345678";
//
// lablCH
//
this.lablCH.AutoSize = true;
this.lablCH.Location = new System.Drawing.Point(196, 63);
this.lablCH.Name = "lablCH";
this.lablCH.Size = new System.Drawing.Size(19, 13);
this.lablCH.TabIndex = 20;
this.lablCH.Text = "12";
this.lablCH.Visible = false;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(6, 201);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(24, 13);
this.label10.TabIndex = 42;
this.label10.Text = "ESI";
//
// lablEDXLabel
//
this.lablEDXLabel.AutoSize = true;
this.lablEDXLabel.Location = new System.Drawing.Point(6, 76);
this.lablEDXLabel.Name = "lablEDXLabel";
this.lablEDXLabel.Size = new System.Drawing.Size(29, 13);
this.lablEDXLabel.TabIndex = 21;
this.lablEDXLabel.Text = "EDX";
//
// lablEBP
//
this.lablEBP.AutoSize = true;
this.lablEBP.Location = new System.Drawing.Point(36, 188);
this.lablEBP.Name = "lablEBP";
this.lablEBP.Size = new System.Drawing.Size(55, 13);
this.lablEBP.TabIndex = 41;
this.lablEBP.Text = "12345678";
//
// lablDXLabel
//
this.lablDXLabel.AutoSize = true;
this.lablDXLabel.Location = new System.Drawing.Point(107, 76);
this.lablDXLabel.Name = "lablDXLabel";
this.lablDXLabel.Size = new System.Drawing.Size(22, 13);
this.lablDXLabel.TabIndex = 22;
this.lablDXLabel.Text = "DX";
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(6, 188);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(28, 13);
this.label12.TabIndex = 40;
this.label12.Text = "EBP";
//
// label20
//
this.label20.AutoSize = true;
this.label20.Location = new System.Drawing.Point(176, 76);
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size(23, 13);
this.label20.TabIndex = 23;
this.label20.Text = "DH";
//
// lablESP
//
this.lablESP.AutoSize = true;
this.lablESP.Location = new System.Drawing.Point(36, 175);
this.lablESP.Name = "lablESP";
this.lablESP.Size = new System.Drawing.Size(55, 13);
this.lablESP.TabIndex = 39;
this.lablESP.Text = "12345678";
//
// lablEDX
//
this.lablEDX.AutoSize = true;
this.lablEDX.Location = new System.Drawing.Point(36, 76);
this.lablEDX.Name = "lablEDX";
this.lablEDX.Size = new System.Drawing.Size(55, 13);
this.lablEDX.TabIndex = 24;
this.lablEDX.Text = "12345678";
this.lablEDX.Visible = false;
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(6, 175);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(28, 13);
this.label15.TabIndex = 38;
this.label15.Text = "ESP";
//
// lablDX
//
this.lablDX.AutoSize = true;
this.lablDX.Location = new System.Drawing.Point(130, 76);
this.lablDX.Name = "lablDX";
this.lablDX.Size = new System.Drawing.Size(31, 13);
this.lablDX.TabIndex = 25;
this.lablDX.Text = "1234";
this.lablDX.Visible = false;
//
// lablEIPText
//
this.lablEIPText.AutoSize = true;
this.lablEIPText.Location = new System.Drawing.Point(36, 117);
this.lablEIPText.Name = "lablEIPText";
this.lablEIPText.Size = new System.Drawing.Size(55, 13);
this.lablEIPText.TabIndex = 37;
this.lablEIPText.Text = "12345678";
//
// lablDH
//
this.lablDH.AutoSize = true;
this.lablDH.Location = new System.Drawing.Point(196, 76);
this.lablDH.Name = "lablDH";
this.lablDH.Size = new System.Drawing.Size(19, 13);
this.lablDH.TabIndex = 26;
this.lablDH.Text = "12";
this.lablDH.Visible = false;
//
// lablEIP
//
this.lablEIP.AutoSize = true;
this.lablEIP.Location = new System.Drawing.Point(36, 104);
this.lablEIP.Name = "lablEIP";
this.lablEIP.Size = new System.Drawing.Size(55, 13);
this.lablEIP.TabIndex = 36;
this.lablEIP.Text = "12345678";
//
// label30
//
this.label30.AutoSize = true;
this.label30.Location = new System.Drawing.Point(230, 37);
this.label30.Name = "label30";
this.label30.Size = new System.Drawing.Size(20, 13);
this.label30.TabIndex = 27;
this.label30.Text = "AL";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(6, 104);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(24, 13);
this.label6.TabIndex = 35;
this.label6.Text = "EIP";
//
// lablAL
//
this.lablAL.AutoSize = true;
this.lablAL.Location = new System.Drawing.Point(250, 37);
this.lablAL.Name = "lablAL";
this.lablAL.Size = new System.Drawing.Size(19, 13);
this.lablAL.TabIndex = 28;
this.lablAL.Text = "12";
this.lablAL.Visible = false;
//
// lablDL
//
this.lablDL.AutoSize = true;
this.lablDL.Location = new System.Drawing.Point(250, 76);
this.lablDL.Name = "lablDL";
this.lablDL.Size = new System.Drawing.Size(19, 13);
this.lablDL.TabIndex = 34;
this.lablDL.Text = "12";
this.lablDL.Visible = false;
//
// label28
//
this.label28.AutoSize = true;
this.label28.Location = new System.Drawing.Point(230, 50);
this.label28.Name = "label28";
this.label28.Size = new System.Drawing.Size(20, 13);
this.label28.TabIndex = 29;
this.label28.Text = "BL";
//
// label24
//
this.label24.AutoSize = true;
this.label24.Location = new System.Drawing.Point(230, 76);
this.label24.Name = "label24";
this.label24.Size = new System.Drawing.Size(21, 13);
this.label24.TabIndex = 33;
this.label24.Text = "DL";
//
// lablBL
//
this.lablBL.AutoSize = true;
this.lablBL.Location = new System.Drawing.Point(250, 50);
this.lablBL.Name = "lablBL";
this.lablBL.Size = new System.Drawing.Size(19, 13);
this.lablBL.TabIndex = 30;
this.lablBL.Text = "12";
//
// lablCL
//
this.lablCL.AutoSize = true;
this.lablCL.Location = new System.Drawing.Point(250, 63);
this.lablCL.Name = "lablCL";
this.lablCL.Size = new System.Drawing.Size(19, 13);
this.lablCL.TabIndex = 32;
this.lablCL.Text = "12";
this.lablCL.Visible = false;
//
// label26
//
this.label26.AutoSize = true;
this.label26.Location = new System.Drawing.Point(230, 63);
this.label26.Name = "label26";
this.label26.Size = new System.Drawing.Size(20, 13);
this.label26.TabIndex = 31;
this.label26.Text = "CL";
//
// FormRegisters
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(275, 263);
this.Controls.Add(this.panel5);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "FormRegisters";
this.ShowInTaskbar = false;
this.Text = "Registers";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormRegisters_FormClosing);
this.panel5.ResumeLayout(false);
this.panel5.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel5;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label lablFlagsText;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label lablFlags;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label lablALText;
private System.Windows.Forms.Label lablGS;
private System.Windows.Forms.Label lablEAX;
private System.Windows.Forms.Label label32;
private System.Windows.Forms.Label lablAX;
private System.Windows.Forms.Label lablFS;
private System.Windows.Forms.Label lablAH;
private System.Windows.Forms.Label label29;
private System.Windows.Forms.Label lablEBXLabel;
private System.Windows.Forms.Label lablES;
private System.Windows.Forms.Label lablBXLabel;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label lablDS;
private System.Windows.Forms.Label lablEBX;
private System.Windows.Forms.Label label19;
private System.Windows.Forms.Label lablBX;
private System.Windows.Forms.Label lablCS;
private System.Windows.Forms.Label lablBH;
private System.Windows.Forms.Label label22;
private System.Windows.Forms.Label lablECXLabel;
private System.Windows.Forms.Label lablSS;
private System.Windows.Forms.Label lablCXLabel;
private System.Windows.Forms.Label label25;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label lablEDI;
private System.Windows.Forms.Label lablECX;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label lablCX;
private System.Windows.Forms.Label lablESI;
private System.Windows.Forms.Label lablCH;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label lablEDXLabel;
private System.Windows.Forms.Label lablEBP;
private System.Windows.Forms.Label lablDXLabel;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label20;
private System.Windows.Forms.Label lablESP;
private System.Windows.Forms.Label lablEDX;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label lablDX;
private System.Windows.Forms.Label lablEIPText;
private System.Windows.Forms.Label lablDH;
private System.Windows.Forms.Label lablEIP;
private System.Windows.Forms.Label label30;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label lablAL;
private System.Windows.Forms.Label lablDL;
private System.Windows.Forms.Label label28;
private System.Windows.Forms.Label label24;
private System.Windows.Forms.Label lablBL;
private System.Windows.Forms.Label lablCL;
private System.Windows.Forms.Label label26;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Reflection.Tests
{
public class PropertyInfoTests
{
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.IntProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.StringProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.DoubleProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.FloatProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.EnumProperty))]
public void GetConstantValue_NotConstant_ThrowsInvalidOperationException(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Throws<InvalidOperationException>(() => propertyInfo.GetConstantValue());
Assert.Throws<InvalidOperationException>(() => propertyInfo.GetRawConstantValue());
}
[Theory]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetClass), "Item", true, true)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetStruct), "Item", true, false)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetInterface), "Item", false, true)]
public void GetMethod_SetMethod(Type type, string name, bool hasGetter, bool hasSetter)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(hasGetter, propertyInfo.GetMethod != null);
Assert.Equal(hasSetter, propertyInfo.SetMethod != null);
}
public static IEnumerable<object[]> GetValue_TestData()
{
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), new BaseClass(), null, -1.0 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadWriteProperty3), typeof(BaseClass), null, -2 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.Name), new BaseClass(), null, "hello" };
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { 1, "2" }, null };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), new BaseClass(), null, 100 };
}
[Theory]
[MemberData(nameof(GetValue_TestData))]
public void GetValue(Type type, string name, object obj, object[] index, object expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
if (index == null)
{
Assert.Equal(expected, propertyInfo.GetValue(obj));
}
Assert.Equal(expected, propertyInfo.GetValue(obj, index));
}
public static IEnumerable<object[]> GetValue_Invalid_TestData()
{
// Incorrect indexer parameters
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { 1, "2", 3 }, typeof(TargetParameterCountException) };
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), null, typeof(TargetParameterCountException) };
// Incorrect type
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { "1", "2" }, typeof(ArgumentException) };
// Readonly
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), new BaseClass(), null, typeof(ArgumentException) };
// Null target
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", null, new object[] { "1", "2" }, typeof(TargetException) };
}
[Theory]
[MemberData(nameof(GetValue_Invalid_TestData))]
public void GetValue_Invalid(Type type, string name, object obj, object[] index, Type exceptionType)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Throws(exceptionType, () => propertyInfo.GetValue(obj, index));
}
public static IEnumerable<object[]> SetValue_TestData()
{
yield return new object[] { typeof(BaseClass), nameof(BaseClass.StaticObjectArrayProperty), typeof(BaseClass), new string[] { "hello" }, null, new string[] { "hello" } };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ObjectArrayProperty), new BaseClass(), new string[] { "hello" }, null, new string[] { "hello" } };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.Name), new BaseClass(), "hello", null, "hello" };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "hello", new object[] { 99, 2, new string[] { "hello" }, "f" }, "992f1" };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "pw", new object[] { 99, 2, new string[] { "hello" }, "SOME string" }, "992SOME string1" };
}
[Theory]
[MemberData(nameof(SetValue_TestData))]
public void SetValue(Type type, string name, object obj, object value, object[] index, object expected)
{
PropertyInfo PropertyInfo = GetProperty(type, name);
object originalValue;
if (index == null)
{
// Use SetValue(object, object)
originalValue = PropertyInfo.GetValue(obj);
try
{
PropertyInfo.SetValue(obj, value);
Assert.Equal(expected, PropertyInfo.GetValue(obj));
}
finally
{
PropertyInfo.SetValue(obj, originalValue);
}
}
// Use SetValue(object, object, object[])
originalValue = PropertyInfo.GetValue(obj, index);
try
{
PropertyInfo.SetValue(obj, value, index);
Assert.Equal(expected, PropertyInfo.GetValue(obj, index));
}
finally
{
PropertyInfo.SetValue(obj, originalValue, index);
}
}
public static IEnumerable<object[]> SetValue_Invalid_TestData()
{
// Incorrect number of parameters
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "value", new object[] { 99, 2, new string[] { "a" } }, typeof(TargetParameterCountException) };
// Obj is null
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), null, null, null, typeof(TargetException) };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", null, "value", new object[] { 99, 2, new string[] { "a" }, "b" }, typeof(TargetException) };
// Readonly
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), new BaseClass(), 100, null, typeof(ArgumentException) };
// Wrong value type
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "value", new object[] { 99, 2, "invalid", "string" }, typeof(ArgumentException) };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), 100, new object[] { 99, 2, new string[] { "a" }, "b" }, typeof(ArgumentException) };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), new BaseClass(), "string", null, typeof(ArgumentException) };
}
[Theory]
[MemberData(nameof(SetValue_Invalid_TestData))]
public void SetValue_Invalid(Type type, string name, object obj, object value, object[] index, Type exceptionType)
{
PropertyInfo PropertyInfo = GetProperty(type, name);
Assert.Throws(exceptionType, () => PropertyInfo.SetValue(obj, value, index));
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty))]
[InlineData("PrivateGetPrivateSetIntProperty")]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty))]
public static void GetRequiredCustomModifiers_GetOptionalCustomModifiers(string name)
{
PropertyInfo property = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Assert.Empty(property.GetRequiredCustomModifiers());
Assert.Empty(property.GetOptionalCustomModifiers());
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty), 2, 2)]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty), 2, 2)]
[InlineData("PrivateGetPrivateSetIntProperty", 0, 2)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty), 1, 2)]
public static void GetAccessors(string name, int accessorPublicCount, int accessorPublicAndNonPublicCount)
{
PropertyInfo pi = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Assert.Equal(accessorPublicCount, pi.GetAccessors().Length);
Assert.Equal(accessorPublicCount, pi.GetAccessors(false).Length);
Assert.Equal(accessorPublicAndNonPublicCount, pi.GetAccessors(true).Length);
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty), true, true, true, true)]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty), true, true, true, true)]
[InlineData("PrivateGetPrivateSetIntProperty", false, true, false, true)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty), true, true, false, true)]
public static void GetGetMethod_GetSetMethod(string name, bool publicGet, bool nonPublicGet, bool publicSet, bool nonPublicSet)
{
PropertyInfo pi = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (publicGet)
{
Assert.Equal("get_" + name, pi.GetGetMethod().Name);
Assert.Equal("get_" + name, pi.GetGetMethod(true).Name);
Assert.Equal("get_" + name, pi.GetGetMethod(false).Name);
}
else
{
Assert.Null(pi.GetGetMethod());
}
if (nonPublicGet)
{
Assert.Equal("get_" + name, pi.GetGetMethod(true).Name);
}
else
{
Assert.Null(pi.GetGetMethod());
Assert.Null(pi.GetGetMethod(false));
}
if (publicSet)
{
Assert.Equal("set_" + name, pi.GetSetMethod().Name);
Assert.Equal("set_" + name, pi.GetSetMethod(true).Name);
Assert.Equal("set_" + name, pi.GetSetMethod(false).Name);
}
else
{
Assert.Null(pi.GetSetMethod());
}
if (nonPublicSet)
{
Assert.Equal("set_" + name, pi.GetSetMethod(true).Name);
}
else
{
Assert.Null(pi.GetSetMethod());
Assert.Null(pi.GetSetMethod(false));
}
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), false)]
public void Equals(Type type1, string name1, Type type2, string name2, bool expected)
{
PropertyInfo propertyInfo1 = GetProperty(type1, name1);
PropertyInfo propertyInfo2 = GetProperty(type2, name2);
Assert.Equal(expected, propertyInfo1.Equals(propertyInfo2));
Assert.Equal(expected, propertyInfo1 == propertyInfo2);
Assert.Equal(!expected, propertyInfo1 != propertyInfo2);
}
[Fact]
public void GetHashCodeTest()
{
PropertyInfo propertyInfo = GetProperty(typeof(BaseClass), "ReadWriteProperty1");
Assert.NotEqual(0, propertyInfo.GetHashCode());
}
[Theory]
[InlineData(typeof(BaseClass), "Item", new string[] { "Index" })]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), new string[0])]
public void GetIndexParameters(Type type, string name, string[] expectedNames)
{
PropertyInfo propertyInfo = GetProperty(type, name);
ParameterInfo[] indexParameters = propertyInfo.GetIndexParameters();
Assert.Equal(expectedNames, indexParameters.Select(p => p.Name));
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), false)]
public void CanRead(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.CanRead);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), true)]
public void CanWrite(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.CanWrite);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1))]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty))]
public void DeclaringType(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(type, propertyInfo.DeclaringType);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(short))]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), typeof(double))]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty), typeof(int))]
public void PropertyType(Type type, string name, Type expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.PropertyType);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1))]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty))]
public void Name(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(name, propertyInfo.Name);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), false)]
public void IsSpecialName(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.IsSpecialName);
}
[Theory]
[InlineData(typeof(SubClass), nameof(SubClass.Description), PropertyAttributes.None)]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty), PropertyAttributes.None)]
public void Attributes(Type type, string name, PropertyAttributes expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.Attributes);
}
public static PropertyInfo GetProperty(Type type, string name)
{
return type.GetTypeInfo().DeclaredProperties.First(propertyInfo => propertyInfo.Name.Equals(name));
}
public interface InterfaceWithPropertyDeclaration
{
string Name { get; set; }
}
public class BaseClass : InterfaceWithPropertyDeclaration
{
public static object[] _staticObjectArrayProperty = new object[1];
public static object[] StaticObjectArrayProperty
{
get { return _staticObjectArrayProperty; }
set { _staticObjectArrayProperty = value; }
}
public object[] _objectArray;
public object[] ObjectArrayProperty
{
get { return _objectArray; }
set { _objectArray = value; }
}
public short _readWriteProperty1 = -2;
public short ReadWriteProperty1
{
get { return _readWriteProperty1; }
set { _readWriteProperty1 = value; }
}
public double _readWriteProperty2 = -1;
public double ReadWriteProperty2
{
get { return _readWriteProperty2; }
set { _readWriteProperty2 = value; }
}
public static int _readWriteProperty3 = -2;
public static int ReadWriteProperty3
{
get { return _readWriteProperty3; }
set { _readWriteProperty3 = value; }
}
public int _readOnlyProperty = 100;
public int ReadOnlyProperty
{
get { return _readOnlyProperty; }
}
public long _writeOnlyProperty = 1;
public int WriteOnlyProperty
{
set { _writeOnlyProperty = value; }
}
// Indexer properties
public string[] _stringArray = { "abc", "def", "ghi", "jkl" };
public string this[int Index]
{
get { return _stringArray[Index]; }
set { _stringArray[Index] = value; }
}
// Interface property
private string _name = "hello";
public string Name
{
get { return _name; }
set { _name = value; }
}
// Const fields
private const int IntField = 100;
private const string StringField = "hello";
private const double DoubleField = 22.314;
private const float FloatField = 99.99F;
private const PublicEnum EnumField = PublicEnum.Case1;
public int IntProperty { get { return IntField; } }
public string StringProperty { get { return StringField; } }
public double DoubleProperty { get { return DoubleField; } }
public float FloatProperty { get { return FloatField; } }
public PublicEnum EnumProperty { get { return EnumField; } }
}
public class SubClass : BaseClass
{
private int _newProperty = 100;
private string _description;
public int NewProperty
{
get { return _newProperty; }
set { _newProperty = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
}
public class CustomIndexerNameClass
{
private object[] _objectArray;
[IndexerName("BasicIndexer")] // Property name will be BasicIndexer instead of Item
public object[] this[int index, string s]
{
get { return _objectArray; }
set { _objectArray = value; }
}
}
public class AdvancedIndexerClass
{
public string _setValue = null;
public string this[int index, int index2, string[] h, string myStr]
{
get
{
string strHashLength = "null";
if (h != null)
{
strHashLength = h.Length.ToString();
}
return index.ToString() + index2.ToString() + myStr + strHashLength;
}
set
{
string strHashLength = "null";
if (h != null)
{
strHashLength = h.Length.ToString();
}
_setValue = _setValue = index.ToString() + index2.ToString() + myStr + strHashLength + value;
}
}
}
public class GetSetClass
{
public int ReadWriteProperty { get { return 1; } set { } }
public string ReadOnlyProperty { get { return "Test"; } }
public char WriteOnlyProperty { set { } }
public int this[int index] { get { return 2; } set { } }
}
public struct GetSetStruct
{
public int ReadWriteProperty { get { return 1; } set { } }
public string ReadOnlyProperty { get { return "Test"; } }
public char WriteOnlyProperty { set { } }
public string this[int index] { get { return "name"; } }
}
public interface GetSetInterface
{
int ReadWriteProperty { get; set; }
string ReadOnlyProperty { get; }
char WriteOnlyProperty { set; }
char this[int index] { set; }
}
public class PropertyInfoMembers
{
public int PublicGetIntProperty { get; }
public string PublicGetPublicSetStringProperty { get; set; }
public double PublicGetDoubleProperty { get; }
public float PublicGetFloatProperty { get; }
public PublicEnum PublicGetEnumProperty { get; set; }
private int PrivateGetPrivateSetIntProperty { get; set; }
public int PublicGetPrivateSetProperty { get; private set; }
}
}
}
| |
using System;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using System.Reflection;
using System.IO.IsolatedStorage;
using System.Collections.Generic;
using Xamarin.Forms;
using Xamarin.Forms.Core.UnitTests;
using System.Security.Cryptography;
using System.Text;
using Xamarin.Forms.Internals;
#if WINDOWS_PHONE
using Xamarin.Forms.Platform.WinPhone;
#endif
[assembly:Dependency (typeof(MockDeserializer))]
[assembly:Dependency (typeof(MockResourcesProvider))]
namespace Xamarin.Forms.Core.UnitTests
{
internal class MockPlatformServices : IPlatformServices
{
Action<Action> invokeOnMainThread;
Action<Uri> openUriAction;
Func<Uri, CancellationToken, Task<Stream>> getStreamAsync;
public MockPlatformServices (Action<Action> invokeOnMainThread = null, Action<Uri> openUriAction = null, Func<Uri, CancellationToken, Task<Stream>> getStreamAsync = null)
{
this.invokeOnMainThread = invokeOnMainThread;
this.openUriAction = openUriAction;
this.getStreamAsync = getStreamAsync;
}
static MD5CryptoServiceProvider checksum = new MD5CryptoServiceProvider ();
public string GetMD5Hash (string input)
{
var bytes = checksum.ComputeHash (Encoding.UTF8.GetBytes (input));
var ret = new char [32];
for (int i = 0; i < 16; i++){
ret [i*2] = (char)hex (bytes [i] >> 4);
ret [i*2+1] = (char)hex (bytes [i] & 0xf);
}
return new string (ret);
}
static int hex (int v)
{
if (v < 10)
return '0' + v;
return 'a' + v-10;
}
public double GetNamedSize (NamedSize size, Type targetElement, bool useOldSizes)
{
switch (size) {
case NamedSize.Default:
return 10;
case NamedSize.Micro:
return 4;
case NamedSize.Small:
return 8;
case NamedSize.Medium:
return 12;
case NamedSize.Large:
return 16;
default:
throw new ArgumentOutOfRangeException ("size");
}
}
public void OpenUriAction (Uri uri)
{
if (openUriAction != null)
openUriAction (uri);
else
throw new NotImplementedException ();
}
public bool IsInvokeRequired
{
get { return false; }
}
public string RuntimePlatform { get; set; }
public void BeginInvokeOnMainThread (Action action)
{
if (invokeOnMainThread == null)
action ();
else
invokeOnMainThread (action);
}
public Ticker CreateTicker()
{
return new MockTicker();
}
public void StartTimer (TimeSpan interval, Func<bool> callback)
{
Timer timer = null;
TimerCallback onTimeout = o => BeginInvokeOnMainThread (() => {
if (callback ())
return;
timer.Dispose ();
});
timer = new Timer (onTimeout, null, interval, interval);
}
public Task<Stream> GetStreamAsync (Uri uri, CancellationToken cancellationToken)
{
if (getStreamAsync == null)
throw new NotImplementedException ();
return getStreamAsync (uri, cancellationToken);
}
public Assembly[] GetAssemblies ()
{
return AppDomain.CurrentDomain.GetAssemblies ();
}
public IIsolatedStorageFile GetUserStoreForApplication ()
{
#if WINDOWS_PHONE
return new MockIsolatedStorageFile (IsolatedStorageFile.GetUserStoreForApplication ());
#else
return new MockIsolatedStorageFile (IsolatedStorageFile.GetUserStoreForAssembly ());
#endif
}
public class MockIsolatedStorageFile : IIsolatedStorageFile
{
readonly IsolatedStorageFile isolatedStorageFile;
public MockIsolatedStorageFile (IsolatedStorageFile isolatedStorageFile)
{
this.isolatedStorageFile = isolatedStorageFile;
}
public Task<bool> GetDirectoryExistsAsync (string path)
{
return Task.FromResult (isolatedStorageFile.DirectoryExists (path));
}
public Task CreateDirectoryAsync (string path)
{
isolatedStorageFile.CreateDirectory (path);
return Task.FromResult (true);
}
public Task<Stream> OpenFileAsync (string path, FileMode mode, FileAccess access)
{
Stream stream = isolatedStorageFile.OpenFile (path, (System.IO.FileMode)mode, (System.IO.FileAccess)access);
return Task.FromResult (stream);
}
public Task<Stream> OpenFileAsync (string path, FileMode mode, FileAccess access, FileShare share)
{
Stream stream = isolatedStorageFile.OpenFile (path, (System.IO.FileMode)mode, (System.IO.FileAccess)access, (System.IO.FileShare)share);
return Task.FromResult (stream);
}
public Task<bool> GetFileExistsAsync (string path)
{
return Task.FromResult (isolatedStorageFile.FileExists (path));
}
public Task<DateTimeOffset> GetLastWriteTimeAsync (string path)
{
return Task.FromResult (isolatedStorageFile.GetLastWriteTime (path));
}
}
}
internal class MockDeserializer : IDeserializer
{
public Task<IDictionary<string, object>> DeserializePropertiesAsync ()
{
return Task.FromResult<IDictionary<string, object>> (new Dictionary<string,object> ());
}
public Task SerializePropertiesAsync (IDictionary<string, object> properties)
{
return Task.FromResult (false);
}
}
internal class MockResourcesProvider : ISystemResourcesProvider
{
public IResourceDictionary GetSystemResources ()
{
var dictionary = new ResourceDictionary ();
Style style;
style = new Style (typeof(Label));
dictionary [Device.Styles.BodyStyleKey] = style;
style = new Style (typeof(Label));
style.Setters.Add (Label.FontSizeProperty, 50);
dictionary [Device.Styles.TitleStyleKey] = style;
style = new Style (typeof(Label));
style.Setters.Add (Label.FontSizeProperty, 40);
dictionary [Device.Styles.SubtitleStyleKey] = style;
style = new Style (typeof(Label));
style.Setters.Add (Label.FontSizeProperty, 30);
dictionary [Device.Styles.CaptionStyleKey] = style;
style = new Style (typeof(Label));
style.Setters.Add (Label.FontSizeProperty, 20);
dictionary [Device.Styles.ListItemTextStyleKey] = style;
style = new Style (typeof(Label));
style.Setters.Add (Label.FontSizeProperty, 10);
dictionary [Device.Styles.ListItemDetailTextStyleKey] = style;
return dictionary;
}
}
public class MockApplication : Application
{
public MockApplication ()
{
}
}
internal class MockTicker : Ticker
{
bool _enabled;
protected override void EnableTimer()
{
_enabled = true;
while (_enabled)
{
SendSignals(16);
}
}
protected override void DisableTimer()
{
_enabled = false;
}
}
}
| |
//
// System.Net.ResponseStream
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 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;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Reactor.Net
{
// FIXME: Does this buffer the response until Close?
// Update: we send a single packet for the first non-chunked Write
// What happens when we set content-length to X and write X-1 bytes then close?
// what if we don't set content-length at all?
public class ResponseStream : Stream
{
private HttpListenerResponse response;
private bool ignore_errors;
private bool disposed;
private bool trailer_sent;
private Stream stream;
internal ResponseStream(Stream stream, HttpListenerResponse response, bool ignore_errors)
{
this.response = response;
this.ignore_errors = ignore_errors;
this.stream = stream;
}
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override long Length
{
get
{
throw new NotSupportedException();
}
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override void Close()
{
if (disposed == false)
{
disposed = true;
byte[] bytes = null;
MemoryStream ms = GetHeaders(true);
bool chunked = response.SendChunked;
if (ms != null)
{
long start = ms.Position;
if (chunked && !trailer_sent)
{
bytes = GetChunkSizeBytes(0, true);
ms.Position = ms.Length;
ms.Write(bytes, 0, bytes.Length);
}
InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start));
trailer_sent = true;
}
else if (chunked && !trailer_sent)
{
bytes = GetChunkSizeBytes(0, true);
InternalWrite(bytes, 0, bytes.Length);
trailer_sent = true;
}
response.Close();
}
}
MemoryStream GetHeaders(bool closing)
{
// SendHeaders works on shared headers
lock (response.headers_lock)
{
if (response.HeadersSent)
{
return null;
}
MemoryStream ms = new MemoryStream();
response.SendHeaders(closing, ms);
return ms;
}
}
public override void Flush()
{
}
static byte[] crlf = new byte[] { 13, 10 };
static byte[] GetChunkSizeBytes(int size, bool final)
{
string str = String.Format("{0:x}\r\n{1}", size, final ? "\r\n" : "");
return Encoding.ASCII.GetBytes(str);
}
internal void InternalWrite(byte[] buffer, int offset, int count)
{
if (ignore_errors)
{
try
{
stream.Write(buffer, offset, count);
}
catch { }
}
else
{
stream.Write(buffer, offset, count);
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
byte[] bytes = null;
MemoryStream ms = GetHeaders(false);
bool chunked = response.SendChunked;
if (ms != null)
{
long start = ms.Position; // After the possible preamble for the encoding
ms.Position = ms.Length;
if (chunked)
{
bytes = GetChunkSizeBytes(count, false);
ms.Write(bytes, 0, bytes.Length);
}
int new_count = Math.Min(count, 16384 - (int)ms.Position + (int)start);
ms.Write(buffer, offset, new_count);
count -= new_count;
offset += new_count;
InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start));
ms.SetLength(0);
ms.Capacity = 0; // 'dispose' the buffer in ms.
}
else if (chunked)
{
bytes = GetChunkSizeBytes(count, false);
InternalWrite(bytes, 0, bytes.Length);
}
if (count > 0)
{
InternalWrite(buffer, offset, count);
}
if (chunked)
{
InternalWrite(crlf, 0, 2);
}
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback cback, object state)
{
if (disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
byte[] bytes = null;
MemoryStream ms = GetHeaders(false);
bool chunked = response.SendChunked;
if (ms != null)
{
long start = ms.Position;
ms.Position = ms.Length;
if (chunked)
{
bytes = GetChunkSizeBytes(count, false);
ms.Write(bytes, 0, bytes.Length);
}
ms.Write(buffer, offset, count);
buffer = ms.GetBuffer();
offset = (int)start;
count = (int)(ms.Position - start);
}
else if (chunked)
{
bytes = GetChunkSizeBytes(count, false);
InternalWrite(bytes, 0, bytes.Length);
}
return stream.BeginWrite(buffer, offset, count, cback, state);
}
public override void EndWrite(IAsyncResult ares)
{
if (disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
if (ignore_errors)
{
try
{
stream.EndWrite(ares);
if (response.SendChunked)
{
stream.Write(crlf, 0, 2);
}
}
catch { }
}
else
{
stream.EndWrite(ares);
if (response.SendChunked)
{
stream.Write(crlf, 0, 2);
}
}
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback cback, object state)
{
throw new NotSupportedException();
}
public override int EndRead(IAsyncResult ares)
{
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Monitor.Query.Models;
namespace Azure.Monitor.Query
{
/// <summary>
/// The <see cref="LogsQueryClient"/> allows to query the Azure Monitor Logs service.
/// </summary>
public class LogsQueryClient
{
private static readonly Uri _defaultEndpoint = new Uri("https://api.loganalytics.io");
private static readonly TimeSpan _networkTimeoutOffset = TimeSpan.FromSeconds(15);
private readonly QueryRestClient _queryClient;
private readonly ClientDiagnostics _clientDiagnostics;
private readonly HttpPipeline _pipeline;
/// <summary>
/// Initializes a new instance of <see cref="LogsQueryClient"/>. Uses the default 'https://api.loganalytics.io' endpoint.
/// <example snippet="Snippet:CreateLogsClient">
/// <code language="csharp">
/// var client = new LogsQueryClient(new DefaultAzureCredential());
/// </code>
/// </example>
/// </summary>
/// <param name="credential">The <see cref="TokenCredential"/> instance to use for authentication.</param>
public LogsQueryClient(TokenCredential credential) : this(credential, null)
{
}
/// <summary>
/// Initializes a new instance of <see cref="LogsQueryClient"/>. Uses the default 'https://api.loganalytics.io' endpoint.
/// </summary>
/// <param name="credential">The <see cref="TokenCredential"/> instance to use for authentication.</param>
/// <param name="options">The <see cref="LogsQueryClientOptions"/> instance to use as client configuration.</param>
public LogsQueryClient(TokenCredential credential, LogsQueryClientOptions options) : this(_defaultEndpoint, credential, options)
{
}
/// <summary>
/// Initializes a new instance of <see cref="LogsQueryClient"/>.
/// </summary>
/// <param name="endpoint">The service endpoint to use.</param>
/// <param name="credential">The <see cref="TokenCredential"/> instance to use for authentication.</param>
public LogsQueryClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, null)
{
}
/// <summary>
/// Initializes a new instance of <see cref="LogsQueryClient"/>.
/// </summary>
/// <param name="endpoint">The service endpoint to use.</param>
/// <param name="credential">The <see cref="TokenCredential"/> instance to use for authentication.</param>
/// <param name="options">The <see cref="LogsQueryClientOptions"/> instance to use as client configuration.</param>
public LogsQueryClient(Uri endpoint, TokenCredential credential, LogsQueryClientOptions options)
{
Argument.AssertNotNull(credential, nameof(credential));
Argument.AssertNotNull(endpoint, nameof(endpoint));
Endpoint = endpoint;
options ??= new LogsQueryClientOptions();
var scope = $"{endpoint.AbsoluteUri}/.default";
endpoint = new Uri(endpoint, options.GetVersionString());
_clientDiagnostics = new ClientDiagnostics(options);
_pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, scope));
_queryClient = new QueryRestClient(_clientDiagnostics, _pipeline, endpoint);
}
/// <summary>
/// Initializes a new instance of <see cref="LogsQueryClient"/> for mocking.
/// </summary>
protected LogsQueryClient()
{
}
/// <summary>
/// Gets the endpoint used by the client.
/// </summary>
public Uri Endpoint { get; }
/// <summary>
/// Executes the logs query. Deserializes the result into a strongly typed model class or a primitive type if the query returns a single column.
///
/// Example of querying a model:
/// <example snippet="Snippet:QueryLogsAsModelCall">
/// <code language="csharp">
/// Response<IReadOnlyList<MyLogEntryModel>> response = await client.QueryWorkspaceAsync<MyLogEntryModel>(
/// workspaceId,
/// "AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count",
/// new QueryTimeRange(TimeSpan.FromDays(1)));
/// </code>
/// </example>
///
/// Example of querying a primitive:
/// <example snippet="Snippet:QueryLogsAsPrimitiveCall">
/// <code language="csharp">
/// Response<IReadOnlyList<string>> response = await client.QueryWorkspaceAsync<string>(
/// workspaceId,
/// "AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count | project ResourceGroup",
/// new QueryTimeRange(TimeSpan.FromDays(1)));
/// </code>
/// </example>
/// </summary>
/// <param name="workspaceId">The workspace id to include in the query (<c>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</c>).</param>
/// <param name="query">The Kusto query to execute.</param>
/// <param name="timeRange">The timespan over which to query data. Logs will be filtered to include entries produced starting at <c>Now - timeSpan</c>. </param>
/// <param name="options">The <see cref="LogsQueryOptions"/> to configure the query.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>Query results mapped to a type <typeparamref name="T"/>.</returns>
public virtual Response<IReadOnlyList<T>> QueryWorkspace<T>(string workspaceId, string query, QueryTimeRange timeRange, LogsQueryOptions options = null, CancellationToken cancellationToken = default)
{
Response<LogsQueryResult> response = QueryWorkspace(workspaceId, query, timeRange, options, cancellationToken);
return Response.FromValue(RowBinder.Shared.BindResults<T>(response.Value.AllTables), response.GetRawResponse());
}
/// <summary>
/// Executes the logs query. Deserializes the result into a strongly typed model class or a primitive type if the query returns a single column.
///
/// Example of querying a model:
/// <example snippet="Snippet:QueryLogsAsModelCall">
/// <code language="csharp">
/// Response<IReadOnlyList<MyLogEntryModel>> response = await client.QueryWorkspaceAsync<MyLogEntryModel>(
/// workspaceId,
/// "AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count",
/// new QueryTimeRange(TimeSpan.FromDays(1)));
/// </code>
/// </example>
///
/// Example of querying a primitive:
/// <example snippet="Snippet:QueryLogsAsPrimitiveCall">
/// <code language="csharp">
/// Response<IReadOnlyList<string>> response = await client.QueryWorkspaceAsync<string>(
/// workspaceId,
/// "AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count | project ResourceGroup",
/// new QueryTimeRange(TimeSpan.FromDays(1)));
/// </code>
/// </example>
/// </summary>
/// <param name="workspaceId">The workspace id to include in the query (<c>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</c>).</param>
/// <param name="query">The Kusto query to execute.</param>
/// <param name="timeRange">The timespan over which to query data. Logs will be filtered to include entries produced starting at <c>Now - timeSpan</c>. </param>
/// <param name="options">The <see cref="LogsQueryOptions"/> to configure the query.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>Query results mapped to a type <typeparamref name="T"/>.</returns>
public virtual async Task<Response<IReadOnlyList<T>>> QueryWorkspaceAsync<T>(string workspaceId, string query, QueryTimeRange timeRange, LogsQueryOptions options = null, CancellationToken cancellationToken = default)
{
Response<LogsQueryResult> response = await QueryWorkspaceAsync(workspaceId, query, timeRange, options, cancellationToken).ConfigureAwait(false);
return Response.FromValue(RowBinder.Shared.BindResults<T>(response.Value.AllTables), response.GetRawResponse());
}
/// <summary>
/// Executes the logs query.
/// </summary>
/// <param name="workspaceId">The workspace id to include in the query (<c>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</c>).</param>
/// <param name="query">The Kusto query to execute.</param>
/// <param name="timeRange">The timespan over which to query data. Logs will be filtered to include entries produced starting at <c>Now - timeSpan</c>. </param>
/// <param name="options">The <see cref="LogsQueryOptions"/> to configure the query.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>The <see cref="LogsQueryResult"/> containing the query results.</returns>
public virtual Response<LogsQueryResult> QueryWorkspace(string workspaceId, string query, QueryTimeRange timeRange, LogsQueryOptions options = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(LogsQueryClient)}.{nameof(QueryWorkspace)}");
scope.Start();
try
{
return ExecuteAsync(workspaceId, query, timeRange, options, false, cancellationToken).EnsureCompleted();
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Executes the logs query.
/// </summary>
/// <param name="workspaceId">The workspace id to include in the query (<c>xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx</c>).</param>
/// <param name="query">The Kusto query to execute.</param>
/// <param name="timeRange">The timespan over which to query data. Logs will be filtered to include entries produced starting at <c>Now - timeSpan</c>. </param>
/// <param name="options">The <see cref="LogsQueryOptions"/> to configure the query.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>The <see cref="LogsQueryResult"/> with the query results.</returns>
public virtual async Task<Response<LogsQueryResult>> QueryWorkspaceAsync(string workspaceId, string query, QueryTimeRange timeRange, LogsQueryOptions options = null, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(LogsQueryClient)}.{nameof(QueryWorkspace)}");
scope.Start();
try
{
return await ExecuteAsync(workspaceId, query, timeRange, options, true, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Submits the batch query. Use the <see cref="LogsBatchQuery"/> to compose a batch query.
/// <example snippet="Snippet:BatchQuery">
/// <code language="csharp">
/// string workspaceId = "<workspace_id>";
///
/// var client = new LogsQueryClient(new DefaultAzureCredential());
///
/// // Query TOP 10 resource groups by event count
/// // And total event count
/// var batch = new LogsBatchQuery();
///
/// string countQueryId = batch.AddWorkspaceQuery(
/// workspaceId,
/// "AzureActivity | count",
/// new QueryTimeRange(TimeSpan.FromDays(1)));
/// string topQueryId = batch.AddWorkspaceQuery(
/// workspaceId,
/// "AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count",
/// new QueryTimeRange(TimeSpan.FromDays(1)));
///
/// Response<LogsBatchQueryResultCollection> response = await client.QueryBatchAsync(batch);
///
/// var count = response.Value.GetResult<int>(countQueryId).Single();
/// var topEntries = response.Value.GetResult<MyLogEntryModel>(topQueryId);
///
/// Console.WriteLine($"AzureActivity has total {count} events");
/// foreach (var logEntryModel in topEntries)
/// {
/// Console.WriteLine($"{logEntryModel.ResourceGroup} had {logEntryModel.Count} events");
/// }
/// </code>
/// </example>
/// </summary>
/// <param name="batch">The batch of queries to send.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>The <see cref="LogsBatchQueryResultCollection"/> containing the query identifier that has to be passed into <see cref="LogsBatchQueryResultCollection.GetResult"/> to get the result.</returns>
public virtual Response<LogsBatchQueryResultCollection> QueryBatch(LogsBatchQuery batch, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(batch, nameof(batch));
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(LogsQueryClient)}.{nameof(QueryBatch)}");
scope.Start();
try
{
return ExecuteBatchAsync(batch, async: false, cancellationToken).EnsureCompleted();
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Submits the batch query. Use the <see cref="LogsBatchQuery"/> to compose a batch query.
/// <example snippet="Snippet:BatchQuery">
/// <code language="csharp">
/// string workspaceId = "<workspace_id>";
///
/// var client = new LogsQueryClient(new DefaultAzureCredential());
///
/// // Query TOP 10 resource groups by event count
/// // And total event count
/// var batch = new LogsBatchQuery();
///
/// string countQueryId = batch.AddWorkspaceQuery(
/// workspaceId,
/// "AzureActivity | count",
/// new QueryTimeRange(TimeSpan.FromDays(1)));
/// string topQueryId = batch.AddWorkspaceQuery(
/// workspaceId,
/// "AzureActivity | summarize Count = count() by ResourceGroup | top 10 by Count",
/// new QueryTimeRange(TimeSpan.FromDays(1)));
///
/// Response<LogsBatchQueryResultCollection> response = await client.QueryBatchAsync(batch);
///
/// var count = response.Value.GetResult<int>(countQueryId).Single();
/// var topEntries = response.Value.GetResult<MyLogEntryModel>(topQueryId);
///
/// Console.WriteLine($"AzureActivity has total {count} events");
/// foreach (var logEntryModel in topEntries)
/// {
/// Console.WriteLine($"{logEntryModel.ResourceGroup} had {logEntryModel.Count} events");
/// }
/// </code>
/// </example>
/// </summary>
/// <param name="batch">The batch of Kusto queries to send.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to use.</param>
/// <returns>The <see cref="LogsBatchQueryResultCollection"/> that allows retrieving query results.</returns>
public virtual async Task<Response<LogsBatchQueryResultCollection>> QueryBatchAsync(LogsBatchQuery batch, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(batch, nameof(batch));
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(LogsQueryClient)}.{nameof(QueryBatch)}");
scope.Start();
try
{
return await ExecuteBatchAsync(batch, async: true, cancellationToken).ConfigureAwait(false);
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Create a Kusto query from an interpolated string. The interpolated values will be quoted and escaped as necessary.
/// </summary>
/// <param name="query">An interpolated query string.</param>
/// <returns>A valid Kusto query.</returns>
public static string CreateQuery(FormattableString query)
{
if (query == null) { return null; }
string[] args = new string[query.ArgumentCount];
for (int i = 0; i < query.ArgumentCount; i++)
{
args[i] = query.GetArgument(i) switch
{
// Null
null => throw new ArgumentException(
$"Unable to convert argument {i} to a Kusto literal. " +
$"Unable to format an untyped null value. Please use typed-null expression " +
$"(bool(null), datetime(null), dynamic(null), guid(null), int(null), long(null), real(null), double(null), time(null))"),
// Boolean
true => "true",
false => "false",
// Numeric
sbyte x => $"int({x.ToString(CultureInfo.InvariantCulture)})",
byte x => $"int({x.ToString(CultureInfo.InvariantCulture)})",
short x => $"int({x.ToString(CultureInfo.InvariantCulture)})",
ushort x => $"int({x.ToString(CultureInfo.InvariantCulture)})",
int x => $"int({x.ToString(CultureInfo.InvariantCulture)})",
uint x => $"int({x.ToString(CultureInfo.InvariantCulture)})",
float x => $"real({x.ToString(CultureInfo.InvariantCulture)})",
double x => $"real({x.ToString(CultureInfo.InvariantCulture)})",
// Int64
long x => $"long({x.ToString(CultureInfo.InvariantCulture)})",
ulong x => $"long({x.ToString(CultureInfo.InvariantCulture)})",
decimal x => $"decimal({x.ToString(CultureInfo.InvariantCulture)})",
// Guid
Guid x => $"guid({x.ToString("D", CultureInfo.InvariantCulture)})",
// Dates as 8601 with a time zone
DateTimeOffset x => $"datetime({x.UtcDateTime.ToString("O", CultureInfo.InvariantCulture)})",
DateTime x => $"datetime({x.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture)})",
TimeSpan x => $"time({x.ToString("c", CultureInfo.InvariantCulture)})",
// Text
string x => EscapeStringValue(x),
char x => EscapeStringValue(x),
// Everything else
object x => throw new ArgumentException(
$"Unable to convert argument {i} from type {x.GetType()} to a Kusto literal.")
};
}
return string.Format(CultureInfo.InvariantCulture, query.Format, args);
}
private static string EscapeStringValue(string s)
{
StringBuilder escaped = new();
escaped.Append('"');
foreach (char c in s)
{
switch (c)
{
case '"':
escaped.Append("\\\"");
break;
case '\\':
escaped.Append("\\\\");
break;
case '\r':
escaped.Append("\\r");
break;
case '\n':
escaped.Append("\\n");
break;
case '\t':
escaped.Append("\\t");
break;
default:
escaped.Append(c);
break;
}
}
escaped.Append('"');
return escaped.ToString();
}
private static string EscapeStringValue(char s) =>
s switch
{
_ when s == '"' => "'\"'",
_ => $"\"{s}\""
};
internal static QueryBody CreateQueryBody(string query, QueryTimeRange timeRange, LogsQueryOptions options, out string prefer)
{
var queryBody = new QueryBody(query);
if (timeRange != QueryTimeRange.All)
{
queryBody.Timespan = timeRange.ToIsoString();
}
if (options != null)
{
queryBody.Workspaces = options.AdditionalWorkspaces;
}
prefer = null;
StringBuilder preferBuilder = null;
if (options?.ServerTimeout is TimeSpan timeout)
{
preferBuilder = new();
preferBuilder.Append("wait=");
preferBuilder.Append((int) timeout.TotalSeconds);
}
if (options?.IncludeStatistics == true)
{
if (preferBuilder == null)
{
preferBuilder = new();
}
else
{
preferBuilder.Append(',');
}
preferBuilder.Append("include-statistics=true");
}
if (options?.IncludeVisualization == true)
{
if (preferBuilder == null)
{
preferBuilder = new();
}
else
{
preferBuilder.Append(',');
}
preferBuilder.Append("include-render=true");
}
prefer = preferBuilder?.ToString();
return queryBody;
}
private async Task<Response<LogsBatchQueryResultCollection>> ExecuteBatchAsync(LogsBatchQuery batch, bool async, CancellationToken cancellationToken = default)
{
Response<LogsBatchQueryResultCollection> ConvertBatchResponse(BatchResponse response, Response rawResponse)
{
List<LogsBatchQueryResult> batchResponses = new List<LogsBatchQueryResult>();
foreach (var innerResponse in response.Responses)
{
var body = innerResponse.Body;
body.Status = innerResponse.Status switch
{
>= 400 => LogsQueryResultStatus.Failure,
_ when body.Error != null => LogsQueryResultStatus.PartialFailure,
_ => LogsQueryResultStatus.Success
};
body.Id = innerResponse.Id;
batchResponses.Add(body);
}
return Response.FromValue(
new LogsBatchQueryResultCollection(batchResponses, batch),
rawResponse);
}
using var message = _queryClient.CreateBatchRequest(new BatchRequest(batch.Requests));
TimeSpan? timeout = null;
foreach (var batchRequest in batch.Requests)
{
var requestTimeout = batchRequest?.Options?.ServerTimeout;
if (requestTimeout != null &&
(timeout == null || requestTimeout.Value > timeout.Value))
{
timeout = requestTimeout;
}
}
if (timeout != null)
{
message.NetworkTimeout = timeout.Value.Add(_networkTimeoutOffset);
message.Request.Headers.SetValue(HttpHeader.Names.Prefer, $"wait={(int) timeout.Value.TotalSeconds}");
}
if (async)
{
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
}
else
{
_pipeline.Send(message, cancellationToken);
}
switch (message.Response.Status)
{
case 200:
{
using var document = JsonDocument.Parse(message.Response.ContentStream);
BatchResponse value = BatchResponse.DeserializeBatchResponse(document.RootElement);
return ConvertBatchResponse(value, message.Response);
}
default:
{
if (async)
{
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
else
{
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
}
}
private async Task<Response<LogsQueryResult>> ExecuteAsync(string workspaceId, string query, QueryTimeRange timeRange, LogsQueryOptions options, bool async, CancellationToken cancellationToken = default)
{
if (workspaceId == null)
{
throw new ArgumentNullException(nameof(workspaceId));
}
QueryBody queryBody = CreateQueryBody(query, timeRange, options, out string prefer);
using var message = _queryClient.CreateExecuteRequest(workspaceId, queryBody, prefer);
if (options?.ServerTimeout != null)
{
// Offset the service timeout a bit to make sure we have time to receive the response.
message.NetworkTimeout = options.ServerTimeout.Value.Add(_networkTimeoutOffset);
}
if (async)
{
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
}
else
{
_pipeline.Send(message, cancellationToken);
}
switch (message.Response.Status)
{
case 200:
{
using var document = async ?
await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false) :
JsonDocument.Parse(message.Response.ContentStream, default);
LogsQueryResult value = LogsQueryResult.DeserializeLogsQueryResult(document.RootElement);
value.Status = value.Error == null ? LogsQueryResultStatus.Success : LogsQueryResultStatus.PartialFailure;
var responseError = value.Error;
if (responseError != null && options?.AllowPartialErrors != true)
{
throw value.CreateExceptionForErrorResponse(message.Response.Status);
}
return Response.FromValue(value, message.Response);
}
default:
{
if (async)
{
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
else
{
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
}
}
}
}
| |
using AnimationOrTween;
using System;
using System.Collections.Generic;
using UnityEngine;
[AddComponentMenu("NGUI/Internal/Active Animation")]
public class ActiveAnimation : MonoBehaviour
{
public static ActiveAnimation current;
public List<EventDelegate> onFinished = new List<EventDelegate>();
[HideInInspector]
public GameObject eventReceiver;
[HideInInspector]
public string callWhenFinished;
private Animation mAnim;
private Direction mLastDirection;
private Direction mDisableDirection;
private bool mNotify;
private Animator mAnimator;
private string mClip = string.Empty;
private float playbackTime
{
get
{
return Mathf.Clamp01(this.mAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime);
}
}
public bool isPlaying
{
get
{
if (!(this.mAnim == null))
{
foreach (AnimationState animationState in this.mAnim)
{
if (this.mAnim.IsPlaying(animationState.name))
{
if (this.mLastDirection == Direction.Forward)
{
if (animationState.time < animationState.length)
{
bool result = true;
return result;
}
}
else
{
if (this.mLastDirection != Direction.Reverse)
{
bool result = true;
return result;
}
if (animationState.time > 0f)
{
bool result = true;
return result;
}
}
}
}
return false;
}
if (this.mAnimator != null)
{
if (this.mLastDirection == Direction.Reverse)
{
if (this.playbackTime == 0f)
{
return false;
}
}
else if (this.playbackTime == 1f)
{
return false;
}
return true;
}
return false;
}
}
public void Reset()
{
if (this.mAnim != null)
{
foreach (AnimationState animationState in this.mAnim)
{
if (this.mLastDirection == Direction.Reverse)
{
animationState.time = animationState.length;
}
else if (this.mLastDirection == Direction.Forward)
{
animationState.time = 0f;
}
}
}
else if (this.mAnimator != null)
{
this.mAnimator.Play(this.mClip, 0, (this.mLastDirection != Direction.Reverse) ? 0f : 1f);
}
}
private void Start()
{
if (this.eventReceiver != null && EventDelegate.IsValid(this.onFinished))
{
this.eventReceiver = null;
this.callWhenFinished = null;
}
}
private void Update()
{
float deltaTime = RealTime.deltaTime;
if (deltaTime == 0f)
{
return;
}
if (this.mAnimator != null)
{
this.mAnimator.Update((this.mLastDirection != Direction.Reverse) ? deltaTime : (-deltaTime));
if (this.isPlaying)
{
return;
}
this.mAnimator.enabled = false;
base.enabled = false;
}
else
{
if (!(this.mAnim != null))
{
base.enabled = false;
return;
}
bool flag = false;
foreach (AnimationState animationState in this.mAnim)
{
if (this.mAnim.IsPlaying(animationState.name))
{
float num = animationState.speed * deltaTime;
animationState.time += num;
if (num < 0f)
{
if (animationState.time > 0f)
{
flag = true;
}
else
{
animationState.time = 0f;
}
}
else if (animationState.time < animationState.length)
{
flag = true;
}
else
{
animationState.time = animationState.length;
}
}
}
this.mAnim.Sample();
if (flag)
{
return;
}
base.enabled = false;
}
if (this.mNotify)
{
this.mNotify = false;
ActiveAnimation.current = this;
EventDelegate.Execute(this.onFinished);
if (this.eventReceiver != null && !string.IsNullOrEmpty(this.callWhenFinished))
{
this.eventReceiver.SendMessage(this.callWhenFinished, SendMessageOptions.DontRequireReceiver);
}
ActiveAnimation.current = null;
if (this.mDisableDirection != Direction.Toggle && this.mLastDirection == this.mDisableDirection)
{
NGUITools.SetActive(base.gameObject, false);
}
}
}
private void Play(string clipName, Direction playDirection)
{
if (playDirection == Direction.Toggle)
{
playDirection = ((this.mLastDirection == Direction.Forward) ? Direction.Reverse : Direction.Forward);
}
if (this.mAnim != null)
{
base.enabled = true;
this.mAnim.enabled = false;
bool flag = string.IsNullOrEmpty(clipName);
if (flag)
{
if (!this.mAnim.isPlaying)
{
this.mAnim.Play();
}
}
else if (!this.mAnim.IsPlaying(clipName))
{
this.mAnim.Play(clipName);
}
foreach (AnimationState animationState in this.mAnim)
{
if (string.IsNullOrEmpty(clipName) || animationState.name == clipName)
{
float num = Mathf.Abs(animationState.speed);
animationState.speed = num * (float)playDirection;
if (playDirection == Direction.Reverse && animationState.time == 0f)
{
animationState.time = animationState.length;
}
else if (playDirection == Direction.Forward && animationState.time == animationState.length)
{
animationState.time = 0f;
}
}
}
this.mLastDirection = playDirection;
this.mNotify = true;
this.mAnim.Sample();
}
else if (this.mAnimator != null)
{
if (base.enabled && this.isPlaying && this.mClip == clipName)
{
this.mLastDirection = playDirection;
return;
}
base.enabled = true;
this.mNotify = true;
this.mLastDirection = playDirection;
this.mClip = clipName;
this.mAnimator.Play(this.mClip, 0, (playDirection != Direction.Forward) ? 1f : 0f);
}
}
private void OnDestroy()
{
this.mAnim = null;
}
public static ActiveAnimation Play(Animation anim, string clipName, Direction playDirection, EnableCondition enableBeforePlay, DisableCondition disableCondition)
{
if (!NGUITools.GetActive(anim.gameObject))
{
if (enableBeforePlay != EnableCondition.EnableThenPlay)
{
return null;
}
NGUITools.SetActive(anim.gameObject, true);
UIPanel[] componentsInChildren = anim.gameObject.GetComponentsInChildren<UIPanel>();
int i = 0;
int num = componentsInChildren.Length;
while (i < num)
{
componentsInChildren[i].Refresh();
i++;
}
}
ActiveAnimation activeAnimation = anim.GetComponent<ActiveAnimation>();
if (activeAnimation == null)
{
activeAnimation = anim.gameObject.AddComponent<ActiveAnimation>();
}
activeAnimation.mAnim = anim;
activeAnimation.mDisableDirection = (Direction)disableCondition;
activeAnimation.onFinished.Clear();
activeAnimation.Play(clipName, playDirection);
return activeAnimation;
}
public static ActiveAnimation Play(Animation anim, string clipName, Direction playDirection)
{
return ActiveAnimation.Play(anim, clipName, playDirection, EnableCondition.DoNothing, DisableCondition.DoNotDisable);
}
public static ActiveAnimation Play(Animation anim, Direction playDirection)
{
return ActiveAnimation.Play(anim, null, playDirection, EnableCondition.DoNothing, DisableCondition.DoNotDisable);
}
public static ActiveAnimation Play(Animator anim, string clipName, Direction playDirection, EnableCondition enableBeforePlay, DisableCondition disableCondition)
{
if (!NGUITools.GetActive(anim.gameObject))
{
if (enableBeforePlay != EnableCondition.EnableThenPlay)
{
return null;
}
NGUITools.SetActive(anim.gameObject, true);
UIPanel[] componentsInChildren = anim.gameObject.GetComponentsInChildren<UIPanel>();
int i = 0;
int num = componentsInChildren.Length;
while (i < num)
{
componentsInChildren[i].Refresh();
i++;
}
}
ActiveAnimation activeAnimation = anim.GetComponent<ActiveAnimation>();
if (activeAnimation == null)
{
activeAnimation = anim.gameObject.AddComponent<ActiveAnimation>();
}
activeAnimation.mAnimator = anim;
activeAnimation.mDisableDirection = (Direction)disableCondition;
activeAnimation.onFinished.Clear();
activeAnimation.Play(clipName, playDirection);
return activeAnimation;
}
}
| |
//
// SelectionRatioDialog.cs
//
// Author:
// Stephane Delcroix <sdelcroix@src.gnome.org>
//
// Copyright (C) 2008 Novell, Inc.
// Copyright (C) 2008 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using Gtk;
using Mono.Unix;
using Hyena;
namespace FSpot.UI.Dialog {
public class SelectionRatioDialog : BuilderDialog
{
[Serializable]
public struct SelectionConstraint {
private string label;
public string Label {
get { return label; }
set { label = value; }
}
private double ratio;
public double XyRatio {
get { return ratio; }
set { ratio = value; }
}
public SelectionConstraint (string label, double ratio)
{
this.label = label;
this.ratio = ratio;
}
}
[GtkBeans.Builder.Object] Button close_button;
[GtkBeans.Builder.Object] Button add_button;
[GtkBeans.Builder.Object] Button delete_button;
[GtkBeans.Builder.Object] Button up_button;
[GtkBeans.Builder.Object] Button down_button;
[GtkBeans.Builder.Object] TreeView content_treeview;
private ListStore constraints_store;
public SelectionRatioDialog () : base ("SelectionRatioDialog.ui", "customratio_dialog")
{
close_button.Clicked += delegate (object o, EventArgs e) {SavePrefs (); this.Destroy (); };
add_button.Clicked += delegate (object o, EventArgs e) {constraints_store.AppendValues (Catalog.GetString("New Selection"), 1.0);};
delete_button.Clicked += DeleteSelectedRows;
up_button.Clicked += MoveUp;
down_button.Clicked += MoveDown;
CellRendererText text_renderer = new CellRendererText ();
text_renderer.Editable = true;
text_renderer.Edited += HandleLabelEdited;
content_treeview.AppendColumn (Catalog.GetString ("Label"), text_renderer, "text", 0);
text_renderer = new CellRendererText ();
text_renderer.Editable = true;
text_renderer.Edited += HandleRatioEdited;
content_treeview.AppendColumn (Catalog.GetString ("Ratio"), text_renderer, "text", 1);
LoadPreference (Preferences.CUSTOM_CROP_RATIOS);
Preferences.SettingChanged += OnPreferencesChanged;
}
private void Populate ()
{
constraints_store = new ListStore (typeof (string), typeof (double));
content_treeview.Model = constraints_store;
XmlSerializer serializer = new XmlSerializer (typeof(SelectionConstraint));
string [] vals = Preferences.Get<string []> (Preferences.CUSTOM_CROP_RATIOS);
if (vals != null)
foreach (string xml in vals) {
SelectionConstraint constraint = (SelectionConstraint)serializer.Deserialize (new StringReader (xml));
constraints_store.AppendValues (constraint.Label, constraint.XyRatio);
}
}
private void OnPreferencesChanged (object sender, NotifyEventArgs args)
{
LoadPreference (args.Key);
}
private void LoadPreference (String key)
{
switch (key) {
case Preferences.CUSTOM_CROP_RATIOS:
Populate ();
break;
}
}
private void SavePrefs ()
{
List<string> prefs = new List<string> ();
XmlSerializer serializer = new XmlSerializer (typeof (SelectionConstraint));
foreach (object[] row in constraints_store) {
StringWriter sw = new StringWriter ();
serializer.Serialize (sw, new SelectionConstraint ((string)row[0], (double)row[1]));
sw.Close ();
prefs.Add (sw.ToString ());
}
#if !GCONF_SHARP_2_18
if (prefs.Count != 0)
#endif
Preferences.Set (Preferences.CUSTOM_CROP_RATIOS, prefs.ToArray());
#if !GCONF_SHARP_2_18
else
Preferences.Set (Preferences.CUSTOM_CROP_RATIOS, -1);
#endif
}
public void HandleLabelEdited (object sender, EditedArgs args)
{
args.RetVal = false;
TreeIter iter;
if (!constraints_store.GetIterFromString (out iter, args.Path))
return;
using (GLib.Value val = new GLib.Value (args.NewText))
constraints_store.SetValue (iter, 0, val);
args.RetVal = true;
}
public void HandleRatioEdited (object sender, EditedArgs args)
{
args.RetVal = false;
TreeIter iter;
if (!constraints_store.GetIterFromString (out iter, args.Path))
return;
double ratio;
try {
ratio = ParseRatio (args.NewText);
} catch (FormatException fe) {
Log.Exception (fe);
return;
}
if (ratio < 1.0)
ratio = 1.0 / ratio;
using (GLib.Value val = new GLib.Value (ratio))
constraints_store.SetValue (iter, 1, val);
args.RetVal = true;
}
private double ParseRatio (string text)
{
try {
return Convert.ToDouble (text);
} catch (FormatException) {
char [] separators = {'/', ':'};
foreach (char c in separators) {
if (text.IndexOf (c) != -1) {
double ratio = Convert.ToDouble (text.Substring (0, text.IndexOf (c)));
ratio /= Convert.ToDouble (text.Substring (text.IndexOf (c) + 1));
return ratio;
}
}
throw new FormatException (String.Format ("unable to parse {0}", text));
}
}
private void DeleteSelectedRows (object o, EventArgs e)
{
TreeIter iter;
TreeModel model;
if (content_treeview.Selection.GetSelected (out model, out iter))
(model as ListStore).Remove (ref iter);
}
private void MoveUp (object o, EventArgs e)
{
TreeIter selected;
TreeModel model;
if (content_treeview.Selection.GetSelected (out model, out selected)) {
//no IterPrev :(
TreeIter prev;
TreePath path = model.GetPath (selected);
if (path.Prev ())
if (model.GetIter (out prev, path))
(model as ListStore).Swap (prev, selected);
}
}
private void MoveDown (object o, EventArgs e)
{
TreeIter current;
TreeModel model;
if (content_treeview.Selection.GetSelected (out model, out current)) {
TreeIter next = current;
if ((model as ListStore).IterNext (ref next))
(model as ListStore).Swap (current, next);
}
}
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Math.Raw;
namespace Org.BouncyCastle.Math.EC.Custom.Sec
{
internal class SecP160R2Point
: AbstractFpPoint
{
/**
* Create a point which encodes with point compression.
*
* @param curve
* the curve to use
* @param x
* affine x co-ordinate
* @param y
* affine y co-ordinate
*
* @deprecated Use ECCurve.CreatePoint to construct points
*/
public SecP160R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y)
: this(curve, x, y, false)
{
}
/**
* Create a point that encodes with or without point compresion.
*
* @param curve
* the curve to use
* @param x
* affine x co-ordinate
* @param y
* affine y co-ordinate
* @param withCompression
* if true encode with point compression
*
* @deprecated per-point compression property will be removed, refer
* {@link #getEncoded(bool)}
*/
public SecP160R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
: base(curve, x, y, withCompression)
{
if ((x == null) != (y == null))
throw new ArgumentException("Exactly one of the field elements is null");
}
internal SecP160R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
: base(curve, x, y, zs, withCompression)
{
}
protected override ECPoint Detach()
{
return new SecP160R2Point(null, AffineXCoord, AffineYCoord);
}
public override ECPoint Add(ECPoint b)
{
if (this.IsInfinity)
return b;
if (b.IsInfinity)
return this;
if (this == b)
return Twice();
ECCurve curve = this.Curve;
SecP160R2FieldElement X1 = (SecP160R2FieldElement)this.RawXCoord, Y1 = (SecP160R2FieldElement)this.RawYCoord;
SecP160R2FieldElement X2 = (SecP160R2FieldElement)b.RawXCoord, Y2 = (SecP160R2FieldElement)b.RawYCoord;
SecP160R2FieldElement Z1 = (SecP160R2FieldElement)this.RawZCoords[0];
SecP160R2FieldElement Z2 = (SecP160R2FieldElement)b.RawZCoords[0];
uint c;
uint[] tt1 = Nat160.CreateExt();
uint[] t2 = Nat160.Create();
uint[] t3 = Nat160.Create();
uint[] t4 = Nat160.Create();
bool Z1IsOne = Z1.IsOne;
uint[] U2, S2;
if (Z1IsOne)
{
U2 = X2.x;
S2 = Y2.x;
}
else
{
S2 = t3;
SecP160R2Field.Square(Z1.x, S2);
U2 = t2;
SecP160R2Field.Multiply(S2, X2.x, U2);
SecP160R2Field.Multiply(S2, Z1.x, S2);
SecP160R2Field.Multiply(S2, Y2.x, S2);
}
bool Z2IsOne = Z2.IsOne;
uint[] U1, S1;
if (Z2IsOne)
{
U1 = X1.x;
S1 = Y1.x;
}
else
{
S1 = t4;
SecP160R2Field.Square(Z2.x, S1);
U1 = tt1;
SecP160R2Field.Multiply(S1, X1.x, U1);
SecP160R2Field.Multiply(S1, Z2.x, S1);
SecP160R2Field.Multiply(S1, Y1.x, S1);
}
uint[] H = Nat160.Create();
SecP160R2Field.Subtract(U1, U2, H);
uint[] R = t2;
SecP160R2Field.Subtract(S1, S2, R);
// Check if b == this or b == -this
if (Nat160.IsZero(H))
{
if (Nat160.IsZero(R))
{
// this == b, i.e. this must be doubled
return this.Twice();
}
// this == -b, i.e. the result is the point at infinity
return curve.Infinity;
}
uint[] HSquared = t3;
SecP160R2Field.Square(H, HSquared);
uint[] G = Nat160.Create();
SecP160R2Field.Multiply(HSquared, H, G);
uint[] V = t3;
SecP160R2Field.Multiply(HSquared, U1, V);
SecP160R2Field.Negate(G, G);
Nat160.Mul(S1, G, tt1);
c = Nat160.AddBothTo(V, V, G);
SecP160R2Field.Reduce32(c, G);
SecP160R2FieldElement X3 = new SecP160R2FieldElement(t4);
SecP160R2Field.Square(R, X3.x);
SecP160R2Field.Subtract(X3.x, G, X3.x);
SecP160R2FieldElement Y3 = new SecP160R2FieldElement(G);
SecP160R2Field.Subtract(V, X3.x, Y3.x);
SecP160R2Field.MultiplyAddToExt(Y3.x, R, tt1);
SecP160R2Field.Reduce(tt1, Y3.x);
SecP160R2FieldElement Z3 = new SecP160R2FieldElement(H);
if (!Z1IsOne)
{
SecP160R2Field.Multiply(Z3.x, Z1.x, Z3.x);
}
if (!Z2IsOne)
{
SecP160R2Field.Multiply(Z3.x, Z2.x, Z3.x);
}
ECFieldElement[] zs = new ECFieldElement[]{ Z3 };
return new SecP160R2Point(curve, X3, Y3, zs, IsCompressed);
}
public override ECPoint Twice()
{
if (this.IsInfinity)
return this;
ECCurve curve = this.Curve;
SecP160R2FieldElement Y1 = (SecP160R2FieldElement)this.RawYCoord;
if (Y1.IsZero)
return curve.Infinity;
SecP160R2FieldElement X1 = (SecP160R2FieldElement)this.RawXCoord, Z1 = (SecP160R2FieldElement)this.RawZCoords[0];
uint c;
uint[] t1 = Nat160.Create();
uint[] t2 = Nat160.Create();
uint[] Y1Squared = Nat160.Create();
SecP160R2Field.Square(Y1.x, Y1Squared);
uint[] T = Nat160.Create();
SecP160R2Field.Square(Y1Squared, T);
bool Z1IsOne = Z1.IsOne;
uint[] Z1Squared = Z1.x;
if (!Z1IsOne)
{
Z1Squared = t2;
SecP160R2Field.Square(Z1.x, Z1Squared);
}
SecP160R2Field.Subtract(X1.x, Z1Squared, t1);
uint[] M = t2;
SecP160R2Field.Add(X1.x, Z1Squared, M);
SecP160R2Field.Multiply(M, t1, M);
c = Nat160.AddBothTo(M, M, M);
SecP160R2Field.Reduce32(c, M);
uint[] S = Y1Squared;
SecP160R2Field.Multiply(Y1Squared, X1.x, S);
c = Nat.ShiftUpBits(5, S, 2, 0);
SecP160R2Field.Reduce32(c, S);
c = Nat.ShiftUpBits(5, T, 3, 0, t1);
SecP160R2Field.Reduce32(c, t1);
SecP160R2FieldElement X3 = new SecP160R2FieldElement(T);
SecP160R2Field.Square(M, X3.x);
SecP160R2Field.Subtract(X3.x, S, X3.x);
SecP160R2Field.Subtract(X3.x, S, X3.x);
SecP160R2FieldElement Y3 = new SecP160R2FieldElement(S);
SecP160R2Field.Subtract(S, X3.x, Y3.x);
SecP160R2Field.Multiply(Y3.x, M, Y3.x);
SecP160R2Field.Subtract(Y3.x, t1, Y3.x);
SecP160R2FieldElement Z3 = new SecP160R2FieldElement(M);
SecP160R2Field.Twice(Y1.x, Z3.x);
if (!Z1IsOne)
{
SecP160R2Field.Multiply(Z3.x, Z1.x, Z3.x);
}
return new SecP160R2Point(curve, X3, Y3, new ECFieldElement[]{ Z3 }, IsCompressed);
}
public override ECPoint TwicePlus(ECPoint b)
{
if (this == b)
return ThreeTimes();
if (this.IsInfinity)
return b;
if (b.IsInfinity)
return Twice();
ECFieldElement Y1 = this.RawYCoord;
if (Y1.IsZero)
return b;
return Twice().Add(b);
}
public override ECPoint ThreeTimes()
{
if (this.IsInfinity || this.RawYCoord.IsZero)
return this;
// NOTE: Be careful about recursions between TwicePlus and ThreeTimes
return Twice().Add(this);
}
public override ECPoint Negate()
{
if (IsInfinity)
return this;
return new SecP160R2Point(Curve, this.RawXCoord, this.RawYCoord.Negate(), this.RawZCoords, IsCompressed);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using WhatsAppApi;
using WhatsAppApi.Account;
using WhatsAppApi.Helper;
using WhatsAppApi.Parser;
using WhatsAppApi.Response;
using WhatsAppPw;
namespace WhatsTest
{
internal class Program
{
private static WhatsApp _WhatsAppApi = null;
private static void Main(string[] args)
{
//Turkish Encoding
System.Console.OutputEncoding = Encoding.GetEncoding(857);
System.Console.InputEncoding = Encoding.GetEncoding(857);
//UTF-8 Encoding
//System.Console.OutputEncoding = Encoding.UTF8;
//System.Console.InputEncoding = Encoding.UTF8;
string _Nickname = "";
string _Sender = ""; //Mobile Number with Country Code (but without + or 00)
string _Password = ""; //v2 password
string _Target = ""; // Mobile Number to Send the Message to
_WhatsAppApi = new WhatsApp(_Sender, _Password, _Nickname, true);
//Event Bindings
_WhatsAppApi.OnLoginSuccess += OnLoginSuccess;
_WhatsAppApi.OnLoginFailed += OnLoginFailed;
_WhatsAppApi.OnGetMessage += OnGetMessage;
_WhatsAppApi.OnGetMessageReadedClient += OnGetMessageReadedClient;
_WhatsAppApi.OnGetMessageReceivedClient += OnGetMessageReceivedClient;
_WhatsAppApi.OnGetMessageReceivedServer += OnGetMessageReceivedServer;
_WhatsAppApi.OnNotificationPicture += OnNotificationPicture;
_WhatsAppApi.OnGetPresence += OnGetPresence;
_WhatsAppApi.OnGetGroupParticipants += OnGetGroupParticipants;
_WhatsAppApi.OnGetLastSeen += OnGetLastSeen;
_WhatsAppApi.OnGetTyping += OnGetTyping;
_WhatsAppApi.OnGetPaused += OnGetPaused;
_WhatsAppApi.OnGetMessageImage += OnGetMessageImage;
_WhatsAppApi.OnGetMessageAudio += OnGetMessageAudio;
_WhatsAppApi.OnGetMessageVideo += OnGetMessageVideo;
_WhatsAppApi.OnGetMessageLocation += OnGetMessageLocation;
_WhatsAppApi.OnGetMessageVcard += OnGetMessageVcard;
_WhatsAppApi.OnGetPhoto += OnGetPhoto;
_WhatsAppApi.OnGetPhotoPreview += OnGetPhotoPreview;
_WhatsAppApi.OnGetGroups += OnGetGroups;
_WhatsAppApi.OnGetSyncResult += OnGetSyncResult;
_WhatsAppApi.OnGetStatus += OnGetStatus;
_WhatsAppApi.OnGetPrivacySettings += OnGetPrivacySettings;
_WhatsAppApi.OnGetBroadcastLists += OnGetBroadcastLists;
/*Debug Code*/
DebugAdapter.Instance.OnPrintDebug += Instance_OnPrintDebug;
_WhatsAppApi.SendGetServerProperties();
// Error Notification ErrorAxolotl
_WhatsAppApi.OnErrorAxolotl += OnErrorAxolotl;
_WhatsAppApi.Connect();
string datFile = GetDatFileName(_Sender);
byte[] nextChallenge = null;
if (File.Exists(datFile))
{
try
{
String foo = File.ReadAllText(datFile);
nextChallenge = Convert.FromBase64String(foo);
}
catch (Exception)
{
};
}
_WhatsAppApi.Login(nextChallenge);
ProcessChat(_WhatsAppApi, _Target);
Console.ReadKey();
}
private static void OnGetBroadcastLists(string phoneNumber, List<WaBroadcast> broadcastLists)
{
foreach (WaBroadcast broadcast in broadcastLists)
{
Console.WriteLine("Broadcast Lists");
Console.WriteLine("Name : " + broadcast.Name);
foreach (string recipient in broadcast.Recipients)
{
Console.WriteLine("Recipient : " + recipient);
}
}
}
private static void OnGetMessageReadedClient(string from, string id)
{
Console.WriteLine("Message {0} to {1} read by client", id, from);
}
private static void Instance_OnPrintDebug(object value)
{
Console.WriteLine("Debug Message : " + value);
}
private static void OnGetPrivacySettings(Dictionary<ApiBase.VisibilityCategory, ApiBase.VisibilitySetting> settings)
{
if (settings != null)
{
foreach (KeyValuePair<ApiBase.VisibilityCategory, ApiBase.VisibilitySetting> visibilitySetting in settings)
{
Console.WriteLine("Visibility Category : " + visibilitySetting.Key);
Console.WriteLine("Visibility Setting : " + visibilitySetting.Value);
}
}
}
private static void OnGetStatus(string from, string type, string name, string status)
{
Console.WriteLine(String.Format("Got Status From {0}: {1}", from, status));
}
private static string GetDatFileName(string pn)
{
string filename = string.Format("{0}.next.dat", pn);
return Path.Combine(Directory.GetCurrentDirectory(), filename);
}
private static void OnGetSyncResult(int index, string sid, Dictionary<string, string> existingUsers, string[] failedNumbers)
{
Console.WriteLine("Sync result for {0}:", sid);
foreach (KeyValuePair<string, string> item in existingUsers)
{
Console.WriteLine("Existing: {0} (username {1})", item.Key, item.Value);
}
foreach (string item in failedNumbers)
{
Console.WriteLine("Non-Existing: {0}", item);
}
}
private static void OnGetGroups(WaGroupInfo[] groups)
{
Console.WriteLine("Got groups:");
foreach (WaGroupInfo info in groups)
{
Console.WriteLine("\t{0} {1}", info.subject, info.id);
}
}
private static void OnGetPhotoPreview(string from, string id, byte[] data)
{
Console.WriteLine("Got preview photo for {0}", from);
File.WriteAllBytes(string.Format("preview_{0}.jpg", from), data);
}
private static void OnGetPhoto(string from, string id, byte[] data)
{
Console.WriteLine("Got full photo for {0}", from);
File.WriteAllBytes(string.Format("{0}.jpg", from), data);
}
private static void OnGetMessageVcard(ProtocolTreeNode vcardNode, string from, string id, string name, byte[] data)
{
Console.WriteLine("Got vcard \"{0}\" from {1}", name, from);
File.WriteAllBytes(string.Format("{0}.vcf", name), data);
}
private static void OnGetMessageLocation(ProtocolTreeNode locationNode, string from, string id, double lon, double lat, string url, string name, byte[] preview, string User)
{
Console.WriteLine("Got location from {0} ({1}, {2})", from, lat, lon);
if (!string.IsNullOrEmpty(name))
{
Console.WriteLine("\t{0}", name);
}
File.WriteAllBytes(string.Format("{0}{1}.jpg", lat, lon), preview);
}
private static void OnGetMessageVideo(ProtocolTreeNode mediaNode, string from, string id, string fileName, int fileSize, string url, byte[] preview, string name)
{
Console.WriteLine("Got video from {0}", from, fileName);
OnGetMedia(fileName, url, preview);
}
private static void OnGetMessageAudio(ProtocolTreeNode mediaNode, string from, string id, string fileName, int fileSize, string url, byte[] preview, string name)
{
Console.WriteLine("Got audio from {0}", from, fileName);
OnGetMedia(fileName, url, preview);
}
private static void OnGetMessageImage(ProtocolTreeNode mediaNode, string from, string id, string fileName, int size, string url, byte[] preview, string name)
{
Console.WriteLine("Got image from {0}", from, fileName);
OnGetMedia(fileName, url, preview);
}
private static void OnGetMedia(string file, string url, byte[] data)
{
File.WriteAllBytes(string.Format("Preview_{0}.jpg", file), data);
using (WebClient wc = new WebClient())
{
wc.DownloadFileAsync(new Uri(url), file, null);
}
}
private static void OnGetPaused(string from)
{
Console.WriteLine("{0} stopped typing", from);
}
private static void OnGetTyping(string from)
{
Console.WriteLine("{0} is typing...", from);
}
private static void OnGetLastSeen(string from, DateTime lastSeen)
{
Console.WriteLine("{0} last seen on {1}", from, lastSeen.ToString(CultureInfo.InvariantCulture));
}
private static void OnGetMessageReceivedServer(string from, string id)
{
Console.WriteLine("Message {0} to {1} received by server", id, from);
}
private static void OnGetMessageReceivedClient(string from, string id)
{
Console.WriteLine("Message {0} to {1} received by client", id, from);
}
private static void OnGetGroupParticipants(string gjid, string[] jids)
{
Console.WriteLine("Got participants from {0}:", gjid);
foreach (string jid in jids)
{
Console.WriteLine("\t{0}", jid);
}
}
private static void OnGetPresence(string from, string type)
{
Console.WriteLine("Presence from {0}: {1}", from, type);
}
private static void OnNotificationPicture(string type, string jid, string id)
{
throw new NotImplementedException();
}
private static void OnGetMessage(ProtocolTreeNode node, string from, string id, string name, string message, bool receipt_sent)
{
Console.WriteLine("Message From {0} {1}: {2}", name, from, message);
}
private static void OnLoginFailed(string data)
{
Console.WriteLine("Login failed. Reason: {0}", data);
}
private static void OnLoginSuccess(string phoneNumber, byte[] data)
{
Console.WriteLine("Login success. Next password:");
string sdata = Convert.ToBase64String(data);
Console.WriteLine(sdata);
try
{
File.WriteAllText(GetDatFileName(phoneNumber), sdata);
}
catch (Exception)
{
}
}
private static void ProcessChat(WhatsApp _WhatsAppApi, string _Dest)
{
Thread thRecv = new Thread(t =>
{
try
{
while (_WhatsAppApi != null)
{
_WhatsAppApi.PollMessages();
Thread.Sleep(100);
continue;
}
}
catch (ThreadAbortException)
{
}
})
{
IsBackground = true
};
thRecv.Start();
WhatsUserManager usrMan = new WhatsUserManager();
WhatsUser tmpUser = usrMan.CreateUser(_Dest, "User");
while (true)
{
String line = Console.ReadLine();
if (String.IsNullOrEmpty(line))
continue;
string command = line.Trim();
switch (command)
{
case "/query":
Console.WriteLine("[] Interactive conversation with {0}:", tmpUser);
break;
case "/accountinfo":
Console.WriteLine("[] Account Info: {0}", _WhatsAppApi.GetAccountInfo().ToString());
break;
case "/lastseen":
Console.WriteLine("[] Request last seen {0}", tmpUser);
_WhatsAppApi.SendQueryLastOnline(tmpUser.GetFullJid());
break;
case "/exit":
_WhatsAppApi = null;
thRecv.Abort();
return;
case "/start":
_WhatsAppApi.SendComposing(tmpUser.GetFullJid());
break;
case "/pause":
_WhatsAppApi.SendPaused(tmpUser.GetFullJid());
break;
default:
Console.WriteLine("[] Send message to {0}: {1}", tmpUser, line);
_WhatsAppApi.SendMessage(tmpUser.GetFullJid(), line);
break;
}
}
}
/// <summary>
/// Recieve All Error Messgaes From the Axolotl Orocess to Record
/// </summary>
/// <param name="ErrorMessage"></param>
private static void OnErrorAxolotl(string ErrorMessage)
{
}
}
}
| |
// 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;
using System.Collections.Generic;
using Xunit;
using SortedList_SortedListUtils;
namespace SortedListAdd
{
public class Driver<K, V> where K : IComparableValue
{
private Test m_test;
public Driver(Test test)
{
m_test = test;
}
public void BasicAdd(K[] keys, V[] values)
{
SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>());
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
m_test.Eval(tbl.Count == keys.Length);
for (int i = 0; i < keys.Length; i++)
{
V val = tbl[keys[i]];
m_test.Eval(((null == (object)val) && (null == (object)values[i])) || (val.Equals(values[i])));
}
}
public void AddSameKey //SameValue - Different Value should not matter
(K[] keys, V[] values, int index, int repeat)
{
SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>());
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
m_test.Eval(tbl.Count == keys.Length);
for (int i = 0; i < repeat; i++)
{
try
{
tbl.Add(keys[index], values[index]);
m_test.Eval(false);
}
catch (ArgumentException)
{
m_test.Eval(true);
}
}
m_test.Eval(tbl.Count == keys.Length);
}
public void AddRemoveKeyValPair(K[] keys, V[] values, int index, int repeat)
{
SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>());
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
m_test.Eval(tbl.Count == keys.Length);
for (int i = 0; i < repeat; i++)
{
V val;
m_test.Eval(tbl.Remove(keys[index]));
try
{
val = tbl[keys[index]];
m_test.Eval(false);
}
catch (KeyNotFoundException)
{
m_test.Eval(true);
}
tbl.Add(keys[index], values[index]);
val = tbl[keys[index]];
m_test.Eval(((null == (object)val) && (null == (object)values[index])) || (val.Equals(values[index])));
}
m_test.Eval(tbl.Count == keys.Length);
}
public void AddValidations(K[] keys, V[] values, K key, V value)
{
SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>());
for (int i = 0; i < keys.Length; i++)
{
tbl.Add(keys[i], values[i]);
}
if (!(key is System.ValueType))
{
try
{
tbl.Add(key, value);
m_test.Eval(false);
}
catch (ArgumentException)
{
m_test.Eval(true);
}
}
}
public void NonGenericIDictionaryBasicAdd(K[] keys, V[] values)
{
SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>());
IDictionary _idic = tbl;
for (int i = 0; i < keys.Length; i++)
{
_idic.Add(keys[i], values[i]);
}
m_test.Eval(tbl.Count == keys.Length);
for (int i = 0; i < keys.Length; i++)
{
V val = tbl[keys[i]];
m_test.Eval(((null == (object)val) && (null == (object)values[i])) || (val.Equals(values[i])));
}
}
public void NonGenericIDictionaryAddSameKey //SameValue - Different Value should not matter
(K[] keys, V[] values, int index, int repeat)
{
SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>());
IDictionary _idic = tbl;
for (int i = 0; i < keys.Length; i++)
{
_idic.Add(keys[i], values[i]);
}
m_test.Eval(tbl.Count == keys.Length);
for (int i = 0; i < repeat; i++)
{
try
{
_idic.Add(keys[index], values[index]);
m_test.Eval(false);
}
catch (ArgumentException)
{
m_test.Eval(true);
}
}
m_test.Eval(tbl.Count == keys.Length);
}
public void NonGenericIDictionaryAddRemoveKeyValPair(K[] keys, V[] values, int index, int repeat)
{
SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>());
IDictionary _idic = tbl;
for (int i = 0; i < keys.Length; i++)
{
_idic.Add(keys[i], values[i]);
}
m_test.Eval(tbl.Count == keys.Length);
for (int i = 0; i < repeat; i++)
{
V val;
m_test.Eval(tbl.Remove(keys[index]));
try
{
val = tbl[keys[index]];
m_test.Eval(false);
}
catch (KeyNotFoundException)
{
m_test.Eval(true);
}
_idic.Add(keys[index], values[index]);
val = tbl[keys[index]];
m_test.Eval(((null == (object)val) && (null == (object)values[index])) || (val.Equals(values[index])));
}
m_test.Eval(tbl.Count == keys.Length);
}
public void NonGenericIDictionaryAddValidations(K[] keys, V[] values, K key, V value)
{
SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>());
IDictionary _idic = tbl;
for (int i = 0; i < keys.Length; i++)
{
_idic.Add(keys[i], values[i]);
}
//
//try null key
//
try
{
_idic.Add(null, value);
m_test.Eval(false);
}
catch (ArgumentNullException)
{
m_test.Eval(true);
}
try
{
_idic.Add(new Random(-55), value);
m_test.Eval(false);
}
catch (ArgumentException)
{
m_test.Eval(true);
}
try
{
_idic.Add(key, new Random(-55));
m_test.Eval(false);
}
catch (ArgumentException)
{
m_test.Eval(true);
}
}
}
public class Add
{
[Fact]
public static void MainAdd()
{
Test test = new Test();
Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(test);
RefX1<int>[] intArr = new RefX1<int>[100];
for (int i = 0; i < 100; i++)
{
intArr[i] = new RefX1<int>(i);
}
Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(test);
ValX1<string>[] stringArr = new ValX1<string>[100];
for (int i = 0; i < 100; i++)
{
stringArr[i] = new ValX1<string>("SomeTestString" + i.ToString());
}
//Ref<val>,Val<Ref>
IntDriver.BasicAdd(intArr, stringArr);
IntDriver.AddSameKey(intArr, stringArr, 0, 2);
IntDriver.AddSameKey(intArr, stringArr, 99, 3);
IntDriver.AddSameKey(intArr, stringArr, 50, 4);
IntDriver.AddSameKey(intArr, stringArr, 1, 5);
IntDriver.AddSameKey(intArr, stringArr, 98, 6);
IntDriver.AddRemoveKeyValPair(intArr, stringArr, 0, 2);
IntDriver.AddRemoveKeyValPair(intArr, stringArr, 99, 3);
IntDriver.AddRemoveKeyValPair(intArr, stringArr, 50, 4);
IntDriver.AddRemoveKeyValPair(intArr, stringArr, 1, 5);
IntDriver.AddRemoveKeyValPair(intArr, stringArr, 98, 6);
IntDriver.AddValidations(intArr, stringArr, null, stringArr[0]);
IntDriver.AddValidations(new RefX1<int>[] { }, new ValX1<string>[] { }, null, stringArr[0]);
IntDriver.NonGenericIDictionaryBasicAdd(intArr, stringArr);
IntDriver.NonGenericIDictionaryAddSameKey(intArr, stringArr, 0, 2);
IntDriver.NonGenericIDictionaryAddSameKey(intArr, stringArr, 99, 3);
IntDriver.NonGenericIDictionaryAddSameKey(intArr, stringArr, 50, 4);
IntDriver.NonGenericIDictionaryAddSameKey(intArr, stringArr, 1, 5);
IntDriver.NonGenericIDictionaryAddSameKey(intArr, stringArr, 98, 6);
IntDriver.NonGenericIDictionaryAddRemoveKeyValPair(intArr, stringArr, 0, 2);
IntDriver.NonGenericIDictionaryAddRemoveKeyValPair(intArr, stringArr, 99, 3);
IntDriver.NonGenericIDictionaryAddRemoveKeyValPair(intArr, stringArr, 50, 4);
IntDriver.NonGenericIDictionaryAddRemoveKeyValPair(intArr, stringArr, 1, 5);
IntDriver.NonGenericIDictionaryAddRemoveKeyValPair(intArr, stringArr, 98, 6);
IntDriver.NonGenericIDictionaryAddValidations(intArr, stringArr, null, stringArr[0]);
IntDriver.NonGenericIDictionaryAddValidations(new RefX1<int>[] { }, new ValX1<string>[] { }, null, stringArr[0]);
//Val<Ref>,Ref<Val>
StringDriver.BasicAdd(stringArr, intArr);
StringDriver.AddSameKey(stringArr, intArr, 0, 2);
StringDriver.AddSameKey(stringArr, intArr, 99, 3);
StringDriver.AddSameKey(stringArr, intArr, 50, 4);
StringDriver.AddSameKey(stringArr, intArr, 1, 5);
StringDriver.AddSameKey(stringArr, intArr, 98, 6);
StringDriver.AddRemoveKeyValPair(stringArr, intArr, 0, 2);
StringDriver.AddRemoveKeyValPair(stringArr, intArr, 99, 3);
StringDriver.AddRemoveKeyValPair(stringArr, intArr, 50, 4);
StringDriver.AddRemoveKeyValPair(stringArr, intArr, 1, 5);
StringDriver.AddRemoveKeyValPair(stringArr, intArr, 98, 6);
StringDriver.AddValidations(stringArr, intArr, stringArr[0], intArr[0]);
StringDriver.AddValidations(new ValX1<string>[] { }, new RefX1<int>[] { }, stringArr[0], intArr[0]);
StringDriver.NonGenericIDictionaryBasicAdd(stringArr, intArr);
StringDriver.NonGenericIDictionaryAddSameKey(stringArr, intArr, 0, 2);
StringDriver.NonGenericIDictionaryAddSameKey(stringArr, intArr, 99, 3);
StringDriver.NonGenericIDictionaryAddSameKey(stringArr, intArr, 50, 4);
StringDriver.NonGenericIDictionaryAddSameKey(stringArr, intArr, 1, 5);
StringDriver.NonGenericIDictionaryAddSameKey(stringArr, intArr, 98, 6);
StringDriver.NonGenericIDictionaryAddRemoveKeyValPair(stringArr, intArr, 0, 2);
StringDriver.NonGenericIDictionaryAddRemoveKeyValPair(stringArr, intArr, 99, 3);
StringDriver.NonGenericIDictionaryAddRemoveKeyValPair(stringArr, intArr, 50, 4);
StringDriver.NonGenericIDictionaryAddRemoveKeyValPair(stringArr, intArr, 1, 5);
StringDriver.NonGenericIDictionaryAddRemoveKeyValPair(stringArr, intArr, 98, 6);
StringDriver.NonGenericIDictionaryAddValidations(stringArr, intArr, stringArr[0], intArr[0]);
StringDriver.NonGenericIDictionaryAddValidations(new ValX1<string>[] { }, new RefX1<int>[] { }, stringArr[0], intArr[0]);
Assert.True(test.result);
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Contoso.Core.EventReceiversWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System;
using Duality.Resources;
using Duality.Editor;
using Duality.Properties;
using Duality.Cloning;
using Duality.Drawing;
namespace Duality.Components.Renderers
{
/// <summary>
/// Renders a sprite to represent the <see cref="GameObject"/>.
/// </summary>
[ManuallyCloned]
[EditorHintCategory(CoreResNames.CategoryGraphics)]
[EditorHintImage(CoreResNames.ImageSpriteRenderer)]
public class SpriteRenderer : Renderer
{
/// <summary>
/// Specifies how the sprites uv-Coordinates are calculated.
/// </summary>
[Flags]
public enum UVMode
{
/// <summary>
/// The uv-Coordinates are constant, stretching the supplied texture to fit the SpriteRenderers dimensions.
/// </summary>
Stretch = 0x0,
/// <summary>
/// The u-Coordinate is calculated based on the available horizontal space, allowing the supplied texture to be
/// tiled across the SpriteRenderers width.
/// </summary>
WrapHorizontal = 0x1,
/// <summary>
/// The v-Coordinate is calculated based on the available vertical space, allowing the supplied texture to be
/// tiled across the SpriteRenderers height.
/// </summary>
WrapVertical = 0x2,
/// <summary>
/// The uv-Coordinates are calculated based on the available space, allowing the supplied texture to be
/// tiled across the SpriteRenderers size.
/// </summary>
WrapBoth = WrapHorizontal | WrapVertical
}
/// <summary>
/// Specifies whether the sprite should be flipped on a given axis.
/// </summary>
[Flags]
public enum FlipMode
{
/// <summary>
/// The sprite will not be flipped at all.
/// </summary>
None = 0x0,
/// <summary>
/// The sprite will be flipped on its horizontal axis.
/// </summary>
Horizontal = 0x1,
/// <summary>
/// The sprite will be flipped on its vertical axis.
/// </summary>
Vertical = 0x2
}
protected Rect rect = Rect.Align(Alignment.Center, 0, 0, 256, 256);
protected ContentRef<Material> sharedMat = Material.DualityIcon;
protected BatchInfo customMat = null;
protected ColorRgba colorTint = ColorRgba.White;
protected UVMode rectMode = UVMode.Stretch;
protected bool pixelGrid = false;
protected int offset = 0;
protected FlipMode flipMode = FlipMode.None;
[DontSerialize] protected VertexC1P3T2[] vertices = null;
[EditorHintFlags(MemberFlags.Invisible)]
public override float BoundRadius
{
get { return this.rect.Transformed(this.gameobj.Transform.Scale, this.gameobj.Transform.Scale).BoundingRadius; }
}
/// <summary>
/// [GET / SET] The rectangular area the sprite occupies. Relative to the <see cref="GameObject"/>.
/// </summary>
[EditorHintDecimalPlaces(1)]
public Rect Rect
{
get { return this.rect; }
set { this.rect = value; }
}
/// <summary>
/// [GET / SET] The <see cref="Duality.Resources.Material"/> that is used for rendering the sprite.
/// </summary>
public ContentRef<Material> SharedMaterial
{
get { return this.sharedMat; }
set { this.sharedMat = value; }
}
/// <summary>
/// [GET / SET] A custom, local <see cref="Duality.Drawing.BatchInfo"/> overriding the <see cref="SharedMaterial"/>,
/// allowing this sprite to look unique without having to create its own <see cref="Duality.Resources.Material"/> Resource.
/// However, this feature should be used with caution: Performance is better using <see cref="SharedMaterial">shared Materials</see>.
/// </summary>
public BatchInfo CustomMaterial
{
get { return this.customMat; }
set { this.customMat = value; }
}
/// <summary>
/// [GET / SET] A color by which the sprite is tinted.
/// </summary>
public ColorRgba ColorTint
{
get { return this.colorTint; }
set { this.colorTint = value; }
}
/// <summary>
/// [GET / SET] Specifies how the sprites uv-Coordinates are calculated.
/// </summary>
public UVMode RectMode
{
get { return this.rectMode; }
set { this.rectMode = value; }
}
/// <summary>
/// [GET / SET] Specified whether or not the rendered sprite will be aligned to actual screen pixels.
/// </summary>
public bool AlignToPixelGrid
{
get { return this.pixelGrid; }
set { this.pixelGrid = value; }
}
/// <summary>
/// [GET / SET] A virtual Z offset that affects the order in which objects are drawn. If you want to assure an object is drawn after another one,
/// just assign a higher Offset value to the background object.
/// </summary>
public int Offset
{
get { return this.offset; }
set { this.offset = value; }
}
/// <summary>
/// [GET] The internal Z-Offset added to the renderers vertices based on its <see cref="Offset"/> value.
/// </summary>
[EditorHintFlags(MemberFlags.Invisible)]
public float VertexZOffset
{
get { return this.offset * 0.01f; }
}
/// <summary>
/// [GET / SET] Specifies whether the sprite should be flipped on a given axis when redered.
/// </summary>
public FlipMode Flip
{
get { return this.flipMode; }
set { this.flipMode = value; }
}
public SpriteRenderer() {}
public SpriteRenderer(Rect rect, ContentRef<Material> mainMat)
{
this.rect = rect;
this.sharedMat = mainMat;
}
protected Texture RetrieveMainTex()
{
if (this.customMat != null)
return this.customMat.MainTexture.Res;
else if (this.sharedMat.IsAvailable)
return this.sharedMat.Res.MainTexture.Res;
else
return null;
}
protected ColorRgba RetrieveMainColor()
{
if (this.customMat != null)
return this.customMat.MainColor * this.colorTint;
else if (this.sharedMat.IsAvailable)
return this.sharedMat.Res.MainColor * this.colorTint;
else
return this.colorTint;
}
protected DrawTechnique RetrieveDrawTechnique()
{
if (this.customMat != null)
return this.customMat.Technique.Res;
else if (this.sharedMat.IsAvailable)
return this.sharedMat.Res.Technique.Res;
else
return null;
}
protected void PrepareVertices(ref VertexC1P3T2[] vertices, IDrawDevice device, ColorRgba mainClr, Rect uvRect)
{
Vector3 posTemp = this.gameobj.Transform.Pos;
float scaleTemp = 1.0f;
device.PreprocessCoords(ref posTemp, ref scaleTemp);
Vector2 xDot, yDot;
MathF.GetTransformDotVec(this.GameObj.Transform.Angle, scaleTemp, out xDot, out yDot);
Rect rectTemp = this.rect.Transformed(this.gameobj.Transform.Scale, this.gameobj.Transform.Scale);
Vector2 edge1 = rectTemp.TopLeft;
Vector2 edge2 = rectTemp.BottomLeft;
Vector2 edge3 = rectTemp.BottomRight;
Vector2 edge4 = rectTemp.TopRight;
if ((this.flipMode & FlipMode.Horizontal) != FlipMode.None)
{
edge1.X = -edge1.X;
edge2.X = -edge2.X;
edge3.X = -edge3.X;
edge4.X = -edge4.X;
}
if ((this.flipMode & FlipMode.Vertical) != FlipMode.None)
{
edge1.Y = -edge1.Y;
edge2.Y = -edge2.Y;
edge3.Y = -edge3.Y;
edge4.Y = -edge4.Y;
}
MathF.TransformDotVec(ref edge1, ref xDot, ref yDot);
MathF.TransformDotVec(ref edge2, ref xDot, ref yDot);
MathF.TransformDotVec(ref edge3, ref xDot, ref yDot);
MathF.TransformDotVec(ref edge4, ref xDot, ref yDot);
float left = uvRect.X;
float right = uvRect.RightX;
float top = uvRect.Y;
float bottom = uvRect.BottomY;
if (vertices == null || vertices.Length != 4) vertices = new VertexC1P3T2[4];
vertices[0].Pos.X = posTemp.X + edge1.X;
vertices[0].Pos.Y = posTemp.Y + edge1.Y;
vertices[0].Pos.Z = posTemp.Z + this.VertexZOffset;
vertices[0].TexCoord.X = left;
vertices[0].TexCoord.Y = top;
vertices[0].Color = mainClr;
vertices[1].Pos.X = posTemp.X + edge2.X;
vertices[1].Pos.Y = posTemp.Y + edge2.Y;
vertices[1].Pos.Z = posTemp.Z + this.VertexZOffset;
vertices[1].TexCoord.X = left;
vertices[1].TexCoord.Y = bottom;
vertices[1].Color = mainClr;
vertices[2].Pos.X = posTemp.X + edge3.X;
vertices[2].Pos.Y = posTemp.Y + edge3.Y;
vertices[2].Pos.Z = posTemp.Z + this.VertexZOffset;
vertices[2].TexCoord.X = right;
vertices[2].TexCoord.Y = bottom;
vertices[2].Color = mainClr;
vertices[3].Pos.X = posTemp.X + edge4.X;
vertices[3].Pos.Y = posTemp.Y + edge4.Y;
vertices[3].Pos.Z = posTemp.Z + this.VertexZOffset;
vertices[3].TexCoord.X = right;
vertices[3].TexCoord.Y = top;
vertices[3].Color = mainClr;
if (this.pixelGrid)
{
vertices[0].Pos.X = MathF.Round(vertices[0].Pos.X);
vertices[1].Pos.X = MathF.Round(vertices[1].Pos.X);
vertices[2].Pos.X = MathF.Round(vertices[2].Pos.X);
vertices[3].Pos.X = MathF.Round(vertices[3].Pos.X);
if (MathF.RoundToInt(device.TargetSize.X) != (MathF.RoundToInt(device.TargetSize.X) / 2) * 2)
{
vertices[0].Pos.X += 0.5f;
vertices[1].Pos.X += 0.5f;
vertices[2].Pos.X += 0.5f;
vertices[3].Pos.X += 0.5f;
}
vertices[0].Pos.Y = MathF.Round(vertices[0].Pos.Y);
vertices[1].Pos.Y = MathF.Round(vertices[1].Pos.Y);
vertices[2].Pos.Y = MathF.Round(vertices[2].Pos.Y);
vertices[3].Pos.Y = MathF.Round(vertices[3].Pos.Y);
if (MathF.RoundToInt(device.TargetSize.Y) != (MathF.RoundToInt(device.TargetSize.Y) / 2) * 2)
{
vertices[0].Pos.Y += 0.5f;
vertices[1].Pos.Y += 0.5f;
vertices[2].Pos.Y += 0.5f;
vertices[3].Pos.Y += 0.5f;
}
}
}
public override void Draw(IDrawDevice device)
{
Texture mainTex = this.RetrieveMainTex();
ColorRgba mainClr = this.RetrieveMainColor();
Rect uvRect;
if (mainTex != null)
{
if (this.rectMode == UVMode.WrapBoth)
uvRect = new Rect(mainTex.UVRatio.X * this.rect.W / mainTex.PixelWidth, mainTex.UVRatio.Y * this.rect.H / mainTex.PixelHeight);
else if (this.rectMode == UVMode.WrapHorizontal)
uvRect = new Rect(mainTex.UVRatio.X * this.rect.W / mainTex.PixelWidth, mainTex.UVRatio.Y);
else if (this.rectMode == UVMode.WrapVertical)
uvRect = new Rect(mainTex.UVRatio.X, mainTex.UVRatio.Y * this.rect.H / mainTex.PixelHeight);
else
uvRect = new Rect(mainTex.UVRatio.X, mainTex.UVRatio.Y);
}
else
uvRect = new Rect(1.0f, 1.0f);
this.PrepareVertices(ref this.vertices, device, mainClr, uvRect);
if (this.customMat != null)
device.AddVertices(this.customMat, VertexMode.Quads, this.vertices);
else
device.AddVertices(this.sharedMat, VertexMode.Quads, this.vertices);
}
protected override void OnSetupCloneTargets(object targetObj, ICloneTargetSetup setup)
{
base.OnSetupCloneTargets(targetObj, setup);
SpriteRenderer target = targetObj as SpriteRenderer;
setup.HandleObject(this.customMat, target.customMat);
}
protected override void OnCopyDataTo(object targetObj, ICloneOperation operation)
{
base.OnCopyDataTo(targetObj, operation);
SpriteRenderer target = targetObj as SpriteRenderer;
target.rect = this.rect;
target.colorTint = this.colorTint;
target.rectMode = this.rectMode;
target.offset = this.offset;
operation.HandleValue(ref this.sharedMat, ref target.sharedMat);
operation.HandleObject(this.customMat, ref target.customMat);
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2014-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the DescribeSpotPriceHistory operation.
/// Describes the Spot Price history. The prices returned are listed in chronological
/// order, from the oldest to the most recent, for up to the past 90 days. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html">Spot
/// Instance Pricing History</a> in the <i>Amazon Elastic Compute Cloud User Guide for
/// Linux</i>.
///
///
/// <para>
/// When you specify a start and end time, this operation returns the prices of the instance
/// types within the time range that you specified and the time when the price changed.
/// The price is valid within the time period that you specified; the response merely
/// indicates the last time that the price changed.
/// </para>
/// </summary>
public partial class DescribeSpotPriceHistoryRequest : AmazonEC2Request
{
private string _availabilityZone;
private DateTime? _endTime;
private List<Filter> _filters = new List<Filter>();
private List<string> _instanceTypes = new List<string>();
private int? _maxResults;
private string _nextToken;
private List<string> _productDescriptions = new List<string>();
private DateTime? _startTime;
/// <summary>
/// Gets and sets the property AvailabilityZone.
/// <para>
/// Filters the results by the specified Availability Zone.
/// </para>
/// </summary>
public string AvailabilityZone
{
get { return this._availabilityZone; }
set { this._availabilityZone = value; }
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this._availabilityZone != null;
}
/// <summary>
/// Gets and sets the property EndTime.
/// <para>
/// The date and time, up to the current date, from which to stop retrieving the price
/// history data.
/// </para>
/// </summary>
public DateTime EndTime
{
get { return this._endTime.GetValueOrDefault(); }
set { this._endTime = value; }
}
// Check to see if EndTime property is set
internal bool IsSetEndTime()
{
return this._endTime.HasValue;
}
/// <summary>
/// Gets and sets the property Filters.
/// <para>
/// One or more filters.
/// </para>
/// <ul> <li>
/// <para>
/// <code>availability-zone</code> - The Availability Zone for which prices should be
/// returned.
/// </para>
/// </li> <li>
/// <para>
/// <code>instance-type</code> - The type of instance (for example, <code>m1.small</code>).
/// </para>
/// </li> <li>
/// <para>
/// <code>product-description</code> - The product description for the Spot Price (<code>Linux/UNIX</code>
/// | <code>SUSE Linux</code> | <code>Windows</code> | <code>Linux/UNIX (Amazon VPC)</code>
/// | <code>SUSE Linux (Amazon VPC)</code> | <code>Windows (Amazon VPC)</code>).
/// </para>
/// </li> <li>
/// <para>
/// <code>spot-price</code> - The Spot Price. The value must match exactly (or use wildcards;
/// greater than or less than comparison is not supported).
/// </para>
/// </li> <li>
/// <para>
/// <code>timestamp</code> - The timestamp of the Spot Price history (for example, 2010-08-16T05:06:11.000Z).
/// You can use wildcards (* and ?). Greater than or less than comparison is not supported.
/// </para>
/// </li> </ul>
/// </summary>
public List<Filter> Filters
{
get { return this._filters; }
set { this._filters = value; }
}
// Check to see if Filters property is set
internal bool IsSetFilters()
{
return this._filters != null && this._filters.Count > 0;
}
/// <summary>
/// Gets and sets the property InstanceTypes.
/// <para>
/// Filters the results by the specified instance types.
/// </para>
/// </summary>
public List<string> InstanceTypes
{
get { return this._instanceTypes; }
set { this._instanceTypes = value; }
}
// Check to see if InstanceTypes property is set
internal bool IsSetInstanceTypes()
{
return this._instanceTypes != null && this._instanceTypes.Count > 0;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of items to return for this call. The call also returns a token
/// that you can specify in a subsequent call to get the next set of results.
/// </para>
/// </summary>
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token for the next set of items. (You received this token from a prior call.)
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property ProductDescriptions.
/// <para>
/// Filters the results by the specified basic product descriptions.
/// </para>
/// </summary>
public List<string> ProductDescriptions
{
get { return this._productDescriptions; }
set { this._productDescriptions = value; }
}
// Check to see if ProductDescriptions property is set
internal bool IsSetProductDescriptions()
{
return this._productDescriptions != null && this._productDescriptions.Count > 0;
}
/// <summary>
/// Gets and sets the property StartTime.
/// <para>
/// The date and time, up to the past 90 days, from which to start retrieving the price
/// history data.
/// </para>
/// </summary>
public DateTime StartTime
{
get { return this._startTime.GetValueOrDefault(); }
set { this._startTime = value; }
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this._startTime.HasValue;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using Xunit;
using Tests.Collections;
using System.Reflection;
using System.Linq;
namespace System.Collections.ObjectModel.Tests
{
public class ReadOnlyDictionaryTests
{
/// <summary>
/// Current key that the m_generateItemFunc is at.
/// </summary>
private static int s_currentKey = int.MaxValue;
/// <summary>
/// Function to generate a KeyValuePair.
/// </summary>
private static Func<KeyValuePair<int, string>> s_generateItemFunc = () =>
{
var kvp = new KeyValuePair<int, string>(s_currentKey, s_currentKey.ToString());
s_currentKey--;
return kvp;
};
/// <summary>
/// Tests that the ReadOnlyDictionary is constructed with the given
/// Dictionary.
/// </summary>
[Fact]
public static void CtorTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.InitialItems_Tests();
IDictionary<int, string> dictAsIDictionary = dictionary;
Assert.True(dictAsIDictionary.IsReadOnly, "ReadonlyDictionary Should be readonly");
IDictionary dictAsNonGenericIDictionary = dictionary;
Assert.True(dictAsNonGenericIDictionary.IsFixedSize);
Assert.True(dictAsNonGenericIDictionary.IsReadOnly);
}
/// <summary>
/// Tests that an argument null exception is returned when given
/// a null dictionary to initialise ReadOnlyDictionary.
/// </summary>
[Fact]
public static void CtorTests_Negative()
{
AssertExtensions.Throws<ArgumentNullException>("dictionary", () => new ReadOnlyDictionary<int, string>(null));
}
/// <summary>
/// Tests that true is returned when the key exists in the dictionary
/// and false otherwise.
/// </summary>
[Fact]
public static void ContainsKeyTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.ContainsKey_Tests();
}
/// <summary>
/// Tests that the value is retrieved from a dictionary when its
/// key exists in the dictionary and false when it does not.
/// </summary>
[Fact]
public static void TryGetValueTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.TryGetValue_Tests();
}
/// <summary>
/// Tests that the dictionary's keys can be retrieved.
/// </summary>
[Fact]
public static void GetKeysTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.Keys_get_Tests();
}
/// <summary>
/// Tests that the dictionary's values can be retrieved.
/// </summary>
[Fact]
public static void GetValuesTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.Values_get_Tests();
}
/// <summary>
/// Tests that items can be retrieved by key from the Dictionary.
/// </summary>
[Fact]
public static void GetItemTests()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.Item_get_Tests();
}
/// <summary>
/// Tests that an KeyNotFoundException is thrown when retrieving the
/// value of an item whose key is not in the dictionary.
/// </summary>
[Fact]
public static void GetItemTests_Negative()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>(dictionary, expectedArr, s_generateItemFunc);
helper.Item_get_Tests_Negative();
}
/// <summary>
/// Tests that a ReadOnlyDictionary cannot be modified. That is, that
/// Add, Remove, Clear does not work.
/// </summary>
[Fact]
public static void CannotModifyDictionaryTests_Negative()
{
KeyValuePair<int, string>[] expectedArr = new KeyValuePair<int, string>[] {
new KeyValuePair<int, string>(1, "one"),
new KeyValuePair<int, string>(2, "two"),
new KeyValuePair<int, string>(3, "three"),
new KeyValuePair<int, string>(4, "four"),
new KeyValuePair<int, string>(5, "five")
};
DummyDictionary<int, string> dummyExpectedDict = new DummyDictionary<int, string>(expectedArr);
ReadOnlyDictionary<int, string> dictionary = new ReadOnlyDictionary<int, string>(dummyExpectedDict);
IReadOnlyDictionary_T_Test<int, string> helper = new IReadOnlyDictionary_T_Test<int, string>();
IDictionary<int, string> dictAsIDictionary = dictionary;
Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Add(new KeyValuePair<int, string>(7, "seven")));
Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Add(7, "seven"));
Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Remove(new KeyValuePair<int, string>(1, "one")));
Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Remove(1));
Assert.Throws<NotSupportedException>(() => dictAsIDictionary.Clear());
helper.VerifyCollection(dictionary, expectedArr); //verifying that the collection has not changed.
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttributeTests()
{
ReadOnlyDictionary<int, int> dict = new ReadOnlyDictionary<int, int>(new Dictionary<int, int>{{1, 2}, {2, 4}, {3, 6}});
DebuggerAttributes.ValidateDebuggerDisplayReferences(dict);
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(dict);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
KeyValuePair<int, int>[] pairs = itemProperty.GetValue(info.Instance) as KeyValuePair<int, int>[];
Assert.Equal(dict, pairs);
DebuggerAttributes.ValidateDebuggerDisplayReferences(dict.Keys);
info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(ReadOnlyDictionary<int, int>.KeyCollection), new Type[] { typeof(int) }, dict.Keys);
itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
int[] items = itemProperty.GetValue(info.Instance) as int[];
Assert.Equal(dict.Keys, items);
DebuggerAttributes.ValidateDebuggerDisplayReferences(dict.Values);
info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(ReadOnlyDictionary<int, int>.KeyCollection), new Type[] { typeof(int) }, dict.Values);
itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
items = itemProperty.GetValue(info.Instance) as int[];
Assert.Equal(dict.Values, items);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttribute_NullDictionary_ThrowsArgumentNullException()
{
TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(ReadOnlyDictionary<int, int>), null));
ArgumentNullException argumentNullException = Assert.IsType<ArgumentNullException>(ex.InnerException);
Assert.Equal("dictionary", argumentNullException.ParamName);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttribute_NullDictionaryKeys_ThrowsArgumentNullException()
{
TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(ReadOnlyDictionary<int, int>.KeyCollection), new Type[] { typeof(int) }, null));
ArgumentNullException argumentNullException = Assert.IsType<ArgumentNullException>(ex.InnerException);
Assert.Equal("collection", argumentNullException.ParamName);
}
}
public class TestReadOnlyDictionary<TKey, TValue> : ReadOnlyDictionary<TKey, TValue>
{
public TestReadOnlyDictionary(IDictionary<TKey, TValue> dict)
: base(dict)
{
}
public IDictionary<TKey, TValue> GetDictionary()
{
return Dictionary;
}
}
public class DictionaryThatDoesntImplementNonGeneric<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> _inner;
public DictionaryThatDoesntImplementNonGeneric(IDictionary<TKey, TValue> inner)
{
_inner = inner;
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _inner.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) _inner).GetEnumerator();
}
public void Add(KeyValuePair<TKey, TValue> item)
{
_inner.Add(item);
}
public void Clear()
{
_inner.Clear();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return _inner.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_inner.CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return _inner.Remove(item);
}
public int Count
{
get { return _inner.Count; }
}
public bool IsReadOnly
{
get { return _inner.IsReadOnly; }
}
public void Add(TKey key, TValue value)
{
_inner.Add(key, value);
}
public bool ContainsKey(TKey key)
{
return _inner.ContainsKey(key);
}
public bool Remove(TKey key)
{
return _inner.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value)
{
return _inner.TryGetValue(key, out value);
}
public TValue this[TKey key]
{
get { return _inner[key]; }
set { _inner[key] = value; }
}
public ICollection<TKey> Keys
{
get { return _inner.Keys; }
}
public ICollection<TValue> Values
{
get { return _inner.Values; }
}
}
public class ReadOnlyDictionaryOverNonGenericTests
: IDictionaryTest<string, int>
{
public ReadOnlyDictionaryOverNonGenericTests()
: base(false)
{
}
private int m_next_item = 1;
protected override bool IsResetNotSupported { get { return false; } }
protected override bool IsGenericCompatibility { get { return false; } }
protected override bool ItemsMustBeUnique { get { return true; } }
protected override bool ItemsMustBeNonNull { get { return true; } }
protected override object GenerateItem()
{
return new KeyValuePair<string, int>(m_next_item.ToString(), m_next_item++);
}
protected override IEnumerable GetEnumerable(object[] items)
{
var dict = new DictionaryThatDoesntImplementNonGeneric<string, int>(new Dictionary<string, int>());
foreach (KeyValuePair<string, int> p in items)
dict[p.Key] = p.Value;
return new TestReadOnlyDictionary<string, int>(dict);
}
protected override object[] InvalidateEnumerator(IEnumerable enumerable)
{
var roDict = (TestReadOnlyDictionary<string, int>)enumerable;
var dict = roDict.GetDictionary();
var item = (KeyValuePair<string, int>)GenerateItem();
dict.Add(item.Key, item.Value);
var arr = new object[dict.Count];
((ICollection)roDict).CopyTo(arr, 0);
return arr;
}
}
public class ReadOnlyDictionaryTestsStringInt
: IDictionaryTest<string, int>
{
public ReadOnlyDictionaryTestsStringInt()
: base(false)
{
}
private int m_next_item = 1;
protected override bool IsResetNotSupported { get { return false; } }
protected override bool IsGenericCompatibility { get { return false; } }
protected override bool ItemsMustBeUnique { get { return true; } }
protected override bool ItemsMustBeNonNull { get { return true; } }
protected override object GenerateItem()
{
return new KeyValuePair<string, int>(m_next_item.ToString(), m_next_item++);
}
protected override IEnumerable GetEnumerable(object[] items)
{
var dict = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> p in items)
dict[p.Key] = p.Value;
return new TestReadOnlyDictionary<string, int>(dict);
}
protected override object[] InvalidateEnumerator(IEnumerable enumerable)
{
var roDict = (TestReadOnlyDictionary<string, int>)enumerable;
var dict = roDict.GetDictionary();
var item = (KeyValuePair<string, int>)GenerateItem();
dict.Add(item.Key, item.Value);
var arr = new object[dict.Count];
((ICollection)roDict).CopyTo(arr, 0);
return arr;
}
}
/// <summary>
/// Helper class that performs all of the IReadOnlyDictionary
/// verifications.
/// </summary>
public class IReadOnlyDictionary_T_Test<TKey, TValue>
{
private readonly IReadOnlyDictionary<TKey, TValue> _collection;
private readonly KeyValuePair<TKey, TValue>[] _expectedItems;
private readonly Func<KeyValuePair<TKey, TValue>> _generateItem;
/// <summary>
/// Initializes a new instance of the IReadOnlyDictionary_T_Test.
/// </summary>
public IReadOnlyDictionary_T_Test(
IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems,
Func<KeyValuePair<TKey, TValue>> generateItem)
{
_collection = collection;
_expectedItems = expectedItems;
_generateItem = generateItem;
}
public IReadOnlyDictionary_T_Test()
{
}
/// <summary>
/// Tests that the initial items in the readonly collection
/// are equivalent to the collection it was initialised with.
/// </summary>
public void InitialItems_Tests()
{
//[] Verify the initial items in the collection
VerifyCollection(_collection, _expectedItems);
//verifies the non-generic enumerator.
VerifyEnumerator(_collection, _expectedItems);
}
/// <summary>
/// Checks that the dictionary contains all keys of the expected items.
/// And returns false when the dictionary does not contain a key.
/// </summary>
public void ContainsKey_Tests()
{
Assert.Equal(_expectedItems.Length, _collection.Count);
for (int i = 0; i < _collection.Count; i++)
{
Assert.True(_collection.ContainsKey(_expectedItems[i].Key),
"Err_5983muqjl Verifying ContainsKey the item in the collection and the expected existing items(" + _expectedItems[i].Key + ")");
}
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
KeyValuePair<TKey, TValue> nonExistingItem = _generateItem();
while (!IsUniqueKey(_expectedItems, nonExistingItem))
{
nonExistingItem = _generateItem();
}
TKey nonExistingKey = nonExistingItem.Key;
Assert.False(_collection.ContainsKey(nonExistingKey), "Err_4713ebda Verifying ContainsKey the non-existing item in the collection and the expected non-existing items key:" + nonExistingKey);
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
}
/// <summary>
/// Tests that you can get values that exist in the collection
/// and not when the value is not in the collection.
/// </summary>
public void TryGetValue_Tests()
{
Assert.Equal(_expectedItems.Length, _collection.Count);
for (int i = 0; i < _collection.Count; i++)
{
TValue itemValue;
Assert.True(_collection.TryGetValue(_expectedItems[i].Key, out itemValue),
"Err_2621pnyan Verifying TryGetValue the item in the collection and the expected existing items(" + _expectedItems[i].Value + ")");
Assert.Equal(_expectedItems[i].Value, itemValue);
}
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
KeyValuePair<TKey, TValue> nonExistingItem = _generateItem();
while (!IsUniqueKey(_expectedItems, nonExistingItem))
{
nonExistingItem = _generateItem();
}
TValue nonExistingItemValue;
Assert.False(_collection.TryGetValue(nonExistingItem.Key, out nonExistingItemValue),
"Err_4561rtio Verifying TryGetValue returns false when looking for a non-existing item in the collection (" + nonExistingItem.Key + ")");
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
}
/// <summary>
/// Tests that you can get all the keys in the collection.
/// </summary>
public void Keys_get_Tests()
{
// Verify Key get_Values
int numItemsSeen = 0;
foreach (TKey key in _collection.Keys)
{
numItemsSeen++;
TValue value;
Assert.True(_collection.TryGetValue(key, out value), "Items in the Keys collection should exist in the dictionary!");
}
Assert.Equal(_collection.Count, numItemsSeen);
}
/// <summary>
/// Tests that you can get all the values in the collection.
/// </summary>
public void Values_get_Tests()
{
// Verify Values get_Values
// Copy collection values to another collection, then compare them.
List<TValue> knownValuesList = new List<TValue>();
foreach (KeyValuePair<TKey, TValue> pair in _collection)
knownValuesList.Add(pair.Value);
int numItemsSeen = 0;
foreach (TValue value in _collection.Values)
{
numItemsSeen++;
Assert.True(knownValuesList.Contains(value), "Items in the Values collection should exist in the dictionary!");
}
Assert.Equal(_collection.Count, numItemsSeen);
}
/// <summary>
/// Runs all of the tests on get Item.
/// </summary>
public void Item_get_Tests()
{
// Verify get_Item with existing item on Collection
Assert.Equal(_expectedItems.Length, _collection.Count);
for (int i = 0; i < _expectedItems.Length; ++i)
{
TKey expectedKey = _expectedItems[i].Key;
TValue expectedValue = _expectedItems[i].Value;
TValue actualValue = _collection[expectedKey];
Assert.Equal(expectedValue, actualValue);
}
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
}
/// <summary>
/// Tests that KeyNotFoundException is thrown when trying to get from
/// a Dictionary whose key is not in the collection.
/// </summary>
public void Item_get_Tests_Negative()
{
// Verify get_Item with non-existing on Collection
TKey nonExistingKey = _generateItem().Key;
Assert.Throws<KeyNotFoundException>(() => { TValue itemValue = _collection[nonExistingKey]; });
//Verify that the collection was not mutated
VerifyCollection(_collection, _expectedItems);
}
/// <summary>
/// Verifies that the items in the given collection match the expected items.
/// </summary>
public void VerifyCollection(IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems)
{
// verify that you can get all items in collection.
Assert.Equal(expectedItems.Length, collection.Count);
for (int i = 0; i < expectedItems.Length; ++i)
{
TKey expectedKey = expectedItems[i].Key;
TValue expectedValue = expectedItems[i].Value;
Assert.Equal(expectedValue, collection[expectedKey]);
}
VerifyGenericEnumerator(collection, expectedItems);
}
#region Helper Methods
/// <summary>
/// Verifies that the generic enumerator retrieves the correct items.
/// </summary>
private void VerifyGenericEnumerator(IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems)
{
IEnumerator<KeyValuePair<TKey, TValue>> enumerator = collection.GetEnumerator();
int iterations = 0;
int expectedCount = expectedItems.Length;
// There is no sequential order to the collection, so we're testing that all the items
// in the readonlydictionary exist in the array.
bool[] itemsVisited = new bool[expectedCount];
bool itemFound;
while ((iterations < expectedCount) && enumerator.MoveNext())
{
KeyValuePair<TKey, TValue> currentItem = enumerator.Current;
KeyValuePair<TKey, TValue> tempItem;
// Verify we have not gotten more items then we expected
Assert.True(iterations < expectedCount,
"Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) then are in the expectedElements(" + expectedCount + " items)");
// Verify Current returned the correct value
itemFound = false;
for (int i = 0; i < itemsVisited.Length; ++i)
{
if (!itemsVisited[i] && currentItem.Equals(expectedItems[i]))
{
itemsVisited[i] = true;
itemFound = true;
break;
}
}
Assert.True(itemFound, "Err_1432pauy Current returned unexpected value=" + currentItem);
// Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
Assert.Equal(currentItem, tempItem);
}
iterations++;
}
for (int i = 0; i < expectedCount; ++i)
{
Assert.True(itemsVisited[i], "Err_052848ahiedoi Expected Current to return true for item: " + expectedItems[i] + "index: " + i);
}
Assert.Equal(expectedCount, iterations);
for (int i = 0; i < 3; i++)
{
Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations");
}
enumerator.Dispose();
}
/// <summary>
/// Verifies that the non-generic enumerator retrieves the correct items.
/// </summary>
private void VerifyEnumerator(IReadOnlyDictionary<TKey, TValue> collection, KeyValuePair<TKey, TValue>[] expectedItems)
{
IEnumerator enumerator = collection.GetEnumerator();
int iterations = 0;
int expectedCount = expectedItems.Length;
// There is no sequential order to the collection, so we're testing that all the items
// in the readonlydictionary exist in the array.
bool[] itemsVisited = new bool[expectedCount];
bool itemFound;
while ((iterations < expectedCount) && enumerator.MoveNext())
{
object currentItem = enumerator.Current;
object tempItem;
// Verify we have not gotten more items then we expected
Assert.True(iterations < expectedCount,
"Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) then are in the expectedElements(" + expectedCount + " items)");
// Verify Current returned the correct value
itemFound = false;
for (int i = 0; i < itemsVisited.Length; ++i)
{
if (!itemsVisited[i] && expectedItems[i].Equals(currentItem))
{
itemsVisited[i] = true;
itemFound = true;
break;
}
}
Assert.True(itemFound, "Err_1432pauy Current returned unexpected value=" + currentItem);
// Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
Assert.Equal(currentItem, tempItem);
}
iterations++;
}
for (int i = 0; i < expectedCount; ++i)
{
Assert.True(itemsVisited[i], "Err_052848ahiedoi Expected Current to return true for item: " + expectedItems[i] + "index: " + i);
}
Assert.Equal(expectedCount, iterations);
for (int i = 0; i < 3; i++)
{
Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations");
}
}
/// <summary>
/// tests whether the given item's key is unique in a collection.
/// returns true if it is and false otherwise.
/// </summary>
private bool IsUniqueKey(KeyValuePair<TKey, TValue>[] items, KeyValuePair<TKey, TValue> item)
{
for (int i = 0; i < items.Length; ++i)
{
if (items[i].Key != null && items[i].Key.Equals(item.Key))
{
return false;
}
}
return true;
}
#endregion
}
/// <summary>
/// Helper Dictionary class that implements basic IDictionary
/// functionality but none of the modifier methods.
/// </summary>
public class DummyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly List<KeyValuePair<TKey, TValue>> _items;
private readonly TKey[] _keys;
private readonly TValue[] _values;
public DummyDictionary(KeyValuePair<TKey, TValue>[] items)
{
_keys = new TKey[items.Length];
_values = new TValue[items.Length];
_items = new List<KeyValuePair<TKey, TValue>>(items);
for (int i = 0; i < items.Length; i++)
{
_keys[i] = items[i].Key;
_values[i] = items[i].Value;
}
}
#region IDictionary<TKey, TValue> methods
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _items.GetEnumerator();
}
public int Count
{
get { return _items.Count; }
}
public bool ContainsKey(TKey key)
{
foreach (var item in _items)
{
if (item.Key.Equals(key))
return true;
}
return false;
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
foreach (var i in _items)
{
if (i.Equals(item))
return true;
}
return false;
}
public ICollection<TKey> Keys
{
get { return _keys; }
}
public ICollection<TValue> Values
{
get { return _values; }
}
public TValue this[TKey key]
{
get
{
foreach (var item in _items)
{
if (item.Key.Equals(key))
return item.Value;
}
throw new KeyNotFoundException("key does not exist");
}
set
{
throw new NotImplementedException();
}
}
public bool TryGetValue(TKey key, out TValue value)
{
value = default(TValue);
if (!ContainsKey(key))
return false;
value = this[key];
return true;
}
public bool IsReadOnly
{
get { return false; }
}
#endregion
#region Not Implemented Methods
public void Add(TKey key, TValue value)
{
throw new NotImplementedException("Should not have been able to add to the collection.");
}
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException("Should not have been able to add to the collection.");
}
public bool Remove(TKey key)
{
throw new NotImplementedException("Should not have been able remove items from the collection.");
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotImplementedException("Should not have been able remove items from the collection.");
}
public void Clear()
{
throw new NotImplementedException("Should not have been able clear the collection.");
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw new NotImplementedException();
}
#endregion
}
}
| |
namespace MSDN.Html.Editor
{
partial class FindReplaceForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FindReplaceForm));
this.tabControl = new System.Windows.Forms.TabControl();
this.tabFind = new System.Windows.Forms.TabPage();
this.tabReplace = new System.Windows.Forms.TabPage();
this.labelFind = new System.Windows.Forms.Label();
this.bCancel = new System.Windows.Forms.Button();
this.textFind = new System.Windows.Forms.TextBox();
this.bFindNext = new System.Windows.Forms.Button();
this.labelReplace = new System.Windows.Forms.Label();
this.textReplace = new System.Windows.Forms.TextBox();
this.bReplaceAll = new System.Windows.Forms.Button();
this.bReplace = new System.Windows.Forms.Button();
this.bOptions = new System.Windows.Forms.Button();
this.optionMatchCase = new System.Windows.Forms.CheckBox();
this.optionMatchWhole = new System.Windows.Forms.CheckBox();
this.panelOptions = new System.Windows.Forms.Panel();
this.panelInput = new System.Windows.Forms.Panel();
this.tabControl.SuspendLayout();
this.panelOptions.SuspendLayout();
this.panelInput.SuspendLayout();
this.SuspendLayout();
//
// tabControl
//
this.tabControl.Controls.Add(this.tabFind);
this.tabControl.Controls.Add(this.tabReplace);
this.tabControl.Location = new System.Drawing.Point(8, 8);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
this.tabControl.ShowToolTips = true;
this.tabControl.Size = new System.Drawing.Size(440, 32);
this.tabControl.TabIndex = 0;
this.tabControl.TabStop = false;
this.tabControl.SelectedIndexChanged += new System.EventHandler(this.tabControl_SelectedIndexChanged);
//
// tabFind
//
this.tabFind.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.tabFind.Location = new System.Drawing.Point(4, 22);
this.tabFind.Name = "tabFind";
this.tabFind.Size = new System.Drawing.Size(432, 6);
this.tabFind.TabIndex = 0;
this.tabFind.Text = "Find";
this.tabFind.ToolTipText = "Find Text";
//
// tabReplace
//
this.tabReplace.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.tabReplace.Location = new System.Drawing.Point(4, 22);
this.tabReplace.Name = "tabReplace";
this.tabReplace.Size = new System.Drawing.Size(432, 6);
this.tabReplace.TabIndex = 1;
this.tabReplace.Text = "Replace";
this.tabReplace.ToolTipText = "Find and Replace Text";
//
// labelFind
//
this.labelFind.Location = new System.Drawing.Point(8, 16);
this.labelFind.Name = "labelFind";
this.labelFind.Size = new System.Drawing.Size(96, 23);
this.labelFind.TabIndex = 0;
this.labelFind.Text = "Find What:";
//
// bCancel
//
this.bCancel.BackColor = System.Drawing.SystemColors.Control;
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(344, 80);
this.bCancel.Name = "bCancel";
this.bCancel.Size = new System.Drawing.Size(75, 23);
this.bCancel.TabIndex = 4;
this.bCancel.Text = "Cancel";
this.bCancel.UseVisualStyleBackColor = false;
//
// textFind
//
this.textFind.Location = new System.Drawing.Point(112, 16);
this.textFind.Name = "textFind";
this.textFind.Size = new System.Drawing.Size(296, 20);
this.textFind.TabIndex = 1;
this.textFind.TextChanged += new System.EventHandler(this.textFind_TextChanged);
//
// bFindNext
//
this.bFindNext.BackColor = System.Drawing.SystemColors.Control;
this.bFindNext.Location = new System.Drawing.Point(264, 80);
this.bFindNext.Name = "bFindNext";
this.bFindNext.Size = new System.Drawing.Size(75, 23);
this.bFindNext.TabIndex = 3;
this.bFindNext.Text = "Find Next";
this.bFindNext.UseVisualStyleBackColor = false;
this.bFindNext.Click += new System.EventHandler(this.bFindNext_Click);
//
// labelReplace
//
this.labelReplace.Location = new System.Drawing.Point(8, 48);
this.labelReplace.Name = "labelReplace";
this.labelReplace.Size = new System.Drawing.Size(96, 23);
this.labelReplace.TabIndex = 0;
this.labelReplace.Text = "Replace With:";
//
// textReplace
//
this.textReplace.Location = new System.Drawing.Point(112, 48);
this.textReplace.Name = "textReplace";
this.textReplace.Size = new System.Drawing.Size(296, 20);
this.textReplace.TabIndex = 2;
this.textReplace.TextChanged += new System.EventHandler(this.textReplace_TextChanged);
//
// bReplaceAll
//
this.bReplaceAll.BackColor = System.Drawing.SystemColors.Control;
this.bReplaceAll.Location = new System.Drawing.Point(176, 80);
this.bReplaceAll.Name = "bReplaceAll";
this.bReplaceAll.Size = new System.Drawing.Size(75, 23);
this.bReplaceAll.TabIndex = 7;
this.bReplaceAll.Text = "Replace All";
this.bReplaceAll.UseVisualStyleBackColor = false;
this.bReplaceAll.Click += new System.EventHandler(this.bReplaceAll_Click);
//
// bReplace
//
this.bReplace.BackColor = System.Drawing.SystemColors.Control;
this.bReplace.Location = new System.Drawing.Point(96, 80);
this.bReplace.Name = "bReplace";
this.bReplace.Size = new System.Drawing.Size(75, 23);
this.bReplace.TabIndex = 6;
this.bReplace.Text = "Replace";
this.bReplace.UseVisualStyleBackColor = false;
this.bReplace.Click += new System.EventHandler(this.bReplace_Click);
//
// bOptions
//
this.bOptions.BackColor = System.Drawing.SystemColors.Control;
this.bOptions.Location = new System.Drawing.Point(8, 80);
this.bOptions.Name = "bOptions";
this.bOptions.Size = new System.Drawing.Size(80, 23);
this.bOptions.TabIndex = 5;
this.bOptions.Text = "Options";
this.bOptions.UseVisualStyleBackColor = false;
this.bOptions.Click += new System.EventHandler(this.bOptions_Click);
//
// optionMatchCase
//
this.optionMatchCase.Location = new System.Drawing.Point(8, 8);
this.optionMatchCase.Name = "optionMatchCase";
this.optionMatchCase.Size = new System.Drawing.Size(240, 24);
this.optionMatchCase.TabIndex = 8;
this.optionMatchCase.Text = "Match Exact Case";
//
// optionMatchWhole
//
this.optionMatchWhole.Location = new System.Drawing.Point(8, 32);
this.optionMatchWhole.Name = "optionMatchWhole";
this.optionMatchWhole.Size = new System.Drawing.Size(240, 24);
this.optionMatchWhole.TabIndex = 9;
this.optionMatchWhole.Text = "Match Whole Word Only";
//
// panelOptions
//
this.panelOptions.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.panelOptions.Controls.Add(this.optionMatchCase);
this.panelOptions.Controls.Add(this.optionMatchWhole);
this.panelOptions.Location = new System.Drawing.Point(16, 152);
this.panelOptions.Name = "panelOptions";
this.panelOptions.Size = new System.Drawing.Size(424, 64);
this.panelOptions.TabIndex = 8;
//
// panelInput
//
this.panelInput.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.panelInput.Controls.Add(this.labelFind);
this.panelInput.Controls.Add(this.textFind);
this.panelInput.Controls.Add(this.labelReplace);
this.panelInput.Controls.Add(this.textReplace);
this.panelInput.Controls.Add(this.bOptions);
this.panelInput.Controls.Add(this.bReplace);
this.panelInput.Controls.Add(this.bReplaceAll);
this.panelInput.Controls.Add(this.bFindNext);
this.panelInput.Controls.Add(this.bCancel);
this.panelInput.Location = new System.Drawing.Point(16, 40);
this.panelInput.Name = "panelInput";
this.panelInput.Size = new System.Drawing.Size(424, 112);
this.panelInput.TabIndex = 9;
//
// FindReplaceForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(458, 224);
this.Controls.Add(this.panelOptions);
this.Controls.Add(this.panelInput);
this.Controls.Add(this.tabControl);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FindReplaceForm";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "Find and Replace";
this.tabControl.ResumeLayout(false);
this.panelOptions.ResumeLayout(false);
this.panelInput.ResumeLayout(false);
this.panelInput.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabPage tabFind;
private System.Windows.Forms.TabPage tabReplace;
private System.Windows.Forms.Label labelFind;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.Button bCancel;
private System.Windows.Forms.TextBox textFind;
private System.Windows.Forms.Button bFindNext;
private System.Windows.Forms.Label labelReplace;
private System.Windows.Forms.Button bReplaceAll;
private System.Windows.Forms.Button bReplace;
private System.Windows.Forms.Button bOptions;
private System.Windows.Forms.CheckBox optionMatchCase;
private System.Windows.Forms.CheckBox optionMatchWhole;
private System.Windows.Forms.TextBox textReplace;
private System.Windows.Forms.Panel panelOptions;
private System.Windows.Forms.Panel panelInput;
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BidiFlowSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Akka.IO;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
namespace Akka.Streams.Tests.Dsl
{
public class BidiFlowSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public BidiFlowSpec()
{
var settings = ActorMaterializerSettings.Create(Sys);
Materializer = ActorMaterializer.Create(Sys, settings);
}
private static BidiFlow<int, long, ByteString, string, NotUsed> Bidi()
{
return
BidiFlow.FromFlows(
Flow.Create<int>().Select(x => ((long) x) + 2).WithAttributes(Attributes.CreateName("top")),
Flow.Create<ByteString>()
.Select(x => x.DecodeString(Encoding.UTF8))
.WithAttributes(Attributes.CreateName("bottom")));
}
private static BidiFlow<long, int, string, ByteString, NotUsed> Inverse()
{
return
BidiFlow.FromFlows(
Flow.Create<long>().Select(x => ((int)x) + 2).WithAttributes(Attributes.CreateName("top")),
Flow.Create<string>()
.Select(ByteString.FromString)
.WithAttributes(Attributes.CreateName("bottom")));
}
private static BidiFlow<int, long, ByteString, string, Task<int>> BidiMaterialized()
{
return BidiFlow.FromGraph(GraphDsl.Create(Sink.First<int>(), (b, s) =>
{
b.From(Source.Single(42).MapMaterializedValue(_=>Task.FromResult(0))).To(s);
var top = b.Add(Flow.Create<int>().Select(x => ((long) x) + 2));
var bottom = b.Add(Flow.Create<ByteString>().Select(x => x.DecodeString(Encoding.UTF8)));
return new BidiShape<int,long,ByteString, string>(top.Inlet, top.Outlet, bottom.Inlet, bottom.Outlet);
}));
}
private const string String = "Hello World";
private static readonly ByteString Bytes = ByteString.FromString(String);
[Fact]
public void A_BidiFlow_must_work_top_and_bottom_in_isolation()
{
var t = RunnableGraph.FromGraph(GraphDsl.Create(Sink.First<long>(), Sink.First<string>(), Keep.Both,
(b, st, sb) =>
{
var s = b.Add(Bidi());
b.From(
Source.Single(1)
.MapMaterializedValue(_ => Tuple.Create(Task.FromResult(1L), Task.FromResult(""))))
.To(s.Inlet1);
b.From(s.Outlet1).To(st);
b.To(sb).From(s.Outlet2);
b.To(s.Inlet2)
.From(
Source.Single(Bytes)
.MapMaterializedValue(_ => Tuple.Create(Task.FromResult(1L), Task.FromResult(""))));
return ClosedShape.Instance;
})).Run(Materializer);
var top = t.Item1;
var bottom = t.Item2;
top.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
bottom.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
top.Result.Should().Be(3);
bottom.Result.Should().Be(String);
}
[Fact]
public void A_BidiFlow_must_work_as_a_Flow_that_is_open_to_the_left()
{
var f = Bidi().Join(Flow.Create<long>().Select(x => ByteString.FromString($"Hello {x}")));
var result = Source.From(Enumerable.Range(1, 3)).Via(f).Limit(10).RunWith(Sink.Seq<string>(), Materializer);
result.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
result.Result.ShouldAllBeEquivalentTo(new[] {"Hello 3", "Hello 4", "Hello 5"});
}
[Fact]
public void A_BidiFlow_must_work_as_a_Flow_that_is_open_on_the_right()
{
var f = Flow.Create<string>().Select(int.Parse).Join(Bidi());
var result =
Source.From(new[] {ByteString.FromString("1"), ByteString.FromString("2")})
.Via(f)
.Limit(10)
.RunWith(Sink.Seq<long>(), Materializer);
result.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
result.Result.ShouldAllBeEquivalentTo(new[] {3L, 4L});
}
[Fact]
public void A_BidiFlow_must_work_when_atop_its_iverse()
{
var f = Bidi().Atop(Inverse()).Join(Flow.Create<int>().Select(x => x.ToString()));
var result = Source.From(Enumerable.Range(1, 3)).Via(f).Limit(10).RunWith(Sink.Seq<string>(), Materializer);
result.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
result.Result.ShouldAllBeEquivalentTo(new[] { "5", "6", "7" });
}
[Fact]
public void A_BidiFlow_must_work_when_reversed()
{
// just reversed from the case above; observe that Flow inverts itself automatically by being on the left side
var f = Flow.Create<int>().Select(x => x.ToString()).Join(Inverse().Reversed()).Join(Bidi().Reversed());
var result = Source.From(Enumerable.Range(1, 3)).Via(f).Limit(10).RunWith(Sink.Seq<string>(), Materializer);
result.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
result.Result.ShouldAllBeEquivalentTo(new[] { "5", "6", "7" });
}
[Fact]
public void A_BidiFlow_must_materialize_its_value()
{
var f = RunnableGraph.FromGraph(GraphDsl.Create(BidiMaterialized(), (b, bidi) =>
{
var flow1 = b.Add(Flow.Create<string>().Select(int.Parse).MapMaterializedValue(_ => Task.FromResult(0)));
var flow2 =
b.Add(
Flow.Create<long>()
.Select(x => ByteString.FromString($"Hello {x}"))
.MapMaterializedValue(_ => Task.FromResult(0)));
b.AddEdge(flow1.Outlet, bidi.Inlet1);
b.AddEdge(bidi.Outlet2, flow1.Inlet);
b.AddEdge(bidi.Outlet1, flow2.Inlet);
b.AddEdge(flow2.Outlet, bidi.Inlet2);
return ClosedShape.Instance;
})).Run(Materializer);
f.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
f.Result.Should().Be(42);
}
[Fact]
public void A_BidiFlow_must_combine_materialization_values()
{
this.AssertAllStagesStopped(() =>
{
var left = Flow.FromGraph(GraphDsl.Create(Sink.First<int>(), (b, sink) =>
{
var broadcast = b.Add(new Broadcast<int>(2));
var merge = b.Add(new Merge<int>(2));
var flow = b.Add(Flow.Create<string>().Select(int.Parse));
b.From(broadcast).To(sink);
b.From(Source.Single(1).MapMaterializedValue(_ => Task.FromResult(0))).Via(broadcast).To(merge);
b.From(flow).To(merge);
return new FlowShape<string, int>(flow.Inlet, merge.Out);
}));
var right = Flow.FromGraph(GraphDsl.Create(Sink.First<List<long>>(), (b, sink) =>
{
var flow = b.Add(Flow.Create<long>().Grouped(10));
var source = b.Add(Source.Single(ByteString.FromString("10")));
b.From(flow).To(sink);
return new FlowShape<long, ByteString>(flow.Inlet, source.Outlet);
}));
var tt = left.JoinMaterialized(BidiMaterialized(), Keep.Both)
.JoinMaterialized(right, Keep.Both)
.Run(Materializer);
var t = tt.Item1;
var l = t.Item1;
var m = t.Item2;
var r = tt.Item2;
Task.WhenAll(l, m, r).Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
l.Result.Should().Be(1);
m.Result.Should().Be(42);
r.Result.ShouldAllBeEquivalentTo(new [] {3L, 12L});
}, Materializer);
}
[Fact]
public void A_BidiFlow_must_suitably_ovveride_attribute_handling_methods()
{
var b = (BidiFlow<int, long, ByteString, string, NotUsed>)
Bidi().WithAttributes(Attributes.CreateName("")).Async().Named("name");
b.Module.Attributes.GetFirstAttribute<Attributes.Name>().Value.Should().Be("name");
b.Module.Attributes.GetFirstAttribute<Attributes.AsyncBoundary>()
.Should()
.Be(Attributes.AsyncBoundary.Instance);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.Protocols.TestTools.StackSdk.Swn;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net;
namespace Microsoft.Protocols.TestSuites.FileSharing.ServerFailover.TestSuite
{
/// <summary>
/// This test class is for SWN Registration.
/// </summary>
[TestClass]
public class SWNRegistration : ServerFailoverTestBase
{
#region Variables
/// <summary>
/// SWN client to get interface list.
/// </summary>
private SwnClient swnClientForInterface;
/// <summary>
/// SWN client to witness.
/// </summary>
private SwnClient swnClientForWitness;
/// <summary>
/// The registered handle of witness.
/// </summary>
private System.IntPtr pContext;
#endregion
#region Test Suite Initialization
// Use ClassInitialize to run code before running the first test in the class
[ClassInitialize()]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
SWNTestUtility.BaseTestSite = BaseTestSite;
}
// Use ClassCleanup to run code after all tests in a class have run
[ClassCleanup()]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
#endregion
// Use TestInitialize to run code before running every test in the class
protected override void TestInitialize()
{
base.TestInitialize();
swnClientForInterface = null;
swnClientForWitness = null;
pContext = IntPtr.Zero;
}
// Use TestCleanup to run code after every test in a class have run
protected override void TestCleanup()
{
if (pContext != IntPtr.Zero)
{
if (swnClientForWitness != null)
{
swnClientForWitness.WitnessrUnRegister(pContext);
}
pContext = IntPtr.Zero;
}
try
{
if (swnClientForInterface != null)
{
swnClientForInterface.SwnUnbind(TestConfig.FailoverTimeout);
swnClientForInterface = null;
}
if (swnClientForWitness != null)
{
swnClientForWitness.SwnUnbind(TestConfig.FailoverTimeout);
swnClientForInterface = null;
}
}
catch (Exception ex)
{
BaseTestSite.Log.Add(LogEntryKind.Warning, "TestCleanup: Unexpected Exception: {0}", ex);
}
base.TestCleanup();
}
[TestMethod]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("Register with WitnessrRegister and invalid netname.")]
public void SWNRegistration_InvalidNetName()
{
SWNRegister(SwnRegisterType.InvalidNetName, SwnVersion.SWN_VERSION_1);
}
[TestMethod]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("Register with WitnessrRegister and invalid version.")]
public void SWNRegistration_InvalidVersion()
{
SWNRegister(SwnRegisterType.InvalidVersion, SwnVersion.SWN_VERSION_1);
}
[TestMethod]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("Register with WitnessrRegister and invalid IpAddress.")]
public void SWNRegistration_InvalidIpAddress()
{
SWNRegister(SwnRegisterType.InvalidIpAddress, SwnVersion.SWN_VERSION_1);
}
[TestMethod]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("Register with WitnessrRegister and Unregister the client twice.")]
public void SWNRegistration_InvalidUnRegister()
{
SWNRegister(SwnRegisterType.InvalidUnRegister, SwnVersion.SWN_VERSION_1);
}
[TestMethod]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("Assure that server responses correctly with invalid context.")]
public void SWNAsyncNotification_InvalidRequest()
{
SWNRegister(SwnRegisterType.InvalidRequest, SwnVersion.SWN_VERSION_1);
}
[TestMethod]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("Register with WitnessrRegisterEx and invalid NetName.")]
public void SWNRegistrationEx_InvalidNetName()
{
SWNRegister(SwnRegisterType.InvalidNetName, SwnVersion.SWN_VERSION_2);
}
[TestMethod]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("Register with WitnessrRegisterEx and invalid version.")]
public void SWNRegistrationEx_InvalidVersion()
{
SWNRegister(SwnRegisterType.InvalidVersion, SwnVersion.SWN_VERSION_2);
}
[TestMethod]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("Register with WitnessrRegisterEx and invalid IpAddress.")]
public void SWNRegistrationEx_InvalidIpAddress()
{
SWNRegister(SwnRegisterType.InvalidIpAddress, SwnVersion.SWN_VERSION_2);
}
[TestMethod]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("Register with WitnessrRegisterEx and Unregister the client twice.")]
public void SWNRegistrationEx_InvalidUnRegister()
{
SWNRegister(SwnRegisterType.InvalidUnRegister, SwnVersion.SWN_VERSION_2);
}
[TestMethod]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("Register with invalid sharename.")]
public void SWNRegistrationEx_InvalidShareName()
{
SWNRegister(SwnRegisterType.InvalidShareName, SwnVersion.SWN_VERSION_2);
}
[TestMethod]
[TestCategory(TestCategories.Swn)]
[TestCategory(TestCategories.Compatibility)]
[Description("Get Timeout notification on scaleout cluster server.")]
public void WitnessrRegisterEx_SWNAsyncNotification_Timeout()
{
SWNRegister(SwnRegisterType.KeepAliveTimeout, SwnVersion.SWN_VERSION_2);
}
private void SWNRegister(SwnRegisterType registerType, SwnVersion expectedVersion)
{
WITNESS_INTERFACE_INFO registerInterface;
IntPtr pDuplicateContext = IntPtr.Zero;
swnClientForInterface = new SwnClient();
swnClientForWitness = new SwnClient();
string server = TestConfig.ClusteredFileServerName;
IPAddress currentAccessIpAddr = SWNTestUtility.GetCurrentAccessIP(server);
#region Get SWN witness interface list
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Get SWN witness interface list.");
DoUntilSucceed(() => SWNTestUtility.BindServer(swnClientForInterface, currentAccessIpAddr,
TestConfig.DomainName, TestConfig.UserName, TestConfig.UserPassword, TestConfig.DefaultSecurityPackage,
TestConfig.DefaultRpceAuthenticationLevel, TestConfig.FailoverTimeout, server), TestConfig.FailoverTimeout,
"Retry BindServer until succeed within timeout span");
int ret;
WITNESS_INTERFACE_LIST interfaceList = new WITNESS_INTERFACE_LIST();
DoUntilSucceed(() =>
{
ret = swnClientForInterface.WitnessrGetInterfaceList(out interfaceList);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_SUCCESS, (SwnErrorCode)ret, "WitnessrGetInterfaceList returns with result code = 0x{0:x8}", ret);
return SWNTestUtility.VerifyInterfaceList(interfaceList, TestConfig.Platform);
}, TestConfig.FailoverTimeout, "Retry to call WitnessrGetInterfaceList until succeed within timeout span");
swnClientForInterface.SwnUnbind(TestConfig.FailoverTimeout);
swnClientForInterface = null;
SWNTestUtility.GetRegisterInterface(interfaceList, out registerInterface);
SWNTestUtility.CheckVersion(expectedVersion, (SwnVersion)registerInterface.Version);
#endregion
#region Register SWN witness
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Register SWN witness with {0}.", registerType.ToString());
DoUntilSucceed(() => SWNTestUtility.BindServer(swnClientForWitness,
(registerInterface.Flags & (uint)SwnNodeFlagsValue.IPv4) != 0 ? new IPAddress(registerInterface.IPV4) : SWNTestUtility.ConvertIPV6(registerInterface.IPV6),
TestConfig.DomainName, TestConfig.UserName, TestConfig.UserPassword, TestConfig.DefaultSecurityPackage,
TestConfig.DefaultRpceAuthenticationLevel, TestConfig.FailoverTimeout), TestConfig.FailoverTimeout,
"Retry BindServer until succeed within timeout span");
SwnVersion registerVersion;
if (SwnVersion.SWN_VERSION_2 == expectedVersion)
registerVersion = (registerType == SwnRegisterType.InvalidVersion ? SwnVersion.SWN_VERSION_1 : SwnVersion.SWN_VERSION_2);
else
registerVersion = (registerType == SwnRegisterType.InvalidVersion ? SwnVersion.SWN_VERSION_2 : SwnVersion.SWN_VERSION_1);
string registerNetName =
(registerType == SwnRegisterType.InvalidNetName ? "XXXXInvalid.contoso.comXXXX" : SWNTestUtility.GetPrincipleName(TestConfig.DomainName, server));
string accessIpAddr =
(registerType == SwnRegisterType.InvalidIpAddress ? "255.255.255.255" : currentAccessIpAddr.ToString());
string registerClientName = Guid.NewGuid().ToString();
string shareName =
(registerType == SwnRegisterType.InvalidShareName ? "XXXXInvalidShareNameXXXX" : TestConfig.ClusteredFileShare);
uint keepAliveTimout =
(registerType == SwnRegisterType.KeepAliveTimeout ? (uint)10 : (uint)120);
BaseTestSite.Log.Add(LogEntryKind.Debug, "Register witness:");
BaseTestSite.Log.Add(LogEntryKind.Debug, "\tVersion: {0:x8}", (uint)registerVersion);
BaseTestSite.Log.Add(LogEntryKind.Debug, "\tNetName: {0}", registerNetName);
BaseTestSite.Log.Add(LogEntryKind.Debug, "\tShareName: {0}", shareName);
BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIpAddress: {0}", accessIpAddr);
BaseTestSite.Log.Add(LogEntryKind.Debug, "\tClientName: {0}", registerClientName);
if (SwnVersion.SWN_VERSION_2 == expectedVersion)
{
ret = swnClientForWitness.WitnessrRegisterEx(registerVersion,
registerNetName,
shareName,
accessIpAddr,
registerClientName,
WitnessrRegisterExFlagsValue.WITNESS_REGISTER_NONE,
keepAliveTimout,
out pContext);
}
else
{
ret = swnClientForWitness.WitnessrRegister(registerVersion,
registerNetName,
accessIpAddr,
registerClientName,
out pContext);
}
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Verify server response for WitnessrRegister request.");
bool isScaleOutFsShare = ShareContainsSofs(server, Smb2Utility.GetUncPath(server, TestConfig.ClusteredFileShare));
if (registerType == SwnRegisterType.InvalidNetName)
{
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_INVALID_PARAMETER, (SwnErrorCode)ret, "WitnessrRegister returns with result code = 0x{0:x8}", ret);
}
else if (registerType == SwnRegisterType.InvalidVersion)
{
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_REVISION_MISMATCH, (SwnErrorCode)ret, "WitnessrRegister returns with result code = 0x{0:x8}", ret);
}
else if (registerType == SwnRegisterType.InvalidIpAddress)
{
if (!isScaleOutFsShare)
{
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_SUCCESS, (SwnErrorCode)ret, "WitnessrRegister returns with result code = 0x{0:x8}", ret);
}
else
{
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_INVALID_STATE, (SwnErrorCode)ret, "WitnessrRegister returns with result code = 0x{0:x8}", ret);
}
}
else if (registerType == SwnRegisterType.InvalidShareName)
{
if (!isScaleOutFsShare)
{
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_SUCCESS, (SwnErrorCode)ret, "WitnessrRegister returns with result code = 0x{0:x8}", ret);
}
else
{
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_INVALID_STATE, (SwnErrorCode)ret, "WitnessrRegister returns with result code = 0x{0:x8}", ret);
}
}
else
{
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_SUCCESS, (SwnErrorCode)ret, "WitnessrRegister returns with result code = 0x{0:x8}", ret);
}
if (registerType == SwnRegisterType.InvalidUnRegister)
{
ret = swnClientForWitness.WitnessrUnRegister(pContext);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_SUCCESS, (SwnErrorCode)ret, "WitnessrUnRegister returns with result code = 0x{0:x8}", ret);
ret = swnClientForWitness.WitnessrUnRegister(pContext);
if (TestConfig.Platform == Platform.WindowsServer2012)
{
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_NOT_FOUND, (SwnErrorCode)ret, "WitnessrUnRegister returns with result code = 0x{0:x8}", ret);
}
else
{
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_INVALID_PARAMETER, (SwnErrorCode)ret, "WitnessrUnRegister returns with result code = 0x{0:x8}", ret);
}
pContext = IntPtr.Zero;
swnClientForWitness.SwnUnbind(TestConfig.FailoverTimeout);
}
if (registerType == SwnRegisterType.InvalidRequest)
{
ret = swnClientForWitness.WitnessrUnRegister(pContext);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_SUCCESS, (SwnErrorCode)ret, "WitnessrUnRegister returns with result code = 0x{0:x8}", ret);
uint callId;
callId = swnClientForWitness.WitnessrAsyncNotify(pContext);
BaseTestSite.Assert.AreNotEqual<uint>(0, callId, "WitnessrAsyncNotify returns callId = {0}", callId);
RESP_ASYNC_NOTIFY respNotify;
ret = swnClientForWitness.ExpectWitnessrAsyncNotify(callId, out respNotify);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_NOT_FOUND, (SwnErrorCode)ret, "ExpectWitnessrAsyncNotify returns with result code = 0x{0:x8}", ret);
pContext = IntPtr.Zero;
swnClientForWitness.SwnUnbind(TestConfig.FailoverTimeout);
}
if (registerType == SwnRegisterType.KeepAliveTimeout)
{
uint callId;
callId = swnClientForWitness.WitnessrAsyncNotify(pContext);
BaseTestSite.Assert.AreNotEqual<uint>(0, callId, "WitnessrAsyncNotify returns callId = {0}", callId);
RESP_ASYNC_NOTIFY respNotify;
ret = swnClientForWitness.ExpectWitnessrAsyncNotify(callId, out respNotify);
BaseTestSite.Assert.AreEqual<SwnErrorCode>(SwnErrorCode.ERROR_TIMEOUT, (SwnErrorCode)ret, "ExpectWitnessrAsyncNotify returns with result code = 0x{0:x8}", ret);
pContext = IntPtr.Zero;
swnClientForWitness.SwnUnbind(TestConfig.FailoverTimeout);
}
#endregion
#region Cleanup
pContext = IntPtr.Zero;
swnClientForWitness.SwnUnbind(TestConfig.FailoverTimeout);
swnClientForWitness = null;
#endregion
}
/// <summary>
/// Determine if a share has shi*_type set to STYPE_CLUSTER_SOFS
/// </summary>
/// <param name="server">Server of the share</param>
/// <param name="sharePath">Path of the share</param>
/// <returns>Return true if share has shi*_type set to STYPE_CLUSTER_SOFS, otherwise return false</returns>
private bool ShareContainsSofs(string server, string sharePath)
{
Smb2FunctionalClient client = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
client.ConnectToServerOverTCP(SWNTestUtility.GetCurrentAccessIP(server));
client.Negotiate(TestConfig.RequestDialects, TestConfig.IsSMB1NegotiateEnabled);
client.SessionSetup(TestConfig.DefaultSecurityPackage, server, TestConfig.AccountCredential, false);
uint treeId;
bool ret = false;
client.TreeConnect(sharePath, out treeId,
(header, response) =>
{
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_SUCCESS,
header.Status,
"{0} should be successful.", header.Command);
ret = response.Capabilities.HasFlag(Share_Capabilities_Values.SHARE_CAP_SCALEOUT);
});
client.TreeDisconnect(treeId);
client.LogOff();
client.Disconnect();
return ret;
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace SharpScss
{
/// <summary>
/// Struct and functions of libsass used manually. All other functions/types are defined in LibSass.Generated.cs
/// </summary>
internal static partial class LibSass
{
private const string LibSassDll = "libsass";
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate Sass_Import_List sass_importer_delegate(LibSass.StringUtf8 cur_path, LibSass.Sass_Importer_Entry cb, LibSass.Sass_Compiler compiler);
public partial struct Sass_File_Context
{
public static implicit operator Sass_Context(Sass_File_Context context)
{
return new Sass_Context(context.Handle);
}
public static explicit operator Sass_File_Context(Sass_Context context)
{
return new Sass_File_Context(context.Handle);
}
}
public partial struct Sass_Data_Context
{
public static implicit operator Sass_Context(Sass_Data_Context context)
{
return new Sass_Context(context.Handle);
}
public static explicit operator Sass_Data_Context(Sass_Context context)
{
return new Sass_Data_Context(context.Handle);
}
}
public partial struct size_t
{
public size_t(int value)
{
Value = new IntPtr(value);
}
public size_t(long value)
{
Value = new IntPtr(value);
}
public static implicit operator long(size_t size)
{
return size.Value.ToInt64();
}
public static implicit operator int(size_t size)
{
return size.Value.ToInt32();
}
public static implicit operator size_t(long size)
{
return new size_t(size);
}
public static implicit operator size_t(int size)
{
return new size_t(size);
}
}
public struct StringUtf8
{
public StringUtf8(IntPtr pointer)
{
this.pointer = pointer;
}
private readonly IntPtr pointer;
public bool IsEmpty => pointer == IntPtr.Zero;
public static implicit operator string(StringUtf8 stringUtf8)
{
if (stringUtf8.pointer != IntPtr.Zero)
{
return Utf8ToString(stringUtf8.pointer);
}
return null;
}
public static unsafe implicit operator StringUtf8(string text)
{
if (text == null)
{
return new StringUtf8(IntPtr.Zero);
}
var length = Encoding.UTF8.GetByteCount(text);
var pointer = sass_alloc_memory(length+1);
fixed (char* pText = text)
Encoding.UTF8.GetBytes(pText, text.Length, (byte*) pointer, length);
((byte*)pointer)[length] = 0;
return new StringUtf8(pointer);
}
private static unsafe string Utf8ToString(IntPtr utfString)
{
var pText = (byte*)utfString;
// find the end of the string
while (*pText != 0)
{
pText++;
}
int length = (int)(pText - (byte*)utfString);
var text = Encoding.UTF8.GetString((byte*)utfString, length);
return text;
}
}
private sealed class UTF8EncodingRelaxed : UTF8Encoding
{
public new static readonly UTF8EncodingRelaxed Default = new UTF8EncodingRelaxed();
public UTF8EncodingRelaxed() : base(false, false)
{
}
}
internal abstract class SassAllocator
{
[ThreadStatic]
private static List<IntPtr> PointersToFree;
public static void FreeNative()
{
var pointersToFree = PointersToFree;
if (pointersToFree == null) return;
try
{
foreach (var pData in pointersToFree)
{
sass_free_memory(pData);
}
}
finally
{
pointersToFree.Clear();
}
}
public static void RecordFreeNative(IntPtr pNativeData)
{
if (pNativeData == IntPtr.Zero) return;
if (PointersToFree == null)
{
PointersToFree = new List<IntPtr>();
}
var pointersToFree = PointersToFree;
pointersToFree.Add(pNativeData);
}
}
private class UTF8MarshallerBase<T> : SassAllocator, ICustomMarshaler where T : Encoding, new()
{
private static readonly Encoding EncodingUsed = new T();
private readonly bool _freeNative;
protected UTF8MarshallerBase(bool freeNative)
{
_freeNative = freeNative;
}
public static unsafe string FromNative(IntPtr pNativeData)
{
var pBuffer = (byte*)pNativeData;
if (pBuffer == null) return string.Empty;
int length = 0;
while (pBuffer[length] != 0)
{
length++;
}
return EncodingUsed.GetString((byte*)pNativeData, length);
}
public static unsafe IntPtr ToNative(string text, bool strict = false)
{
if (text == null) return IntPtr.Zero;
var length = EncodingUsed.GetByteCount(text);
var pBuffer = (byte*)sass_alloc_memory(length + 1);
if (pBuffer == null) return IntPtr.Zero;
if (length > 0)
{
fixed (char* ptr = text)
{
EncodingUsed.GetBytes(ptr, text.Length, pBuffer, length);
}
}
pBuffer[length] = 0;
return new IntPtr(pBuffer);
}
public virtual object MarshalNativeToManaged(IntPtr pNativeData)
{
return FromNative(pNativeData);
}
public virtual IntPtr MarshalManagedToNative(object managedObj)
{
var text = (string)managedObj;
return ToNative(text);
}
public virtual void CleanUpNativeData(IntPtr pNativeData)
{
if (!_freeNative) return;
RecordFreeNative(pNativeData);
}
public virtual void CleanUpManagedData(object ManagedObj)
{
}
public int GetNativeDataSize()
{
return -1;
}
}
private sealed class UTF8MarshallerNoFree : UTF8MarshallerBase<UTF8EncodingRelaxed>
{
private static readonly UTF8MarshallerNoFree Instance = new UTF8MarshallerNoFree(false);
public UTF8MarshallerNoFree(bool freeNative) : base(freeNative)
{
}
public static ICustomMarshaler GetInstance(string cookie)
{
return Instance;
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using EcsRx.Entities;
using EcsRx.Extensions;
using EcsRx.Groups.Observable;
using EcsRx.MicroRx.Extensions;
using EcsRx.Tests.Models;
using EcsRx.Tests.Plugins.Computeds.Models;
using NSubstitute;
using Xunit;
namespace EcsRx.Tests.Plugins.Computeds
{
public class ComputedFromGroupTests
{
[Fact]
public void should_populate_on_creation()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = new List<IEntity> {fakeEntity2, fakeEntity3}.Average(x => x.GetHashCode());
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2, fakeEntity3};
var mockObservableGroup = Substitute.For<IObservableGroup>();
mockObservableGroup.OnEntityAdded.Returns(Observable.Empty<IEntity>());
mockObservableGroup.OnEntityRemoving.Returns(Observable.Empty<IEntity>());
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedFromGroup(mockObservableGroup);
Assert.Equal(expectedData, computedGroupData.CachedData);
}
[Fact]
public void should_refresh_when_entities_added_and_value_requested()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = fakeEntity3.GetHashCode();
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2, fakeEntity3};
var mockObservableGroup = Substitute.For<IObservableGroup>();
var addedEvent = new Subject<IEntity>();
mockObservableGroup.OnEntityAdded.Returns(addedEvent);
mockObservableGroup.OnEntityRemoving.Returns(Observable.Empty<IEntity>());
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedFromGroup(mockObservableGroup);
fakeEntities.Remove(fakeEntity2);
addedEvent.OnNext(null);
var actualData = computedGroupData.Value;
Assert.Equal(expectedData, actualData);
}
[Fact]
public void should_refresh_when_entities_removed_and_value_requested()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = fakeEntity3.GetHashCode();
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2, fakeEntity3};
var mockObservableGroup = Substitute.For<IObservableGroup>();
var removedEvent = new Subject<IEntity>();
mockObservableGroup.OnEntityAdded.Returns(Observable.Empty<IEntity>());
mockObservableGroup.OnEntityRemoving.Returns(removedEvent);
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedFromGroup(mockObservableGroup);
fakeEntities.Remove(fakeEntity2);
removedEvent.OnNext(null);
var actualData = computedGroupData.Value;
Assert.Equal(expectedData, actualData);
}
[Fact]
public void should_refresh_on_trigger_and_value_requested()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = fakeEntity3.GetHashCode();
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2, fakeEntity3};
var mockObservableGroup = Substitute.For<IObservableGroup>();
mockObservableGroup.OnEntityAdded.Returns(Observable.Empty<IEntity>());
mockObservableGroup.OnEntityRemoving.Returns(Observable.Empty<IEntity>());
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedFromGroup(mockObservableGroup);
fakeEntities.Remove(fakeEntity2);
computedGroupData.ManuallyRefresh.OnNext(true);
var actualData = computedGroupData.Value;
Assert.Equal(expectedData, actualData);
}
[Fact]
public void should_not_refresh_value_with_no_subs_and_value_requested()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = new [] { fakeEntity2.GetHashCode(), fakeEntity3.GetHashCode() }.Average();
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2, fakeEntity3};
var mockObservableGroup = Substitute.For<IObservableGroup>();
mockObservableGroup.OnEntityAdded.Returns(Observable.Empty<IEntity>());
mockObservableGroup.OnEntityRemoving.Returns(Observable.Empty<IEntity>());
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedFromGroup(mockObservableGroup);
fakeEntities.Remove(fakeEntity2);
var actualData = computedGroupData.Value;
Assert.Equal(expectedData, actualData);
}
[Fact]
public void should_not_refresh_cached_data_on_change_notified_but_no_subs_without_value_request()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2, fakeEntity3};
var mockObservableGroup = Substitute.For<IObservableGroup>();
var addingSubject = new Subject<IEntity>();
mockObservableGroup.OnEntityAdded.Returns(addingSubject);
var removingSubject = new Subject<IEntity>();
mockObservableGroup.OnEntityRemoving.Returns(removingSubject);
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedFromGroup(mockObservableGroup);
var expectedOutput = computedGroupData.CachedData;
addingSubject.OnNext(null);
removingSubject.OnNext(null);
computedGroupData.ManuallyRefresh.OnNext(true);
Assert.Equal(expectedOutput, computedGroupData.CachedData);
}
[Fact]
public void should_refresh_cached_data_on_change_notified_with_active_subs_without_value_request()
{
var fakeEntity1 = Substitute.For<IEntity>();
fakeEntity1.HasComponent<TestComponentThree>().Returns(false);
var fakeEntity2 = Substitute.For<IEntity>();
fakeEntity2.HasComponent<TestComponentThree>().Returns(true);
var fakeEntity3 = Substitute.For<IEntity>();
fakeEntity3.HasComponent<TestComponentThree>().Returns(true);
var expectedData = new [] { fakeEntity2.GetHashCode(), fakeEntity3.GetHashCode() }.Average();
var fakeEntities = new List<IEntity> {fakeEntity1, fakeEntity2, fakeEntity3};
var mockObservableGroup = Substitute.For<IObservableGroup>();
var addingSubject = new Subject<IEntity>();
mockObservableGroup.OnEntityAdded.Returns(addingSubject);
var removingSubject = new Subject<IEntity>();
mockObservableGroup.OnEntityRemoving.Returns(removingSubject);
mockObservableGroup.GetEnumerator().Returns(x => fakeEntities.GetEnumerator());
var computedGroupData = new TestComputedFromGroup(mockObservableGroup);
computedGroupData.Subscribe(x => {});
fakeEntities.Remove(fakeEntity2);
removingSubject.OnNext(null);
Assert.NotEqual(expectedData, computedGroupData.CachedData);
fakeEntities.Add(fakeEntity2);
addingSubject.OnNext(null);
Assert.Equal(expectedData, computedGroupData.CachedData);
fakeEntities.Remove(fakeEntity2);
computedGroupData.ManuallyRefresh.OnNext(true);
Assert.NotEqual(expectedData, computedGroupData.CachedData);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Text;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Mono.Addins;
using Amib.Threading;
/*****************************************************
*
* ScriptsHttpRequests
*
* Implements the llHttpRequest and http_response
* callback.
*
* Some stuff was already in LSLLongCmdHandler, and then
* there was this file with a stub class in it. So,
* I am moving some of the objects and functions out of
* LSLLongCmdHandler, such as the HttpRequestClass, the
* start and stop methods, and setting up pending and
* completed queues. These are processed in the
* LSLLongCmdHandler polling loop. Similiar to the
* XMLRPCModule, since that seems to work.
*
* //TODO
*
* This probably needs some throttling mechanism but
* it's wide open right now. This applies to both
* number of requests and data volume.
*
* Linden puts all kinds of header fields in the requests.
* Not doing any of that:
* User-Agent
* X-SecondLife-Shard
* X-SecondLife-Object-Name
* X-SecondLife-Object-Key
* X-SecondLife-Region
* X-SecondLife-Local-Position
* X-SecondLife-Local-Velocity
* X-SecondLife-Local-Rotation
* X-SecondLife-Owner-Name
* X-SecondLife-Owner-Key
*
* HTTPS support
*
* Configurable timeout?
* Configurable max response size?
* Configurable
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.HttpRequest
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HttpRequestModule")]
public class HttpRequestModule : ISharedRegionModule, IHttpRequestModule
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private object HttpListLock = new object();
private int httpTimeout = 30000;
private string m_name = "HttpScriptRequests";
private OutboundUrlFilter m_outboundUrlFilter;
private string m_proxyurl = "";
private string m_proxyexcepts = "";
// <request id, HttpRequestClass>
private Dictionary<UUID, HttpRequestClass> m_pendingRequests;
private Scene m_scene;
// private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>();
public static SmartThreadPool ThreadPool = null;
public HttpRequestModule()
{
ServicePointManager.ServerCertificateValidationCallback +=ValidateServerCertificate;
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
// If this is a web request we need to check the headers first
// We may want to ignore SSL
if (sender is HttpWebRequest)
{
HttpWebRequest Request = (HttpWebRequest)sender;
ServicePoint sp = Request.ServicePoint;
// We don't case about encryption, get out of here
if (Request.Headers.Get("NoVerifyCert") != null)
{
return true;
}
// If there was an upstream cert verification error, bail
if ((((int)sslPolicyErrors) & ~4) != 0)
return false;
// Check for policy and execute it if defined
#pragma warning disable 0618
if (ServicePointManager.CertificatePolicy != null)
{
return ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, Request, 0);
}
#pragma warning restore 0618
return true;
}
// If it's not HTTP, trust .NET to check it
if ((((int)sslPolicyErrors) & ~4) != 0)
return false;
return true;
}
#region IHttpRequestModule Members
public UUID MakeHttpRequest(string url, string parameters, string body)
{
return UUID.Zero;
}
public UUID StartHttpRequest(
uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body,
out HttpInitialRequestStatus status)
{
UUID reqID = UUID.Random();
HttpRequestClass htc = new HttpRequestClass();
// Partial implementation: support for parameter flags needed
// see http://wiki.secondlife.com/wiki/LlHTTPRequest
//
// Parameters are expected in {key, value, ... , key, value}
if (parameters != null)
{
string[] parms = parameters.ToArray();
for (int i = 0; i < parms.Length; i += 2)
{
switch (Int32.Parse(parms[i]))
{
case (int)HttpRequestConstants.HTTP_METHOD:
htc.HttpMethod = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_MIMETYPE:
htc.HttpMIMEType = parms[i + 1];
break;
case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH:
int len;
if(int.TryParse(parms[i + 1], out len))
{
if(len > HttpRequestClass.HttpBodyMaxLenMAX)
len = HttpRequestClass.HttpBodyMaxLenMAX;
else if(len < 64) //???
len = 64;
htc.HttpBodyMaxLen = len;
}
break;
case (int)HttpRequestConstants.HTTP_VERIFY_CERT:
htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0);
break;
case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE:
// TODO implement me
break;
case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER:
//Parameters are in pairs and custom header takes
//arguments in pairs so adjust for header marker.
++i;
//Maximum of 8 headers are allowed based on the
//Second Life documentation for llHTTPRequest.
for (int count = 1; count <= 8; ++count)
{
//Not enough parameters remaining for a header?
if (parms.Length - i < 2)
break;
//Have we reached the end of the list of headers?
//End is marked by a string with a single digit.
//We already know we have at least one parameter
//so it is safe to do this check at top of loop.
if (Char.IsDigit(parms[i][0]))
break;
if (htc.HttpCustomHeaders == null)
htc.HttpCustomHeaders = new List<string>();
htc.HttpCustomHeaders.Add(parms[i]);
htc.HttpCustomHeaders.Add(parms[i+1]);
i += 2;
}
break;
case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE:
htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0);
break;
}
}
}
htc.RequestModule = this;
htc.LocalID = localID;
htc.ItemID = itemID;
htc.Url = url;
htc.ReqID = reqID;
htc.HttpTimeout = httpTimeout;
htc.OutboundBody = body;
htc.ResponseHeaders = headers;
htc.proxyurl = m_proxyurl;
htc.proxyexcepts = m_proxyexcepts;
// Same number as default HttpWebRequest.MaximumAutomaticRedirections
htc.MaxRedirects = 50;
if (StartHttpRequest(htc))
{
status = HttpInitialRequestStatus.OK;
return htc.ReqID;
}
else
{
status = HttpInitialRequestStatus.DISALLOWED_BY_FILTER;
return UUID.Zero;
}
}
/// <summary>
/// Would a caller to this module be allowed to make a request to the given URL?
/// </summary>
/// <returns></returns>
public bool CheckAllowed(Uri url)
{
return m_outboundUrlFilter.CheckAllowed(url);
}
public bool StartHttpRequest(HttpRequestClass req)
{
if (!CheckAllowed(new Uri(req.Url)))
return false;
lock (HttpListLock)
{
m_pendingRequests.Add(req.ReqID, req);
}
req.Process();
return true;
}
public void StopHttpRequest(uint m_localID, UUID m_itemID)
{
if (m_pendingRequests != null)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq))
{
tmpReq.Stop();
m_pendingRequests.Remove(m_itemID);
}
}
}
}
/*
* TODO
* Not sure how important ordering is is here - the next first
* one completed in the list is returned, based soley on its list
* position, not the order in which the request was started or
* finished. I thought about setting up a queue for this, but
* it will need some refactoring and this works 'enough' right now
*/
public IServiceRequest GetNextCompletedRequest()
{
lock (HttpListLock)
{
foreach (UUID luid in m_pendingRequests.Keys)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(luid, out tmpReq))
{
if (tmpReq.Finished)
{
return tmpReq;
}
}
}
}
return null;
}
public void RemoveCompletedRequest(UUID id)
{
lock (HttpListLock)
{
HttpRequestClass tmpReq;
if (m_pendingRequests.TryGetValue(id, out tmpReq))
{
tmpReq.Stop();
tmpReq = null;
m_pendingRequests.Remove(id);
}
}
}
#endregion
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
HttpRequestClass.HttpBodyMaxLenMAX = config.Configs["Network"].GetInt("HttpBodyMaxLenMAX", 16384);
m_outboundUrlFilter = new OutboundUrlFilter("Script HTTP request module", config);
int maxThreads = 15;
IConfig httpConfig = config.Configs["HttpRequestModule"];
if (httpConfig != null)
{
maxThreads = httpConfig.GetInt("MaxPoolThreads", maxThreads);
}
m_pendingRequests = new Dictionary<UUID, HttpRequestClass>();
// First instance sets this up for all sims
if (ThreadPool == null)
{
STPStartInfo startInfo = new STPStartInfo();
startInfo.IdleTimeout = 20000;
startInfo.MaxWorkerThreads = maxThreads;
startInfo.MinWorkerThreads = 1;
startInfo.ThreadPriority = ThreadPriority.BelowNormal;
startInfo.StartSuspended = true;
startInfo.ThreadPoolName = "ScriptsHttpReq";
ThreadPool = new SmartThreadPool(startInfo);
ThreadPool.Start();
}
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IHttpRequestModule>(this);
}
public void RemoveRegion(Scene scene)
{
scene.UnregisterModuleInterface<IHttpRequestModule>(this);
if (scene == m_scene)
m_scene = null;
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
}
public class HttpRequestClass : IServiceRequest
{
// Constants for parameters
// public const int HTTP_BODY_MAXLENGTH = 2;
// public const int HTTP_METHOD = 0;
// public const int HTTP_MIMETYPE = 1;
// public const int HTTP_VERIFY_CERT = 3;
// public const int HTTP_VERBOSE_THROTTLE = 4;
// public const int HTTP_CUSTOM_HEADER = 5;
// public const int HTTP_PRAGMA_NO_CACHE = 6;
/// <summary>
/// Module that made this request.
/// </summary>
public HttpRequestModule RequestModule { get; set; }
private bool _finished;
public bool Finished
{
get { return _finished; }
}
public static int HttpBodyMaxLenMAX = 16384;
// Parameter members and default values
public int HttpBodyMaxLen = 2048;
public string HttpMethod = "GET";
public string HttpMIMEType = "text/plain;charset=utf-8";
public int HttpTimeout;
public bool HttpVerifyCert = true;
public IWorkItemResult WorkItem = null;
//public bool HttpVerboseThrottle = true; // not implemented
public List<string> HttpCustomHeaders = null;
public bool HttpPragmaNoCache = true;
// Request info
private UUID _itemID;
public UUID ItemID
{
get { return _itemID; }
set { _itemID = value; }
}
private uint _localID;
public uint LocalID
{
get { return _localID; }
set { _localID = value; }
}
public DateTime Next;
public string proxyurl;
public string proxyexcepts;
/// <summary>
/// Number of HTTP redirects that this request has been through.
/// </summary>
public int Redirects { get; private set; }
/// <summary>
/// Maximum number of HTTP redirects allowed for this request.
/// </summary>
public int MaxRedirects { get; set; }
public string OutboundBody;
private UUID _reqID;
public UUID ReqID
{
get { return _reqID; }
set { _reqID = value; }
}
public HttpWebRequest Request;
public string ResponseBody;
public List<string> ResponseMetadata;
public Dictionary<string, string> ResponseHeaders;
public int Status;
public string Url;
public void Process()
{
_finished = false;
lock (HttpRequestModule.ThreadPool)
WorkItem = HttpRequestModule.ThreadPool.QueueWorkItem(new WorkItemCallback(StpSendWrapper), null);
}
private object StpSendWrapper(object o)
{
SendRequest();
return null;
}
/*
* TODO: More work on the response codes. Right now
* returning 200 for success or 499 for exception
*/
public void SendRequest()
{
HttpWebResponse response = null;
Stream resStream = null;
byte[] buf = new byte[HttpBodyMaxLenMAX + 16];
string tempString = null;
int count = 0;
try
{
Request = (HttpWebRequest)WebRequest.Create(Url);
Request.AllowAutoRedirect = false;
//This works around some buggy HTTP Servers like Lighttpd
Request.ServicePoint.Expect100Continue = false;
Request.Method = HttpMethod;
Request.ContentType = HttpMIMEType;
if (!HttpVerifyCert)
{
// We could hijack Connection Group Name to identify
// a desired security exception. But at the moment we'll use a dummy header instead.
Request.Headers.Add("NoVerifyCert", "true");
}
// else
// {
// Request.ConnectionGroupName="Verify";
// }
if (!HttpPragmaNoCache)
{
Request.Headers.Add("Pragma", "no-cache");
}
if (HttpCustomHeaders != null)
{
for (int i = 0; i < HttpCustomHeaders.Count; i += 2)
Request.Headers.Add(HttpCustomHeaders[i],
HttpCustomHeaders[i+1]);
}
if (!string.IsNullOrEmpty(proxyurl))
{
if (!string.IsNullOrEmpty(proxyexcepts))
{
string[] elist = proxyexcepts.Split(';');
Request.Proxy = new WebProxy(proxyurl, true, elist);
}
else
{
Request.Proxy = new WebProxy(proxyurl, true);
}
}
foreach (KeyValuePair<string, string> entry in ResponseHeaders)
if (entry.Key.ToLower().Equals("user-agent"))
Request.UserAgent = entry.Value;
else
Request.Headers[entry.Key] = entry.Value;
// Encode outbound data
if (!string.IsNullOrEmpty(OutboundBody))
{
byte[] data = Util.UTF8.GetBytes(OutboundBody);
Request.ContentLength = data.Length;
using (Stream bstream = Request.GetRequestStream())
bstream.Write(data, 0, data.Length);
}
Request.Timeout = HttpTimeout;
try
{
// execute the request
response = (HttpWebResponse) Request.GetResponse();
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.ProtocolError)
{
throw;
}
response = (HttpWebResponse)e.Response;
}
Status = (int)response.StatusCode;
resStream = response.GetResponseStream();
int totalBodyBytes = 0;
int maxBytes = HttpBodyMaxLen;
if(maxBytes > buf.Length)
maxBytes = buf.Length;
// we need to read all allowed or UFT8 conversion may fail
do
{
// fill the buffer with data
count = resStream.Read(buf, totalBodyBytes, maxBytes - totalBodyBytes);
totalBodyBytes += count;
if (totalBodyBytes >= maxBytes)
break;
} while (count > 0); // any more data to read?
if(totalBodyBytes > 0)
{
tempString = Util.UTF8.GetString(buf, 0, totalBodyBytes);
ResponseBody = tempString.Replace("\r", "");
}
else
ResponseBody = "";
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse webRsp = (HttpWebResponse)((WebException)e).Response;
Status = (int)webRsp.StatusCode;
try
{
using (Stream responseStream = webRsp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
ResponseBody = reader.ReadToEnd();
}
}
catch
{
ResponseBody = webRsp.StatusDescription;
}
}
else
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = e.Message;
}
if (ResponseBody == null)
ResponseBody = String.Empty;
_finished = true;
return;
}
catch (Exception e)
{
// Don't crash on anything else
}
finally
{
if (resStream != null)
resStream.Close();
if (response != null)
response.Close();
// We need to resubmit
if (
(Status == (int)HttpStatusCode.MovedPermanently
|| Status == (int)HttpStatusCode.Found
|| Status == (int)HttpStatusCode.SeeOther
|| Status == (int)HttpStatusCode.TemporaryRedirect))
{
if (Redirects >= MaxRedirects)
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "Number of redirects exceeded max redirects";
_finished = true;
}
else
{
string location = response.Headers["Location"];
if (location == null)
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "HTTP redirect code but no location header";
_finished = true;
}
else if (!RequestModule.CheckAllowed(new Uri(location)))
{
Status = (int)OSHttpStatusCode.ClientErrorJoker;
ResponseBody = "URL from HTTP redirect blocked: " + location;
_finished = true;
}
else
{
Status = 0;
Url = response.Headers["Location"];
Redirects++;
ResponseBody = null;
// m_log.DebugFormat("Redirecting to [{0}]", Url);
Process();
}
}
}
else
{
_finished = true;
}
}
if (ResponseBody == null)
ResponseBody = String.Empty;
_finished = true;
}
public void Stop()
{
try
{
if (!WorkItem.Cancel())
{
WorkItem.Cancel(true);
}
}
catch (Exception)
{
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DZ.Tools
{
/// <summary>
/// Comaprison report that contains structured information about tags comparison
/// </summary>
/// <typeparam name="TType"></typeparam>
public class ComparisonReport<TType>
{
private const string _IntFormat = "0000000";
private const string _DoubleFormat = "0.00000";
private readonly List<TType> _valuesSet;
/// <summary>
/// Undefined tag type value
/// </summary>
public readonly TType Undefined;
/// <summary>
/// Creates new comparison report
/// </summary>
public ComparisonReport(
List<Match<TType>> matches,
List<Mismatch<TType>> mismatch,
List<Tag<TType>> retrieved,
List<Tag<TType>> relevant,
List<TType> valuesSet,
TType undefined)
{
_valuesSet = valuesSet;
Undefined = undefined;
Retrieved = Fill(() => new List<Tag<TType>>(), retrieved);
Spread(Retrieved);
Relevant = Fill(() => new List<Tag<TType>>(), relevant);
Spread(Relevant);
Matches = Fill(() => new List<Match<TType>>(), matches);
Spread(Matches);
Mismatches = Fill(() => new List<Mismatch<TType>>(), new List<Mismatch<TType>>());
Spread(Mismatches, mismatch);
Statistics = Fill(() => new PrecRecall(), new PrecRecall());
Fill(Statistics);
}
/// <summary>
/// Per type Prec/Recall/F1 collection
/// </summary>
public Dictionary<TType, PrecRecall> Statistics { get; private set; }
/// <summary>
/// Per type retrieved tags
/// </summary>
public Dictionary<TType, List<Tag<TType>>> Retrieved { get; private set; }
/// <summary>
/// Per type relevant tags
/// </summary>
public Dictionary<TType, List<Tag<TType>>> Relevant { get; private set; }
/// <summary>
/// Per type matches
/// </summary>
public Dictionary<TType, List<Match<TType>>> Matches { get; private set; }
/// <summary>
/// Per expected type Mismatches
/// </summary>
public Dictionary<TType, List<Mismatch<TType>>> Mismatches { get; private set; }
private Dictionary<TType, T> Fill<T>(Func<T> creator, T undefinedValue)
{
var target = new Dictionary<TType, T>();
for (var i = 0; i < _valuesSet.Count; i++)
{
var v = _valuesSet[i];
if (!v.Equals(Undefined))
{
target[_valuesSet[i]] = creator();
}
else
{
target[v] = undefinedValue;
}
}
return target;
}
/// <summary>
/// Renders report to string
/// </summary>
/// <returns></returns>
public string Render(int maxWidth = 10)
{
var res = new StringBuilder();
AppendConfusionMatrix(res, maxWidth);
res.Append("===================FMeasure:..............")
.AppendLine(Statistics[Undefined].FMeasure.ToString(_DoubleFormat));
Append(res, Statistics, s => s.FMeasure, maxWidth);
res.Append("==================Precision:..............")
.AppendLine(Statistics[Undefined].Precision.ToString(_DoubleFormat));
Append(res, Statistics, s => s.Precision, maxWidth);
res.Append("=====================Recall:..............")
.AppendLine(Statistics[Undefined].Recall.ToString(_DoubleFormat));
Append(res, Statistics, s => s.Recall, maxWidth);
res.Append("==============Matches count:..............")
.AppendLine(Matches[Undefined].Count.ToString(_IntFormat));
Append(res, Matches, maxWidth);
res.Append("============Retrieved count:..............")
.AppendLine(Retrieved[Undefined].Count.ToString(_IntFormat));
Append(res, Retrieved, maxWidth);
res.Append("=============Relevant count:..............")
.AppendLine(Relevant[Undefined].Count.ToString(_IntFormat));
Append(res, Relevant, maxWidth);
res.Append("===========Mismatches count:..............")
.AppendLine(Mismatches.Sum(p => p.Value.Count).ToString(_IntFormat));
Append(res, Mismatches, maxWidth, true);
return res.ToString();
}
private void Append<T>(StringBuilder res, Dictionary<TType, T> source, Func<T, double> selector, int maxWidth)
{
foreach (var pair in source)
{
if (!pair.Key.Equals(Undefined))
{
res
.Append("*****************")
.Append(StringValue(pair.Key.ToString(), maxWidth))
.Append(":..............")
.AppendLine(selector(pair.Value).ToString(_DoubleFormat));
}
}
}
private void Append<T>(StringBuilder res, Dictionary<TType, List<T>> source, int maxWidth, bool appendUndefined = false)
{
foreach (var pair in source)
{
if (appendUndefined || !pair.Key.Equals(Undefined))
{
res
.Append("*****************")
.Append(StringValue(pair.Key.ToString(), maxWidth))
.Append(":..............")
.AppendLine(pair.Value.Count.ToString(_IntFormat));
}
}
}
private void Fill(Dictionary<TType, PrecRecall> statistics)
{
foreach (var pair in statistics)
{
statistics[pair.Key].Precision = Score(Matches[pair.Key]) /
(Convert.ToDouble(Retrieved[pair.Key].Count) + double.Epsilon);
statistics[pair.Key].Recall = Score(Matches[pair.Key]) /
(Convert.ToDouble(Relevant[pair.Key].Count) + double.Epsilon);
statistics[pair.Key].FMeasure = FMeasure(pair.Value);
}
}
private static double FMeasure(PrecRecall data)
{
return (2 * data.Recall * data.Precision + double.Epsilon) / (data.Recall + data.Precision + double.Epsilon);
}
private void Spread(Dictionary<TType, List<Mismatch<TType>>> dict, List<Mismatch<TType>> errors)
{
foreach (var entity in errors)
{
dict[entity.ExpectedType].Add(entity);
}
}
private void Spread(Dictionary<TType, List<Tag<TType>>> dict)
{
foreach (var entity in dict[Undefined])
{
dict[entity.Type].Add(entity);
}
}
private void Spread(Dictionary<TType, List<Match<TType>>> dict)
{
foreach (var entity in dict[Undefined])
{
dict[entity.Actual.Tag.Type].Add(entity);
}
}
private double Score(List<Match<TType>> list) { return list.Sum(m => m.Actual.Score) + double.Epsilon; }
private void AppendConfusionMatrix(StringBuilder table, int maxWidth)
{
//preparing columns: First is undefined (fake column for names), then <v1> <v2> ...
var colls = _valuesSet.Where(v => !v.Equals(Undefined)).ToList();
colls.Insert(0, Undefined);
colls.Add(Undefined);
//peparing rows: last one is undefined for all non-categorized mismatches
var rows = _valuesSet.Where(v => !v.Equals(Undefined)).ToList();
rows.Add(Undefined);
for (var i = 0; i < colls.Count; i++)
{
table.Append(i != 0 ? CellValue(colls[i].ToString(), maxWidth) : CellValue(@"Act\Exp", maxWidth));
}
table.AppendLine();
for (var i = 0; i < rows.Count; i++)
{
var type = rows[i];
for (var j = 0; j < colls.Count; j++)
{
var coll = colls[j];
if (j != 0)
{
table.Append(
coll.Equals(type)
? CellValue(Matches[coll].Count.ToString(), maxWidth)
: CellValue(Mismatches[coll].Count(e => e.ActualType.Equals(type)).ToString(), maxWidth));
}
else
{
table.Append(CellValue(type.ToString(), maxWidth));
}
}
table.AppendLine();
}
for (var j = 0; j < colls.Count; j++)
{
var coll = colls[j];
table.Append(j != 0 ? CellValue(Mismatches[coll].Count.ToString(), maxWidth) : CellValue("All", maxWidth));
}
table.AppendLine();
}
private static string CellValue(string content, int maxWidth)
{
return Const.SpaceS + StringValue(content, maxWidth) + Const.SpaceS;
}
private static string StringValue(string content, int maxWidth)
{
if (content.Length >= maxWidth)
{
return content.Substring(0, maxWidth);
}
var len = content.Length;
for (var i = 0; i < maxWidth - len; i++)
{
content = Const.SpaceS + content;
}
return content;
}
}
/// <summary>
/// Prec/Recall/F1 container
/// </summary>
public class PrecRecall
{
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Object" /> class.
/// </summary>
public PrecRecall()
{
Precision = double.Epsilon;
Recall = double.Epsilon;
FMeasure = double.Epsilon;
}
/// <summary>
/// Precision
/// </summary>
public double Precision { get; set; }
/// <summary>
/// Recall
/// </summary>
public double Recall { get; set; }
/// <summary>
/// F1 measure
/// </summary>
public double FMeasure { get; set; }
}
}
| |
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Internal
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Events;
using Exceptions;
using log4net;
using Magnum.InterfaceExtensions;
using Magnum.Pipeline;
using Magnum.Reflection;
public class ServiceBusReceiveContext
{
private static readonly ILog _log = LogManager.GetLogger(typeof (ServiceBusReceiveContext));
private readonly Stopwatch _receiveTime;
private readonly Stopwatch _consumeTime;
private readonly IServiceBus _bus;
private readonly IObjectBuilder _objectBuilder;
private readonly Pipe _eventAggregator;
private IEnumerator<Action<object>> _consumers;
private int _consumeCount;
private bool _receiveNotified;
private bool _consumeNotified;
private readonly TimeSpan _receiveTimeout;
public ServiceBusReceiveContext(IServiceBus bus, IObjectBuilder objectBuilder, Pipe eventAggregator, TimeSpan receiveTimeout)
{
_bus = bus;
_receiveTimeout = receiveTimeout;
_objectBuilder = objectBuilder;
_eventAggregator = eventAggregator;
_receiveTime = new Stopwatch();
_consumeTime = new Stopwatch();
_consumeCount = 0;
}
public void ReceiveFromEndpoint()
{
try
{
if(_log.IsDebugEnabled)
_log.DebugFormat("Calling Receive on {0} from thread {1} ({2})", _bus.Endpoint.Uri,
Thread.CurrentThread.ManagedThreadId, _receiveTimeout);
_receiveTime.Start();
_bus.Endpoint.Receive(message =>
{
if (_log.IsDebugEnabled)
_log.DebugFormat("Enumerating pipeline on {0} from thread {1}", _bus.Endpoint.Uri,
Thread.CurrentThread.ManagedThreadId);
InboundMessageHeaders.SetCurrent(context =>
{
context.ReceivedOn(_bus);
context.SetObjectBuilder(_objectBuilder);
context.ReceivedAs(message);
});
IEnumerable<Action<object>> enumerable = _bus.InboundPipeline.Enumerate(message);
_consumers = enumerable.GetEnumerator();
if (!_consumers.MoveNext())
{
_consumers.Dispose();
return null;
}
return DeliverMessageToConsumers;
}, _receiveTimeout);
}
catch (Exception ex)
{
_log.Error("Consumer Exception Exposed", ex);
}
finally
{
NotifyReceiveCompleted();
NotifyConsumeCompleted();
}
}
public void DeliverMessageToConsumers(object message)
{
try
{
NotifyReceiveCompleted();
_receiveTime.Stop();
_consumeTime.Start();
if (_log.IsDebugEnabled)
_log.DebugFormat("Dispatching message on {0} from thread {1}", _bus.Endpoint.Uri, Thread.CurrentThread.ManagedThreadId);
bool atLeastOneConsumerFailed = false;
Exception lastException = null;
do
{
try
{
_consumers.Current(message);
_consumeCount++;
}
catch (Exception ex)
{
_log.Error(string.Format("'{0}' threw an exception consuming message '{1}'",
_consumers.Current.GetType().FullName,
message.GetType().FullName), ex);
atLeastOneConsumerFailed = true;
lastException = ex;
CreateAndPublishFault(message, ex);
}
} while (_consumers.MoveNext());
if (atLeastOneConsumerFailed)
{
throw new MessageException(message.GetType(),
"At least one consumer threw an exception",
lastException);
}
}
finally
{
_consumeTime.Stop();
_consumers.Dispose();
_consumers = null;
ReportConsumerTime(message.GetType(), _receiveTime.Elapsed, _consumeTime.Elapsed);
ReportConsumerCount(message.GetType(), _consumeCount);
}
}
private void CreateAndPublishFault(object message, Exception ex)
{
if (message.Implements(typeof (CorrelatedBy<>)))
this.FastInvoke("PublishFault", FastActivator.Create(typeof (Fault<,>), message, ex));
else
this.FastInvoke("PublishFault", FastActivator.Create(typeof (Fault<>), message, ex));
}
// this is called via reflection
// ReSharper disable UnusedMember.Local
private void PublishFault<T>(T message) where T : class
// ReSharper restore UnusedMember.Local
{
CurrentMessage.GenerateFault(message);
}
private void ReportConsumerTime(Type messageType, TimeSpan receiveTime, TimeSpan consumeTime)
{
var message = new MessageReceived
{
MessageType = messageType,
ReceiveDuration = receiveTime,
ConsumeDuration = consumeTime,
};
_eventAggregator.Send(message);
}
private void ReportConsumerCount(Type messageType, int count)
{
var message = new MessageConsumed
{
MessageType = messageType,
ConsumeCount = count,
};
_eventAggregator.Send(message);
}
private void NotifyReceiveCompleted()
{
if(_receiveNotified)
return;
_eventAggregator.Send(new ReceiveCompleted());
_receiveNotified = true;
}
private void NotifyConsumeCompleted()
{
if(_consumeNotified)
return;
_eventAggregator.Send(new ConsumeCompleted());
_consumeNotified = true;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Data;
using System.Reflection;
using System.Collections.Generic;
using log4net;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// An asset storage interface for the SQLite database system
/// </summary>
public class SQLiteAssetData : AssetDataBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const string SelectAssetSQL = "select * from assets where UUID=:UUID";
private const string SelectAssetMetadataSQL = "select Name, Description, Type, Temporary, asset_flags, UUID, CreatorID from assets limit :start, :count";
private const string DeleteAssetSQL = "delete from assets where UUID=:UUID";
private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, Local, Temporary, asset_flags, CreatorID, Data) values(:UUID, :Name, :Description, :Type, :Local, :Temporary, :Flags, :CreatorID, :Data)";
private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, asset_flags=:Flags, CreatorID=:CreatorID, Data=:Data where UUID=:UUID";
private const string assetSelect = "select * from assets";
private SqliteConnection m_conn;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
override public void Dispose()
{
if (m_conn != null)
{
m_conn.Close();
m_conn = null;
}
}
/// <summary>
/// <list type="bullet">
/// <item>Initialises AssetData interface</item>
/// <item>Loads and initialises a new SQLite connection and maintains it.</item>
/// <item>use default URI if connect string is empty.</item>
/// </list>
/// </summary>
/// <param name="dbconnect">connect string</param>
override public void Initialise(string dbconnect)
{
if (Util.IsWindows())
Util.LoadArchSpecificWindowsDll("sqlite3.dll");
if (dbconnect == string.Empty)
{
dbconnect = "URI=file:Asset.db,version=3";
}
m_conn = new SqliteConnection(dbconnect);
m_conn.Open();
Migration m = new Migration(m_conn, Assembly, "AssetStore");
m.Update();
return;
}
/// <summary>
/// Fetch Asset
/// </summary>
/// <param name="uuid">UUID of ... ?</param>
/// <returns>Asset base</returns>
override public AssetBase GetAsset(UUID uuid)
{
lock (this)
{
using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString()));
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
AssetBase asset = buildAsset(reader);
reader.Close();
return asset;
}
else
{
reader.Close();
return null;
}
}
}
}
}
/// <summary>
/// Create an asset
/// </summary>
/// <param name="asset">Asset Base</param>
override public void StoreAsset(AssetBase asset)
{
string assetName = asset.Name;
if (asset.Name.Length > 64)
{
assetName = asset.Name.Substring(0, 64);
m_log.WarnFormat(
"[ASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Name, asset.ID, asset.Name.Length, assetName.Length);
}
string assetDescription = asset.Description;
if (asset.Description.Length > 64)
{
assetDescription = asset.Description.Substring(0, 64);
m_log.WarnFormat(
"[ASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add",
asset.Description, asset.ID, asset.Description.Length, assetDescription.Length);
}
//m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID.ToString());
if (ExistsAsset(asset.FullID))
{
//LogAssetLoad(asset);
lock (this)
{
using (SqliteCommand cmd = new SqliteCommand(UpdateAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":Name", assetName));
cmd.Parameters.Add(new SqliteParameter(":Description", assetDescription));
cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags));
cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID));
cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data));
cmd.ExecuteNonQuery();
}
}
}
else
{
lock (this)
{
using (SqliteCommand cmd = new SqliteCommand(InsertAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":Name", assetName));
cmd.Parameters.Add(new SqliteParameter(":Description", assetDescription));
cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SqliteParameter(":Flags", asset.Flags));
cmd.Parameters.Add(new SqliteParameter(":CreatorID", asset.Metadata.CreatorID));
cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data));
cmd.ExecuteNonQuery();
}
}
}
}
// /// <summary>
// /// Some... logging functionnality
// /// </summary>
// /// <param name="asset"></param>
// private static void LogAssetLoad(AssetBase asset)
// {
// string temporary = asset.Temporary ? "Temporary" : "Stored";
// string local = asset.Local ? "Local" : "Remote";
//
// int assetLength = (asset.Data != null) ? asset.Data.Length : 0;
//
// m_log.Debug("[ASSET DB]: " +
// string.Format("Loaded {5} {4} Asset: [{0}][{3}] \"{1}\":{2} ({6} bytes)",
// asset.FullID, asset.Name, asset.Description, asset.Type,
// temporary, local, assetLength));
// }
/// <summary>
/// Check if an asset exist in database
/// </summary>
/// <param name="uuid">The asset UUID</param>
/// <returns>True if exist, or false.</returns>
override public bool ExistsAsset(UUID uuid)
{
lock (this)
{
using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString()));
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
reader.Close();
return true;
}
else
{
reader.Close();
return false;
}
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
private static AssetBase buildAsset(IDataReader row)
{
// TODO: this doesn't work yet because something more
// interesting has to be done to actually get these values
// back out. Not enough time to figure it out yet.
AssetBase asset = new AssetBase(
new UUID((String)row["UUID"]),
(String)row["Name"],
Convert.ToSByte(row["Type"]),
(String)row["CreatorID"]
);
asset.Description = (String) row["Description"];
asset.Local = Convert.ToBoolean(row["Local"]);
asset.Temporary = Convert.ToBoolean(row["Temporary"]);
asset.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]);
asset.Data = (byte[])row["Data"];
return asset;
}
private static AssetMetadata buildAssetMetadata(IDataReader row)
{
AssetMetadata metadata = new AssetMetadata();
metadata.FullID = new UUID((string) row["UUID"]);
metadata.Name = (string) row["Name"];
metadata.Description = (string) row["Description"];
metadata.Type = Convert.ToSByte(row["Type"]);
metadata.Temporary = Convert.ToBoolean(row["Temporary"]); // Not sure if this is correct.
metadata.Flags = (AssetFlags)Convert.ToInt32(row["asset_flags"]);
metadata.CreatorID = row["CreatorID"].ToString();
// Current SHA1s are not stored/computed.
metadata.SHA1 = new byte[] {};
return metadata;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
lock (this)
{
using (SqliteCommand cmd = new SqliteCommand(SelectAssetMetadataSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":start", start));
cmd.Parameters.Add(new SqliteParameter(":count", count));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
AssetMetadata metadata = buildAssetMetadata(reader);
retList.Add(metadata);
}
}
}
}
return retList;
}
/***********************************************************************
*
* Database Binding functions
*
* These will be db specific due to typing, and minor differences
* in databases.
*
**********************************************************************/
#region IPlugin interface
/// <summary>
///
/// </summary>
override public string Version
{
get
{
Module module = GetType().Module;
// string dllName = module.Assembly.ManifestModule.Name;
Version dllVersion = module.Assembly.GetName().Version;
return
string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
dllVersion.Revision);
}
}
/// <summary>
/// Initialise the AssetData interface using default URI
/// </summary>
override public void Initialise()
{
Initialise("URI=file:Asset.db,version=3");
}
/// <summary>
/// Name of this DB provider
/// </summary>
override public string Name
{
get { return "SQLite Asset storage engine"; }
}
// TODO: (AlexRa): one of these is to be removed eventually (?)
/// <summary>
/// Delete an asset from database
/// </summary>
/// <param name="uuid"></param>
public bool DeleteAsset(UUID uuid)
{
lock (this)
{
using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString()));
cmd.ExecuteNonQuery();
}
}
return true;
}
public override bool Delete(string id)
{
UUID assetID;
if (!UUID.TryParse(id, out assetID))
return false;
return DeleteAsset(assetID);
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Compute
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Compute.Closure;
using Apache.Ignite.Core.Impl.Unmanaged;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Compute implementation.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
internal class ComputeImpl : PlatformTarget
{
/** */
private const int OpAffinity = 1;
/** */
private const int OpBroadcast = 2;
/** */
private const int OpExec = 3;
/** */
private const int OpExecAsync = 4;
/** */
private const int OpUnicast = 5;
/** Underlying projection. */
private readonly ClusterGroupImpl _prj;
/** Whether objects must be kept in binary form. */
private readonly ThreadLocal<bool> _keepBinary = new ThreadLocal<bool>(() => false);
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="prj">Projection.</param>
/// <param name="keepBinary">Binary flag.</param>
public ComputeImpl(IUnmanagedTarget target, Marshaller marsh, ClusterGroupImpl prj, bool keepBinary)
: base(target, marsh)
{
_prj = prj;
_keepBinary.Value = keepBinary;
}
/// <summary>
/// Grid projection to which this compute instance belongs.
/// </summary>
public IClusterGroup ClusterGroup
{
get
{
return _prj;
}
}
/// <summary>
/// Sets no-failover flag for the next executed task on this projection in the current thread.
/// If flag is set, job will be never failed over even if remote node crashes or rejects execution.
/// When task starts execution, the no-failover flag is reset, so all other task will use default
/// failover policy, unless this flag is set again.
/// </summary>
public void WithNoFailover()
{
UU.ComputeWithNoFailover(Target);
}
/// <summary>
/// Sets task timeout for the next executed task on this projection in the current thread.
/// When task starts execution, the timeout is reset, so one timeout is used only once.
/// </summary>
/// <param name="timeout">Computation timeout in milliseconds.</param>
public void WithTimeout(long timeout)
{
UU.ComputeWithTimeout(Target, timeout);
}
/// <summary>
/// Sets keep-binary flag for the next executed Java task on this projection in the current
/// thread so that task argument passed to Java and returned task results will not be
/// deserialized.
/// </summary>
public void WithKeepBinary()
{
_keepBinary.Value = true;
}
/// <summary>
/// Executes given Java task on the grid projection. If task for given name has not been deployed yet,
/// then 'taskName' will be used as task class name to auto-deploy the task.
/// </summary>
public TReduceRes ExecuteJavaTask<TReduceRes>(string taskName, object taskArg)
{
IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName");
ICollection<IClusterNode> nodes = _prj.Predicate == null ? null : _prj.GetNodes();
try
{
TReduceRes res = DoOutInOp<TReduceRes>(OpExec, writer =>
{
WriteTask(writer, taskName, taskArg, nodes);
});
return res;
}
finally
{
_keepBinary.Value = false;
}
}
/// <summary>
/// Executes given Java task asynchronously on the grid projection.
/// If task for given name has not been deployed yet,
/// then 'taskName' will be used as task class name to auto-deploy the task.
/// </summary>
public Future<TReduceRes> ExecuteJavaTaskAsync<TReduceRes>(string taskName, object taskArg)
{
IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName");
ICollection<IClusterNode> nodes = _prj.Predicate == null ? null : _prj.GetNodes();
try
{
Future<TReduceRes> fut = null;
DoOutInOp(OpExecAsync, writer =>
{
WriteTask(writer, taskName, taskArg, nodes);
}, input =>
{
fut = GetFuture<TReduceRes>((futId, futTyp) => UU.TargetListenFuture(Target, futId, futTyp), _keepBinary.Value);
});
return fut;
}
finally
{
_keepBinary.Value = false;
}
}
/// <summary>
/// Executes given task on the grid projection. For step-by-step explanation of task execution process
/// refer to <see cref="IComputeTask{A,T,R}"/> documentation.
/// </summary>
/// <param name="task">Task to execute.</param>
/// <param name="taskArg">Optional task argument.</param>
/// <returns>Task result.</returns>
public Future<TReduceRes> Execute<TArg, TJobRes, TReduceRes>(IComputeTask<TArg, TJobRes, TReduceRes> task,
TArg taskArg)
{
IgniteArgumentCheck.NotNull(task, "task");
var holder = new ComputeTaskHolder<TArg, TJobRes, TReduceRes>((Ignite) _prj.Ignite, this, task, taskArg);
long ptr = Marshaller.Ignite.HandleRegistry.Allocate(holder);
UU.ComputeExecuteNative(Target, ptr, _prj.TopologyVersion);
return holder.Future;
}
/// <summary>
/// Executes given task on the grid projection. For step-by-step explanation of task execution process
/// refer to <see cref="IComputeTask{A,T,R}"/> documentation.
/// </summary>
/// <param name="taskType">Task type.</param>
/// <param name="taskArg">Optional task argument.</param>
/// <returns>Task result.</returns>
public Future<TReduceRes> Execute<TArg, TJobRes, TReduceRes>(Type taskType, TArg taskArg)
{
IgniteArgumentCheck.NotNull(taskType, "taskType");
object task = FormatterServices.GetUninitializedObject(taskType);
var task0 = task as IComputeTask<TArg, TJobRes, TReduceRes>;
if (task0 == null)
throw new IgniteException("Task type doesn't implement IComputeTask: " + taskType.Name);
return Execute(task0, taskArg);
}
/// <summary>
/// Executes provided job on a node in this grid projection. The result of the
/// job execution is returned from the result closure.
/// </summary>
/// <param name="clo">Job to execute.</param>
/// <returns>Job result for this execution.</returns>
public Future<TJobRes> Execute<TJobRes>(IComputeFunc<TJobRes> clo)
{
IgniteArgumentCheck.NotNull(clo, "clo");
return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(),
new ComputeOutFuncJob(clo.ToNonGeneric()), null, false);
}
/// <summary>
/// Executes provided delegate on a node in this grid projection. The result of the
/// job execution is returned from the result closure.
/// </summary>
/// <param name="func">Func to execute.</param>
/// <returns>Job result for this execution.</returns>
public Future<TJobRes> Execute<TJobRes>(Func<TJobRes> func)
{
IgniteArgumentCheck.NotNull(func, "func");
var wrappedFunc = new ComputeOutFuncWrapper(func, () => func());
return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(),
new ComputeOutFuncJob(wrappedFunc), null, false);
}
/// <summary>
/// Executes collection of jobs on nodes within this grid projection.
/// </summary>
/// <param name="clos">Collection of jobs to execute.</param>
/// <returns>Collection of job results for this execution.</returns>
public Future<ICollection<TJobRes>> Execute<TJobRes>(IEnumerable<IComputeFunc<TJobRes>> clos)
{
IgniteArgumentCheck.NotNull(clos, "clos");
ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(clos));
foreach (IComputeFunc<TJobRes> clo in clos)
jobs.Add(new ComputeOutFuncJob(clo.ToNonGeneric()));
return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(jobs.Count),
null, jobs, false);
}
/// <summary>
/// Executes collection of jobs on nodes within this grid projection.
/// </summary>
/// <param name="clos">Collection of jobs to execute.</param>
/// <param name="rdc">Reducer to reduce all job results into one individual return value.</param>
/// <returns>Collection of job results for this execution.</returns>
public Future<TReduceRes> Execute<TJobRes, TReduceRes>(IEnumerable<IComputeFunc<TJobRes>> clos,
IComputeReducer<TJobRes, TReduceRes> rdc)
{
IgniteArgumentCheck.NotNull(clos, "clos");
ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(clos));
foreach (var clo in clos)
jobs.Add(new ComputeOutFuncJob(clo.ToNonGeneric()));
return ExecuteClosures0(new ComputeReducingClosureTask<object, TJobRes, TReduceRes>(rdc), null, jobs, false);
}
/// <summary>
/// Broadcasts given job to all nodes in grid projection. Every participating node will return a job result.
/// </summary>
/// <param name="clo">Job to broadcast to all projection nodes.</param>
/// <returns>Collection of results for this execution.</returns>
public Future<ICollection<TJobRes>> Broadcast<TJobRes>(IComputeFunc<TJobRes> clo)
{
IgniteArgumentCheck.NotNull(clo, "clo");
return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(1),
new ComputeOutFuncJob(clo.ToNonGeneric()), null, true);
}
/// <summary>
/// Broadcasts given closure job with passed in argument to all nodes in grid projection.
/// Every participating node will return a job result.
/// </summary>
/// <param name="clo">Job to broadcast to all projection nodes.</param>
/// <param name="arg">Job closure argument.</param>
/// <returns>Collection of results for this execution.</returns>
public Future<ICollection<TJobRes>> Broadcast<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg)
{
IgniteArgumentCheck.NotNull(clo, "clo");
return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(1),
new ComputeFuncJob(clo.ToNonGeneric(), arg), null, true);
}
/// <summary>
/// Broadcasts given job to all nodes in grid projection.
/// </summary>
/// <param name="action">Job to broadcast to all projection nodes.</param>
public Future<object> Broadcast(IComputeAction action)
{
IgniteArgumentCheck.NotNull(action, "action");
return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(),
new ComputeActionJob(action), opId: OpBroadcast);
}
/// <summary>
/// Executes provided job on a node in this grid projection.
/// </summary>
/// <param name="action">Job to execute.</param>
public Future<object> Run(IComputeAction action)
{
IgniteArgumentCheck.NotNull(action, "action");
return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(),
new ComputeActionJob(action));
}
/// <summary>
/// Executes collection of jobs on Ignite nodes within this grid projection.
/// </summary>
/// <param name="actions">Jobs to execute.</param>
public Future<object> Run(IEnumerable<IComputeAction> actions)
{
IgniteArgumentCheck.NotNull(actions, "actions");
var actions0 = actions as ICollection;
if (actions0 == null)
{
var jobs = actions.Select(a => new ComputeActionJob(a)).ToList();
return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), jobs: jobs,
jobsCount: jobs.Count);
}
else
{
var jobs = actions.Select(a => new ComputeActionJob(a));
return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), jobs: jobs,
jobsCount: actions0.Count);
}
}
/// <summary>
/// Executes provided closure job on a node in this grid projection.
/// </summary>
/// <param name="clo">Job to run.</param>
/// <param name="arg">Job argument.</param>
/// <returns>Job result for this execution.</returns>
public Future<TJobRes> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg)
{
IgniteArgumentCheck.NotNull(clo, "clo");
return ExecuteClosures0(new ComputeSingleClosureTask<TArg, TJobRes, TJobRes>(),
new ComputeFuncJob(clo.ToNonGeneric(), arg), null, false);
}
/// <summary>
/// Executes provided closure job on nodes within this grid projection. A new job is executed for
/// every argument in the passed in collection. The number of actual job executions will be
/// equal to size of the job arguments collection.
/// </summary>
/// <param name="clo">Job to run.</param>
/// <param name="args">Job arguments.</param>
/// <returns>Collection of job results.</returns>
public Future<ICollection<TJobRes>> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo,
IEnumerable<TArg> args)
{
IgniteArgumentCheck.NotNull(clo, "clo");
IgniteArgumentCheck.NotNull(clo, "clo");
var jobs = new List<IComputeJob>(GetCountOrZero(args));
var func = clo.ToNonGeneric();
foreach (TArg arg in args)
jobs.Add(new ComputeFuncJob(func, arg));
return ExecuteClosures0(new ComputeMultiClosureTask<TArg, TJobRes, ICollection<TJobRes>>(jobs.Count),
null, jobs, false);
}
/// <summary>
/// Executes provided closure job on nodes within this grid projection. A new job is executed for
/// every argument in the passed in collection. The number of actual job executions will be
/// equal to size of the job arguments collection. The returned job results will be reduced
/// into an individual result by provided reducer.
/// </summary>
/// <param name="clo">Job to run.</param>
/// <param name="args">Job arguments.</param>
/// <param name="rdc">Reducer to reduce all job results into one individual return value.</param>
/// <returns>Reduced job result for this execution.</returns>
public Future<TReduceRes> Apply<TArg, TJobRes, TReduceRes>(IComputeFunc<TArg, TJobRes> clo,
IEnumerable<TArg> args, IComputeReducer<TJobRes, TReduceRes> rdc)
{
IgniteArgumentCheck.NotNull(clo, "clo");
IgniteArgumentCheck.NotNull(clo, "clo");
IgniteArgumentCheck.NotNull(clo, "clo");
ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(args));
var func = clo.ToNonGeneric();
foreach (TArg arg in args)
jobs.Add(new ComputeFuncJob(func, arg));
return ExecuteClosures0(new ComputeReducingClosureTask<TArg, TJobRes, TReduceRes>(rdc),
null, jobs, false);
}
/// <summary>
/// Executes given job on the node where data for provided affinity key is located
/// (a.k.a. affinity co-location).
/// </summary>
/// <param name="cacheName">Name of the cache to use for affinity co-location.</param>
/// <param name="affinityKey">Affinity key.</param>
/// <param name="action">Job to execute.</param>
public Future<object> AffinityRun(string cacheName, object affinityKey, IComputeAction action)
{
IgniteArgumentCheck.NotNull(action, "action");
return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(),
new ComputeActionJob(action), opId: OpAffinity,
writeAction: w => WriteAffinity(w, cacheName, affinityKey));
}
/// <summary>
/// Executes given job on the node where data for provided affinity key is located
/// (a.k.a. affinity co-location).
/// </summary>
/// <param name="cacheName">Name of the cache to use for affinity co-location.</param>
/// <param name="affinityKey">Affinity key.</param>
/// <param name="clo">Job to execute.</param>
/// <returns>Job result for this execution.</returns>
/// <typeparam name="TJobRes">Type of job result.</typeparam>
public Future<TJobRes> AffinityCall<TJobRes>(string cacheName, object affinityKey, IComputeFunc<TJobRes> clo)
{
IgniteArgumentCheck.NotNull(clo, "clo");
return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(),
new ComputeOutFuncJob(clo.ToNonGeneric()), opId: OpAffinity,
writeAction: w => WriteAffinity(w, cacheName, affinityKey));
}
/** <inheritDoc /> */
protected override T Unmarshal<T>(IBinaryStream stream)
{
bool keep = _keepBinary.Value;
return Marshaller.Unmarshal<T>(stream, keep);
}
/// <summary>
/// Internal routine for closure-based task execution.
/// </summary>
/// <param name="task">Task.</param>
/// <param name="job">Job.</param>
/// <param name="jobs">Jobs.</param>
/// <param name="broadcast">Broadcast flag.</param>
/// <returns>Future.</returns>
private Future<TReduceRes> ExecuteClosures0<TArg, TJobRes, TReduceRes>(
IComputeTask<TArg, TJobRes, TReduceRes> task, IComputeJob job,
ICollection<IComputeJob> jobs, bool broadcast)
{
return ExecuteClosures0(task, job, jobs, broadcast ? OpBroadcast : OpUnicast,
jobs == null ? 1 : jobs.Count);
}
/// <summary>
/// Internal routine for closure-based task execution.
/// </summary>
/// <param name="task">Task.</param>
/// <param name="job">Job.</param>
/// <param name="jobs">Jobs.</param>
/// <param name="opId">Op code.</param>
/// <param name="jobsCount">Jobs count.</param>
/// <param name="writeAction">Custom write action.</param>
/// <returns>Future.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "User code can throw any exception")]
private Future<TReduceRes> ExecuteClosures0<TArg, TJobRes, TReduceRes>(
IComputeTask<TArg, TJobRes, TReduceRes> task, IComputeJob job = null,
IEnumerable<IComputeJob> jobs = null, int opId = OpUnicast, int jobsCount = 0,
Action<BinaryWriter> writeAction = null)
{
Debug.Assert(job != null || jobs != null);
var holder = new ComputeTaskHolder<TArg, TJobRes, TReduceRes>((Ignite) _prj.Ignite, this, task, default(TArg));
var taskHandle = Marshaller.Ignite.HandleRegistry.Allocate(holder);
var jobHandles = new List<long>(job != null ? 1 : jobsCount);
try
{
Exception err = null;
try
{
DoOutOp(opId, writer =>
{
writer.WriteLong(taskHandle);
if (job != null)
{
writer.WriteInt(1);
jobHandles.Add(WriteJob(job, writer));
}
else
{
writer.WriteInt(jobsCount);
Debug.Assert(jobs != null, "jobs != null");
jobHandles.AddRange(jobs.Select(jobEntry => WriteJob(jobEntry, writer)));
}
holder.JobHandles(jobHandles);
if (writeAction != null)
writeAction(writer);
});
}
catch (Exception e)
{
err = e;
}
if (err != null)
{
// Manual job handles release because they were not assigned to the task yet.
foreach (var hnd in jobHandles)
Marshaller.Ignite.HandleRegistry.Release(hnd);
holder.CompleteWithError(taskHandle, err);
}
}
catch (Exception e)
{
// This exception means that out-op failed.
holder.CompleteWithError(taskHandle, e);
}
return holder.Future;
}
/// <summary>
/// Writes the job.
/// </summary>
/// <param name="job">The job.</param>
/// <param name="writer">The writer.</param>
/// <returns>Handle to the job holder</returns>
private long WriteJob(IComputeJob job, BinaryWriter writer)
{
var jobHolder = new ComputeJobHolder((Ignite) _prj.Ignite, job);
var jobHandle = Marshaller.Ignite.HandleRegistry.Allocate(jobHolder);
writer.WriteLong(jobHandle);
try
{
writer.WriteObject(jobHolder);
}
catch (Exception)
{
Marshaller.Ignite.HandleRegistry.Release(jobHandle);
throw;
}
return jobHandle;
}
/// <summary>
/// Write task to the writer.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="taskName">Task name.</param>
/// <param name="taskArg">Task arg.</param>
/// <param name="nodes">Nodes.</param>
private void WriteTask(BinaryWriter writer, string taskName, object taskArg,
ICollection<IClusterNode> nodes)
{
writer.WriteString(taskName);
writer.WriteBoolean(_keepBinary.Value);
writer.Write(taskArg);
WriteNodeIds(writer, nodes);
}
/// <summary>
/// Write node IDs.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="nodes">Nodes.</param>
private static void WriteNodeIds(BinaryWriter writer, ICollection<IClusterNode> nodes)
{
if (nodes == null)
writer.WriteBoolean(false);
else
{
writer.WriteBoolean(true);
writer.WriteInt(nodes.Count);
foreach (IClusterNode node in nodes)
writer.WriteGuid(node.Id);
}
}
/// <summary>
/// Writes the affinity info.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="cacheName">Name of the cache to use for affinity co-location.</param>
/// <param name="affinityKey">Affinity key.</param>
private static void WriteAffinity(BinaryWriter writer, string cacheName, object affinityKey)
{
writer.WriteString(cacheName);
writer.WriteObject(affinityKey);
}
/// <summary>
/// Gets element count or zero.
/// </summary>
private static int GetCountOrZero(object collection)
{
var coll = collection as ICollection;
return coll == null ? 0 : coll.Count;
}
}
}
| |
// <copyright file="MlkBiCgStabTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2014 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double.Solvers.Iterative
{
/// <summary>
/// Tests for Multiple-Lanczos Bi-Conjugate Gradient stabilized iterative matrix solver.
/// </summary>
[TestFixture, Category("LASolver")]
public class MlkBiCgStabTest
{
/// <summary>
/// Convergence boundary.
/// </summary>
const double ConvergenceBoundary = 1e-10;
/// <summary>
/// Maximum iterations.
/// </summary>
const int MaximumIterations = 1000;
/// <summary>
/// Solve wide matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveWideMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(2, 3);
var input = new DenseVector(2);
var solver = new MlkBiCgStab();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve long matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveLongMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(3, 2);
var input = new DenseVector(3);
var solver = new MlkBiCgStab();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve unit matrix and back multiply.
/// </summary>
[Test]
public void SolveUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = Matrix<double>.Build.SparseIdentity(100);
// Create the y vector
var y = Vector<double>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(MaximumIterations),
new ResidualStopCriterion<double>(ConvergenceBoundary),
new DivergenceStopCriterion<double>(),
new FailureStopCriterion<double>());
var solver = new MlkBiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, Math.Abs(y[i] - z[i]), "#05-" + i);
}
}
/// <summary>
/// Solve scaled unit matrix and back multiply.
/// </summary>
[Test]
public void SolveScaledUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = Matrix<double>.Build.SparseIdentity(100);
// Scale it with a funny number
matrix.Multiply(Math.PI, matrix);
// Create the y vector
var y = Vector<double>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(MaximumIterations),
new ResidualStopCriterion<double>(ConvergenceBoundary),
new DivergenceStopCriterion<double>(),
new FailureStopCriterion<double>());
var solver = new MlkBiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, Math.Abs(y[i] - z[i]), "#05-" + i);
}
}
/// <summary>
/// Solve poisson matrix and back multiply.
/// </summary>
[Test]
public void SolvePoissonMatrixAndBackMultiply()
{
// Create the matrix
var matrix = Matrix<double>.Build.Sparse(100, 100);
// Assemble the matrix. We assume we're solving the Poisson equation
// on a rectangular 10 x 10 grid
const int GridSize = 10;
// The pattern is:
// 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
for (var i = 0; i < matrix.RowCount; i++)
{
// Insert the first set of -1's
if (i > (GridSize - 1))
{
matrix[i, i - GridSize] = -1;
}
// Insert the second set of -1's
if (i > 0)
{
matrix[i, i - 1] = -1;
}
// Insert the centerline values
matrix[i, i] = 4;
// Insert the first trailing set of -1's
if (i < matrix.RowCount - 1)
{
matrix[i, i + 1] = -1;
}
// Insert the second trailing set of -1's
if (i < matrix.RowCount - GridSize)
{
matrix[i, i + GridSize] = -1;
}
}
// Create the y vector
var y = Vector<double>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(MaximumIterations),
new ResidualStopCriterion<double>(ConvergenceBoundary),
new DivergenceStopCriterion<double>(),
new FailureStopCriterion<double>());
var solver = new MlkBiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, Math.Abs(y[i] - z[i]), "#05-" + i);
}
}
/// <summary>
/// Can solve for a random vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomVector(int order)
{
var matrixA = Matrix<double>.Build.Random(order, order, 1);
var vectorb = Vector<double>.Build.Random(order, 1);
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(1000),
new ResidualStopCriterion<double>(1e-10));
var solver = new MlkBiCgStab();
var resultx = matrixA.SolveIterative(vectorb, solver, monitor);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-7);
}
}
/// <summary>
/// Can solve for random matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = Matrix<double>.Build.Random(order, order, 1);
var matrixB = Matrix<double>.Build.Random(order, order, 1);
var monitor = new Iterator<double>(
new IterationCountStopCriterion<double>(1000),
new ResidualStopCriterion<double>(1e-10));
var solver = new MlkBiCgStab();
var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-7);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
/// <summary>
/// An immutable queue.
/// </summary>
/// <typeparam name="T">The type of elements stored in the queue.</typeparam>
[DebuggerDisplay("IsEmpty = {IsEmpty}")]
[DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))]
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableQueue<T> : IImmutableQueue<T>
{
/// <summary>
/// The singleton empty queue.
/// </summary>
/// <remarks>
/// Additional instances representing the empty queue may exist on deserialized instances.
/// Actually since this queue is a struct, instances don't even apply and there are no singletons.
/// </remarks>
private static readonly ImmutableQueue<T> s_EmptyField = new ImmutableQueue<T>(ImmutableStack<T>.Empty, ImmutableStack<T>.Empty);
/// <summary>
/// The end of the queue that enqueued elements are pushed onto.
/// </summary>
private readonly ImmutableStack<T> _backwards;
/// <summary>
/// The end of the queue from which elements are dequeued.
/// </summary>
private readonly ImmutableStack<T> _forwards;
/// <summary>
/// Backing field for the <see cref="BackwardsReversed"/> property.
/// </summary>
private ImmutableStack<T> _backwardsReversed;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableQueue{T}"/> class.
/// </summary>
/// <param name="forward">The forward stack.</param>
/// <param name="backward">The backward stack.</param>
private ImmutableQueue(ImmutableStack<T> forward, ImmutableStack<T> backward)
{
Requires.NotNull(forward, nameof(forward));
Requires.NotNull(backward, nameof(backward));
_forwards = forward;
_backwards = backward;
_backwardsReversed = null;
}
/// <summary>
/// Gets the empty queue.
/// </summary>
public ImmutableQueue<T> Clear()
{
Contract.Ensures(Contract.Result<ImmutableQueue<T>>().IsEmpty);
Contract.Assume(s_EmptyField.IsEmpty);
return Empty;
}
/// <summary>
/// Gets a value indicating whether this instance is empty.
/// </summary>
/// <value>
/// <c>true</c> if this instance is empty; otherwise, <c>false</c>.
/// </value>
public bool IsEmpty
{
get { return _forwards.IsEmpty && _backwards.IsEmpty; }
}
/// <summary>
/// Gets the empty queue.
/// </summary>
public static ImmutableQueue<T> Empty
{
get
{
Contract.Ensures(Contract.Result<ImmutableQueue<T>>().IsEmpty);
Contract.Assume(s_EmptyField.IsEmpty);
return s_EmptyField;
}
}
/// <summary>
/// Gets an empty queue.
/// </summary>
IImmutableQueue<T> IImmutableQueue<T>.Clear()
{
Contract.Assume(s_EmptyField.IsEmpty);
return this.Clear();
}
/// <summary>
/// Gets the reversed <see cref="_backwards"/> stack.
/// </summary>
private ImmutableStack<T> BackwardsReversed
{
get
{
Contract.Ensures(Contract.Result<ImmutableStack<T>>() != null);
// Although this is a lazy-init pattern, no lock is required because
// this instance is immutable otherwise, and a double-assignment from multiple
// threads is harmless.
if (_backwardsReversed == null)
{
_backwardsReversed = _backwards.Reverse();
}
return _backwardsReversed;
}
}
/// <summary>
/// Gets the element at the front of the queue.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[Pure]
public T Peek()
{
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
return _forwards.Peek();
}
/// <summary>
/// Adds an element to the back of the queue.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>
/// The new queue.
/// </returns>
[Pure]
public ImmutableQueue<T> Enqueue(T value)
{
Contract.Ensures(!Contract.Result<ImmutableQueue<T>>().IsEmpty);
if (this.IsEmpty)
{
return new ImmutableQueue<T>(ImmutableStack<T>.Empty.Push(value), ImmutableStack<T>.Empty);
}
else
{
return new ImmutableQueue<T>(_forwards, _backwards.Push(value));
}
}
/// <summary>
/// Adds an element to the back of the queue.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>
/// The new queue.
/// </returns>
[Pure]
IImmutableQueue<T> IImmutableQueue<T>.Enqueue(T value)
{
return this.Enqueue(value);
}
/// <summary>
/// Returns a queue that is missing the front element.
/// </summary>
/// <returns>A queue; never <c>null</c>.</returns>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[Pure]
public ImmutableQueue<T> Dequeue()
{
if (this.IsEmpty)
{
throw new InvalidOperationException(SR.InvalidEmptyOperation);
}
ImmutableStack<T> f = _forwards.Pop();
if (!f.IsEmpty)
{
return new ImmutableQueue<T>(f, _backwards);
}
else if (_backwards.IsEmpty)
{
return ImmutableQueue<T>.Empty;
}
else
{
return new ImmutableQueue<T>(this.BackwardsReversed, ImmutableStack<T>.Empty);
}
}
/// <summary>
/// Retrieves the item at the head of the queue, and returns a queue with the head element removed.
/// </summary>
/// <param name="value">Receives the value from the head of the queue.</param>
/// <returns>The new queue with the head element removed.</returns>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")]
[Pure]
public ImmutableQueue<T> Dequeue(out T value)
{
value = this.Peek();
return this.Dequeue();
}
/// <summary>
/// Returns a queue that is missing the front element.
/// </summary>
/// <returns>A queue; never <c>null</c>.</returns>
/// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception>
[Pure]
IImmutableQueue<T> IImmutableQueue<T>.Dequeue()
{
return this.Dequeue();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An <see cref="Enumerator"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new EnumeratorObject(this);
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
[Pure]
IEnumerator IEnumerable.GetEnumerator()
{
return new EnumeratorObject(this);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="BlockBasedBlobReader.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement.TransferControllers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;
internal sealed class BlockBasedBlobReader : TransferReaderWriterBase
{
/// <summary>
/// Block/append blob instance to be downloaded from.
/// </summary>
private CloudBlob blob;
/// <summary>
/// Window to record unfinished chunks to be retransferred again.
/// </summary>
private Queue<long> lastTransferWindow;
/// <summary>
/// Instance to represent source location.
/// </summary>
private TransferLocation transferLocation;
private TransferJob transferJob;
/// <summary>
/// Value to indicate whether the transfer is finished.
/// This is to tell the caller that the reader can be disposed,
/// Both error happened or completed will be treated to be finished.
/// </summary>
private volatile bool isFinished = false;
private volatile bool hasWork;
private CountdownEvent downloadCountdownEvent;
public BlockBasedBlobReader(
TransferScheduler scheduler,
SyncTransferController controller,
CancellationToken cancellationToken)
: base(scheduler, controller, cancellationToken)
{
this.transferLocation = this.SharedTransferData.TransferJob.Source;
this.transferJob = this.SharedTransferData.TransferJob;
this.blob = this.transferLocation.Blob;
Debug.Assert(
(this.blob is CloudBlockBlob) ||(this.blob is CloudAppendBlob),
"Initializing BlockBlobReader while source location is not a block blob or an append blob.");
this.hasWork = true;
}
public override bool IsFinished
{
get
{
return this.isFinished;
}
}
public override bool HasWork
{
get
{
return this.hasWork;
}
}
public override async Task DoWorkInternalAsync()
{
try
{
if (!this.PreProcessed)
{
await this.FetchAttributeAsync();
}
else
{
await this.DownloadBlockBlobAsync();
}
}
catch (Exception)
{
this.isFinished = true;
throw;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (null != this.downloadCountdownEvent)
{
this.downloadCountdownEvent.Dispose();
this.downloadCountdownEvent = null;
}
}
}
private async Task FetchAttributeAsync()
{
this.hasWork = false;
this.NotifyStarting();
AccessCondition accessCondition = Utils.GenerateIfMatchConditionWithCustomerCondition(
this.transferLocation.ETag,
this.transferLocation.AccessCondition,
this.transferLocation.CheckedAccessCondition);
try
{
await this.blob.FetchAttributesAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.transferLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken);
}
catch (StorageException e)
{
if (null != e.RequestInformation &&
e.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
throw new InvalidOperationException(Resources.SourceBlobDoesNotExistException);
}
else
{
throw;
}
}
this.transferLocation.CheckedAccessCondition = true;
if (this.blob.Properties.BlobType == BlobType.Unspecified)
{
throw new InvalidOperationException(Resources.FailedToGetBlobTypeException);
}
if (string.IsNullOrEmpty(this.transferLocation.ETag))
{
if (0 != this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset)
{
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
this.transferLocation.ETag = this.blob.Properties.ETag;
}
else if ((this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset > this.blob.Properties.Length)
|| (this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset < 0))
{
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
this.SharedTransferData.SourceLocation = this.blob.Uri.ToString();
this.SharedTransferData.DisableContentMD5Validation =
null != this.transferLocation.BlobRequestOptions ?
this.transferLocation.BlobRequestOptions.DisableContentMD5Validation.HasValue ?
this.transferLocation.BlobRequestOptions.DisableContentMD5Validation.Value : false : false;
this.SharedTransferData.TotalLength = this.blob.Properties.Length;
this.SharedTransferData.Attributes = Utils.GenerateAttributes(this.blob);
if ((0 == this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset)
&& (null != this.SharedTransferData.TransferJob.CheckPoint.TransferWindow)
&& (0 != this.SharedTransferData.TransferJob.CheckPoint.TransferWindow.Count))
{
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
this.lastTransferWindow = new Queue<long>(this.SharedTransferData.TransferJob.CheckPoint.TransferWindow);
int downloadCount = this.lastTransferWindow.Count +
(int)Math.Ceiling((double)(this.blob.Properties.Length - this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset) / this.Scheduler.TransferOptions.BlockSize);
if (0 == downloadCount)
{
this.isFinished = true;
this.PreProcessed = true;
this.hasWork = true;
}
else
{
this.downloadCountdownEvent = new CountdownEvent(downloadCount);
this.PreProcessed = true;
this.hasWork = true;
}
}
private async Task DownloadBlockBlobAsync()
{
this.hasWork = false;
byte[] memoryBuffer = this.Scheduler.MemoryManager.RequireBuffer();
if (null != memoryBuffer)
{
long startOffset = 0;
if (!this.IsTransferWindowEmpty())
{
startOffset = this.lastTransferWindow.Dequeue();
}
else
{
bool canUpload = false;
lock (this.transferJob.CheckPoint.TransferWindowLock)
{
if (this.transferJob.CheckPoint.TransferWindow.Count < Constants.MaxCountInTransferWindow)
{
startOffset = this.transferJob.CheckPoint.EntryTransferOffset;
if (this.transferJob.CheckPoint.EntryTransferOffset < this.SharedTransferData.TotalLength)
{
this.transferJob.CheckPoint.TransferWindow.Add(startOffset);
this.transferJob.CheckPoint.EntryTransferOffset = Math.Min(
this.transferJob.CheckPoint.EntryTransferOffset + this.Scheduler.TransferOptions.BlockSize,
this.SharedTransferData.TotalLength);
canUpload = true;
}
}
}
if (!canUpload)
{
this.hasWork = true;
this.Scheduler.MemoryManager.ReleaseBuffer(memoryBuffer);
return;
}
}
if ((startOffset > this.SharedTransferData.TotalLength)
|| (startOffset < 0))
{
this.Scheduler.MemoryManager.ReleaseBuffer(memoryBuffer);
throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
}
this.SetBlockDownloadHasWork();
ReadDataState asyncState = new ReadDataState
{
MemoryBuffer = memoryBuffer,
BytesRead = 0,
StartOffset = startOffset,
Length = (int)Math.Min(this.Scheduler.TransferOptions.BlockSize, this.SharedTransferData.TotalLength - startOffset),
MemoryManager = this.Scheduler.MemoryManager,
};
using (asyncState)
{
await this.DownloadChunkAsync(asyncState);
}
return;
}
this.SetBlockDownloadHasWork();
}
private async Task DownloadChunkAsync(ReadDataState asyncState)
{
Debug.Assert(null != asyncState, "asyncState object expected");
// If a parallel operation caused the controller to be placed in
// error state exit early to avoid unnecessary I/O.
if (this.Controller.ErrorOccurred)
{
return;
}
AccessCondition accessCondition = Utils.GenerateIfMatchConditionWithCustomerCondition(
this.blob.Properties.ETag,
this.transferLocation.AccessCondition);
// We're to download this block.
asyncState.MemoryStream =
new MemoryStream(
asyncState.MemoryBuffer,
0,
asyncState.Length);
await this.blob.DownloadRangeToStreamAsync(
asyncState.MemoryStream,
asyncState.StartOffset,
asyncState.Length,
accessCondition,
Utils.GenerateBlobRequestOptions(this.transferLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken);
TransferData transferData = new TransferData(this.Scheduler.MemoryManager)
{
StartOffset = asyncState.StartOffset,
Length = asyncState.Length,
MemoryBuffer = asyncState.MemoryBuffer
};
this.SharedTransferData.AvailableData.TryAdd(transferData.StartOffset, transferData);
// Set memory buffer to null. We don't want its dispose method to
// be called once our asyncState is disposed. The memory should
// not be reused yet, we still need to write it to disk.
asyncState.MemoryBuffer = null;
this.SetFinish();
this.SetBlockDownloadHasWork();
}
private void SetFinish()
{
if (this.downloadCountdownEvent.Signal())
{
this.isFinished = true;
}
}
private void SetBlockDownloadHasWork()
{
if (this.HasWork)
{
return;
}
// Check if we have blocks available to download.
if (!this.IsTransferWindowEmpty()
|| this.transferJob.CheckPoint.EntryTransferOffset < this.SharedTransferData.TotalLength)
{
this.hasWork = true;
return;
}
}
private bool IsTransferWindowEmpty()
{
return null == this.lastTransferWindow || this.lastTransferWindow.Count == 0;
}
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Threading;
using Alachisoft.NCache.Runtime.Serialization.IO;
using Alachisoft.NCache.Runtime.Serialization;
using Alachisoft.NCache.Common.Net;
namespace Alachisoft.NCache.Caching.DataGrouping
{
/// <summary>
/// This class is used to store data groups settings
/// for a node in the cluster
/// </summary>
[Serializable]
public class DataAffinity : ICloneable, ICompactSerializable
{
private ArrayList _groups = new ArrayList();
private ArrayList _allBindedGroups = new ArrayList();
private ArrayList _unbindedGroups = new ArrayList();
private bool _strict;
public DataAffinity()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="groups"></param>
/// <param name="strict"></param>
public DataAffinity(ArrayList groups, bool strict)
{
if (groups != null)
{
_groups = (ArrayList) groups.Clone();
_groups.Sort();
}
_strict = strict;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="groups"></param>
/// <param name="strict"></param>
public DataAffinity(ArrayList groups, ArrayList allBindedGroups, ArrayList unbindGroups, bool strict)
{
if (groups != null)
{
_groups = (ArrayList) groups.Clone();
_groups.Sort();
}
if (allBindedGroups != null)
{
_allBindedGroups = (ArrayList) allBindedGroups.Clone();
_allBindedGroups.Sort();
}
if (unbindGroups != null)
{
_unbindedGroups = (ArrayList) unbindGroups.Clone();
_unbindedGroups.Sort();
}
_strict = strict;
}
/// <summary>
/// Overloaded Constructor
/// </summary>
/// <param name="props"></param>
public DataAffinity(IDictionary props)
{
if (props.Contains("strict"))
{
_strict = Convert.ToBoolean(props["strict"]);
}
if (props.Contains("data-groups"))
{
string groupsStr = (string) props["data-groups"];
if (groupsStr.Trim().Length > 0)
{
string[] groups = groupsStr.Split(new char[] {','});
ArrayList list = new ArrayList();
for (int i = 0; i < groups.Length; i++)
{
list.Add(groups[i]);
}
list.Sort();
_groups = list;
}
}
if (props.Contains("binded-groups-list"))
{
string groupsStr = (string) props["binded-groups-list"];
if (groupsStr.Trim().Length > 0)
{
string[] groups = groupsStr.Split(new char[] {','});
ArrayList list = new ArrayList();
for (int i = 0; i < groups.Length; i++)
{
list.Add(groups[i]);
}
list.Sort();
_allBindedGroups = list;
}
}
}
/// <summary>
/// list of groups
/// </summary>
public ArrayList Groups
{
get { return _groups == null ? null : (ArrayList) _groups.Clone(); }
set
{
_groups = value;
if (_groups != null)
_groups.Sort();
}
}
/// <summary>
/// list of all the binded groups
/// </summary>
public ArrayList AllBindedGroups
{
get { return _allBindedGroups == null ? null : (ArrayList) _allBindedGroups.Clone(); }
set
{
_allBindedGroups = value;
if (_allBindedGroups != null)
_allBindedGroups.Sort();
}
}
/// <summary>
/// list of all the groups which are not binded to any node.
/// </summary>
public ArrayList AllUndbindedGroups
{
get { return _unbindedGroups == null ? null : (ArrayList) _unbindedGroups.Clone(); }
set
{
_unbindedGroups = value;
if (_unbindedGroups != null)
_unbindedGroups.Sort();
}
}
/// <summary>
/// Allow data without any group or not
/// </summary>
public bool Strict
{
get { return _strict; }
}
/// <summary>
/// Is the specified group exists in the list
/// </summary>
/// <param name="group"></param>
/// <returns></returns>
public bool IsExists(string group)
{
if (group == null) return false;
if (_groups == null) return false;
if (_groups.BinarySearch(group) < 0)
return false;
return true;
}
/// <summary>
/// Determine whether the spceified group exist in unbinded groups list or not.
/// </summary>
/// <param name="group"></param>
/// <returns></returns>
public bool IsUnbindedGroups(string group)
{
if (group == null) return false;
if (_unbindedGroups == null) return false;
if (_unbindedGroups.BinarySearch(group) < 0)
return false;
return true;
}
#region ICloneable Members
public object Clone()
{
return new DataAffinity(_groups, _allBindedGroups, _unbindedGroups, _strict);
}
#endregion
#region ICompactSerializable Members
public void Serialize(CompactWriter writer)
{
writer.Write(_strict);
writer.WriteObject(_groups);
writer.WriteObject(_allBindedGroups);
writer.WriteObject(_unbindedGroups);
}
public void Deserialize(CompactReader reader)
{
_strict = (bool) reader.ReadBoolean();
_groups = (ArrayList) reader.ReadObject();
_allBindedGroups = (ArrayList) reader.ReadObject();
_unbindedGroups = (ArrayList) reader.ReadObject();
}
#endregion
public static DataAffinity ReadDataAffinity(CompactReader reader)
{
byte isNull = reader.ReadByte();
if (isNull == 1)
return null;
DataAffinity newAffinity = new DataAffinity();
newAffinity.Deserialize(reader);
return newAffinity;
}
public static void WriteDataAffinity(CompactWriter writer, DataAffinity dataAffinity)
{
byte isNull = 1;
if (dataAffinity == null)
writer.Write(isNull);
else
{
isNull = 0;
writer.Write(isNull);
dataAffinity.Serialize(writer);
}
return;
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Adxstudio.Xrm.AspNet.Cms;
using Adxstudio.Xrm.AspNet.Mvc;
using Adxstudio.Xrm.Blogs;
using Adxstudio.Xrm.Cases;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Forums;
using Adxstudio.Xrm.Ideas;
using Adxstudio.Xrm.Issues;
using Adxstudio.Xrm.Web;
using Microsoft.Xrm.Sdk;
namespace Site.Helpers
{
public static class UrlHelpers
{
public static string ActionWithQueryString(this UrlHelper url, string actionName, object routeValues)
{
var routeDictionary = new RouteValueDictionary(routeValues);
var queryString = url.RequestContext.HttpContext.Request.QueryString;
foreach (var key in queryString.Cast<string>().Where(key => !routeDictionary.ContainsKey(key) && !string.IsNullOrWhiteSpace(queryString[key])))
{
routeDictionary[key] = queryString[key];
}
return url.Action(actionName, routeDictionary);
}
public static bool RegistrationEnabled(this UrlHelper url)
{
var settings = GetAuthenticationSettings(url);
return settings.RegistrationEnabled && !Adxstudio.Xrm.Configuration.PortalSettings.Instance.Ess.IsEss;
}
public static string SignInUrl(this UrlHelper url, string returnUrl = null)
{
return SignInUrlOwin(url, returnUrl);
}
private static string SignInUrlOwin(this UrlHelper url, string returnUrl = null)
{
var settings = GetAuthenticationSettings(url);
return !string.IsNullOrWhiteSpace(settings.LoginButtonAuthenticationType)
? url.Action("ExternalLogin", "Login",
new
{
area = "Account",
region = settings.Region,
returnUrl = GetReturnUrl(url.RequestContext.HttpContext.Request, returnUrl),
provider = settings.LoginButtonAuthenticationType
})
: LocalSignInUrl(url, returnUrl);
}
public static string LocalSignInUrl(this UrlHelper url, string returnUrl = null)
{
return GetAccountUrl(url, "Login", "Login", returnUrl);
}
public static string FacebookSignInUrl(this UrlHelper url)
{
return url.Action("FacebookExternalLogin", "Login", new { area = "Account" });
}
public static string SignOutUrl(this UrlHelper url, string returnUrl = null)
{
return GetAccountUrl(url, "LogOff", "Login", returnUrl);
}
public static string RegisterUrl(this UrlHelper url, string returnUrl = null)
{
return GetAccountUrl(url, "Register", "Login", returnUrl);
}
public static string RedeemUrl(this UrlHelper url, string returnUrl = null)
{
return GetAccountUrl(url, "RedeemInvitation", "Login", returnUrl);
}
private static string GetAccountUrl(UrlHelper url, string actionName, string controllerName, string returnUrl)
{
var settings = GetAuthenticationSettings(url);
var routeValues = new
{
area = "Account",
region = settings.Region,
returnUrl = GetReturnUrl(url.RequestContext.HttpContext.Request, returnUrl)
};
return url.Action(actionName, controllerName, routeValues);
}
private static string GetReturnUrl(HttpRequestBase request, string returnUrl)
{
return request["ReturnUrl"] ?? returnUrl ?? request.RawUrl;
}
public static string SecureRegistrationUrl(this UrlHelper url, string returnUrl = null, string invitationCode = null)
{
return GetAccountRegistrationUrl(url, "Register", returnUrl, invitationCode);
}
private static string GetAccountRegistrationUrl(UrlHelper url, string actionName, string returnUrl, string invitationCode)
{
var returnLocalUrl = GetReturnUrl(url.RequestContext.HttpContext.Request, returnUrl);
return url.RouteUrl(actionName, new { returnUrl = returnLocalUrl, invitationCode });
}
private static AuthenticationSettings GetAuthenticationSettings(this UrlHelper url)
{
var website = url.RequestContext.HttpContext.GetWebsite();
var settings = website.GetAuthenticationSettings();
var contextLanguageInfo = url.RequestContext.HttpContext.GetContextLanguageInfo();
var region = (contextLanguageInfo.IsCrmMultiLanguageEnabled && ContextLanguageInfo.DisplayLanguageCodeInUrl)
? contextLanguageInfo.ContextLanguage.Code : null;
return new AuthenticationSettings
{
RegistrationEnabled = settings.RegistrationEnabled && settings.OpenRegistrationEnabled,
LoginButtonAuthenticationType = settings.LoginButtonAuthenticationType,
Region = region
};
}
private class AuthenticationSettings
{
public bool RegistrationEnabled { get; set; }
public string LoginButtonAuthenticationType { get; set; }
public string Region { get; set; }
}
private const string _defaultAuthorUrl = null;
public static string AuthorUrl(this UrlHelper urlHelper, IBlogAuthor author)
{
try
{
return author == null
? _defaultAuthorUrl
: urlHelper.RouteUrl("PublicProfileBlogPosts", new { contactId = author.Id });
}
catch
{
return _defaultAuthorUrl;
}
}
public static string AuthorUrl(this UrlHelper urlHelper, ICase @case)
{
if (@case == null || @case.ResponsibleContact == null)
{
return _defaultAuthorUrl;
}
try
{
return urlHelper.RouteUrl("PublicProfileForumPosts", new { contactId = @case.ResponsibleContact.Id });
}
catch
{
return _defaultAuthorUrl;
}
}
public static string AuthorUrl(this UrlHelper urlHelper, IComment comment)
{
if (comment == null || comment.Author == null)
{
return _defaultAuthorUrl;
}
try
{
return comment.Author.EntityReference == null
? comment.Author.WebsiteUrl
: urlHelper.RouteUrl("PublicProfileForumPosts", new { contactId = comment.Author.EntityReference.Id });
}
catch
{
return _defaultAuthorUrl;
}
}
public static string AuthorUrl(this UrlHelper urlHelper, IIdea idea)
{
try
{
return idea == null || idea.AuthorId == null
? _defaultAuthorUrl
: urlHelper.RouteUrl("PublicProfileIdeas", new { contactId = idea.AuthorId.Value });
}
catch
{
return _defaultAuthorUrl;
}
}
public static string AuthorUrl(this UrlHelper urlHelper, IIssue issue)
{
try
{
return issue == null || issue.AuthorId == null
? _defaultAuthorUrl
: urlHelper.RouteUrl("PublicProfileForumPosts", new { contactId = issue.AuthorId.Value });
}
catch
{
return _defaultAuthorUrl;
}
}
public static string AuthorUrl(this UrlHelper urlHelper, IForumAuthor author)
{
try
{
return author == null || author.EntityReference == null
? _defaultAuthorUrl
: urlHelper.RouteUrl("PublicProfileForumPosts", new { contactId = author.EntityReference.Id });
}
catch
{
return _defaultAuthorUrl;
}
}
public static string UserImageUrl(this UrlHelper urlHelper, IForumAuthor author, int? size = null)
{
return author == null ? null : urlHelper.UserImageUrl(author.EmailAddress, size);
}
public static string UserImageUrl(this UrlHelper urlHelper, ICase @case, int? size = null)
{
return @case == null || string.IsNullOrEmpty(@case.ResponsibleContactEmailAddress)
? null
: urlHelper.UserImageUrl(@case.ResponsibleContactEmailAddress, size);
}
public static string UserImageUrl(this UrlHelper urlHelper, Entity contact, int? size = null)
{
return contact == null ? null : urlHelper.UserImageUrl(contact.GetAttributeValue<string>("emailaddress1"), size);
}
public static string UserImageUrl(this UrlHelper urlHelper, object email, int? size = null)
{
return email == null ? null : urlHelper.UserImageUrl(email.ToString(), size);
}
public static string UserImageUrl(this UrlHelper urlHelper, string email, int? size = null)
{
return VirtualPathUtility.ToAbsolute("~/xrm-adx/images/contact_photo.png");
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.XWPF.UserModel
{
using System;
using System.Collections.Generic;
/**
* @author Yegor Kozlov
*/
public class XWPFRelation : POIXMLRelation
{
/**
* A map to lookup POIXMLRelation by its relation type
*/
protected static Dictionary<String, XWPFRelation> _table = new Dictionary<String, XWPFRelation>();
public static XWPFRelation DOCUMENT = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
"/word/document.xml",
null
);
public static XWPFRelation TEMPLATE = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
"/word/document.xml",
null
);
public static XWPFRelation MACRO_DOCUMENT = new XWPFRelation(
"application/vnd.ms-word.document.macroEnabled.main+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
"/word/document.xml",
null
);
public static XWPFRelation MACRO_TEMPLATE_DOCUMENT = new XWPFRelation(
"application/vnd.ms-word.template.macroEnabledTemplate.main+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
"/word/document.xml",
null
);
public static XWPFRelation GLOSSARY_DOCUMENT = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/glossaryDocument",
"/word/glossary/document.xml",
null
);
public static XWPFRelation NUMBERING = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",
"/word/numbering.xml",
typeof(XWPFNumbering)
);
public static XWPFRelation FONT_TABLE = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",
"/word/fontTable.xml",
null
);
public static XWPFRelation SETTINGS = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",
"/word/settings.xml",
typeof(XWPFSettings)
);
public static XWPFRelation STYLES = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
"/word/styles.xml",
typeof(XWPFStyles)
);
public static XWPFRelation WEB_SETTINGS = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings",
"/word/webSettings.xml",
null
);
public static XWPFRelation HEADER = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",
"/word/header#.xml",
typeof(XWPFHeader)
);
public static XWPFRelation FOOTER = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer",
"/word/footer#.xml",
typeof(XWPFFooter)
);
public static XWPFRelation THEME = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.theme+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",
"/word/theme/theme#.xml",
null
);
public static XWPFRelation HYPERLINK = new XWPFRelation(
null,
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
null,
null
);
public static XWPFRelation COMMENT = new XWPFRelation(
null,
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",
null,
null
);
public static XWPFRelation FOOTNOTE = new XWPFRelation(
"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",
"/word/footnotes.xml",
typeof(XWPFFootnotes)
);
public static XWPFRelation ENDNOTE = new XWPFRelation(
null,
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes",
null,
null
);
/**
* Supported image formats
*/
public static XWPFRelation IMAGE_EMF = new XWPFRelation(
"image/x-emf",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.emf",
typeof(XWPFPictureData)
);
public static XWPFRelation IMAGE_WMF = new XWPFRelation(
"image/x-wmf",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.wmf",
typeof(XWPFPictureData)
);
public static XWPFRelation IMAGE_PICT = new XWPFRelation(
"image/pict",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.pict",
typeof(XWPFPictureData)
);
public static XWPFRelation IMAGE_JPEG = new XWPFRelation(
"image/jpeg",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.jpeg",
typeof(XWPFPictureData)
);
public static XWPFRelation IMAGE_PNG = new XWPFRelation(
"image/png",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.png",
typeof(XWPFPictureData)
);
public static XWPFRelation IMAGE_DIB = new XWPFRelation(
"image/dib",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.dib",
typeof(XWPFPictureData)
);
public static XWPFRelation IMAGE_GIF = new XWPFRelation(
"image/gif",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.gif",
typeof(XWPFPictureData)
);
public static XWPFRelation IMAGE_TIFF = new XWPFRelation(
"image/tiff",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.tiff",
typeof(XWPFPictureData)
);
public static XWPFRelation IMAGE_EPS = new XWPFRelation(
"image/x-eps",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.eps",
typeof(XWPFPictureData)
);
public static XWPFRelation IMAGE_BMP = new XWPFRelation(
"image/x-ms-bmp",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.bmp",
typeof(XWPFPictureData)
);
public static XWPFRelation IMAGE_WPG = new XWPFRelation(
"image/x-wpg",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
"/word/media/image#.wpg",
typeof(XWPFPictureData)
);
public static XWPFRelation IMAGES = new XWPFRelation(
null,
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",
null,
null
);
private XWPFRelation(String type, String rel, String defaultName, Type cls)
: base(type, rel, defaultName, cls)
{
;
if (cls != null && !_table.ContainsKey(rel)) _table.Add(rel, this);
}
/**
* Get POIXMLRelation by relation type
*
* @param rel relation type, for example,
* <code>http://schemas.openxmlformats.org/officeDocument/2006/relationships/image</code>
* @return registered POIXMLRelation or null if not found
*/
public static XWPFRelation GetInstance(String rel)
{
if (_table.ContainsKey(rel))
return _table[(rel)];
return null;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using UnityEngine;
#if UNITY_WSA
using UnityEngine.VR.WSA;
using UnityEngine.VR.WSA.Persistence;
using UnityEngine.VR.WSA.Sharing;
#endif
using System.Collections;
using System.Collections.Generic;
using HUX.Receivers;
using HUX.Dialogs.Debug;
using HUX.Utility;
public class PointOfReferenceManager : Singleton<PointOfReferenceManager>
{
public GameObject m_PointOfReferenceCube;
#if UNITY_WSA
List<string> m_MessagesAsync = new List<string>();
public event System.Action OnPlacement;
WorldAnchorStore store = null;
private WorldAnchor m_PointOfReference = null;
public WorldAnchor PointOfReference
{
get { return m_PointOfReference; }
}
#endif
public const string PointOfReferenceID = "PointOfReference";
private bool m_LoadedAndPlaced = false;
public bool LoadedAndPlaced
{
get { return m_LoadedAndPlaced; }
}
enum ManualPointOfReferenceAcquisitionStage
{
Idle,
FirstPoint,
SecondPoint,
Acquired,
}
ManualPointOfReferenceAcquisitionStage m_ManualAnchorAcquisitionState = ManualPointOfReferenceAcquisitionStage.Idle;
Vector3 m_ManualAnchorPos = Vector3.zero;
Vector3 m_ManualAnchorForward = Vector3.forward;
#if UNITY_WSA
// Use this for initialization
void Start()
{
if (DebugMenu.Instance)
{
DebugMenu.Instance.AddButtonItem("Point Of Reference\\Generate Point of Reference", "Generate New", CreateManualPointOfReference);
}
#if UNITY_EDITOR
m_LoadedAndPlaced = true;
#else
WorldAnchorStore.GetAsync(StoreLoaded);
#endif
InputSources.Instance.hands.OnFingerPressed += OnFingerPressed;
}
// Update is called once per frame
void Update ()
{
lock (m_MessagesAsync)
{
while (m_MessagesAsync.Count > 0)
{
Debug.Log("(async)" + m_MessagesAsync[0]);
m_MessagesAsync.RemoveAt(0);
}
}
if ((m_PointOfReference != null) && (m_PointOfReference.isLocated))
{
m_LoadedAndPlaced = true;
}
}
#endif
public void CreatePointOfReference(Vector3 pos, Quaternion rot)
{
m_PointOfReferenceCube.transform.position = pos;
m_PointOfReferenceCube.transform.rotation = rot;
#if UNITY_WSA
if (store != null)
{
store.Delete(PointOfReferenceID);
}
if (m_PointOfReference)
{
DestroyImmediate(m_PointOfReference);
}
m_PointOfReference = m_PointOfReferenceCube.AddComponent<WorldAnchor>();
if (StatusText.Instance)
{
StatusText.Instance.SetText("Point of Reference Created");
}
// SaveAnchorToStore(m_PointOfReferenceID, m_PointOfReference);
StartCoroutine(SaveAnchor());
#endif
}
#if UNITY_WSA
void LogAsync(string message)
{
lock (m_MessagesAsync)
{
m_MessagesAsync.Add(message);
}
}
private void StoreLoaded(WorldAnchorStore store)
{
this.store = store;
// We've loaded. Wait to place.
StartCoroutine(PlaceWorldAnchor());
}
private IEnumerator PlaceWorldAnchor()
{
// Wait while the SR loads a bit.
yield return new WaitForSeconds(0.5f);
if (m_PointOfReference)
{
DestroyImmediate(m_PointOfReference);
}
m_PointOfReferenceCube.transform.position = Vector3.zero;
m_PointOfReferenceCube.transform.localScale = Vector3.one * 0.1f;
m_PointOfReference = store.Load(PointOfReferenceID, m_PointOfReferenceCube);
if (m_PointOfReference == null)
{
if (StatusText.Instance)
{
StatusText.Instance.SetText("No Point of Reference created.");
}
}
else
{
Debug.Log("Created anchor from WorldAnchorStore: " + PointOfReferenceID);
if (StatusText.Instance)
{
StatusText.Instance.SetText("Loaded WorldAnchorStore");
}
}
}
private IEnumerator SaveAnchor()
{
#if !UNITY_EDITOR
while (!m_PointOfReference.isLocated)
{
yield return new WaitForEndOfFrame();
}
#else
yield return 0;
#endif
SaveAnchorToStore(PointOfReferenceID, m_PointOfReference);
Debug.Log("SaveAnchor: Point of Reference Saved.");
}
private void SaveAnchorToStore(string id, WorldAnchor worldAnchor)
{
#if !UNITY_EDITOR
if ((store != null) && (store.Save(id, worldAnchor)))
{
Debug.Log("WorldAnchor Saved: " + id);
if (OnPlacement != null)
{
OnPlacement();
}
}
else
{
Debug.Log("Failed to Save WorldAnchor " + id);
}
#else
if (OnPlacement != null)
{
OnPlacement();
}
#endif
if (StatusText.Instance)
{
StatusText.Instance.SetText("Anchor Saved");
}
}
public void SetPointOfReference(byte[] pointOfReferenceData)
{
WorldAnchorTransferBatch.ImportAsync(pointOfReferenceData, OnImportComplete);
}
private void OnImportComplete(SerializationCompletionReason completionReason, WorldAnchorTransferBatch deserializedTransferBatch)
{
if (completionReason != SerializationCompletionReason.Succeeded)
{
LogAsync("Failed to import: " + completionReason.ToString());
return;
}
string[] ids = deserializedTransferBatch.GetAllIds();
if (ids.Length > 0)
{
if (m_PointOfReference)
{
DestroyImmediate(m_PointOfReference);
}
m_PointOfReferenceCube.transform.position = Vector3.zero;
m_PointOfReferenceCube.transform.localScale = Vector3.one * 0.1f;
m_PointOfReference = deserializedTransferBatch.LockObject(ids[0], m_PointOfReferenceCube);
if (StatusText.Instance)
{
StatusText.Instance.SetText("Anchor Created");
}
Debug.Log("Anchor Created");
if (store != null)
{
store.Delete(PointOfReferenceID);
}
StartCoroutine(SaveAnchor());
if (StatusText.Instance)
{
StatusText.Instance.SetText("Anchor Saved to Store");
}
Debug.Log("Anchor Saved to Store");
}
}
private void ClearAnchors()
{
if (store != null)
{
store.Clear();
}
Debug.Log("Cleared WorldAnchorStore");
m_PointOfReference = null;
if (StatusText.Instance)
{
StatusText.Instance.SetText("Anchors Cleared");
}
}
#endif
public void CreateManualPointOfReference()
{
m_ManualAnchorAcquisitionState = ManualPointOfReferenceAcquisitionStage.FirstPoint;
if (StatusText.Instance)
{
StatusText.Instance.SetTextUntimed("Click First Point for Point-of-Reference");
}
}
public void OnFingerPressed(InputSourceHands.CurrentHandState state)
{
switch (m_ManualAnchorAcquisitionState)
{
case ManualPointOfReferenceAcquisitionStage.Idle:
{
break;
}
case ManualPointOfReferenceAcquisitionStage.FirstPoint:
{
if (StatusText.Instance)
{
StatusText.Instance.SetTextUntimed("Click Second Point for Point-of-Reference");
}
m_ManualAnchorPos = HUX.Focus.FocusManager.Instance.GazeFocuser.Cursor.transform.position;
m_ManualAnchorAcquisitionState = ManualPointOfReferenceAcquisitionStage.SecondPoint;
break;
}
case ManualPointOfReferenceAcquisitionStage.SecondPoint:
{
if (StatusText.Instance)
{
StatusText.Instance.SetText("Point of Reference Created!");
}
m_ManualAnchorForward = (HUX.Focus.FocusManager.Instance.GazeFocuser.Cursor.transform.position - m_ManualAnchorPos).normalized;
m_ManualAnchorAcquisitionState = ManualPointOfReferenceAcquisitionStage.Acquired;
CreatePointOfReference(m_ManualAnchorPos, Quaternion.LookRotation(m_ManualAnchorForward));
break;
}
case ManualPointOfReferenceAcquisitionStage.Acquired:
{
break;
}
}
}
public void CalculateOffsetFromPointOfReference(Vector3 pos, Quaternion rot, out Vector3 posOffset, out Quaternion rotOffset)
{
if (m_PointOfReferenceCube != null)
{
Vector3 flattenedDir = m_PointOfReferenceCube.transform.forward;
flattenedDir.y = 0.0f;
rotOffset = Quaternion.Inverse(m_PointOfReferenceCube.transform.rotation) * rot;
Quaternion localRot = Quaternion.LookRotation(flattenedDir, Vector3.up);
posOffset = Quaternion.Inverse(localRot) * (pos - m_PointOfReferenceCube.transform.position);
}
else
{
posOffset = pos;
rotOffset = rot;
}
}
public void CalculatePosRotFromPointOfReference(Vector3 posOffset, Quaternion rotOffset, out Vector3 pos, out Quaternion rot)
{
if (m_PointOfReferenceCube != null)
{
Vector3 flattenedDir = m_PointOfReferenceCube.transform.forward;
flattenedDir.y = 0.0f;
rot = m_PointOfReferenceCube.transform.rotation * rotOffset;
Quaternion localRot = Quaternion.LookRotation(flattenedDir, Vector3.up);
pos = m_PointOfReferenceCube.transform.position + localRot * posOffset;
}
else
{
pos = posOffset;
rot = rotOffset;
}
}
}
| |
/*
* 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.
*/
// #define NUNIT25
using System;
using log4net.Config;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using OpenMetaverse;
using OpenSim.Framework;
using log4net;
using System.Reflection;
using System.Data.Common;
#if !NUNIT25
using NUnit.Framework.SyntaxHelpers;
#endif
// DBMS-specific:
using MySql.Data.MySqlClient;
using OpenSim.Data.MySQL;
using System.Data.SqlClient;
using OpenSim.Data.MSSQL;
using Mono.Data.Sqlite;
using OpenSim.Data.SQLite;
namespace OpenSim.Data.Tests
{
#if NUNIT25
[TestFixture(typeof(SqliteConnection), typeof(SQLiteInventoryStore), Description = "Inventory store tests (SQLite)")]
[TestFixture(typeof(MySqlConnection), typeof(MySQLInventoryData), Description = "Inventory store tests (MySQL)")]
[TestFixture(typeof(SqlConnection), typeof(MSSQLInventoryData), Description = "Inventory store tests (MS SQL Server)")]
#else
[TestFixture(Description = "Inventory store tests (SQLite)")]
public class SQLiteInventoryTests : InventoryTests<SqliteConnection, SQLiteInventoryStore>
{
}
[TestFixture(Description = "Inventory store tests (MySQL)")]
public class MySqlInventoryTests : InventoryTests<MySqlConnection, MySQLInventoryData>
{
}
[TestFixture(Description = "Inventory store tests (MS SQL Server)")]
public class MSSQLInventoryTests : InventoryTests<SqlConnection, MSSQLInventoryData>
{
}
#endif
public class InventoryTests<TConn, TInvStore> : BasicDataServiceTest<TConn, TInvStore>
where TConn : DbConnection, new()
where TInvStore : class, IInventoryDataPlugin, new()
{
public IInventoryDataPlugin db;
public UUID zero = UUID.Zero;
public UUID folder1 = UUID.Random();
public UUID folder2 = UUID.Random();
public UUID folder3 = UUID.Random();
public UUID owner1 = UUID.Random();
public UUID owner2 = UUID.Random();
public UUID owner3 = UUID.Random();
public UUID item1 = UUID.Random();
public UUID item2 = UUID.Random();
public UUID item3 = UUID.Random();
public UUID asset1 = UUID.Random();
public UUID asset2 = UUID.Random();
public UUID asset3 = UUID.Random();
public string name1;
public string name2 = "First Level folder";
public string name3 = "First Level folder 2";
public string niname1 = "My Shirt";
public string iname1 = "Shirt";
public string iname2 = "Text Board";
public string iname3 = "No Pants Barrel";
public InventoryTests(string conn) : base(conn)
{
name1 = "Root Folder for " + owner1.ToString();
}
public InventoryTests() : this("") { }
protected override void InitService(object service)
{
ClearDB();
db = (IInventoryDataPlugin)service;
db.Initialise(m_connStr);
}
private void ClearDB()
{
DropTables("inventoryitems", "inventoryfolders");
ResetMigrations("InventoryStore");
}
[Test]
public void T001_LoadEmpty()
{
Assert.That(db.getInventoryFolder(zero), Is.Null);
Assert.That(db.getInventoryFolder(folder1), Is.Null);
Assert.That(db.getInventoryFolder(folder2), Is.Null);
Assert.That(db.getInventoryFolder(folder3), Is.Null);
Assert.That(db.getInventoryItem(zero), Is.Null);
Assert.That(db.getInventoryItem(item1), Is.Null);
Assert.That(db.getInventoryItem(item2), Is.Null);
Assert.That(db.getInventoryItem(item3), Is.Null);
Assert.That(db.getUserRootFolder(zero), Is.Null);
Assert.That(db.getUserRootFolder(owner1), Is.Null);
}
// 01x - folder tests
[Test]
public void T010_FolderNonParent()
{
InventoryFolderBase f1 = NewFolder(folder2, folder1, owner1, name2);
// the folder will go in
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner1);
Assert.That(f1a, Is.Null);
}
[Test]
public void T011_FolderCreate()
{
InventoryFolderBase f1 = NewFolder(folder1, zero, owner1, name1);
// TODO: this is probably wrong behavior, but is what we have
// db.updateInventoryFolder(f1);
// InventoryFolderBase f1a = db.getUserRootFolder(owner1);
// Assert.That(uuid1, Is.EqualTo(f1a.ID))
// Assert.That(name1, Text.Matches(f1a.Name), "Assert.That(name1, Text.Matches(f1a.Name))");
// Assert.That(db.getUserRootFolder(owner1), Is.Null);
// succeed with true
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner1);
Assert.That(folder1, Is.EqualTo(f1a.ID), "Assert.That(folder1, Is.EqualTo(f1a.ID))");
Assert.That(name1, Text.Matches(f1a.Name), "Assert.That(name1, Text.Matches(f1a.Name))");
}
// we now have the following tree
// folder1
// +--- folder2
// +--- folder3
[Test]
public void T012_FolderList()
{
InventoryFolderBase f2 = NewFolder(folder3, folder1, owner1, name3);
db.addInventoryFolder(f2);
Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(2), "Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T013_FolderHierarchy()
{
int n = db.getFolderHierarchy(zero).Count; // (for dbg - easier to see what's returned)
Assert.That(n, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))");
n = db.getFolderHierarchy(folder1).Count;
Assert.That(n, Is.EqualTo(2), "Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T014_MoveFolder()
{
InventoryFolderBase f2 = db.getInventoryFolder(folder2);
f2.ParentID = folder3;
db.moveInventoryFolder(f2);
Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(zero).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(folder1).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(1), "Assert.That(db.getInventoryFolders(folder3).Count, Is.EqualTo(1))");
Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getInventoryFolders(UUID.Random()).Count, Is.EqualTo(0))");
}
[Test]
public void T015_FolderHierarchy()
{
Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2), "Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2))");
Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(1), "Assert.That(db.getFolderHierarchy(folder3).Count, Is.EqualTo(1))");
Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(UUID.Random()).Count, Is.EqualTo(0))");
}
// Item tests
[Test]
public void T100_NoItems()
{
Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder1).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder1).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder2).Count, Is.EqualTo(0))");
Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(0))");
}
// TODO: Feeding a bad inventory item down the data path will
// crash the system. This is largely due to the builder
// routines. That should be fixed and tested for.
[Test]
public void T101_CreatItems()
{
db.addInventoryItem(NewItem(item1, folder3, owner1, iname1, asset1));
db.addInventoryItem(NewItem(item2, folder3, owner1, iname2, asset2));
db.addInventoryItem(NewItem(item3, folder3, owner1, iname3, asset3));
Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(3), "Assert.That(db.getInventoryInFolder(folder3).Count, Is.EqualTo(3))");
}
[Test]
public void T102_CompareItems()
{
InventoryItemBase i1 = db.getInventoryItem(item1);
InventoryItemBase i2 = db.getInventoryItem(item2);
InventoryItemBase i3 = db.getInventoryItem(item3);
Assert.That(i1.Name, Is.EqualTo(iname1), "Assert.That(i1.Name, Is.EqualTo(iname1))");
Assert.That(i2.Name, Is.EqualTo(iname2), "Assert.That(i2.Name, Is.EqualTo(iname2))");
Assert.That(i3.Name, Is.EqualTo(iname3), "Assert.That(i3.Name, Is.EqualTo(iname3))");
Assert.That(i1.Owner, Is.EqualTo(owner1), "Assert.That(i1.Owner, Is.EqualTo(owner1))");
Assert.That(i2.Owner, Is.EqualTo(owner1), "Assert.That(i2.Owner, Is.EqualTo(owner1))");
Assert.That(i3.Owner, Is.EqualTo(owner1), "Assert.That(i3.Owner, Is.EqualTo(owner1))");
Assert.That(i1.AssetID, Is.EqualTo(asset1), "Assert.That(i1.AssetID, Is.EqualTo(asset1))");
Assert.That(i2.AssetID, Is.EqualTo(asset2), "Assert.That(i2.AssetID, Is.EqualTo(asset2))");
Assert.That(i3.AssetID, Is.EqualTo(asset3), "Assert.That(i3.AssetID, Is.EqualTo(asset3))");
}
[Test]
public void T103_UpdateItem()
{
// TODO: probably shouldn't have the ability to have an
// owner of an item in a folder not owned by the user
InventoryItemBase i1 = db.getInventoryItem(item1);
i1.Name = niname1;
i1.Description = niname1;
i1.Owner = owner2;
db.updateInventoryItem(i1);
i1 = db.getInventoryItem(item1);
Assert.That(i1.Name, Is.EqualTo(niname1), "Assert.That(i1.Name, Is.EqualTo(niname1))");
Assert.That(i1.Description, Is.EqualTo(niname1), "Assert.That(i1.Description, Is.EqualTo(niname1))");
Assert.That(i1.Owner, Is.EqualTo(owner2), "Assert.That(i1.Owner, Is.EqualTo(owner2))");
}
[Test]
public void T104_RandomUpdateItem()
{
PropertyScrambler<InventoryFolderBase> folderScrambler =
new PropertyScrambler<InventoryFolderBase>()
.DontScramble(x => x.Owner)
.DontScramble(x => x.ParentID)
.DontScramble(x => x.ID);
UUID owner = UUID.Random();
UUID folder = UUID.Random();
UUID rootId = UUID.Random();
UUID rootAsset = UUID.Random();
InventoryFolderBase f1 = NewFolder(folder, zero, owner, name1);
folderScrambler.Scramble(f1);
db.addInventoryFolder(f1);
InventoryFolderBase f1a = db.getUserRootFolder(owner);
Assert.That(f1a, Constraints.PropertyCompareConstraint(f1));
folderScrambler.Scramble(f1a);
db.updateInventoryFolder(f1a);
InventoryFolderBase f1b = db.getUserRootFolder(owner);
Assert.That(f1b, Constraints.PropertyCompareConstraint(f1a));
//Now we have a valid folder to insert into, we can insert the item.
PropertyScrambler<InventoryItemBase> inventoryScrambler =
new PropertyScrambler<InventoryItemBase>()
.DontScramble(x => x.ID)
.DontScramble(x => x.AssetID)
.DontScramble(x => x.Owner)
.DontScramble(x => x.Folder);
InventoryItemBase root = NewItem(rootId, folder, owner, iname1, rootAsset);
inventoryScrambler.Scramble(root);
db.addInventoryItem(root);
InventoryItemBase expected = db.getInventoryItem(rootId);
Assert.That(expected, Constraints.PropertyCompareConstraint(root)
.IgnoreProperty(x => x.InvType)
.IgnoreProperty(x => x.CreatorIdAsUuid)
.IgnoreProperty(x => x.Description)
.IgnoreProperty(x => x.CreatorId));
inventoryScrambler.Scramble(expected);
db.updateInventoryItem(expected);
InventoryItemBase actual = db.getInventoryItem(rootId);
Assert.That(actual, Constraints.PropertyCompareConstraint(expected)
.IgnoreProperty(x => x.InvType)
.IgnoreProperty(x => x.CreatorIdAsUuid)
.IgnoreProperty(x => x.Description)
.IgnoreProperty(x => x.CreatorId));
}
[Test]
public void T999_StillNull()
{
// After all tests are run, these should still return no results
Assert.That(db.getInventoryFolder(zero), Is.Null);
Assert.That(db.getInventoryItem(zero), Is.Null);
Assert.That(db.getUserRootFolder(zero), Is.Null);
Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0))");
}
private InventoryItemBase NewItem(UUID id, UUID parent, UUID owner, string name, UUID asset)
{
InventoryItemBase i = new InventoryItemBase();
i.ID = id;
i.Folder = parent;
i.Owner = owner;
i.CreatorId = owner.ToString();
i.Name = name;
i.Description = name;
i.AssetID = asset;
return i;
}
private InventoryFolderBase NewFolder(UUID id, UUID parent, UUID owner, string name)
{
InventoryFolderBase f = new InventoryFolderBase();
f.ID = id;
f.ParentID = parent;
f.Owner = owner;
f.Name = name;
return f;
}
}
}
| |
// 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.IO;
using System.Text;
using Microsoft.Xml;
using Microsoft.Xml.Schema;
//using Microsoft.Xml.Query;
using System.Diagnostics;
using MS.Internal.Xml;
namespace Microsoft.Xml
{
using System;
internal class HtmlUtf8RawTextWriter : XmlUtf8RawTextWriter
{
//
// Fields
//
protected ByteStack elementScope;
protected ElementProperties currentElementProperties;
private AttributeProperties _currentAttributeProperties;
private bool _endsWithAmpersand;
private byte[] _uriEscapingBuffer;
// settings
private string _mediaType;
private bool _doNotEscapeUriAttributes;
//
// Static fields
//
protected static TernaryTreeReadOnly elementPropertySearch;
protected static TernaryTreeReadOnly attributePropertySearch;
//
// Constants
//
private const int StackIncrement = 10;
//
// Constructors
//
public HtmlUtf8RawTextWriter(Stream stream, XmlWriterSettings settings) : base(stream, settings)
{
Init(settings);
}
//
// XmlRawWriter implementation
//
internal override void WriteXmlDeclaration(XmlStandalone standalone)
{
// Ignore xml declaration
}
internal override void WriteXmlDeclaration(string xmldecl)
{
// Ignore xml declaration
}
/// Html rules allow public ID without system ID and always output "html"
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
Debug.Assert(name != null && name.Length > 0);
RawText("<!DOCTYPE ");
// Bug 114337: Always output "html" or "HTML" in doc-type, even if "name" is something else
if (name == "HTML")
RawText("HTML");
else
RawText("html");
if (pubid != null)
{
RawText(" PUBLIC \"");
RawText(pubid);
if (sysid != null)
{
RawText("\" \"");
RawText(sysid);
}
bufBytes[bufPos++] = (byte)'"';
}
else if (sysid != null)
{
RawText(" SYSTEM \"");
RawText(sysid);
bufBytes[bufPos++] = (byte)'"';
}
else
{
bufBytes[bufPos++] = (byte)' ';
}
if (subset != null)
{
bufBytes[bufPos++] = (byte)'[';
RawText(subset);
bufBytes[bufPos++] = (byte)']';
}
bufBytes[this.bufPos++] = (byte)'>';
}
// For the HTML element, it should call this method with ns and prefix as String.Empty
public override void WriteStartElement(string prefix, string localName, string ns)
{
Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null);
elementScope.Push((byte)currentElementProperties);
if (ns.Length == 0)
{
Debug.Assert(prefix.Length == 0);
currentElementProperties = (ElementProperties)elementPropertySearch.FindCaseInsensitiveString(localName);
base.bufBytes[bufPos++] = (byte)'<';
base.RawText(localName);
base.attrEndPos = bufPos;
}
else
{
// Since the HAS_NS has no impact to the ElementTextBlock behavior,
// we don't need to push it into the stack.
currentElementProperties = ElementProperties.HAS_NS;
base.WriteStartElement(prefix, localName, ns);
}
}
// Output >. For HTML needs to output META info
internal override void StartElementContent()
{
base.bufBytes[base.bufPos++] = (byte)'>';
// Detect whether content is output
this.contentPos = this.bufPos;
if ((currentElementProperties & ElementProperties.HEAD) != 0)
{
WriteMetaElement();
}
}
// end element with />
// for HTML(ns.Length == 0)
// not an empty tag <h1></h1>
// empty tag <basefont>
internal override void WriteEndElement(string prefix, string localName, string ns)
{
if (ns.Length == 0)
{
Debug.Assert(prefix.Length == 0);
if ((currentElementProperties & ElementProperties.EMPTY) == 0)
{
bufBytes[base.bufPos++] = (byte)'<';
bufBytes[base.bufPos++] = (byte)'/';
base.RawText(localName);
bufBytes[base.bufPos++] = (byte)'>';
}
}
else
{
//xml content
base.WriteEndElement(prefix, localName, ns);
}
currentElementProperties = (ElementProperties)elementScope.Pop();
}
internal override void WriteFullEndElement(string prefix, string localName, string ns)
{
if (ns.Length == 0)
{
Debug.Assert(prefix.Length == 0);
if ((currentElementProperties & ElementProperties.EMPTY) == 0)
{
bufBytes[base.bufPos++] = (byte)'<';
bufBytes[base.bufPos++] = (byte)'/';
base.RawText(localName);
bufBytes[base.bufPos++] = (byte)'>';
}
}
else
{
//xml content
base.WriteFullEndElement(prefix, localName, ns);
}
currentElementProperties = (ElementProperties)elementScope.Pop();
}
// 1. How the outputBooleanAttribute(fBOOL) and outputHtmlUriText(fURI) being set?
// When SA is called.
//
// BOOL_PARENT URI_PARENT Others
// fURI
// URI att false true false
//
// fBOOL
// BOOL att true false false
//
// How they change the attribute output behaviors?
//
// 1) fURI=true fURI=false
// SA a=" a="
// AT HtmlURIText HtmlText
// EA " "
//
// 2) fBOOL=true fBOOL=false
// SA a a="
// AT HtmlText output nothing
// EA output nothing "
//
// When they get reset?
// At the end of attribute.
// 2. How the outputXmlTextElementScoped(fENs) and outputXmlTextattributeScoped(fANs) are set?
// fANs is in the scope of the fENs.
//
// SE(localName) SE(ns, pre, localName) SA(localName) SA(ns, pre, localName)
// fENs false(default) true(action)
// fANs false(default) false(default) false(default) true(action)
// how they get reset?
//
// EE(localName) EE(ns, pre, localName) EENC(ns, pre, localName) EA(localName) EA(ns, pre, localName)
// fENs false(action)
// fANs false(action)
// How they change the TextOutput?
//
// fENs | fANs Else
// AT XmlText HtmlText
//
//
// 3. Flags for processing &{ split situations
//
// When the flag is set?
//
// AT src[lastchar]='&' flag&{ = true;
//
// when it get result?
//
// AT method.
//
// How it changes the behaviors?
//
// flag&{=true
//
// AT if (src[0] == '{') {
// output "&{"
// }
// else {
// output &
// }
//
// EA output amp;
//
// SA if (flagBOOL == false) { output =";}
//
// AT if (flagBOOL) { return};
// if (flagNS) {XmlText;} {
// }
// else if (flagURI) {
// HtmlURIText;
// }
// else {
// HtmlText;
// }
//
// AT if (flagNS) {XmlText;} {
// }
// else if (flagURI) {
// HtmlURIText;
// }
// else if (!flagBOOL) {
// HtmlText; //flag&{ handling
// }
//
//
// EA if (flagBOOL == false) { output "
// }
// else if (flag&{) {
// output amp;
// }
//
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null);
if (ns.Length == 0)
{
Debug.Assert(prefix.Length == 0);
if (base.attrEndPos == bufPos)
{
base.bufBytes[bufPos++] = (byte)' ';
}
base.RawText(localName);
if ((currentElementProperties & (ElementProperties.BOOL_PARENT | ElementProperties.URI_PARENT | ElementProperties.NAME_PARENT)) != 0)
{
_currentAttributeProperties = (AttributeProperties)attributePropertySearch.FindCaseInsensitiveString(localName) &
(AttributeProperties)currentElementProperties;
if ((_currentAttributeProperties & AttributeProperties.BOOLEAN) != 0)
{
base.inAttributeValue = true;
return;
}
}
else
{
_currentAttributeProperties = AttributeProperties.DEFAULT;
}
base.bufBytes[bufPos++] = (byte)'=';
base.bufBytes[bufPos++] = (byte)'"';
}
else
{
base.WriteStartAttribute(prefix, localName, ns);
_currentAttributeProperties = AttributeProperties.DEFAULT;
}
base.inAttributeValue = true;
}
// Output the amp; at end of EndAttribute
public override void WriteEndAttribute()
{
if ((_currentAttributeProperties & AttributeProperties.BOOLEAN) != 0)
{
base.attrEndPos = bufPos;
}
else
{
if (_endsWithAmpersand)
{
OutputRestAmps();
_endsWithAmpersand = false;
}
base.bufBytes[bufPos++] = (byte)'"';
}
base.inAttributeValue = false;
base.attrEndPos = bufPos;
}
// HTML PI's use ">" to terminate rather than "?>".
public override void WriteProcessingInstruction(string target, string text)
{
Debug.Assert(target != null && target.Length != 0 && text != null);
bufBytes[base.bufPos++] = (byte)'<';
bufBytes[base.bufPos++] = (byte)'?';
base.RawText(target);
bufBytes[base.bufPos++] = (byte)' ';
base.WriteCommentOrPi(text, '?');
base.bufBytes[base.bufPos++] = (byte)'>';
if (base.bufPos > base.bufLen)
{
FlushBuffer();
}
}
// Serialize either attribute or element text using HTML rules.
public override unsafe void WriteString(string text)
{
Debug.Assert(text != null);
fixed (char* pSrc = text)
{
char* pSrcEnd = pSrc + text.Length;
if (base.inAttributeValue)
{
WriteHtmlAttributeTextBlock(pSrc, pSrcEnd);
}
else
{
WriteHtmlElementTextBlock(pSrc, pSrcEnd);
}
}
}
public override void WriteEntityRef(string name)
{
throw new InvalidOperationException(ResXml.Xml_InvalidOperation);
}
public override void WriteCharEntity(char ch)
{
throw new InvalidOperationException(ResXml.Xml_InvalidOperation);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
throw new InvalidOperationException(ResXml.Xml_InvalidOperation);
}
public override unsafe void WriteChars(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null);
Debug.Assert(index >= 0);
Debug.Assert(count >= 0 && index + count <= buffer.Length);
fixed (char* pSrcBegin = &buffer[index])
{
if (inAttributeValue)
{
WriteAttributeTextBlock(pSrcBegin, pSrcBegin + count);
}
else
{
WriteElementTextBlock(pSrcBegin, pSrcBegin + count);
}
}
}
//
// Private methods
//
private void Init(XmlWriterSettings settings)
{
Debug.Assert((int)ElementProperties.URI_PARENT == (int)AttributeProperties.URI);
Debug.Assert((int)ElementProperties.BOOL_PARENT == (int)AttributeProperties.BOOLEAN);
Debug.Assert((int)ElementProperties.NAME_PARENT == (int)AttributeProperties.NAME);
if (elementPropertySearch == null)
{
//elementPropertySearch should be init last for the mutli thread safe situation.
attributePropertySearch = new TernaryTreeReadOnly(HtmlTernaryTree.htmlAttributes);
elementPropertySearch = new TernaryTreeReadOnly(HtmlTernaryTree.htmlElements);
}
elementScope = new ByteStack(StackIncrement);
_uriEscapingBuffer = new byte[5];
currentElementProperties = ElementProperties.DEFAULT;
_mediaType = settings.MediaType;
_doNotEscapeUriAttributes = settings.DoNotEscapeUriAttributes;
}
protected void WriteMetaElement()
{
base.RawText("<META http-equiv=\"Content-Type\"");
if (_mediaType == null)
{
_mediaType = "text/html";
}
base.RawText(" content=\"");
base.RawText(_mediaType);
base.RawText("; charset=");
base.RawText(base.encoding.WebName);
base.RawText("\">");
}
// Justify the stack usage:
//
// Nested elements has following possible position combinations
// 1. <E1>Content1<E2>Content2</E2></E1>
// 2. <E1><E2>Content2</E2>Content1</E1>
// 3. <E1>Content<E2>Cotent2</E2>Content1</E1>
//
// In the situation 2 and 3, the stored currentElementProrperties will be E2's,
// only the top of the stack is the real E1 element properties.
protected unsafe void WriteHtmlElementTextBlock(char* pSrc, char* pSrcEnd)
{
if ((currentElementProperties & ElementProperties.NO_ENTITIES) != 0)
{
base.RawText(pSrc, pSrcEnd);
}
else
{
base.WriteElementTextBlock(pSrc, pSrcEnd);
}
}
protected unsafe void WriteHtmlAttributeTextBlock(char* pSrc, char* pSrcEnd)
{
if ((_currentAttributeProperties & (AttributeProperties.BOOLEAN | AttributeProperties.URI | AttributeProperties.NAME)) != 0)
{
if ((_currentAttributeProperties & AttributeProperties.BOOLEAN) != 0)
{
//if output boolean attribute, ignore this call.
return;
}
if ((_currentAttributeProperties & (AttributeProperties.URI | AttributeProperties.NAME)) != 0 && !_doNotEscapeUriAttributes)
{
WriteUriAttributeText(pSrc, pSrcEnd);
}
else
{
WriteHtmlAttributeText(pSrc, pSrcEnd);
}
}
else if ((currentElementProperties & ElementProperties.HAS_NS) != 0)
{
base.WriteAttributeTextBlock(pSrc, pSrcEnd);
}
else
{
WriteHtmlAttributeText(pSrc, pSrcEnd);
}
}
//
// &{ split cases
// 1). HtmlAttributeText("a&");
// HtmlAttributeText("{b}");
//
// 2). HtmlAttributeText("a&");
// EndAttribute();
// 3).split with Flush by the user
// HtmlAttributeText("a&");
// FlushBuffer();
// HtmlAttributeText("{b}");
//
// Solutions:
// case 1)hold the & output as &
// if the next income character is {, output {
// else output amp;
//
private unsafe void WriteHtmlAttributeText(char* pSrc, char* pSrcEnd)
{
if (_endsWithAmpersand)
{
if (pSrcEnd - pSrc > 0 && pSrc[0] != '{')
{
OutputRestAmps();
}
_endsWithAmpersand = false;
}
fixed (byte* pDstBegin = bufBytes)
{
byte* pDst = pDstBegin + this.bufPos;
char ch = (char)0;
for (; ; )
{
byte* pDstEnd = pDst + (pSrcEnd - pSrc);
if (pDstEnd > pDstBegin + bufLen)
{
pDstEnd = pDstBegin + bufLen;
}
while (pDst < pDstEnd && (((xmlCharType.charProperties[(ch = *pSrc)] & XmlCharType.fAttrValue) != 0) && ch <= 0x7F))
{
*pDst++ = (byte)ch;
pSrc++;
}
Debug.Assert(pSrc <= pSrcEnd);
// end of value
if (pSrc >= pSrcEnd)
{
break;
}
// end of buffer
if (pDst >= pDstEnd)
{
bufPos = (int)(pDst - pDstBegin);
FlushBuffer();
pDst = pDstBegin + 1;
continue;
}
// some character needs to be escaped
switch (ch)
{
case '&':
if (pSrc + 1 == pSrcEnd)
{
_endsWithAmpersand = true;
}
else if (pSrc[1] != '{')
{
pDst = XmlUtf8RawTextWriter.AmpEntity(pDst);
break;
}
*pDst++ = (byte)ch;
break;
case '"':
pDst = QuoteEntity(pDst);
break;
case '<':
case '>':
case '\'':
case (char)0x9:
*pDst++ = (byte)ch;
break;
case (char)0xD:
// do not normalize new lines in attributes - just escape them
pDst = CarriageReturnEntity(pDst);
break;
case (char)0xA:
// do not normalize new lines in attributes - just escape them
pDst = LineFeedEntity(pDst);
break;
default:
EncodeChar(ref pSrc, pSrcEnd, ref pDst);
continue;
}
pSrc++;
}
bufPos = (int)(pDst - pDstBegin);
}
}
private unsafe void WriteUriAttributeText(char* pSrc, char* pSrcEnd)
{
if (_endsWithAmpersand)
{
if (pSrcEnd - pSrc > 0 && pSrc[0] != '{')
{
OutputRestAmps();
}
_endsWithAmpersand = false;
}
fixed (byte* pDstBegin = bufBytes)
{
byte* pDst = pDstBegin + this.bufPos;
char ch = (char)0;
for (; ; )
{
byte* pDstEnd = pDst + (pSrcEnd - pSrc);
if (pDstEnd > pDstBegin + bufLen)
{
pDstEnd = pDstBegin + bufLen;
}
while (pDst < pDstEnd && (((xmlCharType.charProperties[(ch = *pSrc)] & XmlCharType.fAttrValue) != 0) && ch < 0x80))
{
*pDst++ = (byte)ch;
pSrc++;
}
Debug.Assert(pSrc <= pSrcEnd);
// end of value
if (pSrc >= pSrcEnd)
{
break;
}
// end of buffer
if (pDst >= pDstEnd)
{
bufPos = (int)(pDst - pDstBegin);
FlushBuffer();
pDst = pDstBegin + 1;
continue;
}
// some character needs to be escaped
switch (ch)
{
case '&':
if (pSrc + 1 == pSrcEnd)
{
_endsWithAmpersand = true;
}
else if (pSrc[1] != '{')
{
pDst = XmlUtf8RawTextWriter.AmpEntity(pDst);
break;
}
*pDst++ = (byte)ch;
break;
case '"':
pDst = QuoteEntity(pDst);
break;
case '<':
case '>':
case '\'':
case (char)0x9:
*pDst++ = (byte)ch;
break;
case (char)0xD:
// do not normalize new lines in attributes - just escape them
pDst = CarriageReturnEntity(pDst);
break;
case (char)0xA:
// do not normalize new lines in attributes - just escape them
pDst = LineFeedEntity(pDst);
break;
default:
const string hexDigits = "0123456789ABCDEF";
fixed (byte* pUriEscapingBuffer = _uriEscapingBuffer)
{
byte* pByte = pUriEscapingBuffer;
byte* pEnd = pByte;
XmlUtf8RawTextWriter.CharToUTF8(ref pSrc, pSrcEnd, ref pEnd);
while (pByte < pEnd)
{
*pDst++ = (byte)'%';
*pDst++ = (byte)hexDigits[*pByte >> 4];
*pDst++ = (byte)hexDigits[*pByte & 0xF];
pByte++;
}
}
continue;
}
pSrc++;
}
bufPos = (int)(pDst - pDstBegin);
}
}
// For handling &{ in Html text field. If & is not followed by {, it still needs to be escaped.
private void OutputRestAmps()
{
base.bufBytes[bufPos++] = (byte)'a';
base.bufBytes[bufPos++] = (byte)'m';
base.bufBytes[bufPos++] = (byte)'p';
base.bufBytes[bufPos++] = (byte)';';
}
}
//
// Indentation HtmlWriter only indent <BLOCK><BLOCK> situations
//
// Here are all the cases:
// ELEMENT1 actions ELEMENT2 actions SC EE
// 1). SE SC store SE blockPro SE a). check ELEMENT1 blockPro <A> </A>
// EE if SE, EE are blocks b). true: check ELEMENT2 blockPro <B> <B>
// c). detect ELEMENT is SE, SC
// d). increase the indexlevel
//
// 2). SE SC, Store EE blockPro EE a). check stored blockPro <A></A> </A>
// EE if SE, EE are blocks b). true: indexLevel same </B>
//
//
// This is an alternative way to make the output looks better
//
// Indentation HtmlWriter only indent <BLOCK><BLOCK> situations
//
// Here are all the cases:
// ELEMENT1 actions ELEMENT2 actions Samples
// 1). SE SC store SE blockPro SE a). check ELEMENT1 blockPro <A>(blockPos)
// b). true: check ELEMENT2 blockPro <B>
// c). detect ELEMENT is SE, SC
// d). increase the indentLevel
//
// 2). EE Store EE blockPro SE a). check stored blockPro </A>
// b). true: indentLevel same <B>
// c). output block2
//
// 3). EE same as above EE a). check stored blockPro </A>
// b). true: --indentLevel </B>
// c). output block2
//
// 4). SE SC same as above EE a). check stored blockPro <A></A>
// b). true: indentLevel no change
internal class HtmlUtf8RawTextWriterIndent : HtmlUtf8RawTextWriter
{
//
// Fields
//
private int _indentLevel;
// for detecting SE SC sitution
private int _endBlockPos;
// settings
private string _indentChars;
private bool _newLineOnAttributes;
//
// Constructors
//
public HtmlUtf8RawTextWriterIndent(Stream stream, XmlWriterSettings settings) : base(stream, settings)
{
Init(settings);
}
//
// XmlRawWriter overrides
//
/// <summary>
/// Serialize the document type declaration.
/// </summary>
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
base.WriteDocType(name, pubid, sysid, subset);
// Allow indentation after DocTypeDecl
_endBlockPos = base.bufPos;
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null);
base.elementScope.Push((byte)base.currentElementProperties);
if (ns.Length == 0)
{
Debug.Assert(prefix.Length == 0);
base.currentElementProperties = (ElementProperties)elementPropertySearch.FindCaseInsensitiveString(localName);
if (_endBlockPos == base.bufPos && (base.currentElementProperties & ElementProperties.BLOCK_WS) != 0)
{
WriteIndent();
}
_indentLevel++;
base.bufBytes[bufPos++] = (byte)'<';
}
else
{
base.currentElementProperties = ElementProperties.HAS_NS | ElementProperties.BLOCK_WS;
if (_endBlockPos == base.bufPos)
{
WriteIndent();
}
_indentLevel++;
base.bufBytes[base.bufPos++] = (byte)'<';
if (prefix.Length != 0)
{
base.RawText(prefix);
base.bufBytes[base.bufPos++] = (byte)':';
}
}
base.RawText(localName);
base.attrEndPos = bufPos;
}
internal override void StartElementContent()
{
base.bufBytes[base.bufPos++] = (byte)'>';
// Detect whether content is output
base.contentPos = base.bufPos;
if ((currentElementProperties & ElementProperties.HEAD) != 0)
{
WriteIndent();
WriteMetaElement();
_endBlockPos = base.bufPos;
}
else if ((base.currentElementProperties & ElementProperties.BLOCK_WS) != 0)
{
// store the element block position
_endBlockPos = base.bufPos;
}
}
internal override void WriteEndElement(string prefix, string localName, string ns)
{
bool isBlockWs;
Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null);
_indentLevel--;
// If this element has block whitespace properties,
isBlockWs = (base.currentElementProperties & ElementProperties.BLOCK_WS) != 0;
if (isBlockWs)
{
// And if the last node to be output had block whitespace properties,
// And if content was output within this element,
if (_endBlockPos == base.bufPos && base.contentPos != base.bufPos)
{
// Then indent
WriteIndent();
}
}
base.WriteEndElement(prefix, localName, ns);
// Reset contentPos in case of empty elements
base.contentPos = 0;
// Mark end of element in buffer for element's with block whitespace properties
if (isBlockWs)
{
_endBlockPos = base.bufPos;
}
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
if (_newLineOnAttributes)
{
RawText(base.newLineChars);
_indentLevel++;
WriteIndent();
_indentLevel--;
}
base.WriteStartAttribute(prefix, localName, ns);
}
protected override void FlushBuffer()
{
// Make sure the buffer will reset the block position
_endBlockPos = (_endBlockPos == base.bufPos) ? 1 : 0;
base.FlushBuffer();
}
//
// Private methods
//
private void Init(XmlWriterSettings settings)
{
_indentLevel = 0;
_indentChars = settings.IndentChars;
_newLineOnAttributes = settings.NewLineOnAttributes;
}
private void WriteIndent()
{
// <block><inline> -- suppress ws betw <block> and <inline>
// <block><block> -- don't suppress ws betw <block> and <block>
// <block>text -- suppress ws betw <block> and text (handled by wcharText method)
// <block><?PI?> -- suppress ws betw <block> and PI
// <block><!-- --> -- suppress ws betw <block> and comment
// <inline><block> -- suppress ws betw <inline> and <block>
// <inline><inline> -- suppress ws betw <inline> and <inline>
// <inline>text -- suppress ws betw <inline> and text (handled by wcharText method)
// <inline><?PI?> -- suppress ws betw <inline> and PI
// <inline><!-- --> -- suppress ws betw <inline> and comment
RawText(base.newLineChars);
for (int i = _indentLevel; i > 0; i--)
{
RawText(_indentChars);
}
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Collections;
using System.Collections.Generic;
using Alachisoft.NCache.Caching.DataGrouping;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.DataStructures.Clustered;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Runtime.Caching;
using Alachisoft.NCache.Runtime.Serialization;
using Alachisoft.NCache.Runtime.Serialization.IO;
using System.Collections.Concurrent;
namespace Alachisoft.NCache.Caching.Statistics
{
/// <summary>
/// The class that contains information specific to a single node in the cluster.
/// Contains the address as well as statistics of the local cache.
/// </summary>
[Serializable]
public class NodeInfo : ICloneable, IComparable, ICompactSerializable
{
/// <summary> The IP address, port tuple; uniquely identifying the node. </summary>
private Address _address;
/// <summary> The name of the sub-cluster this node belongs to. </summary>
private string _subgroupName;
/// <summary> The statistics of the node. </summary>
public CacheStatistics _stats;
/// <summary> Up status of node. </summary>
private BitSet _status = new BitSet();
/// <summary>Data groups associated with this node</summary>
private DataAffinity _dataAffinity;
private ArrayList _connectedClients = ArrayList.Synchronized(new ArrayList());
/// <summary>Client/Server address of the node.</summary>
private Address _rendererAddress;
/// <summary>For sequencing stats replication, we will keep node guid to identify if node is restarted</summary>
private string _nodeGuid = System.Guid.NewGuid().ToString();
/// <summary>For sequencing stats replication </summary>
private int _statsReplicationCounter = 0;
private bool _isInproc;
private bool _isStartedAsMirror;
private ArrayList _localConnectedClientsInfo = ArrayList.Synchronized(new ArrayList());
/// <summary>
/// Constructor.
/// </summary>
public NodeInfo()
{
}
/// <summary>
/// Overloaded Constructor
/// </summary>
/// <param name="address"></param>
public NodeInfo(Address address)
{
_address = address;
}
public NodeInfo(Address address, bool isStartedAsMirror)
{
_address = address;
_isStartedAsMirror = isStartedAsMirror;
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="info"></param>
protected NodeInfo(NodeInfo info)
{
this._address = info._address == null ? null : info._address.Clone() as Address;
this._rendererAddress = info._rendererAddress != null ? info._rendererAddress.Clone() as Address : null;
this._stats = info._stats == null ? null : info._stats.Clone() as CacheStatistics;
this._status = info._status;
this._subgroupName = info._subgroupName;
this._isInproc = info._isInproc;
this._dataAffinity = info._dataAffinity == null ? null : info._dataAffinity.Clone() as DataAffinity;
_isStartedAsMirror = info.IsStartedAsMirror;
this._nodeGuid = info._nodeGuid;
_statsReplicationCounter = info._statsReplicationCounter;
this.CacheNodeStatus = info.CacheNodeStatus;
if (info._connectedClients != null)
{
lock (info._connectedClients.SyncRoot)
{
this._connectedClients = info._connectedClients.Clone() as ArrayList;
this._localConnectedClientsInfo = info._localConnectedClientsInfo.Clone() as ArrayList;
}
}
}
/// <summary>
/// The IP address, port tuple; uniquely identifying the node.
/// </summary>
public Address Address
{
get { return _address; }
set { _address = value; }
}
public Address RendererAddress
{
get { return _rendererAddress; }
set { _rendererAddress = value; }
}
public bool IsStartedAsMirror
{
get { return _isStartedAsMirror; }
set { _isStartedAsMirror = value; }
}
/// <summary>
/// Gets/sets the status of the node whether a node is InProc or OutProc.
/// </summary>
public bool IsInproc
{
get { return _isInproc; }
set { _isInproc = value; }
}
public string NodeGuid
{
get { return _nodeGuid; }
set { _nodeGuid = value; }
}
public int StatsReplicationCounter
{
get { return _statsReplicationCounter; }
set { _statsReplicationCounter = value; }
}
/// <summary>
/// The name of the sub-cluster this node belongs to.
/// </summary>
public string SubgroupName
{
get { return _subgroupName; }
set { _subgroupName = value; }
}
/// <summary>
/// The data groups settings for the node.
/// </summary>
public DataAffinity DataAffinity
{
get { return _dataAffinity; }
set { _dataAffinity = value; }
}
/// <summary>
/// The number of nodes in the cluster that are providers or consumers, i.e., group members.
/// </summary>
public CacheStatistics Statistics
{
get { return _stats; }
set { _stats = value; }
}
/// <summary>
/// The runtime status of node.
/// </summary>
internal BitSet Status
{
get { return _status; }
set { _status = value; }
}
public ArrayList ConnectedClients
{
get { return _connectedClients; }
set { _connectedClients = value; }
}
public ArrayList OldConnectedClientsInfo
{
get { return _localConnectedClientsInfo; }
set { _localConnectedClientsInfo = value; }
}
/// <summary>
/// Get/Set the value indicating whether this node is active or not.
/// This property is valid only for Mirror Cache Topology.
/// </summary>
public bool IsActive
{
get { return Status.IsAnyBitSet(NodeStatus.Coordinator); }
}
#region / --- IComparable --- /
/// <summary>
/// Compares the current instance with another object of the same type.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>A 32-bit signed integer that indicates the relative order of the comparands.</returns>
public int CompareTo(object obj)
{
return _address.CompareTo(((NodeInfo) obj).Address);
}
#endregion
public override bool Equals(object obj)
{
return CompareTo(obj) == 0;
}
#region / --- ICloneable --- /
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>A new object that is a copy of this instance.</returns>
public object Clone()
{
return new NodeInfo(this);
}
#endregion
/// <summary>
/// returns the string representation of the statistics.
/// </summary>
/// <returns></returns>
public override string ToString()
{
System.Text.StringBuilder ret = new System.Text.StringBuilder();
try
{
ret.Append("Node[Adr:" + _address);
if (_stats != null)
ret.Append(", " + _stats);
ret.Append("]");
}
catch (Exception e)
{
}
return ret.ToString();
}
#region / --- ICompactSerializable --- /
public void Deserialize(CompactReader reader)
{
_address = Address.ReadAddress(reader);
_subgroupName = reader.ReadObject() as string;
_stats = CacheStatistics.ReadCacheStatistics(reader);
_status = reader.ReadObject() as BitSet;
_dataAffinity = DataAffinity.ReadDataAffinity(reader);
_connectedClients = (ArrayList) reader.ReadObject();
_isInproc = reader.ReadBoolean();
_rendererAddress = Address.ReadAddress(reader);
_isStartedAsMirror = reader.ReadBoolean();
_nodeGuid = reader.ReadObject() as string;
_statsReplicationCounter = reader.ReadInt32();
this.CacheNodeStatus =(Alachisoft.NCache.Common.Monitoring.CacheNodeStatus) reader.ReadByte();
_localConnectedClientsInfo = (ArrayList)reader.ReadObject();
}
public void Serialize(CompactWriter writer)
{
Address.WriteAddress(writer, _address);
writer.WriteObject(_subgroupName);
CacheStatistics.WriteCacheStatistics(writer, _stats);
writer.WriteObject(_status);
DataAffinity.WriteDataAffinity(writer, _dataAffinity);
writer.WriteObject(_connectedClients);
writer.Write(_isInproc);
Address.WriteAddress(writer, _rendererAddress);
writer.Write(_isStartedAsMirror);
writer.WriteObject(_nodeGuid);
writer.Write(_statsReplicationCounter);
writer.Write((byte)CacheNodeStatus);
writer.WriteObject(_localConnectedClientsInfo);
}
#endregion
public static NodeInfo ReadNodeInfo(CompactReader reader)
{
byte isNull = reader.ReadByte();
if (isNull == 1)
return null;
NodeInfo newInfo = new NodeInfo();
newInfo.Deserialize(reader);
return newInfo;
}
public static void WriteNodeInfo(CompactWriter writer, NodeInfo nodeInfo)
{
byte isNull = 1;
if (nodeInfo == null)
writer.Write(isNull);
else
{
isNull = 0;
writer.Write(isNull);
nodeInfo.Serialize(writer);
}
return;
}
public Common.Monitoring.CacheNodeStatus CacheNodeStatus { get; set; }
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for ProtectedItemsOperations.
/// </summary>
public static partial class ProtectedItemsOperationsExtensions
{
/// <summary>
/// Provides a pageable list of all items that can be backed up within a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='skipToken'>
/// skipToken Filter.
/// </param>
public static Microsoft.Rest.Azure.IPage<ProtectedItemResource> List(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<ProtectedItemQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<ProtectedItemQueryObject>), string skipToken = default(string))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectedItemsOperations)s).ListAsync(vaultName, resourceGroupName, odataQuery, skipToken), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Provides a pageable list of all items that can be backed up within a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='skipToken'>
/// skipToken Filter.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<ProtectedItemResource>> ListAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<ProtectedItemQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<ProtectedItemQueryObject>), string skipToken = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(vaultName, resourceGroupName, odataQuery, skipToken, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Provides the details of the backed up item. This is an asynchronous
/// operation. To know the status of the operation, call the
/// GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item name whose details are to be fetched.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static ProtectedItemResource Get(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, Microsoft.Rest.Azure.OData.ODataQuery<GetProtectedItemQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<GetProtectedItemQueryObject>))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectedItemsOperations)s).GetAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, odataQuery), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Provides the details of the backed up item. This is an asynchronous
/// operation. To know the status of the operation, call the
/// GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item name whose details are to be fetched.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<ProtectedItemResource> GetAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, Microsoft.Rest.Azure.OData.ODataQuery<GetProtectedItemQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<GetProtectedItemQueryObject>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Enables backup of an item or to modifies the backup policy information of
/// an already backed up item. This is an asynchronous operation. To know the
/// status of the operation, call the GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backup item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backup item.
/// </param>
/// <param name='protectedItemName'>
/// Item name to be backed up.
/// </param>
/// <param name='resourceProtectedItem'>
/// resource backed up item
/// </param>
public static void CreateOrUpdate(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ProtectedItemResource resourceProtectedItem)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectedItemsOperations)s).CreateOrUpdateAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, resourceProtectedItem), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Enables backup of an item or to modifies the backup policy information of
/// an already backed up item. This is an asynchronous operation. To know the
/// status of the operation, call the GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backup item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backup item.
/// </param>
/// <param name='protectedItemName'>
/// Item name to be backed up.
/// </param>
/// <param name='resourceProtectedItem'>
/// resource backed up item
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task CreateOrUpdateAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ProtectedItemResource resourceProtectedItem, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.CreateOrUpdateWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, resourceProtectedItem, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Used to disable backup of an item within a container. This is an
/// asynchronous operation. To know the status of the request, call the
/// GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item to be deleted.
/// </param>
public static void Delete(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectedItemsOperations)s).DeleteAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Used to disable backup of an item within a container. This is an
/// asynchronous operation. To know the status of the request, call the
/// GetItemOperationResult API.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backed up item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backed up item.
/// </param>
/// <param name='protectedItemName'>
/// Backed up item to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task DeleteAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Provides a pageable list of all items that can be backed up within a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<ProtectedItemResource> ListNext(this IProtectedItemsOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectedItemsOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Provides a pageable list of all items that can be backed up within a
/// subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<ProtectedItemResource>> ListNextAsync(this IProtectedItemsOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
namespace CsvHelper.Excel
{
using System;
using System.Text.RegularExpressions;
using ClosedXML.Excel;
using CsvHelper.Configuration;
/// <summary>
/// Defines methods used to serialize data into an Excel (2007+) file.
/// </summary>
public class ExcelSerializer : ICsvSerializer
{
private readonly string path;
private readonly bool disposeWorkbook;
private readonly IXLRangeBase range;
private readonly bool disposeWorksheet;
private bool disposed;
private int currentRow = 1;
/// <summary>
/// Creates a new serializer using a new <see cref="XLWorkbook"/> saved to the given <paramref name="path"/>.
/// <remarks>
/// The workbook will not be saved until the serializer is disposed.
/// </remarks>
/// </summary>
/// <param name="path">The path to which to save the workbook.</param>
/// <param name="configuration">The configuration</param>
public ExcelSerializer(string path, CsvConfiguration configuration = null)
: this(new XLWorkbook(XLEventTracking.Disabled), configuration)
{
this.path = path;
disposeWorkbook = true;
}
/// <summary>
/// Creates a new serializer using a new <see cref="XLWorkbook"/> saved to the given <paramref name="path"/>.
/// <remarks>
/// The workbook will not be saved until the serializer is disposed.
/// </remarks>
/// </summary>
/// <param name="path">The path to which to save the workbook.</param>
/// <param name="sheetName">The name of the sheet to which to save</param>
public ExcelSerializer(string path, string sheetName) : this(new XLWorkbook(XLEventTracking.Disabled).AddWorksheet(sheetName))
{
this.path = path;
disposeWorkbook = true;
}
/// <summary>
/// Creates a new serializer using the given <see cref="XLWorkbook"/> and <see cref="CsvConfiguration"/>.
/// <remarks>
/// The <paramref name="workbook"/> will <b><i>not</i></b> be disposed of when the serializer is disposed.
/// The workbook will <b><i>not</i></b> be saved by the serializer.
/// A new worksheet will be added to the workbook.
/// </remarks>
/// </summary>
/// <param name="workbook">The workbook to write the data to.</param>
/// <param name="configuration">The configuration.</param>
public ExcelSerializer(XLWorkbook workbook, CsvConfiguration configuration = null)
: this(workbook, "Export", configuration)
{
disposeWorksheet = true;
}
/// <summary>
/// Creates a new serializer using the given <see cref="XLWorkbook"/> and <see cref="CsvConfiguration"/>.
/// <remarks>
/// The <paramref name="workbook"/> will <b><i>not</i></b> be disposed of when the serializer is disposed.
/// The workbook will <b><i>not</i></b> be saved by the serializer.
/// A new worksheet will be added to the workbook.
/// </remarks>
/// </summary>
/// <param name="workbook">The workbook to write the data to.</param>
/// <param name="sheetName">The name of the sheet to write to.</param>
/// <param name="configuration">The configuration.</param>
public ExcelSerializer(XLWorkbook workbook, string sheetName, CsvConfiguration configuration = null)
: this(workbook.GetOrAddWorksheet(sheetName), configuration)
{
disposeWorksheet = true;
}
/// <summary>
/// Creates a new serializer using the given <see cref="IXLWorksheet"/>.
/// <remarks>
/// The <paramref name="worksheet"/> will <b><i>not</i></b> be disposed of when the serializer is disposed.
/// The workbook will <b><i>not</i></b> be saved by the serializer.
/// </remarks>
/// </summary>
/// <param name="worksheet">The worksheet to write the data to.</param>
/// <param name="configuration">The configuration</param>
public ExcelSerializer(IXLWorksheet worksheet, CsvConfiguration configuration = null) : this((IXLRangeBase)worksheet, configuration) { }
/// <summary>
/// Creates a new serializer using the given <see cref="IXLWorksheet"/>.
/// </summary>
/// <param name="range">The range to write the data to.</param>
/// <param name="configuration">The configuration</param>
public ExcelSerializer(IXLRange range, CsvConfiguration configuration = null) : this((IXLRangeBase)range, configuration) { }
private ExcelSerializer(IXLRangeBase range, CsvConfiguration configuration)
{
Workbook = range.Worksheet.Workbook;
this.range = range;
Configuration = configuration ?? new CsvConfiguration();
Configuration.QuoteNoFields = true;
}
/// <summary>
/// Gets the configuration.
/// </summary>
public CsvConfiguration Configuration { get; }
/// <summary>
/// Gets the workbook to which the data is being written.
/// </summary>
/// <value>
/// The workbook.
/// </value>
public XLWorkbook Workbook { get; }
/// <summary>
/// Gets and sets the number of rows to offset the start position from.
/// </summary>
public int RowOffset { get; set; } = 0;
/// <summary>
/// Gets and sets the number of columns to offset the start position from.
/// </summary>
public int ColumnOffset { get; set; } = 0;
/// <summary>
/// Writes a record to the Excel file.
/// </summary>
/// <param name="record">The record to write.</param>
/// <exception cref="ObjectDisposedException">
/// Thrown is the serializer has been disposed.
/// </exception>
public virtual void Write(string[] record)
{
CheckDisposed();
for (var i = 0; i < record.Length; i++)
{
range.AsRange().Cell(currentRow + RowOffset, i + 1 + ColumnOffset).Value = ReplaceHexadecimalSymbols(record[i]);
}
currentRow++;
}
/// <summary>
/// Replaces the hexadecimal symbols.
/// </summary>
/// <param name="text">The text to replace.</param>
/// <returns>The input</returns>
protected static string ReplaceHexadecimalSymbols(string text)
{
if (String.IsNullOrEmpty(text)) return text;
return Regex.Replace(text, "[\x00-\x08\x0B\x0C\x0E-\x1F]", String.Empty, RegexOptions.Compiled);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Finalizes an instance of the <see cref="ExcelSerializer"/> class.
/// </summary>
~ExcelSerializer()
{
Dispose(false);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposed) return;
if (disposing)
{
if (disposeWorksheet) range.Worksheet.Dispose();
if (disposeWorkbook)
{
Workbook.SaveAs(path);
Workbook.Dispose();
}
}
disposed = true;
}
/// <summary>
/// Checks if the instance has been disposed of.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// Thrown is the serializer has been disposed.
/// </exception>
protected virtual void CheckDisposed()
{
if (disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Security;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Internal.Runtime.CompilerServices;
namespace System.Runtime.InteropServices.WindowsRuntime
{
// This is a set of stub methods implementing the support for the IVector`1 interface on managed
// objects that implement IList`1. Used by the interop mashaling infrastructure.
//
// The methods on this class must be written VERY carefully to avoid introducing security holes.
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not ListToVectorAdapter objects. Rather, they are of type
// IList<T>. No actual ListToVectorAdapter object is ever instantiated. Thus, you will
// see a lot of expressions that cast "this" to "IList<T>".
internal sealed class ListToVectorAdapter
{
private ListToVectorAdapter()
{
Debug.Fail("This class is never instantiated");
}
// T GetAt(uint index)
internal T GetAt<T>(uint index)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
EnsureIndexInt32(index, _this.Count);
try
{
return _this[(Int32)index];
}
catch (ArgumentOutOfRangeException ex)
{
throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
}
}
// uint Size { get }
internal uint Size<T>()
{
IList<T> _this = Unsafe.As<IList<T>>(this);
return (uint)_this.Count;
}
// IVectorView<T> GetView()
internal IReadOnlyList<T> GetView<T>()
{
IList<T> _this = Unsafe.As<IList<T>>(this);
Debug.Assert(_this != null);
// Note: This list is not really read-only - you could QI for a modifiable
// list. We gain some perf by doing this. We believe this is acceptable.
IReadOnlyList<T> roList = _this as IReadOnlyList<T>;
if (roList == null)
{
roList = new ReadOnlyCollection<T>(_this);
}
return roList;
}
// bool IndexOf(T value, out uint index)
internal bool IndexOf<T>(T value, out uint index)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
int ind = _this.IndexOf(value);
if (-1 == ind)
{
index = 0;
return false;
}
index = (uint)ind;
return true;
}
// void SetAt(uint index, T value)
internal void SetAt<T>(uint index, T value)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
EnsureIndexInt32(index, _this.Count);
try
{
_this[(int)index] = value;
}
catch (ArgumentOutOfRangeException ex)
{
throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
}
}
// void InsertAt(uint index, T value)
internal void InsertAt<T>(uint index, T value)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
// Inserting at an index one past the end of the list is equivalent to appending
// so we need to ensure that we're within (0, count + 1).
EnsureIndexInt32(index, _this.Count + 1);
try
{
_this.Insert((int)index, value);
}
catch (ArgumentOutOfRangeException ex)
{
// Change error code to match what WinRT expects
ex.SetErrorCode(HResults.E_BOUNDS);
throw;
}
}
// void RemoveAt(uint index)
internal void RemoveAt<T>(uint index)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
EnsureIndexInt32(index, _this.Count);
try
{
_this.RemoveAt((Int32)index);
}
catch (ArgumentOutOfRangeException ex)
{
// Change error code to match what WinRT expects
ex.SetErrorCode(HResults.E_BOUNDS);
throw;
}
}
// void Append(T value)
internal void Append<T>(T value)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
_this.Add(value);
}
// void RemoveAtEnd()
internal void RemoveAtEnd<T>()
{
IList<T> _this = Unsafe.As<IList<T>>(this);
if (_this.Count == 0)
{
Exception e = new InvalidOperationException(SR.InvalidOperation_CannotRemoveLastFromEmptyCollection);
e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
uint size = (uint)_this.Count;
RemoveAt<T>(size - 1);
}
// void Clear()
internal void Clear<T>()
{
IList<T> _this = Unsafe.As<IList<T>>(this);
_this.Clear();
}
// uint GetMany(uint startIndex, T[] items)
internal uint GetMany<T>(uint startIndex, T[] items)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
return GetManyHelper<T>(_this, startIndex, items);
}
// void ReplaceAll(T[] items)
internal void ReplaceAll<T>(T[] items)
{
IList<T> _this = Unsafe.As<IList<T>>(this);
_this.Clear();
if (items != null)
{
foreach (T item in items)
{
_this.Add(item);
}
}
}
// Helpers:
private static void EnsureIndexInt32(uint index, int listCapacity)
{
// We use '<=' and not '<' becasue Int32.MaxValue == index would imply
// that Size > Int32.MaxValue:
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue);
e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
}
private static uint GetManyHelper<T>(IList<T> sourceList, uint startIndex, T[] items)
{
// Calling GetMany with a start index equal to the size of the list should always
// return 0 elements, regardless of the input item size
if (startIndex == sourceList.Count)
{
return 0;
}
EnsureIndexInt32(startIndex, sourceList.Count);
if (items == null)
{
return 0;
}
uint itemCount = Math.Min((uint)items.Length, (uint)sourceList.Count - startIndex);
for (uint i = 0; i < itemCount; ++i)
{
items[i] = sourceList[(int)(i + startIndex)];
}
if (typeof(T) == typeof(string))
{
string[] stringItems = items as string[];
// Fill in rest of the array with String.Empty to avoid marshaling failure
for (uint i = itemCount; i < items.Length; ++i)
stringItems[i] = String.Empty;
}
return itemCount;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using CPV.Models;
using CPV.Models.ManageViewModels;
using CPV.Services;
namespace CPV.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
// 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.Globalization;
using System.Windows.Forms;
using mshtml;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.HtmlEditor;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Mshtml;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing
{
internal class PostTitleEditingElementBehavior : TitledRegionElementBehavior
{
private bool defaultedText = false;
public PostTitleEditingElementBehavior(IHtmlEditorComponentContext editorContext, IHTMLElement prevEditableRegion, IHTMLElement nextEditableRegion)
: base(editorContext, prevEditableRegion, nextEditableRegion)
{
}
private string DefaultText
{
get
{
return String.Format(CultureInfo.CurrentCulture, Res.Get(StringId.TitleDefaultText), EditingTargetName);
}
}
public bool DefaultedText
{
get
{
return defaultedText;
}
}
internal string EditingTargetName
{
get { return _editingTargetName; }
set { _editingTargetName = value; }
}
private string _editingTargetName = Res.Get(StringId.PostLower);
protected override void OnElementAttached()
{
base.OnElementAttached();
if (PostEditorSettings.AutomationMode)
{
//Test automation requires the element to be explicitly named in the accessibility tree, but
//setting a title causes an annoying tooltip and focus rectanlge, so we only show it in automation mode
HTMLElement2.tabIndex = 0;
HTMLElement.title = " Post Title";
}
if (string.IsNullOrEmpty(HTMLElement.innerText))
{
//set the default text for this editable region
using (IUndoUnit undo = EditorContext.CreateInvisibleUndoUnit())
{
HTMLElement.innerText = DefaultText;
defaultedText = true;
RegionBorderVisible = !Selected && defaultedText;
undo.Commit();
}
}
//fix bug 403230: set the title style to block element so that it takes up the entire line.
(HTMLElement as IHTMLElement2).runtimeStyle.display = "block";
}
public override string GetEditedHtml(bool useXhtml, bool doCleanup)
{
if (defaultedText)
{
return String.Empty;
}
else if (HTMLElement.innerText == null)
{
return String.Empty;
}
else
{
return HTMLElement.innerText.Trim();
}
}
public event EventHandler TitleChanged;
protected virtual void OnTitleChanged(EventArgs evt)
{
if (TitleChanged != null)
{
TitleChanged(null, evt);
}
defaultedText = false;
}
/// <summary>
/// Checks to see if the title has been edited.
/// </summary>
private void CheckForTitleEdits()
{
if (HTMLElement.innerText != DefaultText && defaultedText)
{
OnTitleChanged(EventArgs.Empty);
}
}
public void CleanBeforeInsert()
{
using (IUndoUnit undo = EditorContext.CreateInvisibleUndoUnit())
{
//Fire event if title has changed.
CheckForTitleEdits();
// If the title contains the default text..
if (defaultedText)
{
// Clear it before the insert.
HTMLElement.innerText = null;
defaultedText = false;
}
undo.Commit();
}
}
protected override void OnSelectedChanged()
{
base.OnSelectedChanged();
//Show the region border if the text is defaulted or empty
//If the region is selected, clear any defaulted text
using (IUndoUnit undo = EditorContext.CreateInvisibleUndoUnit())
{
CheckForTitleEdits();
if (Selected)
{
if (defaultedText)
{
HTMLElement.innerText = null;
RegionBorderVisible = true;
defaultedText = false;
}
OnEditableRegionFocusChanged(null, new EditableRegionFocusChangedEventArgs(false));
}
else
{
if (HTMLElement.innerText == null)
{
HTMLElement.innerText = DefaultText;
defaultedText = true;
RegionBorderVisible = true;
}
RegionBorderVisible = defaultedText;
}
undo.Commit();
}
}
protected override void OnCommandKey(object sender, KeyEventArgs e)
{
base.OnCommandKey(sender, e);
bool addDamage = false;
if (e.KeyCode == Keys.Enter)
{
LastChanceKeyboardHook.OnBeforeKeyHandled(this, e);
SelectNextRegion();
e.Handled = true;
addDamage = true;
}
else if (e.KeyCode == Keys.Tab && !e.Shift)
{
LastChanceKeyboardHook.OnBeforeKeyHandled(this, e);
SelectNextRegion();
//Cancel the event so that it doesn't trigger the blockquote command
e.Handled = true;
addDamage = true;
}
if (addDamage)
{
// WinLive 240926
// If we are moving away from this title, add our text for spell checking to be sure any changes are spell checked.
// The Enter/Tab keys are eaten up after this (e.Handled = true) and so WordRangeDamager.OnKeyDown will not get a
// chance to see these keys to update the damaged area.
EditorContext.DamageServices.AddDamage(EditorContext.MarkupServices.CreateMarkupRange(HTMLElement, false));
}
//If the command associated with the shortcut is disabled, eat the command key
//This prevents commands like paste from getting through to the standard handler
//when they are disabled.
Command command = EditorContext.CommandManager.FindCommandWithShortcut(e.KeyData);
if (command != null && !command.Enabled)
{
LastChanceKeyboardHook.OnBeforeKeyHandled(this, e);
e.Handled = true;
}
}
protected override void OnKeyDown(object o, HtmlEventArgs e)
{
base.OnKeyDown(o, e);
if (HtmlEditorSettings.AggressivelyInvalidate)
Invalidate();
}
protected override void OnKeyUp(object o, HtmlEventArgs e)
{
base.OnKeyUp(o, e);
//fire a title changed event
this.OnTitleChanged(EventArgs.Empty);
}
}
}
| |
// 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 Internal.Runtime;
using Internal.Text;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace ILCompiler.DependencyAnalysis
{
public class GCStaticDescNode : EmbeddedObjectNode, ISymbolDefinitionNode, ISortableSymbolNode
{
private MetadataType _type;
private GCPointerMap _gcMap;
private bool _isThreadStatic;
public GCStaticDescNode(MetadataType type, bool isThreadStatic)
{
_type = type;
_gcMap = isThreadStatic ? GCPointerMap.FromThreadStaticLayout(type) : GCPointerMap.FromStaticLayout(type);
_isThreadStatic = isThreadStatic;
}
protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler);
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append(GetMangledName(nameMangler, _type, _isThreadStatic));
}
public static string GetMangledName(NameMangler nameMangler, MetadataType type, bool isThreadStatic)
{
string prefix = isThreadStatic ? "__ThreadStaticGCDesc_" : "__GCStaticDesc_";
return prefix + nameMangler.GetMangledTypeName(type);
}
public int NumSeries
{
get
{
return _gcMap.NumSeries;
}
}
int ISymbolNode.Offset => 0;
int ISymbolDefinitionNode.Offset => OffsetFromBeginningOfArray;
private GCStaticDescRegionNode Region(NodeFactory factory)
{
UtcNodeFactory utcNodeFactory = (UtcNodeFactory)factory;
if (_type.IsCanonicalSubtype(CanonicalFormKind.Any))
{
return null;
}
else
{
if (_isThreadStatic)
{
return utcNodeFactory.ThreadStaticGCDescRegion;
}
else
{
return utcNodeFactory.GCStaticDescRegion;
}
}
}
private ISymbolNode GCStaticsSymbol(NodeFactory factory)
{
UtcNodeFactory utcNodeFactory = (UtcNodeFactory)factory;
if (_isThreadStatic)
{
return utcNodeFactory.TypeThreadStaticsSymbol(_type);
}
else
{
return utcNodeFactory.TypeGCStaticsSymbol(_type);
}
}
protected override void OnMarked(NodeFactory factory)
{
GCStaticDescRegionNode region = Region(factory);
if (region != null)
region.AddEmbeddedObject(this);
}
public override bool StaticDependenciesAreComputed
{
get
{
return true;
}
}
public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory)
{
DependencyListEntry[] result;
if (!_type.IsCanonicalSubtype(CanonicalFormKind.Any))
{
result = new DependencyListEntry[2];
result[0] = new DependencyListEntry(Region(factory), "GCStaticDesc Region");
result[1] = new DependencyListEntry(GCStaticsSymbol(factory), "GC Static Base Symbol");
}
else
{
Debug.Assert(Region(factory) == null);
result = new DependencyListEntry[1];
result[0] = new DependencyListEntry(((UtcNodeFactory)factory).StandaloneGCStaticDescRegion(this), "Standalone GCStaticDesc holder");
}
return result;
}
public override void EncodeData(ref ObjectDataBuilder builder, NodeFactory factory, bool relocsOnly)
{
int gcFieldCount = 0;
int startIndex = 0;
int numSeries = 0;
for (int i = 0; i < _gcMap.Size; i++)
{
// Skip non-GC fields
if (!_gcMap[i])
continue;
gcFieldCount++;
if (i == 0 || !_gcMap[i - 1])
{
// The cell starts a new series
startIndex = i;
}
if (i == _gcMap.Size - 1 || !_gcMap[i + 1])
{
if (_type.IsCanonicalSubtype(CanonicalFormKind.Any))
{
// The cell ends the current series
builder.EmitInt(gcFieldCount * factory.Target.PointerSize);
builder.EmitInt(startIndex * factory.Target.PointerSize);
}
else
{
// The cell ends the current series
builder.EmitInt(gcFieldCount);
if (_isThreadStatic)
{
builder.EmitReloc(factory.TypeThreadStaticsSymbol(_type), RelocType.IMAGE_REL_SECREL, startIndex * factory.Target.PointerSize);
}
else
{
builder.EmitReloc(factory.TypeGCStaticsSymbol(_type), RelocType.IMAGE_REL_BASED_RELPTR32, startIndex * factory.Target.PointerSize);
}
}
gcFieldCount = 0;
numSeries++;
}
}
Debug.Assert(numSeries == NumSeries);
}
internal int CompareTo(GCStaticDescNode other, TypeSystemComparer comparer)
{
var compare = _isThreadStatic.CompareTo(other._isThreadStatic);
return compare != 0 ? compare : comparer.Compare(_type, other._type);
}
public sealed override int ClassCode => 2142332918;
public override int CompareToImpl(ISortableNode other, CompilerComparer comparer)
{
return CompareTo((GCStaticDescNode)other, comparer);
}
}
public class GCStaticDescRegionNode : ArrayOfEmbeddedDataNode<GCStaticDescNode>
{
public GCStaticDescRegionNode(string startSymbolMangledName, string endSymbolMangledName, IComparer<GCStaticDescNode> nodeSorter)
: base(startSymbolMangledName, endSymbolMangledName, nodeSorter)
{
}
public override int ClassCode => 1312891560;
protected override void GetElementDataForNodes(ref ObjectDataBuilder builder, NodeFactory factory, bool relocsOnly)
{
int numSeries = 0;
foreach (GCStaticDescNode descNode in NodesList)
{
numSeries += descNode.NumSeries;
}
builder.EmitInt(numSeries);
foreach (GCStaticDescNode node in NodesList)
{
if (!relocsOnly)
node.InitializeOffsetFromBeginningOfArray(builder.CountBytes);
node.EncodeData(ref builder, factory, relocsOnly);
builder.AddSymbol(node);
}
}
}
public class StandaloneGCStaticDescRegionNode : ObjectNode
{
GCStaticDescNode _standaloneGCStaticDesc;
public StandaloneGCStaticDescRegionNode(GCStaticDescNode standaloneGCStaticDesc)
{
_standaloneGCStaticDesc = standaloneGCStaticDesc;
}
public override ObjectNodeSection Section => ObjectNodeSection.ReadOnlyDataSection;
public override bool IsShareable => true;
public override bool StaticDependenciesAreComputed => true;
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false)
{
ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly);
builder.RequireInitialPointerAlignment();
builder.AddSymbol(_standaloneGCStaticDesc);
_standaloneGCStaticDesc.InitializeOffsetFromBeginningOfArray(0);
builder.EmitInt(_standaloneGCStaticDesc.NumSeries);
_standaloneGCStaticDesc.EncodeData(ref builder, factory, relocsOnly);
return builder.ToObjectData();
}
protected override string GetName(NodeFactory context)
{
return "Standalone" + _standaloneGCStaticDesc.GetMangledName(context.NameMangler);
}
public override int ClassCode => 2091208431;
public override int CompareToImpl(ISortableNode other, CompilerComparer comparer)
{
return _standaloneGCStaticDesc.CompareTo(((StandaloneGCStaticDescRegionNode)other)._standaloneGCStaticDesc, comparer);
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using MORPH3D.COSTUMING;
using MORPH3D;
namespace MORPH3D.EDITORS
{
[CustomEditor (typeof(M3DCharacterManager))]
public class M3DCharacterManagerEditor : Editor
{
protected M3DCharacterManager data = null;
protected M3DBlendshapeNames names = null;
protected string[] namesList = null;
protected bool showAllBlendShapes = false;
protected string selectedBlendShape = "";
protected bool showAllBlendshapesGroups = false;
protected bool[] showBlendshapeGroups = null;
protected string[] selectedBlendshapeNames = null;
protected bool showContentPacks = false;
protected bool showAllClothing = false;
protected bool showAllClothingGroups = false;
protected bool[] showClothingGroups = null;
protected int selectedClothingName = 0;
protected bool showAttachmentPoints = false;
protected bool[] showAttachmentPointsGroups = null;
protected string[] selectedPropsNames = null;
protected string selectedNewAttachmentPointName = "";
protected bool showHair = false;
public override void OnInspectorGUI()
{
#region just_stuff
serializedObject.Update ();
if(data == null)
data = (M3DCharacterManager)target;
if (names == null){
// Debug.Log("NAMES SCIRPTZABLE OBJECT NULL IN EDITOR");
names = (M3DBlendshapeNames)Resources.Load ("M3D_BlendshapesNames");
}
#endregion just_stuff
#region LOD
float lod;
lod = EditorGUILayout.Slider("LOD", data.currentLODLevel, 0, 1);
if(lod != data.currentLODLevel)
{
Undo.RecordObject(data, "Change LOD");
data.setCharacterLODLevel(lod);
EditorUtility.SetDirty(data);
}
EditorGUILayout.Space();
#endregion LOD
#region blendshapes
List<MORPH3D.FOUNDATIONS.CoreBlendshape> shapes = data.GetAllBlendshapes();
if(shapes.Count == 0){//this check houldnt be needed. it's now included in the bendshape model itself
Debug.Log("NO BLEnDSHAPES VIA EDITOR");
data.InitBlendshapeModel();
shapes = data.GetAllBlendshapes();
}
showAllBlendShapes = EditorGUILayout.Foldout (showAllBlendShapes, "All Blendshapes");
if(showAllBlendShapes)
{
EditorGUI.indentLevel++;
GUILayout.BeginHorizontal();
selectedBlendShape = GUILayout.TextField(selectedBlendShape, GUI.skin.FindStyle("ToolbarSeachTextField"));
if (GUILayout.Button("", GUI.skin.FindStyle("ToolbarSeachCancelButton")))
{
selectedBlendShape = "";
GUI.FocusControl(null);
}
GUILayout.EndHorizontal();
EditorGUILayout.Space();
if (GUILayout.Button("Reset All"))
{
Undo.RecordObject(data, "Change Blendshape");
foreach(MORPH3D.FOUNDATIONS.CoreBlendshape shape in shapes)
data.SetBlendshapeValue(shape.displayName, 0);
EditorUtility.SetDirty(data);
}
foreach(MORPH3D.FOUNDATIONS.CoreBlendshape shape in shapes)
{
if(selectedBlendShape != "" && names.GetLabelFromDisplayName(shape.displayName).IndexOf(selectedBlendShape, System.StringComparison.OrdinalIgnoreCase) < 0)
continue;
bool tempLock;
float temp = DisplayBlendShape(shape, out tempLock);
if(tempLock != shape.isLocked)
{
Undo.RecordObject(data, "Lock Blendshape");
if(tempLock)
data.LockBlendshape(shape.displayName);
else
data.UnlockBlendshape(shape.displayName);
EditorUtility.SetDirty(data);
}
if(temp != shape.currentValue)
{
Undo.RecordObject(data, "Change Blendshape");
data.SetBlendshapeValue(shape.displayName, temp);
EditorUtility.SetDirty(data);
}
}
if (GUILayout.Button("Reset All"))
{
Undo.RecordObject(data, "Change Blendshape");
foreach(MORPH3D.FOUNDATIONS.CoreBlendshape shape in shapes)
data.SetBlendshapeValue(shape.displayName, 0);
EditorUtility.SetDirty(data);
}
EditorGUI.indentLevel--;
}
showAllBlendshapesGroups = EditorGUILayout.Foldout (showAllBlendshapesGroups, "Blendshape Groups");
if(showAllBlendshapesGroups)
{
namesList = names.GetAllNames();
List<MORPH3D.FOUNDATIONS.CoreBlendshapeGroup> groups = data.GetAllBlendshapeGroups();
if(showBlendshapeGroups == null || showBlendshapeGroups.Length != groups.Count)
showBlendshapeGroups = new bool[groups.Count];
if(selectedBlendshapeNames == null || selectedBlendshapeNames.Length != groups.Count)
selectedBlendshapeNames = new string[groups.Count];
EditorGUI.indentLevel++;
int remove = -1;
for(int i = 0; i < groups.Count; i++)
{
showBlendshapeGroups[i] = EditorGUILayout.Foldout (showBlendshapeGroups[i], groups[i].groupName);
if(showBlendshapeGroups[i])
{
string tempName;
EditorGUI.indentLevel++;
if(!groups[i].isLocked)
{
tempName = EditorGUILayout.TextField("Name", groups[i].groupName);
if(groups[i].groupName != tempName)
{
groups[i].groupName = tempName;
EditorUtility.SetDirty(data);
}
}
if(groups[i].bsCount > 0)
{
float groupVal = EditorGUILayout.Slider("Group Weight", groups[i].groupValue, 0, 100);
if(groups[i].groupValue != groupVal)
{
Undo.RecordObject(data, "Change Group Value");
data.SetGroupValue(groups[i].groupName, groupVal);
EditorUtility.SetDirty(data);
}
EditorGUILayout.Space();
}
List<MORPH3D.FOUNDATIONS.CoreBlendshape> groupShapes = groups[i].GetAllBlendshapes();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Reset Group", GUILayout.Width(250)))
{
Undo.RecordObject(data, "Change Blendshape");
for(int x = 0; x < groupShapes.Count; x++)
data.SetBlendshapeValue(groupShapes[x].displayName, 0);
EditorUtility.SetDirty(data);
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
int deleteFromGroup = -1;
for(int x = 0; x < groupShapes.Count; x++)
{
bool tempLock;
bool delete=false;
float temp = (groups[i].isLocked) ? DisplayBlendShape(groupShapes[x], out tempLock) : DisplayBlendShape(groupShapes[x], out tempLock, out delete);
if(delete)
deleteFromGroup = x;
if(tempLock != groupShapes[x].isLocked)
{
Undo.RecordObject(data, "Lock Blendshape");
if(tempLock)
data.LockBlendshape(groupShapes[x].displayName);
else
data.UnlockBlendshape(groupShapes[x].displayName);
EditorUtility.SetDirty(data);
}
if(temp != groupShapes[x].currentValue)
{
Undo.RecordObject(data, "Change Blendshape");
data.SetBlendshapeValue(groupShapes[x].displayName, temp);
EditorUtility.SetDirty(data);
}
}
if(deleteFromGroup >= 0)
{
Undo.RecordObject(data, "Delete Blendshape from Group");
groupShapes.RemoveAt(deleteFromGroup);
EditorUtility.SetDirty(data);
}
if(!groups[i].isLocked)
{
if(namesList.Length > 0)
{
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Add Blendshape:", GUILayout.Width(150));
EditorGUILayout.LabelField(selectedBlendshapeNames[i], GUILayout.Width(150));
MORPH3D.FOUNDATIONS.CoreBlendshape tempBlendshape = data.GetBlendshapeByName(names.GetDisplayName(selectedBlendshapeNames[i]));
if(selectedBlendshapeNames[i] != "" && selectedBlendshapeNames[i] != null && tempBlendshape == null)
selectedBlendshapeNames[i] = "";
if(GUILayout.Button("Search"))
{
int num = i;
SearchableWindow.Init(delegate(string newName) { selectedBlendshapeNames[num] = newName; }, namesList);
}
if(selectedBlendshapeNames[i] != "" && selectedBlendshapeNames[i] != null && tempBlendshape != null && GUILayout.Button("Add"))
{
Undo.RecordObject(data, "Add Blendshape to Group");
groups[i].AddBlendshapeToGroup(tempBlendshape);
EditorUtility.SetDirty(data);
selectedBlendshapeNames[i] = "";
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
}
/*
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
selectedBlendshapeName = EditorGUILayout.Popup(selectedBlendshapeName, namesList);
if(GUILayout.Button("Add Shape", GUILayout.Width(100)))
{
MORPH3D.FOUNDATIONS.CoreBlendshape shape = data.GetBlendshapeByName(names.GetDisplayName(namesList[selectedBlendshapeName]));
if(shape != null && !groups[i].ContainsBlendshape(shape))
{
Undo.RecordObject(data, "Add Blendshape to Group");
groups[i].AddBlendshapeToGroup(shape);
EditorUtility.SetDirty(data);
selectedBlendshapeName = 0;
}
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
*/
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if(GUILayout.Button("Delete Group", GUILayout.Width(100)))
remove = i;
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
}
}
if(remove >= 0)
{
Undo.RecordObject(data, "Remove Blendshape Group");
groups.RemoveAt(remove);
EditorUtility.SetDirty(data);
}
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if(GUILayout.Button("Add Group", GUILayout.Width(100)))
{
Undo.RecordObject(data, "Create Blendshape Group");
data.AddBlendShapeGroup("New Group");
EditorUtility.SetDirty(data);
}
if(GUILayout.Button("Save to Group", GUILayout.Width(150)))
{
List<MORPH3D.FOUNDATIONS.CoreBlendshape> lst = new List<MORPH3D.FOUNDATIONS.CoreBlendshape>();
foreach(MORPH3D.FOUNDATIONS.CoreBlendshape shape in shapes)
{
if(shape.currentValue <= 0)
continue;
lst.Add(shape);
}
if(lst.Count > 0)
{
Undo.RecordObject(data, "Save to Blendshape Group");
data.AddBlendShapeGroup("New Group", lst);
EditorUtility.SetDirty(data);
}
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
#endregion blendshapes
#region contentPacks
showContentPacks = EditorGUILayout.Foldout (showContentPacks, "Content Packs");
if(showContentPacks)
{
EditorGUI.indentLevel++;
ContentPack[] allPacks = data.GetAllContentPacks();
for(int i = 0; i < allPacks.Length; i++)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(allPacks[i].name);
if(GUILayout.Button("X"))
{
Undo.RecordObject(data, "Remove Bundle");
data.UnloadContentPackFromFigure(allPacks[i]);
data.RemoveContentPackFromModel(allPacks[i].RootGameObject, true);
EditorUtility.SetDirty(data);
}
EditorGUILayout.EndHorizontal();
}
GameObject tempPack;
tempPack = (GameObject)EditorGUILayout.ObjectField("New", null, typeof(GameObject), false);
if(tempPack != null)
{
ContentPack packScript = new ContentPack(tempPack);
Undo.RecordObject(data, "Add Bundle");
data.AddContentPack(packScript);
EditorUtility.SetDirty(data);
}
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
#endregion contentPacks
#region hair
showHair = EditorGUILayout.Foldout (showHair, "Hair");
if(showHair)
{
EditorGUI.indentLevel++;
List<MORPH3D.COSTUMING.CIhair> allHair = data.GetAllHairItems();
foreach(MORPH3D.COSTUMING.CIhair mesh in allHair)
{
if(DisplayHair(mesh))
{
Undo.RecordObject(data, "Toggle Hair");
data.SetVisibilityOnHairItem(mesh.displayName, !mesh.isVisible);
EditorUtility.SetDirty(data);
}
}
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
#endregion hair
#region clothing
showAllClothing = EditorGUILayout.Foldout (showAllClothing, "Clothing");
if(showAllClothing)
{
EditorGUI.indentLevel++;
List<CIclothing> allClothing = null;
allClothing = data.GetAllLoadedClothingItems();
foreach(CIclothing mesh in allClothing)
{
bool tempLock;
bool temp = DisplayClothingMesh(mesh, out tempLock);
if(tempLock != mesh.isLocked)
{
Undo.RecordObject(data, "Lock Clothing");
if(tempLock)
data.LockClothingItem(mesh.displayName);
else
data.UnlockClothingItem(mesh.displayName);
EditorUtility.SetDirty(data);
}
if(temp)
{
Undo.RecordObject(data, "Toggle Clothing");
data.SetClothingVisibility(mesh.displayName, !mesh.isVisible);
EditorUtility.SetDirty(data);
}
}
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
#endregion clothing
#region props
CIattachmentPoint[] attachmentPoints = data.GetAllAttachmentPoints();
// Debug.Log("AP LENGTH:"+attachmentPoints.Length);
if(showAttachmentPointsGroups == null || showAttachmentPointsGroups.Length != attachmentPoints.Length)
showAttachmentPointsGroups = new bool[attachmentPoints.Length];
/*
if(selectedProps == null || selectedProps.Length != attachmentPoints.Length)
selectedProps = new int[attachmentPoints.Length];
*/
if(selectedPropsNames == null || selectedPropsNames.Length != attachmentPoints.Length)
selectedPropsNames = new string[attachmentPoints.Length];
List<CIprop> props = data.GetAllLoadedProps();
string[] propsNames = new string[]{};
if(props != null){
propsNames = new string[props.Count];
}
for(int i = 0; i < propsNames.Length; i++)
propsNames[i] = props[i].displayName;
showAttachmentPoints = EditorGUILayout.Foldout (showAttachmentPoints, "Attachment Points");
if(showAttachmentPoints)
{
int deleteAttachment = -1;
EditorGUI.indentLevel++;
for(int i = 0; i < attachmentPoints.Length; i++)
{
EditorGUILayout.BeginHorizontal();
showAttachmentPointsGroups[i] = EditorGUILayout.Foldout (showAttachmentPointsGroups[i], attachmentPoints[i].attachmentPointName);
GUILayout.FlexibleSpace();
if(GUILayout.Button("X", GUILayout.Width(45)))
deleteAttachment = i;
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
if(showAttachmentPointsGroups[i])
{
EditorGUI.indentLevel++;
CIprop[] activeProps = attachmentPoints[i].getAttachmentArray();
int destroyProp = -1;
for(int x = 0; x < activeProps.Length; x++)
{
if(DisplayProp(activeProps[x]))
destroyProp = x;
}
if(destroyProp >= 0)
{
Undo.RecordObject(data, "Destroy Prop");
data.DetachPropFromAttachmentPoint(activeProps[destroyProp].displayName, attachmentPoints[i].attachmentPointName);
EditorUtility.SetDirty(data);
}
// Debug.Log("GF");
if(propsNames.Length > 0)
{
// Debug.Log("FDFG");
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Add Prop:", GUILayout.Width(150));
EditorGUILayout.LabelField(selectedPropsNames[i], GUILayout.Width(150));
if(selectedPropsNames[i] != "" && selectedPropsNames[i] != null && data.GetLoadedPropByName(selectedPropsNames[i]) == null)
selectedPropsNames[i] = "";
if(GUILayout.Button("Search"))
{
int num = i;
SearchableWindow.Init(delegate(string newName) { selectedPropsNames[num] = newName; }, propsNames);
}
if(selectedPropsNames[i] != "" && selectedPropsNames[i] != null && GUILayout.Button("Add"))
{
Undo.RecordObject(data, "Attach Prop");
data.AttachPropToAttachmentPoint(selectedPropsNames[i], attachmentPoints[i].attachmentPointName);
EditorUtility.SetDirty(data);
selectedPropsNames[i] = "";
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
/*
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
selectedProps[i] = EditorGUILayout.Popup (selectedProps[i], propsNames, GUILayout.Width(150));
if(GUILayout.Button("Add"))
{
Undo.RecordObject(data, "Attach Prop");
data.AttachPropToAttachmentPoint(propsNames[selectedProps[i]], attachmentPoints[i].attachmentPointName);
EditorUtility.SetDirty(data);
selectedProps[i] = 0;
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
*/
}
EditorGUILayout.Space();
EditorGUI.indentLevel--;
}
}
if(deleteAttachment >= 0)
{
Undo.RecordObject(attachmentPoints[deleteAttachment], "Delete Attachment Point");
data.DeleteAttachmentPoint(attachmentPoints[deleteAttachment].attachmentPointName);
}
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("New Point:", GUILayout.Width(150));
EditorGUILayout.LabelField(selectedNewAttachmentPointName, GUILayout.Width(150));
Transform tempBone = data.GetBoneByName (selectedNewAttachmentPointName);
if(selectedNewAttachmentPointName != "" && selectedNewAttachmentPointName != null && tempBone == null)
selectedNewAttachmentPointName = "";
if(GUILayout.Button("Search"))
{
SearchableWindow.Init(delegate(string newName) { selectedNewAttachmentPointName = newName; }, data.GetAllBonesNames());
}
if(selectedNewAttachmentPointName != "" && selectedNewAttachmentPointName != null && tempBone != null && GUILayout.Button("Add"))
{
Undo.RecordObject(tempBone.gameObject, "New Attachment Point");
data.CreateAttachmentPointOnBone(selectedNewAttachmentPointName);
selectedNewAttachmentPointName = "";
}
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
/*
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
selectedNewAttachmentPointName = EditorGUILayout.TextField("New Point Bone Name", selectedNewAttachmentPointName);
if(GUILayout.Button("Add") && selectedNewAttachmentPointName != "")
{
Transform bone = data.boneService.getBoneByName (selectedNewAttachmentPointName);
if(bone != null)
{
Undo.RecordObject(bone.gameObject, "New Attachment Point");
data.CreateAttachmentPointOnBone(selectedNewAttachmentPointName);
}
selectedNewAttachmentPointName = "";
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
selectedNewAttachmentPoint = (GameObject)EditorGUILayout.ObjectField("New Attachemnt Point", selectedNewAttachmentPoint, typeof(GameObject), true);
if(selectedNewAttachmentPoint != null && !selectedNewAttachmentPoint.activeInHierarchy)
selectedNewAttachmentPoint = null;
if(GUILayout.Button("Add") && selectedNewAttachmentPoint != null)
{
if(selectedNewAttachmentPoint.GetComponent<CIattachmentPoint>() == null)
{
Undo.RecordObject(selectedNewAttachmentPoint, "New Attachment Point");
data.CreateAttachmentPointFromGameObject(selectedNewAttachmentPoint);
}
selectedNewAttachmentPoint = null;
}
EditorGUILayout.EndHorizontal();
*/
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
#endregion props
}
#region blendshapes_display
protected float DisplayBlendShape(MORPH3D.FOUNDATIONS.CoreBlendshape shape, out bool lockShape)
{
float result;
EditorGUILayout.BeginHorizontal();
result = EditorGUILayout.Slider(GetLabelToDisplay(shape), shape.currentValue, 0f, 100f);
lockShape = EditorGUILayout.Toggle(shape.isLocked);
EditorGUILayout.EndHorizontal();
return result;
}
protected string GetLabelToDisplay(MORPH3D.FOUNDATIONS.CoreBlendshape shape){
string name_to_display = names.GetLabelFromDisplayName(shape.displayName);
if (string.IsNullOrEmpty (name_to_display) == true)
name_to_display = shape.displayName;
return name_to_display;
}
protected float DisplayBlendShape(MORPH3D.FOUNDATIONS.CoreBlendshape shape, out bool lockShape, out bool delete)
{
float result;
EditorGUILayout.BeginHorizontal();
string showName = GetLabelToDisplay (shape);//names.GetLabelFromDisplayName (shape.displayName);
result = EditorGUILayout.Slider((string.IsNullOrEmpty(showName)) ? shape.displayName : showName, shape.currentValue, 0f, 100f);
lockShape = EditorGUILayout.Toggle(shape.isLocked);
delete = GUILayout.Button ("X");
EditorGUILayout.EndHorizontal();
return result;
}
#endregion blendshapes_display
#region clothing_display
protected bool DisplayClothingMesh(MORPH3D.COSTUMING.CIclothing mesh, out bool lockItem)
{
bool result;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField (mesh.displayName, GUILayout.Width(150));
if(mesh.isVisible)
GUILayout.Space (60);
result = GUILayout.Button ((mesh.isVisible) ? "Disable" : "Enable", GUILayout.Width(60));
if(!mesh.isVisible)
GUILayout.Space (60);
if (mesh.isVisible)
lockItem = EditorGUILayout.Toggle (mesh.isLocked);
else
lockItem = mesh.isLocked;
EditorGUILayout.EndHorizontal();
return result;
}
#endregion clothing_display
#region props_display
protected bool DisplayProp(MORPH3D.COSTUMING.CIprop prop)
{
bool result;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField (prop.displayName, GUILayout.Width(180));
GUILayout.Space (60);
result = GUILayout.Button ("Disable", GUILayout.Width(60));
EditorGUILayout.EndHorizontal();
return result;
}
#endregion props_display
#region hair_display
protected bool DisplayHair(MORPH3D.COSTUMING.CIhair mesh)
{
bool result;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField (mesh.displayName, GUILayout.Width(150));
if(mesh.isVisible)
GUILayout.Space (60);
result = GUILayout.Button ((mesh.isVisible) ? "Disable" : "Enable", GUILayout.Width(60));
if(!mesh.isVisible)
GUILayout.Space (60);
EditorGUILayout.EndHorizontal();
return result;
}
#endregion hair_display
}
}
| |
/*
* Naiad ver. 0.5
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace Microsoft.Research.Naiad.Util
{
public class Flag
{
public readonly Type FlagType;
private string _stringValue;
public bool _boolValue;
private int _intValue;
private double _doubleValue;
private List<string> _listValue = new List<string>();
public Boolean IsSet = false;
private static List<Type> KnownTypes = new Type[]
{
typeof (bool),
typeof (int),
typeof (string),
typeof (double),
typeof (List<String>)
}.ToList();
private object _enumValue;
public Flag(Type flagType)
{
FlagType = flagType;
if (!FlagType.IsEnum && !KnownTypes.Contains(flagType))
{
throw new Exception("invalid flag type: " + flagType);
}
}
public static implicit operator int(Flag f)
{
//Logging.Assert(f.FlagType == typeof(int), "tried to use a {0} flag as a {1}", f.FlagType, typeof(int));
return f._intValue;
}
public static implicit operator bool(Flag f)
{
//Logging.Assert(f.FlagType == typeof(bool), "tried to use a {0} flag as a {1}", f.FlagType, typeof(bool));
return f._boolValue;
}
public static implicit operator double(Flag f)
{
//Logging.Assert(f.FlagType == typeof(double), "tried to use a {0} flag as a {1}", f.FlagType, typeof(double));
return f._doubleValue;
}
public static implicit operator string(Flag f)
{
//Logging.Assert(f.FlagType == typeof(string), "tried to use a {0} flag as a {1}", f.FlagType, typeof(string));
return f._stringValue;
}
public static implicit operator List<string>(Flag f)
{
//Logging.Assert(f.FlagType == typeof(List<String>), "tried to use a {0} flag as a {1}", f.FlagType, typeof(List<String>));
//Logging.Assert(f.FlagType == typeof(List<string>));
return f._listValue;
}
public static implicit operator Flag(int v)
{
var f = new Flag(typeof(int));
f.Parse(v.ToString());
return f;
}
public static implicit operator Flag(List<string> v)
{
var f = new Flag(typeof(string));
f.IsSet = true;
f.Parse(String.Join(",", v));
return f;
}
public IEnumerable<string> ListValue
{
get { return this._listValue; } // (List<string>)(this); }
}
public string StringValue
{
get { return this._stringValue; } // (String)(this); }
}
public int IntValue
{
get { return this._intValue; }// (int)(this); }
}
public T EnumValue<T>()
{
return (T)_enumValue;
}
public double DoubleValue
{
get { return this._doubleValue; }
}
public bool BooleanValue
{
get { return this._boolValue; }
}
public override string ToString()
{
return _stringValue;
}
public void Parse(string value)
{
// Check flag value is valid before assignment.
IsSet = true;
_stringValue = value;
if (FlagType == typeof(bool))
{
_boolValue = Boolean.Parse(value);
}
else if (FlagType.IsEnum)
{
_enumValue = Enum.Parse(FlagType, _stringValue);
}
else if (FlagType == typeof(int))
{
_intValue = Int32.Parse(value);
}
else if (FlagType == typeof(double))
{
_doubleValue = Double.Parse(value);
}
else if (FlagType == typeof(List<string>))
{
_listValue.AddRange(value.Split(','));
}
else if (FlagType == typeof(string))
{
_stringValue = value;
}
else
{
throw new Exception("Invalid flag type: " + FlagType);
}
}
}
public static class Flags
{
private static Dictionary<string, Flag> _flagMap = new Dictionary<string, Flag>();
public static Flag Define(string names, Type t)
{
var f = new Flag(t);
foreach (var n in names.Split(','))
{
// Strip leading hyphens.
var name = n;
while (name.StartsWith("-"))
{
name = name.Substring(1);
}
_flagMap[name] = f;
}
return f;
}
public static Flag Define(string name, string defValue)
{
var f = Define(name, defValue.GetType());
f.Parse(defValue);
return f;
}
public static Flag Define(string name, bool @default)
{
var f = Define(name, @default.GetType());
f.Parse(@default.ToString());
return f;
}
public static Flag Define(string name, int defValue)
{
var f = Define(name, defValue.GetType());
f.Parse(defValue.ToString());
return f;
}
public static Flag Define(string name, double defValue)
{
var f = Define(name, defValue.GetType());
f.Parse(defValue.ToString());
return f;
}
public static Flag Define<T>(string name, T @default) where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("Only enum structs can be used as flags.");
}
var f = Define(name, typeof(T));
f.Parse(@default.ToString());
return f;
}
public static Flag Get(string name)
{
return _flagMap[name];
}
public static void Parse(NameValueCollection settings)
{
foreach (string key in settings.AllKeys)
{
if (_flagMap.ContainsKey(key))
{
_flagMap[key].Parse(settings.Get(key));
}
}
}
public static String[] Parse(String[] args)
{
var unparsedArgs = new List<string>();
var idx = 0;
while (idx < args.Length)
{
var arg = args[idx];
//Console.Error.WriteLine("Parsing... {0} {1}", idx, arg);
++idx;
string name = null;
if (arg.StartsWith("--"))
{
name = arg.Substring(2);
}
else if (arg.StartsWith("-"))
{
name = arg.Substring(1);
}
else
{
//Console.Error.WriteLine("Skipping non-flag argument " + arg);
unparsedArgs.Add(arg);
continue;
}
String value = null;
if (name.Contains("="))
{
var parts = name.Split(new[] { '=' });
Debug.Assert(parts.Length == 2);
name = parts[0];
value = parts[1];
}
if (name == "helpflags")
{
Console.Error.WriteLine("Application: {0}", Assembly.GetEntryAssembly().GetName());
Console.Error.WriteLine("Flags currently defined:");
foreach (var k in _flagMap.Keys.OrderBy(k => k))
{
var f = _flagMap[k];
Console.Error.WriteLine(" --{0} : {1} ({2})", k, f.FlagType.Name, f.ToString());
}
System.Environment.Exit(0);
}
if (!_flagMap.ContainsKey(name))
{
//Console.Error.WriteLine("Skipping unknown argument " + name);
unparsedArgs.Add(arg);
continue;
}
var flag = _flagMap[name];
if (flag.FlagType == typeof(bool))
{
flag.Parse("true");
}
else
{
if (value == null)
{
value = args[idx++];
}
//Console.WriteLine(name);
flag.Parse(value);
}
}
return unparsedArgs.ToArray();
}
}
}
| |
/*
* 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.Concurrent;
using System.Reflection;
using System.Threading;
using log4net;
using OpenSim.Framework;
namespace OpenSim.Framework.Monitoring
{
public class JobEngine
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public int LogLevel { get; set; }
private object JobLock = new object();
public string Name { get; private set; }
public string LoggingName { get; private set; }
/// <summary>
/// Is this engine running?
/// </summary>
public bool IsRunning { get; private set; }
/// <summary>
/// The current job that the engine is running.
/// </summary>
/// <remarks>
/// Will be null if no job is currently running.
/// </remarks>
public Job CurrentJob { get; private set; }
/// <summary>
/// Number of jobs waiting to be processed.
/// </summary>
public int JobsWaiting { get { return m_jobQueue.Count; } }
/// <summary>
/// The timeout in milliseconds to wait for at least one event to be written when the recorder is stopping.
/// </summary>
public int RequestProcessTimeoutOnStop { get; set; }
/// <summary>
/// Controls whether we need to warn in the log about exceeding the max queue size.
/// </summary>
/// <remarks>
/// This is flipped to false once queue max has been exceeded and back to true when it falls below max, in
/// order to avoid spamming the log with lots of warnings.
/// </remarks>
private bool m_warnOverMaxQueue = true;
private BlockingCollection<Job> m_jobQueue = new BlockingCollection<Job>(new ConcurrentQueue<Job>(), 5000);
private CancellationTokenSource m_cancelSource;
/// <summary>
/// Used to signal that we are ready to complete stop.
/// </summary>
private ManualResetEvent m_finishedProcessingAfterStop = new ManualResetEvent(false);
public JobEngine(string name, string loggingName)
{
Name = name;
LoggingName = loggingName;
RequestProcessTimeoutOnStop = 5000;
}
public void Start()
{
lock (JobLock)
{
if (IsRunning)
return;
IsRunning = true;
m_finishedProcessingAfterStop.Reset();
m_cancelSource = new CancellationTokenSource();
WorkManager.StartThread(
ProcessRequests,
Name,
ThreadPriority.Normal,
false,
true,
null,
int.MaxValue);
}
}
public void Stop()
{
lock (JobLock)
{
try
{
if (!IsRunning)
return;
m_log.DebugFormat("[JobEngine] Stopping {0}", Name);
IsRunning = false;
m_finishedProcessingAfterStop.Reset();
if(m_jobQueue.Count <= 0)
m_cancelSource.Cancel();
m_finishedProcessingAfterStop.WaitOne(RequestProcessTimeoutOnStop);
m_finishedProcessingAfterStop.Close();
}
finally
{
if(m_cancelSource != null)
m_cancelSource.Dispose();
if(m_finishedProcessingAfterStop != null)
m_finishedProcessingAfterStop.Dispose();
}
}
}
/// <summary>
/// Make a job.
/// </summary>
/// <remarks>
/// We provide this method to replace the constructor so that we can later pool job objects if necessary to
/// reduce memory churn. Normally one would directly call QueueJob() with parameters anyway.
/// </remarks>
/// <returns></returns>
/// <param name="name">Name.</param>
/// <param name="action">Action.</param>
/// <param name="commonId">Common identifier.</param>
public static Job MakeJob(string name, Action action, string commonId = null)
{
return Job.MakeJob(name, action, commonId);
}
/// <summary>
/// Remove the next job queued for processing.
/// </summary>
/// <remarks>
/// Returns null if there is no next job.
/// Will not remove a job currently being performed.
/// </remarks>
public Job RemoveNextJob()
{
Job nextJob;
m_jobQueue.TryTake(out nextJob);
return nextJob;
}
/// <summary>
/// Queue the job for processing.
/// </summary>
/// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
/// <param name="name">Name of job. This appears on the console and in logging.</param>
/// <param name="action">Action to perform.</param>
/// <param name="commonId">
/// Common identifier for a set of jobs. This is allows a set of jobs to be removed
/// if required (e.g. all jobs for a given agent. Optional.
/// </param>
public bool QueueJob(string name, Action action, string commonId = null)
{
return QueueJob(MakeJob(name, action, commonId));
}
/// <summary>
/// Queue the job for processing.
/// </summary>
/// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
/// <param name="job">The job</param>
/// </param>
public bool QueueJob(Job job)
{
if (m_jobQueue.Count < m_jobQueue.BoundedCapacity)
{
m_jobQueue.Add(job);
if (!m_warnOverMaxQueue)
m_warnOverMaxQueue = true;
return true;
}
else
{
if (m_warnOverMaxQueue)
{
m_log.WarnFormat(
"[{0}]: Job queue at maximum capacity, not recording job from {1} in {2}",
LoggingName, job.Name, Name);
m_warnOverMaxQueue = false;
}
return false;
}
}
private void ProcessRequests()
{
while(IsRunning || m_jobQueue.Count > 0)
{
try
{
CurrentJob = m_jobQueue.Take(m_cancelSource.Token);
}
catch(ObjectDisposedException e)
{
// If we see this whilst not running then it may be due to a race where this thread checks
// IsRunning after the stopping thread sets it to false and disposes of the cancellation source.
if(IsRunning)
throw e;
else
{
m_log.DebugFormat("[JobEngine] {0} stopping ignoring {1} jobs in queue",
Name,m_jobQueue.Count);
break;
}
}
catch(OperationCanceledException)
{
break;
}
if(LogLevel >= 1)
m_log.DebugFormat("[{0}]: Processing job {1}",LoggingName,CurrentJob.Name);
try
{
CurrentJob.Action();
}
catch(Exception e)
{
m_log.Error(
string.Format(
"[{0}]: Job {1} failed, continuing. Exception ",LoggingName,CurrentJob.Name),e);
}
if(LogLevel >= 1)
m_log.DebugFormat("[{0}]: Processed job {1}",LoggingName,CurrentJob.Name);
CurrentJob = null;
}
Watchdog.RemoveThread(false);
m_finishedProcessingAfterStop.Set();
}
public class Job
{
/// <summary>
/// Name of the job.
/// </summary>
/// <remarks>
/// This appears on console and debug output.
/// </remarks>
public string Name { get; private set; }
/// <summary>
/// Common ID for this job.
/// </summary>
/// <remarks>
/// This allows all jobs with a certain common ID (e.g. a client UUID) to be removed en-masse if required.
/// Can be null if this is not required.
/// </remarks>
public string CommonId { get; private set; }
/// <summary>
/// Action to perform when this job is processed.
/// </summary>
public Action Action { get; private set; }
private Job(string name, string commonId, Action action)
{
Name = name;
CommonId = commonId;
Action = action;
}
/// <summary>
/// Make a job. It needs to be separately queued.
/// </summary>
/// <remarks>
/// We provide this method to replace the constructor so that we can pool job objects if necessary to
/// to reduce memory churn. Normally one would directly call JobEngine.QueueJob() with parameters anyway.
/// </remarks>
/// <returns></returns>
/// <param name="name">Name.</param>
/// <param name="action">Action.</param>
/// <param name="commonId">Common identifier.</param>
public static Job MakeJob(string name, Action action, string commonId = null)
{
return new Job(name, commonId, action);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using NuGet.Resources;
namespace NuGet
{
public class LocalPackageRepository : PackageRepositoryBase, IPackageLookup
{
private readonly ConcurrentDictionary<string, PackageCacheEntry> _packageCache = new ConcurrentDictionary<string, PackageCacheEntry>(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<PackageName, string> _packagePathLookup = new ConcurrentDictionary<PackageName, string>();
private readonly bool _enableCaching;
public LocalPackageRepository(string physicalPath)
: this(physicalPath, enableCaching: true)
{
}
public LocalPackageRepository(string physicalPath, bool enableCaching)
: this(new DefaultPackagePathResolver(physicalPath),
new PhysicalFileSystem(physicalPath),
enableCaching)
{
}
public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem)
: this(pathResolver, fileSystem, enableCaching: true)
{
}
public LocalPackageRepository(IPackagePathResolver pathResolver, IFileSystem fileSystem, bool enableCaching)
{
if (pathResolver == null)
{
throw new ArgumentNullException("pathResolver");
}
if (fileSystem == null)
{
throw new ArgumentNullException("fileSystem");
}
FileSystem = fileSystem;
PathResolver = pathResolver;
_enableCaching = enableCaching;
}
public override string Source
{
get
{
return FileSystem.Root;
}
}
public IPackagePathResolver PathResolver
{
get;
set;
}
public override bool SupportsPrereleasePackages
{
get { return true; }
}
protected IFileSystem FileSystem
{
get;
private set;
}
public override IQueryable<IPackage> GetPackages()
{
return GetPackages(OpenPackage).AsQueryable();
}
public override void AddPackage(IPackage package)
{
string packageFilePath = GetPackageFilePath(package);
FileSystem.AddFileWithCheck(packageFilePath, package.GetStream);
}
public override void RemovePackage(IPackage package)
{
// Delete the package file
string packageFilePath = GetPackageFilePath(package);
FileSystem.DeleteFileSafe(packageFilePath);
// Delete the package directory if any
FileSystem.DeleteDirectorySafe(PathResolver.GetPackageDirectory(package), recursive: false);
// If this is the last package delete the package directory
if (!FileSystem.GetFilesSafe(String.Empty).Any() &&
!FileSystem.GetDirectoriesSafe(String.Empty).Any())
{
FileSystem.DeleteDirectorySafe(String.Empty, recursive: false);
}
}
public virtual IPackage FindPackage(string packageId, SemanticVersion version)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
if (version == null)
{
throw new ArgumentNullException("version");
}
return FindPackage(OpenPackage, packageId, version);
}
public virtual IEnumerable<IPackage> FindPackagesById(string packageId)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
return FindPackagesById(OpenPackage, packageId);
}
public virtual bool Exists(string packageId, SemanticVersion version)
{
return FindPackage(packageId, version) != null;
}
public virtual IEnumerable<string> GetPackageLookupPaths(string packageId, SemanticVersion version)
{
// Files created by the path resolver. This would take into account the non-side-by-side scenario
// and we do not need to match this for id and version.
var packageFileName = PathResolver.GetPackageFileName(packageId, version);
var filesMatchingFullName = GetPackageFiles(packageFileName);
if (version != null && version.Version.Revision < 1)
{
// If the build or revision number is not set, we need to look for combinations of the format
// * Foo.1.2.nupkg
// * Foo.1.2.3.nupkg
// * Foo.1.2.0.nupkg
// * Foo.1.2.0.0.nupkg
// To achieve this, we would look for files named 1.2*.nupkg if both build and revision are 0 and
// 1.2.3*.nupkg if only the revision is set to 0.
string partialName = version.Version.Build < 1 ?
String.Join(".", packageId, version.Version.Major, version.Version.Minor) :
String.Join(".", packageId, version.Version.Major, version.Version.Minor, version.Version.Build);
partialName += "*" + Constants.PackageExtension;
// Partial names would result is gathering package with matching major and minor but different build and revision.
// Attempt to match the version in the path to the version we're interested in.
var partialNameMatches = GetPackageFiles(partialName).Where(path => FileNameMatchesPattern(packageId, version, path));
return Enumerable.Concat(filesMatchingFullName, partialNameMatches);
}
return filesMatchingFullName;
}
internal IPackage FindPackage(Func<string, IPackage> openPackage, string packageId, SemanticVersion version)
{
var lookupPackageName = new PackageName(packageId, version);
string packagePath;
// If caching is enabled, check if we have a cached path. Additionally, verify that the file actually exists on disk since it might have moved.
if (_enableCaching &&
_packagePathLookup.TryGetValue(lookupPackageName, out packagePath) &&
FileSystem.FileExists(packagePath))
{
// When depending on the cached path, verify the file exists on disk.
return GetPackage(openPackage, packagePath);
}
// Lookup files which start with the name "<Id>." and attempt to match it with all possible version string combinations (e.g. 1.2.0, 1.2.0.0)
// before opening the package. To avoid creating file name strings, we attempt to specifically match everything after the last path separator
// which would be the file name and extension.
return (from path in GetPackageLookupPaths(packageId, version)
let package = GetPackage(openPackage, path)
where lookupPackageName.Equals(new PackageName(package.Id, package.Version))
select package).FirstOrDefault();
}
internal IEnumerable<IPackage> FindPackagesById(Func<string, IPackage> openPackage, string packageId)
{
Debug.Assert(!String.IsNullOrEmpty(packageId), "The caller has to ensure packageId is never null.");
var packagePaths = GetPackageFiles(packageId + "*" + Constants.PackageExtension);
return from path in packagePaths
let package = GetPackage(openPackage, path)
where package.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase)
select package;
}
internal IEnumerable<IPackage> GetPackages(Func<string, IPackage> openPackage)
{
return from path in GetPackageFiles()
select GetPackage(openPackage, path);
}
private IPackage GetPackage(Func<string, IPackage> openPackage, string path)
{
PackageCacheEntry cacheEntry;
DateTimeOffset lastModified = FileSystem.GetLastModified(path);
// If we never cached this file or we did and it's current last modified time is newer
// create a new entry
if (!_packageCache.TryGetValue(path, out cacheEntry) ||
(cacheEntry != null && lastModified > cacheEntry.LastModifiedTime))
{
// We need to do this so we capture the correct loop variable
string packagePath = path;
// Create the package
IPackage package = openPackage(packagePath);
// create a cache entry with the last modified time
cacheEntry = new PackageCacheEntry(package, lastModified);
if (_enableCaching)
{
// Store the entry
_packageCache[packagePath] = cacheEntry;
_packagePathLookup[new PackageName(package.Id, package.Version)] = path;
}
}
return cacheEntry.Package;
}
internal IEnumerable<string> GetPackageFiles(string filter = null)
{
filter = filter ?? "*" + Constants.PackageExtension;
Debug.Assert(filter.EndsWith(Constants.PackageExtension, StringComparison.OrdinalIgnoreCase));
// Check for package files one level deep. We use this at package install time
// to determine the set of installed packages. Installed packages are copied to
// {id}.{version}\{packagefile}.{extension}.
foreach (var dir in FileSystem.GetDirectories(String.Empty))
{
foreach (var path in FileSystem.GetFiles(dir, filter))
{
yield return path;
}
}
// Check top level directory
foreach (var path in FileSystem.GetFiles(String.Empty, filter))
{
yield return path;
}
}
protected virtual IPackage OpenPackage(string path)
{
var nuspecPath = Path.ChangeExtension(path, Constants.ManifestExtension);
if (FileSystem.FileExists(nuspecPath))
{
return new UnzippedPackage(FileSystem, Path.GetFileNameWithoutExtension(nuspecPath));
}
ZipPackage package;
try
{
package = new ZipPackage(() => FileSystem.OpenFile(path), _enableCaching);
}
catch (FileFormatException ex)
{
throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ErrorReadingPackage, path), ex);
}
// Set the last modified date on the package
package.Published = FileSystem.GetLastModified(path);
// Clear the cache whenever we open a new package file
ZipPackage.ClearCache(package);
return package;
}
protected virtual string GetPackageFilePath(IPackage package)
{
return Path.Combine(PathResolver.GetPackageDirectory(package),
PathResolver.GetPackageFileName(package));
}
protected virtual string GetPackageFilePath(string id, SemanticVersion version)
{
return Path.Combine(PathResolver.GetPackageDirectory(id, version),
PathResolver.GetPackageFileName(id, version));
}
private static bool FileNameMatchesPattern(string packageId, SemanticVersion version, string path)
{
var name = Path.GetFileNameWithoutExtension(path);
SemanticVersion parsedVersion;
// When matching by pattern, we will always have a version token. Packages without versions would be matched early on by the version-less path resolver
// when doing an exact match.
return name.Length > packageId.Length &&
SemanticVersion.TryParse(name.Substring(packageId.Length + 1), out parsedVersion) &&
parsedVersion == version;
}
private class PackageCacheEntry
{
public PackageCacheEntry(IPackage package, DateTimeOffset lastModifiedTime)
{
Package = package;
LastModifiedTime = lastModifiedTime;
}
public IPackage Package { get; private set; }
public DateTimeOffset LastModifiedTime { get; private set; }
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Management.Automation;
using System.Management.Automation.SecurityAccountsManager;
using System.Management.Automation.SecurityAccountsManager.Extensions;
using Microsoft.PowerShell.LocalAccounts;
#endregion
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The Rename-LocalUser cmdlet renames a local user account in the Security
/// Accounts Manager.
/// </summary>
[Cmdlet(VerbsCommon.Rename, "LocalUser",
SupportsShouldProcess = true,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=717983")]
[Alias("rnlu")]
public class RenameLocalUserCommand : Cmdlet
{
#region Instance Data
private Sam sam = null;
#endregion Instance Data
#region Parameter Properties
/// <summary>
/// The following is the definition of the input parameter "InputObject".
/// Specifies the of the local user account to rename in the local Security
/// Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "InputObject")]
[ValidateNotNull]
public Microsoft.PowerShell.Commands.LocalUser InputObject
{
get { return this.inputobject;}
set { this.inputobject = value; }
}
private Microsoft.PowerShell.Commands.LocalUser inputobject;
/// <summary>
/// The following is the definition of the input parameter "Name".
/// Specifies the local user account to be renamed in the local Security
/// Accounts Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "Default")]
[ValidateNotNullOrEmpty]
public string Name
{
get { return this.name;}
set { this.name = value; }
}
private string name;
/// <summary>
/// The following is the definition of the input parameter "NewName".
/// Specifies the new name for the local user account in the Security Accounts
/// Manager.
/// </summary>
[Parameter(Mandatory = true,
Position = 1)]
[ValidateNotNullOrEmpty]
public string NewName
{
get { return this.newname;}
set { this.newname = value; }
}
private string newname;
/// <summary>
/// The following is the definition of the input parameter "SID".
/// Specifies the local user to rename.
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SecurityIdentifier")]
[ValidateNotNull]
public System.Security.Principal.SecurityIdentifier SID
{
get { return this.sid;}
set { this.sid = value; }
}
private System.Security.Principal.SecurityIdentifier sid;
#endregion Parameter Properties
#region Cmdlet Overrides
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
sam = new Sam();
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
try
{
ProcessUser();
ProcessName();
ProcessSid();
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
if (sam != null)
{
sam.Dispose();
sam = null;
}
}
#endregion Cmdlet Overrides
#region Private Methods
/// <summary>
/// Process user requested by -Name.
/// </summary>
/// <remarks>
/// Arguments to -Name will be treated as names,
/// even if a name looks like a SID.
/// </remarks>
private void ProcessName()
{
if (Name != null)
{
try
{
if (CheckShouldProcess(Name, NewName))
sam.RenameLocalUser(sam.GetLocalUser(Name), NewName);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
/// <summary>
/// Process user requested by -SID.
/// </summary>
private void ProcessSid()
{
if (SID != null)
{
try
{
if (CheckShouldProcess(SID.ToString(), NewName))
sam.RenameLocalUser(SID, NewName);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
/// <summary>
/// Process group given through -InputObject.
/// </summary>
private void ProcessUser()
{
if (InputObject != null)
{
try
{
if (CheckShouldProcess(InputObject.Name, NewName))
sam.RenameLocalUser(InputObject, NewName);
}
catch (Exception ex)
{
WriteError(ex.MakeErrorRecord());
}
}
}
/// <summary>
/// Determine if a user should be processed.
/// Just a wrapper around Cmdlet.ShouldProcess, with localized string
/// formatting.
/// </summary>
/// <param name="userName">
/// Name of the user to rename.
/// </param>
/// <param name="newName">
/// New name for the user.
/// </param>
/// <returns>
/// True if the user should be processed, false otherwise.
/// </returns>
private bool CheckShouldProcess(string userName, string newName)
{
string msg = StringUtil.Format(Strings.ActionRenameUser, newName);
return ShouldProcess(userName, msg);
}
#endregion Private Methods
}
}
| |
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 state or province.
/// </summary>
public class State_Core : TypeCore, IAdministrativeArea
{
public State_Core()
{
this._TypeId = 251;
this._Id = "State";
this._Schema_Org_Url = "http://schema.org/State";
string label = "";
GetLabel(out label, "State", typeof(State_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,10};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{10};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Services.Connectors.SimianGrid;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
namespace OpenSim.Services.Connectors
{
public class HGAssetServiceConnector : IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<string, IAssetService> m_connectors = new Dictionary<string, IAssetService>();
private ReaderWriterLock m_connectorsRwLock = new ReaderWriterLock();
public HGAssetServiceConnector(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
// string name = moduleConfig.GetString("AssetServices", "");
IConfig assetConfig = source.Configs["AssetService"];
if (assetConfig == null)
{
m_log.Error("[HG ASSET SERVICE]: AssetService missing from OpenSim.ini");
return;
}
m_log.Info("[HG ASSET SERVICE]: HG asset service enabled");
}
}
private IAssetService GetConnector(string url)
{
IAssetService connector = null;
m_connectorsRwLock.AcquireReaderLock(-1);
try
{
if (m_connectors.ContainsKey(url))
{
connector = m_connectors[url];
}
else
{
LockCookie lc = m_connectorsRwLock.UpgradeToWriterLock(-1);
try
{
/* recheck since other thread may have created it */
if (m_connectors.ContainsKey(url))
{
connector = m_connectors[url];
}
else
{
// Still not as flexible as I would like this to be,
// but good enough for now
string connectorType = new HeloServicesConnector(url).Helo();
m_log.DebugFormat("[HG ASSET SERVICE]: HELO returned {0}", connectorType);
if (connectorType == "opensim-simian")
{
connector = new SimianAssetServiceConnector(url);
}
else
connector = new AssetServicesConnector(url);
m_connectors.Add(url, connector);
}
}
finally
{
m_connectorsRwLock.DowngradeFromWriterLock(ref lc);
}
}
}
finally
{
m_connectorsRwLock.ReleaseReaderLock();
}
return connector;
}
public AssetBase Get(string id)
{
string url = string.Empty;
string assetID = string.Empty;
if (Util.ParseForeignAssetID(id, out url, out assetID))
{
IAssetService connector = GetConnector(url);
return connector.Get(assetID);
}
return null;
}
public AssetBase GetCached(string id)
{
string url = string.Empty;
string assetID = string.Empty;
if (Util.ParseForeignAssetID(id, out url, out assetID))
{
IAssetService connector = GetConnector(url);
return connector.GetCached(assetID);
}
return null;
}
public AssetMetadata GetMetadata(string id)
{
string url = string.Empty;
string assetID = string.Empty;
if (Util.ParseForeignAssetID(id, out url, out assetID))
{
IAssetService connector = GetConnector(url);
return connector.GetMetadata(assetID);
}
return null;
}
public byte[] GetData(string id)
{
return null;
}
public bool Get(string id, Object sender, AssetRetrieved handler)
{
string url = string.Empty;
string assetID = string.Empty;
if (Util.ParseForeignAssetID(id, out url, out assetID))
{
IAssetService connector = GetConnector(url);
return connector.Get(assetID, sender, handler);
}
return false;
}
private struct AssetAndIndex
{
public UUID assetID;
public int index;
public AssetAndIndex(UUID assetID, int index)
{
this.assetID = assetID;
this.index = index;
}
}
public virtual bool[] AssetsExist(string[] ids)
{
// This method is a bit complicated because it works even if the assets belong to different
// servers; that requires sending separate requests to each server.
// Group the assets by the server they belong to
var url2assets = new Dictionary<string, List<AssetAndIndex>>();
for (int i = 0; i < ids.Length; i++)
{
string url = string.Empty;
string assetID = string.Empty;
if (Util.ParseForeignAssetID(ids[i], out url, out assetID))
{
if (!url2assets.ContainsKey(url))
url2assets.Add(url, new List<AssetAndIndex>());
url2assets[url].Add(new AssetAndIndex(UUID.Parse(assetID), i));
}
}
// Query each of the servers in turn
bool[] exist = new bool[ids.Length];
foreach (string url in url2assets.Keys)
{
IAssetService connector = GetConnector(url);
{
List<AssetAndIndex> curAssets = url2assets[url];
string[] assetIDs = curAssets.ConvertAll(a => a.assetID.ToString()).ToArray();
bool[] curExist = connector.AssetsExist(assetIDs);
int i = 0;
foreach (AssetAndIndex ai in curAssets)
{
exist[ai.index] = curExist[i];
++i;
}
}
}
return exist;
}
public string Store(AssetBase asset)
{
string url = string.Empty;
string assetID = string.Empty;
if (Util.ParseForeignAssetID(asset.ID, out url, out assetID))
{
IAssetService connector = GetConnector(url);
// Restore the assetID to a simple UUID
asset.ID = assetID;
return connector.Store(asset);
}
return String.Empty;
}
public bool UpdateContent(string id, byte[] data)
{
return false;
}
public bool Delete(string id)
{
return false;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
public sealed class DataContractSerializer : XmlObjectSerializer
{
Type rootType;
DataContract rootContract; // post-surrogate
bool needsContractNsAtRoot;
XmlDictionaryString rootName;
XmlDictionaryString rootNamespace;
int maxItemsInObjectGraph;
bool ignoreExtensionDataObject;
bool preserveObjectReferences;
IDataContractSurrogate dataContractSurrogate;
ReadOnlyCollection<Type> knownTypeCollection;
internal IList<Type> knownTypeList;
internal DataContractDictionary knownDataContracts;
DataContractResolver dataContractResolver;
bool serializeReadOnlyTypes;
public DataContractSerializer(Type type)
: this(type, (IEnumerable<Type>)null)
{
}
public DataContractSerializer(Type type, IEnumerable<Type> knownTypes)
: this(type, knownTypes, int.MaxValue, false, false, null)
{
}
public DataContractSerializer(Type type,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
IDataContractSurrogate dataContractSurrogate)
: this(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, null)
{
}
public DataContractSerializer(Type type,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
IDataContractSurrogate dataContractSurrogate,
DataContractResolver dataContractResolver)
{
Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, dataContractResolver, false);
}
public DataContractSerializer(Type type, string rootName, string rootNamespace)
: this(type, rootName, rootNamespace, null)
{
}
public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable<Type> knownTypes)
: this(type, rootName, rootNamespace, knownTypes, int.MaxValue, false, false, null)
{
}
public DataContractSerializer(Type type, string rootName, string rootNamespace,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
IDataContractSurrogate dataContractSurrogate)
: this(type, rootName, rootNamespace, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, null)
{
}
public DataContractSerializer(Type type, string rootName, string rootNamespace,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
IDataContractSurrogate dataContractSurrogate,
DataContractResolver dataContractResolver)
{
XmlDictionary dictionary = new XmlDictionary(2);
Initialize(type, dictionary.Add(rootName), dictionary.Add(DataContract.GetNamespace(rootNamespace)), knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, dataContractResolver, false);
}
public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace)
: this(type, rootName, rootNamespace, null)
{
}
public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable<Type> knownTypes)
: this(type, rootName, rootNamespace, knownTypes, int.MaxValue, false, false, null, null)
{
}
public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
IDataContractSurrogate dataContractSurrogate)
: this(type, rootName, rootNamespace, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, null)
{
}
public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
IDataContractSurrogate dataContractSurrogate,
DataContractResolver dataContractResolver)
{
Initialize(type, rootName, rootNamespace, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, dataContractResolver, false);
}
public DataContractSerializer(Type type, DataContractSerializerSettings settings)
{
if (settings == null)
{
settings = new DataContractSerializerSettings();
}
Initialize(type, settings.RootName, settings.RootNamespace, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject,
settings.PreserveObjectReferences, settings.DataContractSurrogate, settings.DataContractResolver, settings.SerializeReadOnlyTypes);
}
void Initialize(Type type,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
IDataContractSurrogate dataContractSurrogate,
DataContractResolver dataContractResolver,
bool serializeReadOnlyTypes)
{
CheckNull(type, "type");
this.rootType = type;
if (knownTypes != null)
{
this.knownTypeList = new List<Type>();
foreach (Type knownType in knownTypes)
{
this.knownTypeList.Add(knownType);
}
}
if (maxItemsInObjectGraph < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxItemsInObjectGraph", SR.GetString(SR.ValueMustBeNonNegative)));
this.maxItemsInObjectGraph = maxItemsInObjectGraph;
this.ignoreExtensionDataObject = ignoreExtensionDataObject;
this.preserveObjectReferences = preserveObjectReferences;
this.dataContractSurrogate = dataContractSurrogate;
this.dataContractResolver = dataContractResolver;
this.serializeReadOnlyTypes = serializeReadOnlyTypes;
}
void Initialize(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace,
IEnumerable<Type> knownTypes,
int maxItemsInObjectGraph,
bool ignoreExtensionDataObject,
bool preserveObjectReferences,
IDataContractSurrogate dataContractSurrogate,
DataContractResolver dataContractResolver,
bool serializeReadOnlyTypes)
{
Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractSurrogate, dataContractResolver, serializeReadOnlyTypes);
// validate root name and namespace are both non-null
this.rootName = rootName;
this.rootNamespace = rootNamespace;
}
public ReadOnlyCollection<Type> KnownTypes
{
get
{
if (knownTypeCollection == null)
{
if (knownTypeList != null)
{
knownTypeCollection = new ReadOnlyCollection<Type>(knownTypeList);
}
else
{
knownTypeCollection = new ReadOnlyCollection<Type>(Globals.EmptyTypeArray);
}
}
return knownTypeCollection;
}
}
internal override DataContractDictionary KnownDataContracts
{
get
{
if (this.knownDataContracts == null && this.knownTypeList != null)
{
// This assignment may be performed concurrently and thus is a race condition.
// It's safe, however, because at worse a new (and identical) dictionary of
// data contracts will be created and re-assigned to this field. Introduction
// of a lock here could lead to deadlocks.
this.knownDataContracts = XmlObjectSerializerContext.GetDataContractsForKnownTypes(this.knownTypeList);
}
return this.knownDataContracts;
}
}
public int MaxItemsInObjectGraph
{
get { return maxItemsInObjectGraph; }
}
public IDataContractSurrogate DataContractSurrogate
{
get { return dataContractSurrogate; }
}
public bool PreserveObjectReferences
{
get { return preserveObjectReferences; }
}
public bool IgnoreExtensionDataObject
{
get { return ignoreExtensionDataObject; }
}
public DataContractResolver DataContractResolver
{
get { return dataContractResolver; }
}
public bool SerializeReadOnlyTypes
{
get { return serializeReadOnlyTypes; }
}
DataContract RootContract
{
get
{
if (rootContract == null)
{
rootContract = DataContract.GetDataContract(((dataContractSurrogate == null) ? rootType : GetSurrogatedType(dataContractSurrogate, rootType)));
needsContractNsAtRoot = CheckIfNeedsContractNsAtRoot(rootName, rootNamespace, rootContract);
}
return rootContract;
}
}
internal override void InternalWriteObject(XmlWriterDelegator writer, object graph)
{
InternalWriteObject(writer, graph, null);
}
internal override void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
{
InternalWriteStartObject(writer, graph);
InternalWriteObjectContent(writer, graph, dataContractResolver);
InternalWriteEndObject(writer);
}
public override void WriteObject(XmlWriter writer, object graph)
{
WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteStartObject(XmlWriter writer, object graph)
{
WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteObjectContent(XmlWriter writer, object graph)
{
WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteEndObject(XmlWriter writer)
{
WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer));
}
public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
{
WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
{
WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph);
}
public override void WriteEndObject(XmlDictionaryWriter writer)
{
WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer));
}
public void WriteObject(XmlDictionaryWriter writer, object graph, DataContractResolver dataContractResolver)
{
WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph, dataContractResolver);
}
public override object ReadObject(XmlReader reader)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/);
}
public override object ReadObject(XmlReader reader, bool verifyObjectName)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName);
}
public override bool IsStartObject(XmlReader reader)
{
return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader));
}
public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName);
}
public override bool IsStartObject(XmlDictionaryReader reader)
{
return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader));
}
public object ReadObject(XmlDictionaryReader reader, bool verifyObjectName, DataContractResolver dataContractResolver)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName, dataContractResolver);
}
internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph)
{
WriteRootElement(writer, RootContract, rootName, rootNamespace, needsContractNsAtRoot);
}
internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph)
{
InternalWriteObjectContent(writer, graph, null);
}
internal void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
{
if (MaxItemsInObjectGraph == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
DataContract contract = RootContract;
Type declaredType = contract.UnderlyingType;
Type graphType = (graph == null) ? declaredType : graph.GetType();
if (dataContractSurrogate != null)
graph = SurrogateToDataContractType(dataContractSurrogate, graph, declaredType, ref graphType);
if (dataContractResolver == null)
dataContractResolver = this.DataContractResolver;
if (graph == null)
{
if (IsRootXmlAny(rootName, contract))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.IsAnyCannotBeNull, declaredType)));
WriteNull(writer);
}
else
{
if (declaredType == graphType)
{
if (contract.CanContainReferences)
{
XmlObjectSerializerWriteContext context = XmlObjectSerializerWriteContext.CreateContext(this, contract, dataContractResolver);
context.HandleGraphAtTopLevel(writer, graph, contract);
context.SerializeWithoutXsiType(contract, writer, graph, declaredType.TypeHandle);
}
else
{
contract.WriteXmlValue(writer, graph, null);
}
}
else
{
XmlObjectSerializerWriteContext context = null;
if (IsRootXmlAny(rootName, contract))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.IsAnyCannotBeSerializedAsDerivedType, graphType, contract.UnderlyingType)));
contract = GetDataContract(contract, declaredType, graphType);
context = XmlObjectSerializerWriteContext.CreateContext(this, RootContract, dataContractResolver);
if (contract.CanContainReferences)
{
context.HandleGraphAtTopLevel(writer, graph, contract);
}
context.OnHandleIsReference(writer, contract, graph);
context.SerializeWithXsiTypeAtTopLevel(contract, writer, graph, declaredType.TypeHandle, graphType);
}
}
}
internal static DataContract GetDataContract(DataContract declaredTypeContract, Type declaredType, Type objectType)
{
if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
return declaredTypeContract;
}
else if (declaredType.IsArray)//Array covariance is not supported in XSD
{
return declaredTypeContract;
}
else
{
return DataContract.GetDataContract(objectType.TypeHandle, objectType, SerializationMode.SharedContract);
}
}
internal override void InternalWriteEndObject(XmlWriterDelegator writer)
{
if (!IsRootXmlAny(rootName, RootContract))
{
writer.WriteEndElement();
}
}
internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName)
{
return InternalReadObject(xmlReader, verifyObjectName, null);
}
internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName, DataContractResolver dataContractResolver)
{
if (MaxItemsInObjectGraph == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph)));
if (dataContractResolver == null)
dataContractResolver = this.DataContractResolver;
if (verifyObjectName)
{
if (!InternalIsStartObject(xmlReader))
{
XmlDictionaryString expectedName;
XmlDictionaryString expectedNs;
if (rootName == null)
{
expectedName = RootContract.TopLevelElementName;
expectedNs = RootContract.TopLevelElementNamespace;
}
else
{
expectedName = rootName;
expectedNs = rootNamespace;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.GetString(SR.ExpectingElement, expectedNs, expectedName), xmlReader));
}
}
else if (!IsStartElement(xmlReader))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.GetString(SR.ExpectingElementAtDeserialize, XmlNodeType.Element), xmlReader));
}
DataContract contract = RootContract;
if (contract.IsPrimitive && object.ReferenceEquals(contract.UnderlyingType, rootType) /*handle Nullable<T> differently*/)
{
return contract.ReadXmlValue(xmlReader, null);
}
if (IsRootXmlAny(rootName, contract))
{
return XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, contract as XmlDataContract, false /*isMemberType*/);
}
XmlObjectSerializerReadContext context = XmlObjectSerializerReadContext.CreateContext(this, contract, dataContractResolver);
return context.InternalDeserialize(xmlReader, rootType, contract, null, null);
}
internal override bool InternalIsStartObject(XmlReaderDelegator reader)
{
return IsRootElement(reader, RootContract, rootName, rootNamespace);
}
internal override Type GetSerializeType(object graph)
{
return (graph == null) ? rootType : graph.GetType();
}
internal override Type GetDeserializeType()
{
return rootType;
}
internal static object SurrogateToDataContractType(IDataContractSurrogate dataContractSurrogate, object oldObj, Type surrogatedDeclaredType, ref Type objType)
{
object obj = DataContractSurrogateCaller.GetObjectToSerialize(dataContractSurrogate, oldObj, objType, surrogatedDeclaredType);
if (obj != oldObj)
{
if (obj == null)
objType = Globals.TypeOfObject;
else
objType = obj.GetType();
}
return obj;
}
internal static Type GetSurrogatedType(IDataContractSurrogate dataContractSurrogate, Type type)
{
return DataContractSurrogateCaller.GetDataContractType(dataContractSurrogate, DataContract.UnwrapNullableType(type));
}
}
}
| |
using UnityEngine;
using System.Collections;
public class Projectile : MonoBehaviour {
private float projectileSpeed = 100.0f;
private Vector3 reticlePos; // Reticle, used to calculate the direction in which the projectile fires
private Vector3 translation; // Forward vector of the projectile
private AttackType.Type type; // Type of Attack
public string Type;
public Vector3 Translation
{
get { return translation; }
set { translation = value; }
}
private int playerNumber; // The last player to have fired/reflected the projectile
public int PlayerNumber
{
get { return playerNumber; }
set { playerNumber = value; }
}
// PowerUp flags
private bool isGhostShot;
public bool IsGhostShot
{
get { return isGhostShot; }
set { isGhostShot = value; }
}
private bool isChainShot;
public bool IsChainShot
{
get { return isChainShot; }
set { isChainShot = value; }
}
// Used for ChainShot calculations
private const float circleCastRadius = Mathf.Infinity; // Radius of the circleCast used by the projectile when it hits a wizard
private const int wizardLayer = 1 << 8; // Used to find all the wizards on the field
private const int wallsLayer = 1 << 9; // Used to find the Wall(s) (on the field) that was just hit by this projectile
// Use this for initialization
void Start ()
{
Vector3 t = Utilities.CalcDir (transform.position, reticlePos);
if (t == Vector3.zero)
{
translation = Vector3.right * projectileSpeed;
}
else
{
translation = t * projectileSpeed;
}
RotateProjectile ();
}
// Update is called once per frame
void Update ()
{
}
void FixedUpdate ()
{
rigidbody2D.velocity = translation;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Wizard")
{
Wizard otherWizard = other.GetComponent<Wizard>();
if (!otherWizard.IsInvincible && !otherWizard.IsSpawning && !otherWizard.IsDying)
{
otherWizard.DecreaseHealth(type);
// Metadata statements
//MetadataManager.Instance.PlayerDeath(Time.time, MetadataManager.AttackType.PROJECTILE, playerNumber, otherWizard.PlayerNumber);
if (isChainShot)
{
TargetClosestWizard(otherWizard);
}
else
{
//LightLinger();
Destroy(gameObject);
}
}
else
{
//LightLinger();
Destroy(gameObject);
}
}
else if (other.tag == "Wall" &&
Walls.IsReflective)
{
ReflectProjectile();
}
else if (other.tag == "Terrain" &&
isGhostShot)
{
// continue;
}
else if (other.tag == "Mud")
{
// continue;
}
else if (other.tag == "River")
{
// continue;
}
else if (other.tag == "Melee Attack")
{
// continue;
}
else if (other.tag == "AoE Attack")
{
// continue;
}
else if (other.tag == "Power Up")
{
// continue;
}
else if (other.tag == "Projectile Attack")
{
AudioManager.Instance.PlayPPCollection();
Destroy (gameObject);
}
else
{
//LightLinger();
Destroy(gameObject);
}
}
// Rotate the projectile to face the correct direction it is shooting in
private void RotateProjectile()
{
transform.eulerAngles = Vector3.zero;
transform.Rotate(0, 0, Mathf.Atan2(translation.y,translation.x)*Mathf.Rad2Deg);
}
// Get the closest Wizard that is not the given Wizard
// The given Wizard is the Wizard that was just shot
private Transform GetClosestWizard(Wizard otherWizard)
{
Collider2D[] wizards = Physics2D.OverlapCircleAll(transform.position, circleCastRadius, wizardLayer);
float shortestDistance = 0;
Transform closestWizard = null;
foreach (Collider2D collider in wizards)
{
Wizard w = collider.GetComponent<Wizard>();
if (otherWizard.PlayerNumber != w.PlayerNumber &&
playerNumber != w.PlayerNumber)
{
float distance = Vector2.Distance(transform.position, w.transform.position);
if (shortestDistance == 0 ||
distance < shortestDistance)
{
shortestDistance = distance;
closestWizard = w.transform;
}
}
}
return closestWizard;
}
// Change the projectile's trajectory to target the closest Wizard that is not the given Wizard
// THe given Wizard is the Wizard that was just shot
private void TargetClosestWizard(Wizard otherWizard)
{
Transform closestWizard;
try
{
closestWizard = GetClosestWizard(otherWizard);
translation = Utilities.CalcDir(transform.position, closestWizard.position) * projectileSpeed;
RotateProjectile();
}
catch (System.NullReferenceException e)
{
Destroy(gameObject);
}
}
// Reflect the projectile off the wall
private void ReflectProjectile()
{
RaycastHit2D collisionInfo = Physics2D.Raycast(transform.position, translation, Mathf.Infinity, wallsLayer);
translation = Quaternion.AngleAxis(180, collisionInfo.normal) * translation * -1;
RotateProjectile();
AudioManager.Instance.PlayReflection ();
}
// Initializes the Projectile with a playerNumber and the reticlePos
// The reticlePos is used to calculate the projectile's trajectory.
public void Init(int playerNumber, Vector3 reticlePos)
{
this.playerNumber = playerNumber;
this.reticlePos = reticlePos;
if (Type == "FIRE")
type = AttackType.Type.FIRE;
else if (Type == "ICE")
type = AttackType.Type.ICE;
else if (Type == "LIGHTNING")
type = AttackType.Type.LIGHTNING;
else
type = AttackType.Type.EARTH;
}
// ONLY APPLIES TO THE NIGHT LEVEL
private void LightLinger()
{
if (transform.childCount > 0)
{
transform.GetChild(0).parent = null;
}
}
public AttackType.Type getAttackType()
{
if (Type == "FIRE")
return type = AttackType.Type.FIRE;
else if (Type == "ICE")
return AttackType.Type.ICE;
else if (Type == "LIGHTNING")
return AttackType.Type.LIGHTNING;
else
return AttackType.Type.EARTH;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
//using HyperGrid.Framework;
//using OpenSim.Region.Communications.Hypergrid;
namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{
public class HGAssetMapper
{
#region Fields
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// This maps between inventory server urls and inventory server clients
// private Dictionary<string, InventoryClient> m_inventoryServers = new Dictionary<string, InventoryClient>();
private Scene m_scene;
private string m_HomeURI;
#endregion
#region Constructor
public HGAssetMapper(Scene scene, string homeURL)
{
m_scene = scene;
m_HomeURI = homeURL;
}
#endregion
#region Internal functions
private AssetMetadata FetchMetadata(string url, UUID assetID)
{
if (string.IsNullOrEmpty(url))
return null;
if (!url.EndsWith("/") && !url.EndsWith("="))
url = url + "/";
AssetMetadata meta = m_scene.AssetService.GetMetadata(url + assetID.ToString());
if (meta != null)
m_log.DebugFormat("[HG ASSET MAPPER]: Fetched metadata for asset {0} of type {1} from {2} ", assetID, meta.Type, url);
else
m_log.DebugFormat("[HG ASSET MAPPER]: Unable to fetched metadata for asset {0} from {1} ", assetID, url);
return meta;
}
private AssetBase FetchAsset(string url, UUID assetID)
{
// Test if it's already here
AssetBase asset = m_scene.AssetService.Get(assetID.ToString());
if (asset == null)
{
if (string.IsNullOrEmpty(url))
return null;
if (!url.EndsWith("/") && !url.EndsWith("="))
url = url + "/";
asset = m_scene.AssetService.Get(url + assetID.ToString());
//if (asset != null)
// m_log.DebugFormat("[HG ASSET MAPPER]: Fetched asset {0} of type {1} from {2} ", assetID, asset.Metadata.Type, url);
//else
// m_log.DebugFormat("[HG ASSET MAPPER]: Unable to fetch asset {0} from {1} ", assetID, url);
}
return asset;
}
public bool PostAsset(string url, AssetBase asset)
{
if (string.IsNullOrEmpty(url))
return false;
if (asset != null)
{
if (!url.EndsWith("/") && !url.EndsWith("="))
url = url + "/";
bool success = true;
// See long comment in AssetCache.AddAsset
if (!asset.Temporary || asset.Local)
{
// We need to copy the asset into a new asset, because
// we need to set its ID to be URL+UUID, so that the
// HGAssetService dispatches it to the remote grid.
// It's not pretty, but the best that can be done while
// not having a global naming infrastructure
AssetBase asset1 = new AssetBase(asset.FullID, asset.Name, asset.Type, asset.Metadata.CreatorID);
Copy(asset, asset1);
asset1.ID = url + asset.ID;
AdjustIdentifiers(asset1.Metadata);
if (asset1.Metadata.Type == (sbyte)AssetType.Object)
asset1.Data = AdjustIdentifiers(asset.Data);
else
asset1.Data = asset.Data;
string id = m_scene.AssetService.Store(asset1);
if (id == string.Empty)
{
m_log.DebugFormat("[HG ASSET MAPPER]: Asset server {0} did not accept {1}", url, asset.ID);
success = false;
}
else
m_log.DebugFormat("[HG ASSET MAPPER]: Posted copy of asset {0} from local asset server to {1}", asset1.ID, url);
}
return success;
}
else
m_log.Warn("[HG ASSET MAPPER]: Tried to post asset to remote server, but asset not in local cache.");
return false;
}
private void Copy(AssetBase from, AssetBase to)
{
//to.Data = from.Data; // don't copy this, it's copied elsewhere
to.Description = from.Description;
to.FullID = from.FullID;
to.ID = from.ID;
to.Local = from.Local;
to.Name = from.Name;
to.Temporary = from.Temporary;
to.Type = from.Type;
}
private void AdjustIdentifiers(AssetMetadata meta)
{
if (meta.CreatorID != null && meta.CreatorID != string.Empty)
{
UUID uuid = UUID.Zero;
UUID.TryParse(meta.CreatorID, out uuid);
UserAccount creator = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, uuid);
if (creator != null)
meta.CreatorID = m_HomeURI + ";" + creator.FirstName + " " + creator.LastName;
}
}
protected byte[] AdjustIdentifiers(byte[] data)
{
string xml = Utils.BytesToString(data);
return Utils.StringToBytes(RewriteSOP(xml));
}
protected string RewriteSOP(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList sops = doc.GetElementsByTagName("SceneObjectPart");
foreach (XmlNode sop in sops)
{
UserAccount creator = null;
bool hasCreatorData = false;
XmlNodeList nodes = sop.ChildNodes;
foreach (XmlNode node in nodes)
{
if (node.Name == "CreatorID")
{
UUID uuid = UUID.Zero;
UUID.TryParse(node.InnerText, out uuid);
creator = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, uuid);
}
if (node.Name == "CreatorData" && node.InnerText != null && node.InnerText != string.Empty)
hasCreatorData = true;
//if (node.Name == "OwnerID")
//{
// UserAccount owner = GetUser(node.InnerText);
// if (owner != null)
// node.InnerText = m_ProfileServiceURL + "/" + node.InnerText + "/" + owner.FirstName + " " + owner.LastName;
//}
}
if (!hasCreatorData && creator != null)
{
XmlElement creatorData = doc.CreateElement("CreatorData");
creatorData.InnerText = m_HomeURI + ";" + creator.FirstName + " " + creator.LastName;
sop.AppendChild(creatorData);
}
}
using (StringWriter wr = new StringWriter())
{
doc.Save(wr);
return wr.ToString();
}
}
// TODO: unused
// private void Dump(Dictionary<UUID, bool> lst)
// {
// m_log.Debug("XXX -------- UUID DUMP ------- XXX");
// foreach (KeyValuePair<UUID, bool> kvp in lst)
// m_log.Debug(" >> " + kvp.Key + " (texture? " + kvp.Value + ")");
// m_log.Debug("XXX -------- UUID DUMP ------- XXX");
// }
#endregion
#region Public interface
public void Get(UUID assetID, UUID ownerID, string userAssetURL)
{
// Get the item from the remote asset server onto the local AssetService
AssetMetadata meta = FetchMetadata(userAssetURL, assetID);
if (meta == null)
return;
// The act of gathering UUIDs downloads some assets from the remote server
// but not all...
Dictionary<UUID, AssetType> ids = new Dictionary<UUID, AssetType>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, userAssetURL);
uuidGatherer.GatherAssetUuids(assetID, (AssetType)meta.Type, ids);
m_log.DebugFormat("[HG ASSET MAPPER]: Preparing to get {0} assets", ids.Count);
bool success = true;
foreach (UUID uuid in ids.Keys)
if (FetchAsset(userAssetURL, uuid) == null)
success = false;
// maybe all pieces got here...
if (!success)
m_log.DebugFormat("[HG ASSET MAPPER]: Problems getting item {0} from asset server {1}", assetID, userAssetURL);
else
m_log.DebugFormat("[HG ASSET MAPPER]: Successfully got item {0} from asset server {1}", assetID, userAssetURL);
}
public void Post(UUID assetID, UUID ownerID, string userAssetURL)
{
// Post the item from the local AssetCache onto the remote asset server
// and place an entry in m_assetMap
m_log.Debug("[HG ASSET MAPPER]: Posting object " + assetID + " to asset server " + userAssetURL);
AssetBase asset = m_scene.AssetService.Get(assetID.ToString());
if (asset != null)
{
Dictionary<UUID, AssetType> ids = new Dictionary<UUID, AssetType>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(m_scene.AssetService, string.Empty);
uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids);
bool success = false;
foreach (UUID uuid in ids.Keys)
{
asset = m_scene.AssetService.Get(uuid.ToString());
if (asset == null)
m_log.DebugFormat("[HG ASSET MAPPER]: Could not find asset {0}", uuid);
else
success = PostAsset(userAssetURL, asset);
}
// maybe all pieces got there...
if (!success)
m_log.DebugFormat("[HG ASSET MAPPER]: Problems posting item {0} to asset server {1}", assetID, userAssetURL);
else
m_log.DebugFormat("[HG ASSET MAPPER]: Successfully posted item {0} to asset server {1}", assetID, userAssetURL);
}
else
m_log.DebugFormat("[HG ASSET MAPPER]: Something wrong with asset {0}, it could not be found", assetID);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Numerics.Tests
{
public class StackCalc
{
public string[] input;
public Stack<BigInteger> myCalc;
public Stack<BigInteger> snCalc;
public Queue<string> operators;
private BigInteger _snOut = 0;
private BigInteger _myOut = 0;
public StackCalc(string _input)
{
myCalc = new Stack<System.Numerics.BigInteger>();
snCalc = new Stack<System.Numerics.BigInteger>();
string delimStr = " ";
char[] delimiter = delimStr.ToCharArray();
input = _input.Split(delimiter);
operators = new Queue<string>(input);
}
public bool DoNextOperation()
{
string op = "";
bool ret = false;
bool checkValues = false;
BigInteger snnum1 = 0;
BigInteger snnum2 = 0;
BigInteger snnum3 = 0;
BigInteger mynum1 = 0;
BigInteger mynum2 = 0;
BigInteger mynum3 = 0;
if (operators.Count == 0)
{
return false;
}
op = operators.Dequeue();
if (op.StartsWith("u"))
{
checkValues = true;
snnum1 = snCalc.Pop();
snCalc.Push(DoUnaryOperatorSN(snnum1, op));
mynum1 = myCalc.Pop();
myCalc.Push(MyBigIntImp.DoUnaryOperatorMine(mynum1, op));
ret = true;
}
else if (op.StartsWith("b"))
{
checkValues = true;
snnum1 = snCalc.Pop();
snnum2 = snCalc.Pop();
snCalc.Push(DoBinaryOperatorSN(snnum1, snnum2, op, out _snOut));
mynum1 = myCalc.Pop();
mynum2 = myCalc.Pop();
myCalc.Push(MyBigIntImp.DoBinaryOperatorMine(mynum1, mynum2, op, out _myOut));
ret = true;
}
else if (op.StartsWith("t"))
{
checkValues = true;
snnum1 = snCalc.Pop();
snnum2 = snCalc.Pop();
snnum3 = snCalc.Pop();
snCalc.Push(DoTertanaryOperatorSN(snnum1, snnum2, snnum3, op));
mynum1 = myCalc.Pop();
mynum2 = myCalc.Pop();
mynum3 = myCalc.Pop();
myCalc.Push(MyBigIntImp.DoTertanaryOperatorMine(mynum1, mynum2, mynum3, op));
ret = true;
}
else
{
if (op.Equals("make"))
{
snnum1 = DoConstruction();
snCalc.Push(snnum1);
myCalc.Push(snnum1);
}
else if (op.Equals("Corruption"))
{
snCalc.Push(-33);
myCalc.Push(-555);
}
else if (BigInteger.TryParse(op, out snnum1))
{
snCalc.Push(snnum1);
myCalc.Push(snnum1);
}
else
{
Console.WriteLine("Failed to parse string {0}", op);
}
ret = true;
}
if (checkValues)
{
if ((snnum1 != mynum1) || (snnum2 != mynum2) || (snnum3 != mynum3))
{
operators.Enqueue("Corruption");
}
}
return ret;
}
private BigInteger DoConstruction()
{
List<byte> bytes = new List<byte>();
BigInteger ret = new BigInteger(0);
string op = operators.Dequeue();
while (String.CompareOrdinal(op, "endmake") != 0)
{
bytes.Add(byte.Parse(op));
op = operators.Dequeue();
}
return new BigInteger(bytes.ToArray());
}
private BigInteger DoUnaryOperatorSN(BigInteger num1, string op)
{
switch (op)
{
case "uSign":
return new BigInteger(num1.Sign);
case "u~":
return (~(num1));
case "uLog10":
return MyBigIntImp.ApproximateBigInteger(BigInteger.Log10(num1));
case "uLog":
return MyBigIntImp.ApproximateBigInteger(BigInteger.Log(num1));
case "uAbs":
return BigInteger.Abs(num1);
case "uNegate":
return BigInteger.Negate(num1);
case "u--":
return (--(num1));
case "u++":
return (++(num1));
case "u-":
return (-(num1));
case "u+":
return (+(num1));
case "uMultiply":
return BigInteger.Multiply(num1, num1);
case "u*":
return num1 * num1;
default:
throw new ArgumentException(String.Format("Invalid operation found: {0}", op));
}
}
private BigInteger DoBinaryOperatorSN(BigInteger num1, BigInteger num2, string op)
{
BigInteger num3;
return DoBinaryOperatorSN(num1, num2, op, out num3);
}
private BigInteger DoBinaryOperatorSN(BigInteger num1, BigInteger num2, string op, out BigInteger num3)
{
num3 = 0;
switch (op)
{
case "bMin":
return BigInteger.Min(num1, num2);
case "bMax":
return BigInteger.Max(num1, num2);
case "b>>":
return num1 >> (int)num2;
case "b<<":
return num1 << (int)num2;
case "b^":
return num1 ^ num2;
case "b|":
return num1 | num2;
case "b&":
return num1 & num2;
case "b%":
return num1 % num2;
case "b/":
return num1 / num2;
case "b*":
return num1 * num2;
case "b-":
return num1 - num2;
case "b+":
return num1 + num2;
case "bLog":
return MyBigIntImp.ApproximateBigInteger(BigInteger.Log(num1, (double)num2));
case "bGCD":
return BigInteger.GreatestCommonDivisor(num1, num2);
case "bPow":
int arg2 = (int)num2;
return BigInteger.Pow(num1, arg2);
case "bDivRem":
return BigInteger.DivRem(num1, num2, out num3);
case "bRemainder":
return BigInteger.Remainder(num1, num2);
case "bDivide":
return BigInteger.Divide(num1, num2);
case "bMultiply":
return BigInteger.Multiply(num1, num2);
case "bSubtract":
return BigInteger.Subtract(num1, num2);
case "bAdd":
return BigInteger.Add(num1, num2);
default:
throw new ArgumentException(String.Format("Invalid operation found: {0}", op));
}
}
private BigInteger DoTertanaryOperatorSN(BigInteger num1, BigInteger num2, BigInteger num3, string op)
{
switch (op)
{
case "tModPow":
return BigInteger.ModPow(num1, num2, num3);
default:
throw new ArgumentException(String.Format("Invalid operation found: {0}", op));
}
}
public void VerifyOutParameter()
{
Assert.Equal(_snOut, _myOut);
_snOut = 0;
_myOut = 0;
}
private static String Print(byte[] bytes)
{
return MyBigIntImp.PrintFormatX(bytes);
}
}
}
| |
namespace FacebookSharp
{
using System;
using System.Collections.Generic;
using RestSharp;
internal class RestSharpContext<TMessage, TSyncResult, TAsyncResult>
{
private readonly Func<TMessage, RestRequest, RestClient> _prepareRestSharpClient;
private readonly Func<TMessage, Method, RestRequest> _prepareRestSharpRequest;
private readonly Func<TMessage, RestResponse, TSyncResult> _processSyncRestSharpResponse;
private readonly Func<TMessage, RestResponse, TAsyncResult> _processAsyncRestSharpResponse;
public RestSharpContext(
Func<TMessage, RestRequest, RestClient> prepareRestSharpClient,
Func<TMessage, Method, RestRequest> prepareRestSharpRequest,
Func<TMessage, RestResponse, TSyncResult> processSyncRestSharpResponse,
Func<TMessage, RestResponse, TAsyncResult> processAsyncRestSharpResponse)
{
_prepareRestSharpClient = prepareRestSharpClient;
_prepareRestSharpRequest = prepareRestSharpRequest;
_processSyncRestSharpResponse = processSyncRestSharpResponse;
_processAsyncRestSharpResponse = processAsyncRestSharpResponse;
}
#if !(SILVERLIGHT || WINDOWS_PHONE) // NOR logic !(A+B) : if its running on desktop version
#region Synchronous Helpers
public RestResponse Execute(TMessage data, RestRequest request)
{
var client = _prepareRestSharpClient(data, request);
return client.Execute(request);
}
public TSyncResult Execute(TMessage data, Method httpMethod)
{
var request = _prepareRestSharpRequest(data, httpMethod);
var response = Execute(data, request);
return _processSyncRestSharpResponse(data, response);
}
#endregion
#endif
#region Asynchronous Helpers
public void ExecuteAsync(TMessage data, RestRequest request, Action<RestResponse> callback)
{
var client = _prepareRestSharpClient(data, request);
client.ExecuteAsync(
request,
response =>
{
if (callback != null)
callback(response);
});
}
public void ExecuteAsync(TMessage data, Method httpMethod, Action<TAsyncResult> callback)
{
var request = _prepareRestSharpRequest(data, httpMethod);
ExecuteAsync(
data,
request,
response =>
{
var asyncResult = _processAsyncRestSharpResponse(data, response);
if (callback != null)
callback(asyncResult);
});
}
#endregion
}
public partial class Facebook
{
internal class FacebookGraphRestSharpMessage
{
public FacebookGraphRestSharpMessage(Facebook fb)
{
Facebook = fb;
BaseUrl = GraphBaseUrl;
AddAccessToken = true;
}
public string Resource { get; set; }
public string BaseUrl { get; set; }
public Facebook Facebook { get; private set; }
public bool AddAccessToken { get; set; }
public IDictionary<string, string> Parameters { get; set; }
public OAuth2Authenticator GetAuthenticator()
{
if (!string.IsNullOrEmpty(Facebook.Settings.AccessToken))
{
// Note: OAuth2 Authorization Request Header is preferred.
// but for now since Facebook doesn't have clientaccesspolicy.xml file,
// we need to use the QueryString to pass oauth_token to Facebook.
// I have requested Facebook to add clientaccesspolicy.xml at
// http://bugs.developers.facebook.net/show_bug.cgi?id=12818
// Please vote up.
// If it is a silverlight or windows phone app, it uses querystring to
// pass oauth_token, if it is a desktop app it uses Authorization header
#if (SILVERLIGHT || WINDOWS_PHONE)
return new OAuth2UriQueryParameterAuthenticator(Facebook.Settings.AccessToken);
#else
return new OAuth2AuthorizationRequestHeaderAuthenticator(Facebook.Settings.AccessToken);
#endif
}
return null;
}
}
internal class FacebookApiRestSharpMessage : FacebookGraphRestSharpMessage
{
public FacebookApiRestSharpMessage(Facebook fb)
: base(fb)
{
BaseUrl = ApiBaseUrl;
}
}
private static RestSharpContext<FacebookGraphRestSharpMessage, string, FacebookAsyncResult> _graphContext;
internal static RestSharpContext<FacebookGraphRestSharpMessage, string, FacebookAsyncResult> GraphContext
{
get
{
return _graphContext ??
(_graphContext =
new RestSharpContext<FacebookGraphRestSharpMessage, string, FacebookAsyncResult>(
PrepareRestSharpClient,
PrepareRestSharpRequest,
ProcessSyncRestSharpResponse,
ProcessAsyncRestSharpResponse));
}
}
private static RestSharpContext<FacebookApiRestSharpMessage, string, FacebookAsyncResult> _restApiContext;
internal static RestSharpContext<FacebookApiRestSharpMessage, string, FacebookAsyncResult> RestApiContext
{
get
{
return _restApiContext ??
(_restApiContext =
new RestSharpContext<FacebookApiRestSharpMessage, string, FacebookAsyncResult>(
PrepareRestSharpClient,
PrepareRestSharpRequest,
ProcessSyncRestSharpResponse,
ProcessAsyncRestSharpResponse));
}
}
#region Helpers
private static RestClient PrepareRestSharpClient(FacebookGraphRestSharpMessage message, RestRequest request)
{
var client = new RestClient(message.BaseUrl);
client.UserAgent = message.Facebook.Settings.UserAgent;
if (message.AddAccessToken)
client.Authenticator = message.GetAuthenticator();
return client;
}
private static RestRequest PrepareRestSharpRequest(FacebookGraphRestSharpMessage message, Method httpMethod)
{
var request = new RestRequest(message.Resource, httpMethod);
if (message.Parameters != null)
{
foreach (var keyValuePair in message.Parameters)
request.AddParameter(keyValuePair.Key, keyValuePair.Value);
}
return request;
}
private static string ProcessSyncRestSharpResponse(FacebookGraphRestSharpMessage message, RestResponse response)
{
Exception exception;
var result = ProcessRestSharpResponse(message, response, out exception);
if (exception != null)
throw exception;
return result;
}
private static FacebookAsyncResult ProcessAsyncRestSharpResponse(FacebookGraphRestSharpMessage message, RestResponse response)
{
Exception exception;
var result = ProcessRestSharpResponse(message, response, out exception);
return new FacebookAsyncResult(result, exception);
}
private static string ProcessRestSharpResponse(FacebookGraphRestSharpMessage message, RestResponse response, out Exception exception)
{
string result = string.Empty;
if (response.ResponseStatus == ResponseStatus.Completed)
{
exception = (FacebookException)response.Content;
result = response.Content;
}
else
{
if (response.ErrorException is System.Security.SecurityException)
exception = new ClientAccessPolicyException();
else
{
// incase the net is not connected or some other exception
exception = new FacebookRequestException(response);
}
}
return result;
}
#endregion
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 DebuggerApi;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
namespace YetiVSI.DebugEngine
{
public interface IGgpDebugCodeContext : IDebugCodeContext2
{
ulong Address { get; }
string FunctionName { get; }
}
public class DebugCodeContext : IGgpDebugCodeContext
{
public class Factory
{
public virtual IGgpDebugCodeContext Create(
RemoteTarget target, ulong address, string functionName,
IDebugDocumentContext2 documentContext)
{
return new DebugCodeContext(
this, target, address, functionName, documentContext, Guid.Empty);
}
public virtual IGgpDebugCodeContext Create(
RemoteTarget target, ulong address, string functionName,
IDebugDocumentContext2 documentContext, Guid languageGuid)
{
return new DebugCodeContext(
this, target, address, functionName, documentContext, languageGuid);
}
}
readonly Factory _factory;
readonly RemoteTarget _target;
readonly IDebugDocumentContext2 _documentContext;
readonly Guid _languageGuid;
public ulong Address { get; private set; }
string _functionName;
public string FunctionName
{
get
{
if (_functionName == null)
{
// Try resolving the address and extracting the function name from the symbol.
_functionName = _target.ResolveLoadAddress(Address)?.GetFunction()?.GetName();
// Pretty-print the address if the function name is not available.
if (string.IsNullOrWhiteSpace(_functionName))
{
_functionName = ToHexAddr(Address);
}
}
return _functionName;
}
}
DebugCodeContext(Factory factory, RemoteTarget target,
ulong address, string functionName,
IDebugDocumentContext2 documentContext, Guid languageGuid)
{
_factory = factory;
_target = target;
_functionName = functionName;
_documentContext = documentContext;
_languageGuid = languageGuid;
Address = address;
}
#region IDebugMemoryContext2 functions
public int Add(ulong count, out IDebugMemoryContext2 newMemoryContext)
{
// This is not correct for IDebugCodeContext2 according to the docs
// https://docs.microsoft.com/en-us/visualstudio/extensibility/debugger/reference/idebugcodecontext2#remarks
// But it's not used in practice (instead: IDebugDisassemblyStream2.Seek)
// Function name and the document context are no longer valid for the new address, so
// pass null values. Function name will be resolved if needed, but the document
// context is lost.
// TODO: figure out if we need to re-resolve the document context.
newMemoryContext = _factory.Create(
_target, Address + count, null, null, _languageGuid);
return VSConstants.S_OK;
}
public int Subtract(ulong count, out IDebugMemoryContext2 newMemoryContext)
{
// Function name and the document context are no longer valid for the new address, so
// pass null values. Function name will be resolved if needed, but the document
// context is lost.
// TODO: figure out if we need to re-resolve the document context.
newMemoryContext = _factory.Create(
_target, Address - count, null, null, _languageGuid);
return VSConstants.S_OK;
}
public int Compare(enum_CONTEXT_COMPARE comparisonType,
IDebugMemoryContext2[] memoryContexts, uint numMemoryContexts,
out uint matchIndex)
{
matchIndex = uint.MaxValue;
for (uint i = 0; i < numMemoryContexts; i++)
{
ulong otherAddress = ((IGgpDebugCodeContext)memoryContexts[i]).Address;
switch (comparisonType)
{
case enum_CONTEXT_COMPARE.CONTEXT_EQUAL:
if (Address == otherAddress)
{
matchIndex = i;
}
break;
case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN:
if (Address > otherAddress)
{
matchIndex = i;
}
break;
case enum_CONTEXT_COMPARE.CONTEXT_GREATER_THAN_OR_EQUAL:
if (Address >= otherAddress)
{
matchIndex = i;
}
break;
case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN:
if (Address < otherAddress)
{
matchIndex = i;
}
break;
case enum_CONTEXT_COMPARE.CONTEXT_LESS_THAN_OR_EQUAL:
if (Address <= otherAddress)
{
matchIndex = i;
}
break;
case enum_CONTEXT_COMPARE.CONTEXT_SAME_FUNCTION:
memoryContexts[i].GetName(out string otherName);
GetName(out string thisName);
if (Address == otherAddress || thisName == otherName)
{
matchIndex = i;
}
break;
// TODO: if needed, implement other comparison types
default:
return VSConstants.E_NOTIMPL;
}
if (matchIndex != uint.MaxValue)
{
return VSConstants.S_OK;
}
}
return VSConstants.S_FALSE;
}
public int GetInfo(enum_CONTEXT_INFO_FIELDS fields, CONTEXT_INFO[] contextInfo)
{
var info = new CONTEXT_INFO();
if ((enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS & fields) != 0)
{
// Field used for requesting data from Lldb.
info.bstrAddress = ToHexAddr(Address);
info.dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_ADDRESS;
}
if ((enum_CONTEXT_INFO_FIELDS.CIF_ADDRESSABSOLUTE & fields) != 0)
{
// `Name` in the breakpoint list for Disassembly breakpoints and also
// `Address` for all breakpoints types.
info.bstrAddressAbsolute = ToHexAddr(Address);
info.dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_ADDRESSABSOLUTE;
}
// Combination of cif_moduleUrl!cif_function is used in a `Function` column.
// TODO: fix these values, currently they overwrite data from VS
if ((enum_CONTEXT_INFO_FIELDS.CIF_MODULEURL & fields) != 0)
{
info.bstrModuleUrl = "";
info.dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_MODULEURL;
}
if ((enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION & fields) != 0)
{
info.bstrFunction = FunctionName;
info.dwFields |= enum_CONTEXT_INFO_FIELDS.CIF_FUNCTION;
}
// TODO: implement more info fields if we determine they are needed
contextInfo[0] = info;
return VSConstants.S_OK;
}
public int GetName(out string name)
{
name = FunctionName;
return VSConstants.S_OK;
}
#endregion
#region IDebugCodeContext2 functions
public int GetDocumentContext(out IDebugDocumentContext2 documentContext)
{
documentContext = _documentContext;
return documentContext != null ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public int GetLanguageInfo(ref string language, ref Guid languageGuid)
{
if (languageGuid == Guid.Empty)
{
languageGuid = _languageGuid;
language = AD7Constants.GetLanguageByGuid(languageGuid);
}
return VSConstants.S_OK;
}
#endregion
static string ToHexAddr(ulong addr)
{
// TODO: Use x8 for 32-bit processes.
return $"0x{addr:x16}";
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Linq;
using System.Runtime.CompilerServices;
namespace NLog.UnitTests
{
using System;
using NLog.Common;
using System.IO;
using System.Text;
using System.Globalization;
using NLog.Layouts;
using NLog.Config;
using NLog.Targets;
using Xunit;
#if SILVERLIGHT
using System.Xml.Linq;
#else
using System.Xml;
using System.IO.Compression;
using System.Security.Permissions;
#if NET3_5 || NET4_0 || NET4_5
using Ionic.Zip;
#endif
#endif
public abstract class NLogTestBase
{
protected NLogTestBase()
{
//reset before every test
if (LogManager.Configuration != null)
{
//flush all events if needed.
LogManager.Configuration.Close();
}
if (LogManager.LogFactory != null)
{
LogManager.LogFactory.ResetCandidateConfigFilePath();
}
LogManager.Configuration = null;
InternalLogger.Reset();
LogManager.ThrowExceptions = false;
LogManager.ThrowConfigExceptions = null;
}
protected void AssertDebugCounter(string targetName, int val)
{
Assert.Equal(val, GetDebugTarget(targetName).Counter);
}
protected void AssertDebugLastMessage(string targetName, string msg)
{
Assert.Equal(msg, GetDebugLastMessage(targetName));
}
protected void AssertDebugLastMessageContains(string targetName, string msg)
{
string debugLastMessage = GetDebugLastMessage(targetName);
Assert.True(debugLastMessage.Contains(msg),
string.Format("Expected to find '{0}' in last message value on '{1}', but found '{2}'", msg, targetName, debugLastMessage));
}
protected string GetDebugLastMessage(string targetName)
{
return GetDebugLastMessage(targetName, LogManager.Configuration);
}
protected string GetDebugLastMessage(string targetName, LoggingConfiguration configuration)
{
return GetDebugTarget(targetName, configuration).LastMessage;
}
public NLog.Targets.DebugTarget GetDebugTarget(string targetName)
{
return GetDebugTarget(targetName, LogManager.Configuration);
}
protected NLog.Targets.DebugTarget GetDebugTarget(string targetName, LoggingConfiguration configuration)
{
var debugTarget = (NLog.Targets.DebugTarget)configuration.FindTargetByName(targetName);
Assert.NotNull(debugTarget);
return debugTarget;
}
protected void AssertFileContentsStartsWith(string fileName, string contents, Encoding encoding)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(false, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
Assert.True(encodedBuf.Length <= fi.Length);
byte[] buf = new byte[encodedBuf.Length];
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
protected void AssertFileContentsEndsWith(string fileName, string contents, Encoding encoding)
{
if (!File.Exists(fileName))
Assert.True(false, "File '" + fileName + "' doesn't exist.");
string fileText = File.ReadAllText(fileName, encoding);
Assert.True(fileText.Length >= contents.Length);
Assert.Equal(contents, fileText.Substring(fileText.Length - contents.Length));
}
protected class CustomFileCompressor : IFileCompressor
{
public void CompressFile(string fileName, string archiveFileName)
{
#if NET3_5 || NET4_0 || NET4_5
using (ZipFile zip = new ZipFile())
{
zip.AddFile(fileName);
zip.Save(archiveFileName);
}
#endif
}
}
#if NET3_5 || NET4_0
protected void AssertZipFileContents(string fileName, string contents, Encoding encoding)
{
if (!File.Exists(fileName))
Assert.True(false, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
using (var zip = new ZipFile(fileName))
{
Assert.Equal(1, zip.Count);
Assert.Equal(encodedBuf.Length, zip[0].UncompressedSize);
byte[] buf = new byte[zip[0].UncompressedSize];
using (var fs = zip[0].OpenReader())
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
}
#elif NET4_5
protected void AssertZipFileContents(string fileName, string contents, Encoding encoding)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(false, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (var zip = new ZipArchive(stream, ZipArchiveMode.Read))
{
Assert.Equal(1, zip.Entries.Count);
Assert.Equal(encodedBuf.Length, zip.Entries[0].Length);
byte[] buf = new byte[(int)zip.Entries[0].Length];
using (var fs = zip.Entries[0].Open())
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
}
#else
protected void AssertZipFileContents(string fileName, string contents, Encoding encoding)
{
Assert.True(false);
}
#endif
protected void AssertFileContents(string fileName, string contents, Encoding encoding)
{
AssertFileContents(fileName, contents, encoding, false);
}
protected void AssertFileContents(string fileName, string contents, Encoding encoding, bool addBom)
{
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(false, "File '" + fileName + "' doesn't exist.");
byte[] encodedBuf = encoding.GetBytes(contents);
//add bom if needed
if (addBom)
{
var preamble = encoding.GetPreamble();
if (preamble.Length > 0)
{
//insert before
encodedBuf = preamble.Concat(encodedBuf).ToArray();
}
}
Assert.Equal(encodedBuf.Length, fi.Length);
byte[] buf = new byte[(int)fi.Length];
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
fs.Read(buf, 0, buf.Length);
}
for (int i = 0; i < buf.Length; ++i)
{
Assert.Equal(encodedBuf[i], buf[i]);
}
}
protected void AssertFileContains(string fileName, string contentToCheck, Encoding encoding)
{
if (contentToCheck.Contains(Environment.NewLine))
Assert.True(false, "Please use only single line string to check.");
FileInfo fi = new FileInfo(fileName);
if (!fi.Exists)
Assert.True(false, "File '" + fileName + "' doesn't exist.");
using (TextReader fs = new StreamReader(fileName, encoding))
{
string line;
while ((line = fs.ReadLine()) != null)
{
if (line.Contains(contentToCheck))
return;
}
}
Assert.True(false, "File doesn't contains '" + contentToCheck + "'");
}
protected string StringRepeat(int times, string s)
{
StringBuilder sb = new StringBuilder(s.Length * times);
for (int i = 0; i < times; ++i)
sb.Append(s);
return sb.ToString();
}
/// <summary>
/// Render layout <paramref name="layout"/> with dummy <see cref="LogEventInfo" />and compare result with <paramref name="expected"/>.
/// </summary>
protected static void AssertLayoutRendererOutput(Layout layout, string expected)
{
var logEventInfo = LogEventInfo.Create(LogLevel.Info, "loggername", "message");
AssertLayoutRendererOutput(layout, logEventInfo, expected);
}
/// <summary>
/// Render layout <paramref name="layout"/> with <paramref name="logEventInfo"/> and compare result with <paramref name="expected"/>.
/// </summary>
protected static void AssertLayoutRendererOutput(Layout layout, LogEventInfo logEventInfo, string expected)
{
layout.Initialize(null);
string actual = layout.Render(logEventInfo);
layout.Close();
Assert.Equal(expected, actual);
}
#if MONO || NET4_5
/// <summary>
/// Get line number of previous line.
/// </summary>
protected int GetPrevLineNumber([CallerLineNumber] int callingFileLineNumber = 0)
{
return callingFileLineNumber - 1;
}
#else
/// <summary>
/// Get line number of previous line.
/// </summary>
protected int GetPrevLineNumber()
{
//fixed value set with #line 100000
return 100001;
}
#endif
protected static XmlLoggingConfiguration CreateConfigurationFromString(string configXml)
{
#if SILVERLIGHT
XElement element = XElement.Parse(configXml);
return new XmlLoggingConfiguration(element.CreateReader(), null);
#else
XmlDocument doc = new XmlDocument();
doc.LoadXml(configXml);
return new XmlLoggingConfiguration(doc.DocumentElement, Environment.CurrentDirectory);
#endif
}
protected string RunAndCaptureInternalLog(SyncAction action, LogLevel internalLogLevel)
{
var stringWriter = new StringWriter();
InternalLogger.LogWriter = stringWriter;
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.IncludeTimestamp = false;
action();
return stringWriter.ToString();
}
/// <summary>
/// Creates <see cref="CultureInfo"/> instance for test purposes
/// </summary>
/// <param name="cultureName">Culture name to create</param>
/// <remarks>
/// Creates <see cref="CultureInfo"/> instance with non-userOverride
/// flag to provide expected results when running tests in different
/// system cultures(with overriden culture options)
/// </remarks>
protected static CultureInfo GetCultureInfo(string cultureName)
{
#if SILVERLIGHT
return new CultureInfo(cultureName);
#else
return new CultureInfo(cultureName, false);
#endif
}
public delegate void SyncAction();
public class InternalLoggerScope : IDisposable
{
private readonly LogLevel globalThreshold;
private readonly bool throwExceptions;
private readonly bool? throwConfigExceptions;
public InternalLoggerScope()
{
this.globalThreshold = LogManager.GlobalThreshold;
this.throwExceptions = LogManager.ThrowExceptions;
this.throwConfigExceptions = LogManager.ThrowConfigExceptions;
}
public void Dispose()
{
if (File.Exists(InternalLogger.LogFile))
File.Delete(InternalLogger.LogFile);
InternalLogger.Reset();
//restore logmanager
LogManager.GlobalThreshold = this.globalThreshold;
LogManager.ThrowExceptions = this.throwExceptions;
LogManager.ThrowConfigExceptions = this.throwConfigExceptions;
}
}
}
}
| |
//
// Copyright 2011-2013, Xamarin 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.Threading.Tasks;
using System.Threading;
using System.IO;
using System.Linq;
#if __UNIFIED__
using UIKit;
using CoreGraphics;
#else
using MonoTouch.UIKit;
using CGRect = global::System.Drawing.RectangleF;
#endif
namespace Xamarin.Media
{
public class MediaPicker
{
public MediaPicker ()
{
IsCameraAvailable = UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera);
string[] availableCameraMedia = UIImagePickerController.AvailableMediaTypes (UIImagePickerControllerSourceType.Camera) ?? new string[0];
string[] avaialbleLibraryMedia = UIImagePickerController.AvailableMediaTypes (UIImagePickerControllerSourceType.PhotoLibrary) ?? new string[0];
foreach (string type in availableCameraMedia.Concat (avaialbleLibraryMedia))
{
if (type == TypeMovie)
VideosSupported = true;
else if (type == TypeImage)
PhotosSupported = true;
}
}
public bool IsCameraAvailable
{
get;
private set;
}
public bool PhotosSupported
{
get;
private set;
}
public bool VideosSupported
{
get;
private set;
}
public MediaPickerController GetPickPhotoUI()
{
if (!PhotosSupported)
throw new NotSupportedException();
var d = new MediaPickerDelegate (null, UIImagePickerControllerSourceType.PhotoLibrary, null);
return SetupController (d, UIImagePickerControllerSourceType.PhotoLibrary, TypeImage);
}
public Task<MediaFile> PickPhotoAsync()
{
if (!PhotosSupported)
throw new NotSupportedException();
return GetMediaAsync (UIImagePickerControllerSourceType.PhotoLibrary, TypeImage);
}
public MediaPickerController GetTakePhotoUI (StoreCameraMediaOptions options)
{
if (!PhotosSupported)
throw new NotSupportedException();
if (!IsCameraAvailable)
throw new NotSupportedException();
VerifyCameraOptions (options);
var d = new MediaPickerDelegate (null, UIImagePickerControllerSourceType.PhotoLibrary, options);
return SetupController (d, UIImagePickerControllerSourceType.Camera, TypeImage, options);
}
public Task<MediaFile> TakePhotoAsync (StoreCameraMediaOptions options)
{
if (!PhotosSupported)
throw new NotSupportedException();
if (!IsCameraAvailable)
throw new NotSupportedException();
VerifyCameraOptions (options);
return GetMediaAsync (UIImagePickerControllerSourceType.Camera, TypeImage, options);
}
public MediaPickerController GetPickVideoUI()
{
if (!VideosSupported)
throw new NotSupportedException();
var d = new MediaPickerDelegate (null, UIImagePickerControllerSourceType.PhotoLibrary, null);
return SetupController (d, UIImagePickerControllerSourceType.PhotoLibrary, TypeMovie);
}
public Task<MediaFile> PickVideoAsync()
{
if (!VideosSupported)
throw new NotSupportedException();
return GetMediaAsync (UIImagePickerControllerSourceType.PhotoLibrary, TypeMovie);
}
public MediaPickerController GetTakeVideoUI (StoreVideoOptions options)
{
if (!VideosSupported)
throw new NotSupportedException();
if (!IsCameraAvailable)
throw new NotSupportedException();
VerifyCameraOptions (options);
var d = new MediaPickerDelegate (null, UIImagePickerControllerSourceType.Camera, options);
return SetupController (d, UIImagePickerControllerSourceType.Camera, TypeMovie, options);
}
public Task<MediaFile> TakeVideoAsync (StoreVideoOptions options)
{
if (!VideosSupported)
throw new NotSupportedException();
if (!IsCameraAvailable)
throw new NotSupportedException();
VerifyCameraOptions (options);
return GetMediaAsync (UIImagePickerControllerSourceType.Camera, TypeMovie, options);
}
private UIPopoverController popover;
private UIImagePickerControllerDelegate pickerDelegate;
internal const string TypeImage = "public.image";
internal const string TypeMovie = "public.movie";
private void VerifyOptions (StoreMediaOptions options)
{
if (options == null)
throw new ArgumentNullException ("options");
if (options.Directory != null && Path.IsPathRooted (options.Directory))
throw new ArgumentException ("options.Directory must be a relative path", "options");
}
private void VerifyCameraOptions (StoreCameraMediaOptions options)
{
VerifyOptions (options);
if (!Enum.IsDefined (typeof(CameraDevice), options.DefaultCamera))
throw new ArgumentException ("options.Camera is not a member of CameraDevice");
}
private static MediaPickerController SetupController (MediaPickerDelegate mpDelegate, UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null)
{
var picker = new MediaPickerController (mpDelegate);
picker.MediaTypes = new[] { mediaType };
picker.SourceType = sourceType;
if (sourceType == UIImagePickerControllerSourceType.Camera) {
picker.CameraDevice = GetUICameraDevice (options.DefaultCamera);
if (mediaType == TypeImage)
picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo;
else if (mediaType == TypeMovie) {
StoreVideoOptions voptions = (StoreVideoOptions)options;
picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Video;
picker.VideoQuality = GetQuailty (voptions.Quality);
picker.VideoMaximumDuration = voptions.DesiredLength.TotalSeconds;
}
}
return picker;
}
private Task<MediaFile> GetMediaAsync (UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null)
{
UIWindow window = UIApplication.SharedApplication.KeyWindow;
if (window == null)
throw new InvalidOperationException ("There's no current active window");
UIViewController viewController = window.RootViewController;
if (viewController == null) {
window = UIApplication.SharedApplication.Windows.OrderByDescending (w => w.WindowLevel).FirstOrDefault (w => w.RootViewController != null);
if (window == null)
throw new InvalidOperationException ("Could not find current view controller");
else
viewController = window.RootViewController;
}
while (viewController.PresentedViewController != null)
viewController = viewController.PresentedViewController;
MediaPickerDelegate ndelegate = new MediaPickerDelegate (viewController, sourceType, options);
var od = Interlocked.CompareExchange (ref this.pickerDelegate, ndelegate, null);
if (od != null)
throw new InvalidOperationException ("Only one operation can be active at at time");
var picker = SetupController (ndelegate, sourceType, mediaType, options);
if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && sourceType == UIImagePickerControllerSourceType.PhotoLibrary) {
ndelegate.Popover = new UIPopoverController (picker);
ndelegate.Popover.Delegate = new MediaPickerPopoverDelegate (ndelegate, picker);
ndelegate.DisplayPopover();
} else
viewController.PresentViewController (picker, true, null);
return ndelegate.Task.ContinueWith (t => {
if (this.popover != null) {
this.popover.Dispose();
this.popover = null;
}
Interlocked.Exchange (ref this.pickerDelegate, null);
return t;
}).Unwrap();
}
private static UIImagePickerControllerCameraDevice GetUICameraDevice (CameraDevice device)
{
switch (device) {
case CameraDevice.Front:
return UIImagePickerControllerCameraDevice.Front;
case CameraDevice.Rear:
return UIImagePickerControllerCameraDevice.Rear;
default:
throw new NotSupportedException();
}
}
private static UIImagePickerControllerQualityType GetQuailty (VideoQuality quality)
{
switch (quality) {
case VideoQuality.Low:
return UIImagePickerControllerQualityType.Low;
case VideoQuality.Medium:
return UIImagePickerControllerQualityType.Medium;
default:
return UIImagePickerControllerQualityType.High;
}
}
}
}
| |
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.ClientTesting;
using Google.Cloud.Spanner.Data.CommonTesting;
using Google.Cloud.Spanner.V1;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
// All samples now use a connection string variable declared before the start of the snippet.
// There are pros and cons for this:
// - Pro: The tests still run correctly when the fixture specifies extra configuration, e.g. credentials or host
// - Pro: The code is shorter (as connection string building can be verbose, particularly when already indented)
// - Con: There are fewer examples of building a connection string
// - Unsure: Arguably a connection string should be built elsewhere and reused, rather than appearing in the
// code that creates a SpannerConnection. We need to see what actual usage tends towards.
//
// The table name of "TestTable" is hard-coded here, rather than taken from _fixture.TableName. This probably
// leads to simpler snippets.
namespace Google.Cloud.Spanner.Data.Snippets
{
[SnippetOutputCollector]
[Collection(nameof(SampleTableFixture))]
[FileLoggerBeforeAfterTest]
public class SpannerConnectionSnippets
{
private readonly SampleTableFixture _fixture;
public SpannerConnectionSnippets(SampleTableFixture fixture) => _fixture = fixture;
[Fact]
public void CreateConnection()
{
// Snippet: #ctor(string, ChannelCredentials)
string connectionString = "Data Source=projects/my-project/instances/my-instance/databases/my-db";
SpannerConnection connection = new SpannerConnection(connectionString);
Console.WriteLine(connection.Project);
Console.WriteLine(connection.SpannerInstance);
Console.WriteLine(connection.Database);
// End snippet
Assert.Equal("my-project", connection.Project);
Assert.Equal("my-instance", connection.SpannerInstance);
Assert.Equal("my-db", connection.Database);
}
[Fact]
public async Task CreateDatabaseAsync()
{
string databaseName = $"{_fixture.Database.SpannerDatabase}_extra";
string connectionString = new SpannerConnectionStringBuilder(_fixture.ConnectionString)
.WithDatabase(databaseName)
.ConnectionString;
// Sample: CreateDatabaseAsync
// Additional: CreateDdlCommand
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
SpannerCommand createDbCmd = connection.CreateDdlCommand($"CREATE DATABASE {databaseName}");
await createDbCmd.ExecuteNonQueryAsync();
SpannerCommand createTableCmd = connection.CreateDdlCommand(
@"CREATE TABLE TestTable (
Key STRING(MAX) NOT NULL,
StringValue STRING(MAX),
Int64Value INT64,
) PRIMARY KEY (Key)");
await createTableCmd.ExecuteNonQueryAsync();
}
// End sample
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
SpannerCommand createDbCmd = connection.CreateDdlCommand($"DROP DATABASE {databaseName}");
await createDbCmd.ExecuteNonQueryAsync();
}
}
[Fact]
public async Task InsertDataAsync()
{
string connectionString = _fixture.ConnectionString;
// Sample: InsertDataAsync
// Additional: RunWithRetriableTransactionAsync
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
// If the transaction is aborted, RunWithRetriableTransactionAsync will
// retry the whole unit of work with a fresh transaction each time.
await connection.RunWithRetriableTransactionAsync(async transaction =>
{
SpannerCommand cmd = connection.CreateInsertCommand("TestTable");
SpannerParameter keyParameter = cmd.Parameters.Add("Key", SpannerDbType.String);
SpannerParameter stringValueParameter = cmd.Parameters.Add("StringValue", SpannerDbType.String);
SpannerParameter int64ValueParameter = cmd.Parameters.Add("Int64Value", SpannerDbType.Int64);
cmd.Transaction = transaction;
// This executes 5 distinct insert commands using the retriable transaction.
// The mutations will be effective once the transaction has committed successfully.
for (int i = 0; i < 5; i++)
{
keyParameter.Value = Guid.NewGuid().ToString("N");
stringValueParameter.Value = $"StringValue{i}";
int64ValueParameter.Value = i;
int rowsAffected = await cmd.ExecuteNonQueryAsync();
Console.WriteLine($"{rowsAffected} rows written...");
}
});
}
// End sample
}
[Fact]
public async Task DmlUpdate()
{
string connectionString = _fixture.ConnectionString;
// Sample: Dml
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
// If the transaction is aborted, RunWithRetriableTransactionAsync will
// retry the whole unit of work with a fresh transaction each time.
// Please be aware that the whole unit of work needs to be prepared
// to be called more than once.
await connection.RunWithRetriableTransactionAsync(async transaction =>
{
SpannerCommand cmd = connection.CreateDmlCommand(
"UPDATE TestTable SET StringValue='Updated' WHERE Int64Value=@value");
cmd.Parameters.Add("value", SpannerDbType.Int64, 10);
cmd.Transaction = transaction;
int rowsAffected = await cmd.ExecuteNonQueryAsync();
Console.WriteLine($"{rowsAffected} rows updated...");
});
}
// End sample
}
[Fact]
public async Task PartitionedDmlUpdate()
{
string connectionString = _fixture.ConnectionString;
await RetryHelpers.ExecuteWithRetryAsync(async () =>
{
// Sample: PartitionedDml
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
SpannerCommand cmd = connection.CreateDmlCommand(
"UPDATE TestTable SET TestTable.StringValue='Updated in partitions' WHERE TestTable.Int64Value=@value");
cmd.Parameters.Add("value", SpannerDbType.Int64, 9);
long rowsAffected = await cmd.ExecutePartitionedUpdateAsync();
Console.WriteLine($"{rowsAffected} rows updated...");
}
// End sample
});
}
[Fact]
public async Task BatchDml()
{
string connectionString = _fixture.ConnectionString;
// Sample: BatchDml
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
// If the transaction is aborted, RunWithRetriableTransactionAsync will
// retry the whole unit of work with a fresh transaction each time.
// Please be aware that the whole unit of work needs to be prepared
// to be called more than once.
await connection.RunWithRetriableTransactionAsync(async (transaction) =>
{
SpannerBatchCommand cmd = transaction.CreateBatchDmlCommand();
cmd.Add(
"UPDATE TestTable SET StringValue='Updated' WHERE Int64Value=@value",
new SpannerParameterCollection { { "value", SpannerDbType.Int64, 5 } });
cmd.Add(
"DELETE FROM TestTable WHERE Int64Value=@value",
new SpannerParameterCollection { { "value", SpannerDbType.Int64, 250 } });
IEnumerable<long> rowsAffected = await cmd.ExecuteNonQueryAsync();
Console.WriteLine($"{rowsAffected.ElementAt(0)} rows updated...");
Console.WriteLine($"{rowsAffected.ElementAt(1)} rows deleted...");
});
}
// End sample
}
[Fact]
public async Task CommitTimestampAsync()
{
string connectionString = _fixture.ConnectionString;
// Sample: CommitTimestamp
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
string createTableStatement =
@"CREATE TABLE UsersHistory (
Id INT64 NOT NULL,
CommitTs TIMESTAMP NOT NULL OPTIONS
(allow_commit_timestamp=true),
Name STRING(MAX) NOT NULL,
Email STRING(MAX),
Deleted BOOL NOT NULL,
) PRIMARY KEY(Id, CommitTs DESC)";
await connection.CreateDdlCommand(createTableStatement).ExecuteNonQueryAsync();
// Create a command for inserting rows.
SpannerCommand cmd = connection.CreateInsertCommand("UsersHistory",
new SpannerParameterCollection
{
{ "Id", SpannerDbType.Int64 },
{ "CommitTs", SpannerDbType.Timestamp, SpannerParameter.CommitTimestamp },
{ "Name", SpannerDbType.String },
{ "Deleted", SpannerDbType.Bool , false}
});
int rowsAffected = 0;
// If the transaction is aborted, RunWithRetriableTransactionAsync will
// retry the whole unit of work with a fresh transaction each time.
// Please be aware that the whole unit of work needs to be prepared
// to be called more than once.
await connection.RunWithRetriableTransactionAsync(async transaction =>
{
// Insert a first row
cmd.Parameters["Id"].Value = 10L;
cmd.Parameters["Name"].Value = "Demo 1";
cmd.Transaction = transaction;
rowsAffected += await cmd.ExecuteNonQueryAsync();
});
await connection.RunWithRetriableTransactionAsync(async transaction =>
{
// Insert a second row
cmd.Parameters["Id"].Value = 11L;
cmd.Parameters["Name"].Value = "Demo 2";
rowsAffected += await cmd.ExecuteNonQueryAsync();
});
Console.WriteLine($"{rowsAffected} rows written...");
// Display the inserted values
SpannerCommand selectCmd = connection.CreateSelectCommand("SELECT * FROM UsersHistory");
using (SpannerDataReader reader = await selectCmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
long id = reader.GetFieldValue<long>("Id");
string name = reader.GetFieldValue<string>("Name");
DateTime timestamp = reader.GetFieldValue<DateTime>("CommitTs");
Console.WriteLine($"{id}: {name} - {timestamp:HH:mm:ss.ffffff}");
}
}
}
// End sample
}
[Fact]
public async Task ReadUpdateDeleteAsync()
{
string connectionString = _fixture.ConnectionString;
// Sample: ReadUpdateDeleteAsync
// Additional: CreateUpdateCommand
// Additional: CreateDeleteCommand
// Additional: CreateSelectCommand
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.OpenAsync();
// If the transaction is aborted, RunWithRetriableTransactionAsync will
// retry the whole unit of work with a fresh transaction each time.
// Please be aware that the whole unit of work needs to be prepared
// to be called more than once.
await connection.RunWithRetriableTransactionAsync(async (transaction) =>
{
// Read the first two keys in the database.
List<string> keys = new List<string>();
SpannerCommand selectCmd = connection.CreateSelectCommand("SELECT * FROM TestTable");
using (SpannerDataReader reader = await selectCmd.ExecuteReaderAsync())
{
while (keys.Count < 3 && await reader.ReadAsync())
{
keys.Add(reader.GetFieldValue<string>("Key"));
}
}
// Update the Int64Value of keys[0]
// Include the primary key and update columns.
SpannerCommand updateCmd = connection.CreateUpdateCommand("TestTable");
updateCmd.Parameters.Add("Key", SpannerDbType.String, keys[0]);
updateCmd.Parameters.Add("Int64Value", SpannerDbType.Int64, 0L);
await updateCmd.ExecuteNonQueryAsync();
// Delete row for keys[1]
SpannerCommand deleteCmd = connection.CreateDeleteCommand("TestTable");
deleteCmd.Parameters.Add("Key", SpannerDbType.String, keys[1]);
await deleteCmd.ExecuteNonQueryAsync();
});
// End sample
}
}
[Fact]
public void CustomSessionPoolManager()
{
string connectionString = _fixture.ConnectionString;
string instanceId = Guid.NewGuid().ToString();
// Sample: CustomSessionPoolManager
SessionPoolOptions options = new SessionPoolOptions
{
MinimumPooledSessions = 100,
MaximumActiveSessions = 250,
SessionLabels =
{
{ "service", "sales-report-generator" },
{ "service-instance", instanceId }
}
};
SessionPoolManager manager = SessionPoolManager.Create(options);
// Note: a single SpannerConnectionStringBuilder instance can be reused whenever you
// need to build a connection
SpannerConnectionStringBuilder builder = new SpannerConnectionStringBuilder(connectionString)
{
SessionPoolManager = manager
};
// (Elsewhere in your code...)
using (SpannerConnection connection = new SpannerConnection(builder))
{
// Use the connection
}
// End sample
}
// Deliberately not a Fact! We don't want to run this, otherwise the default session pool will be
// shut down after the test...
#pragma warning disable xUnit1013 // Public method should be marked as test
public async Task ShutdownSessionPoolAsync()
#pragma warning restore xUnit1013 // Public method should be marked as test
{
string connectionString = _fixture.ConnectionString;
// Sample: ShutdownSessionPoolAsync
// Additional: ShutdownSessionPoolAsync
// When your application is shutting down. Note that any pending or future requests
// for sessions will fail.
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.ShutdownSessionPoolAsync();
}
// End sample
}
[Fact]
public async Task WhenSessionPoolReady()
{
string connectionString = _fixture.ConnectionString;
// Sample: WhenSessionPoolReady
// Additional: WhenSessionPoolReady
// This would usually be executed during application start-up, before any Spanner
// operations are performed. It can be used at any time, however. It is purely passive:
// it doesn't modify the session pool or trigger any other actions.
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
await connection.WhenSessionPoolReady();
}
// End sample
}
[Fact]
public void GetSessionPoolDatabaseStatistics()
{
string connectionString = _fixture.ConnectionString;
// Sample: GetSessionPoolDatabaseStatistics
// Additional: GetSessionPoolDatabaseStatistics
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
SessionPool.DatabaseStatistics stats = connection.GetSessionPoolDatabaseStatistics();
if (stats is null)
{
Console.WriteLine("No session pool for this connection string yet");
}
else
{
// Access individual properties...
Console.WriteLine($"Database name: {stats.DatabaseName}");
Console.WriteLine($"Active sessions: {stats.ActiveSessionCount}");
Console.WriteLine($"Pooled read-only sessions: {stats.ReadPoolCount}");
Console.WriteLine($"Pooled read-write sessions: {stats.ReadWritePoolCount}");
// ... or just use the overridden ToString method to log all the statistics in one go:
Console.WriteLine(stats);
}
}
// End sample
}
[Fact]
public void DataAdapter()
{
string connectionString = _fixture.ConnectionString;
RetryHelpers.ExecuteWithRetry(() =>
{
// Sample: DataAdapter
using (SpannerConnection connection = new SpannerConnection(connectionString))
{
DataSet untypedDataSet = new DataSet();
// Provide the name of the Cloud Spanner table and primary key column names.
SpannerDataAdapter adapter = new SpannerDataAdapter(connection, "TestTable", "Key");
adapter.Fill(untypedDataSet);
// Insert a row
DataRow row = untypedDataSet.Tables[0].NewRow();
row["Key"] = Guid.NewGuid().ToString("N");
row["StringValue"] = "New String Value";
row["Int64Value"] = 0L;
untypedDataSet.Tables[0].Rows.Add(row);
adapter.Update(untypedDataSet.Tables[0]);
}
// End sample
});
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Orleans;
using Orleans.Configuration;
using Orleans.Internal;
using Orleans.Runtime;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.TestHooks;
using Orleans.Statistics;
using TestExtensions;
using UnitTests.Grains;
using UnitTests.TesterInternal;
using Xunit;
using Xunit.Abstractions;
namespace UnitTests.SchedulerTests
{
public class OrleansTaskSchedulerAdvancedTests_Set2 : IDisposable
{
private static readonly object Lockable = new object();
private static readonly int WaitFactor = Debugger.IsAttached ? 100 : 1;
private readonly ITestOutputHelper output;
private readonly OrleansTaskScheduler masterScheduler;
private readonly UnitTestSchedulingContext context;
private readonly IHostEnvironmentStatistics performanceMetrics;
private readonly ILoggerFactory loggerFactory;
public OrleansTaskSchedulerAdvancedTests_Set2(ITestOutputHelper output)
{
this.output = output;
this.loggerFactory = OrleansTaskSchedulerBasicTests.InitSchedulerLogging();
this.context = new UnitTestSchedulingContext();
this.performanceMetrics = new TestHooksHostEnvironmentStatistics();
this.masterScheduler = TestInternalHelper.InitializeSchedulerForTesting(this.context, this.loggerFactory);
}
public void Dispose()
{
this.masterScheduler.Stop();
this.loggerFactory.Dispose();
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public void ActivationSched_SimpleFifoTest()
{
// This is not a great test because there's a 50/50 shot that it will work even if the scheduling
// is completely and thoroughly broken and both closures are executed "simultaneously"
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
int n = 0;
// ReSharper disable AccessToModifiedClosure
Task task1 = new Task(() => { Thread.Sleep(1000); n = n + 5; });
Task task2 = new Task(() => { n = n * 3; });
// ReSharper restore AccessToModifiedClosure
task1.Start(scheduler);
task2.Start(scheduler);
// Pause to let things run
Thread.Sleep(1500);
// N should be 15, because the two tasks should execute in order
Assert.True(n != 0, "Work items did not get executed");
Assert.Equal(15, n); // "Work items executed out of order"
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public void ActivationSched_NewTask_ContinueWith_Wrapped()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
Task<Task> wrapped = new Task<Task>(() =>
{
this.output.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
SynchronizationContext.Current, TaskScheduler.Current);
Task t0 = new Task(() =>
{
this.output.WriteLine("#1 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
SynchronizationContext.Current, TaskScheduler.Current);
Assert.Equal(scheduler, TaskScheduler.Current); // "TaskScheduler.Current #1"
});
Task t1 = t0.ContinueWith(task =>
{
Assert.False(task.IsFaulted, "Task #1 Faulted=" + task.Exception);
this.output.WriteLine("#2 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
SynchronizationContext.Current, TaskScheduler.Current);
Assert.Equal(scheduler, TaskScheduler.Current); // "TaskScheduler.Current #2"
});
t0.Start(scheduler);
return t1;
});
wrapped.Start(scheduler);
bool ok = wrapped.Unwrap().Wait(TimeSpan.FromSeconds(2));
Assert.True(ok, "Finished OK");
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public void ActivationSched_SubTaskExecutionSequencing()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
LogContext("Main-task " + Task.CurrentId);
int n = 0;
Action action = () =>
{
LogContext("WorkItem-task " + Task.CurrentId);
for (int i = 0; i < 10; i++)
{
int id = -1;
Task.Factory.StartNew(() =>
{
id = Task.CurrentId.HasValue ? (int)Task.CurrentId : -1;
// ReSharper disable AccessToModifiedClosure
LogContext("Sub-task " + id + " n=" + n);
int k = n;
this.output.WriteLine("Sub-task " + id + " sleeping");
Thread.Sleep(100);
this.output.WriteLine("Sub-task " + id + " awake");
n = k + 1;
// ReSharper restore AccessToModifiedClosure
})
.ContinueWith(tsk =>
{
LogContext("Sub-task " + id + "-ContinueWith");
this.output.WriteLine("Sub-task " + id + " Done");
});
}
};
Task t = new Task(action);
t.Start(scheduler);
// Pause to let things run
this.output.WriteLine("Main-task sleeping");
Thread.Sleep(TimeSpan.FromSeconds(2));
this.output.WriteLine("Main-task awake");
// N should be 10, because all tasks should execute serially
Assert.True(n != 0, "Work items did not get executed");
Assert.Equal(10, n); // "Work items executed concurrently"
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task ActivationSched_ContinueWith_1_Test()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
var result = new TaskCompletionSource<bool>();
int n = 0;
Task wrapper = new Task(() =>
{
// ReSharper disable AccessToModifiedClosure
Task task1 = Task.Factory.StartNew(() => { this.output.WriteLine("===> 1a"); Thread.Sleep(1000); n = n + 3; this.output.WriteLine("===> 1b"); });
Task task2 = task1.ContinueWith(task => { n = n * 5; this.output.WriteLine("===> 2"); });
Task task3 = task2.ContinueWith(task => { n = n / 5; this.output.WriteLine("===> 3"); });
Task task4 = task3.ContinueWith(task => { n = n - 2; this.output.WriteLine("===> 4"); result.SetResult(true); });
// ReSharper restore AccessToModifiedClosure
task4.ContinueWith(task =>
{
this.output.WriteLine("Done Faulted={0}", task.IsFaulted);
Assert.False(task.IsFaulted, "Faulted with Exception=" + task.Exception);
});
});
wrapper.Start(scheduler);
var timeoutLimit = TimeSpan.FromSeconds(2);
try
{
await result.Task.WithTimeout(timeoutLimit);
}
catch (TimeoutException)
{
Assert.True(false, "Result did not arrive before timeout " + timeoutLimit);
}
Assert.True(n != 0, "Work items did not get executed");
Assert.Equal(1, n); // "Work items executed out of order"
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task ActivationSched_WhenAny()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
ManualResetEvent pause1 = new ManualResetEvent(false);
ManualResetEvent pause2 = new ManualResetEvent(false);
var finish = new TaskCompletionSource<bool>();
Task<int> task1 = null;
Task<int> task2 = null;
Task join = null;
Task wrapper = new Task(() =>
{
task1 = Task<int>.Factory.StartNew(() =>
{
this.output.WriteLine("Task-1 Started");
Assert.Equal(scheduler, TaskScheduler.Current); // "TaskScheduler.Current=" + TaskScheduler.Current
pause1.WaitOne();
this.output.WriteLine("Task-1 Done");
return 1;
});
task2 = Task<int>.Factory.StartNew(() =>
{
this.output.WriteLine("Task-2 Started");
Assert.Equal(scheduler, TaskScheduler.Current);
pause2.WaitOne();
this.output.WriteLine("Task-2 Done");
return 2;
});
join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2)));
finish.SetResult(true);
});
wrapper.Start(scheduler);
var timeoutLimit = TimeSpan.FromSeconds(1);
try
{
await finish.Task.WithTimeout(timeoutLimit);
}
catch (TimeoutException)
{
Assert.True(false, "Result did not arrive before timeout " + timeoutLimit);
}
pause1.Set();
await join;
Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status);
Assert.False(task1.IsFaulted, "Task-1 Faulted " + task1.Exception);
Assert.False(task2.IsFaulted, "Task-2 Faulted " + task2.Exception);
Assert.True(task1.IsCompleted || task2.IsCompleted, "Task-1 Status = " + task1.Status + " Task-2 Status = " + task2.Status);
pause2.Set();
task2.Ignore();
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task ActivationSched_WhenAny_Timeout()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
ManualResetEvent pause1 = new ManualResetEvent(false);
ManualResetEvent pause2 = new ManualResetEvent(false);
var finish = new TaskCompletionSource<bool>();
Task<int> task1 = null;
Task<int> task2 = null;
Task join = null;
Task wrapper = new Task(() =>
{
task1 = Task<int>.Factory.StartNew(() =>
{
this.output.WriteLine("Task-1 Started");
Assert.Equal(scheduler, TaskScheduler.Current);
pause1.WaitOne();
this.output.WriteLine("Task-1 Done");
return 1;
});
task2 = Task<int>.Factory.StartNew(() =>
{
this.output.WriteLine("Task-2 Started");
Assert.Equal(scheduler, TaskScheduler.Current);
pause2.WaitOne();
this.output.WriteLine("Task-2 Done");
return 2;
});
join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2)));
finish.SetResult(true);
});
wrapper.Start(scheduler);
var timeoutLimit = TimeSpan.FromSeconds(1);
try
{
await finish.Task.WithTimeout(timeoutLimit);
}
catch (TimeoutException)
{
Assert.True(false, "Result did not arrive before timeout " + timeoutLimit);
}
Assert.NotNull(join);
await join;
Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status);
Assert.False(task1.IsFaulted, "Task-1 Faulted " + task1.Exception);
Assert.False(task1.IsCompleted, "Task-1 Status " + task1.Status);
Assert.False(task2.IsFaulted, "Task-2 Faulted " + task2.Exception);
Assert.False(task2.IsCompleted, "Task-2 Status " + task2.Status);
pause1.Set();
task1.Ignore();
pause2.Set();
task2.Ignore();
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task ActivationSched_WhenAny_Busy_Timeout()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
var pause1 = new TaskCompletionSource<bool>();
var pause2 = new TaskCompletionSource<bool>();
var finish = new TaskCompletionSource<bool>();
Task<int> task1 = null;
Task<int> task2 = null;
Task join = null;
Task wrapper = new Task(() =>
{
task1 = Task<int>.Factory.StartNew(() =>
{
this.output.WriteLine("Task-1 Started");
Assert.Equal(scheduler, TaskScheduler.Current);
int num1 = 1;
while (!pause1.Task.Result) // Infinite busy loop
{
num1 = ThreadSafeRandom.Next();
}
this.output.WriteLine("Task-1 Done");
return num1;
});
task2 = Task<int>.Factory.StartNew(() =>
{
this.output.WriteLine("Task-2 Started");
Assert.Equal(scheduler, TaskScheduler.Current);
int num2 = 2;
while (!pause2.Task.Result) // Infinite busy loop
{
num2 = ThreadSafeRandom.Next();
}
this.output.WriteLine("Task-2 Done");
return num2;
});
join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2)));
finish.SetResult(true);
});
wrapper.Start(scheduler);
var timeoutLimit = TimeSpan.FromSeconds(1);
try
{
await finish.Task.WithTimeout(timeoutLimit);
}
catch (TimeoutException)
{
Assert.True(false, "Result did not arrive before timeout " + timeoutLimit);
}
Assert.NotNull(join); // Joined promise assigned
await join;
Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status);
Assert.False(task1.IsFaulted, "Task-1 Faulted " + task1.Exception);
Assert.False(task1.IsCompleted, "Task-1 Status " + task1.Status);
Assert.False(task2.IsFaulted, "Task-2 Faulted " + task2.Exception);
Assert.False(task2.IsCompleted, "Task-2 Status " + task2.Status);
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task ActivationSched_Task_Run()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
ManualResetEvent pause1 = new ManualResetEvent(false);
ManualResetEvent pause2 = new ManualResetEvent(false);
var finish = new TaskCompletionSource<bool>();
Task<int> task1 = null;
Task<int> task2 = null;
Task join = null;
Task wrapper = new Task(() =>
{
task1 = Task.Run(() =>
{
this.output.WriteLine("Task-1 Started");
Assert.NotEqual(scheduler, TaskScheduler.Current);
pause1.WaitOne();
this.output.WriteLine("Task-1 Done");
return 1;
});
task2 = Task.Run(() =>
{
this.output.WriteLine("Task-2 Started");
Assert.NotEqual(scheduler, TaskScheduler.Current);
pause2.WaitOne();
this.output.WriteLine("Task-2 Done");
return 2;
});
join = Task.WhenAll(task1, task2).ContinueWith(t =>
{
this.output.WriteLine("Join Started");
if (t.IsFaulted) throw t.Exception;
Assert.Equal(scheduler, TaskScheduler.Current);
this.output.WriteLine("Join Done");
});
finish.SetResult(true);
});
wrapper.Start(scheduler);
var timeoutLimit = TimeSpan.FromSeconds(1);
try
{
await finish.Task.WithTimeout(timeoutLimit);
}
catch (TimeoutException)
{
Assert.True(false, "Result did not arrive before timeout " + timeoutLimit);
}
pause1.Set();
pause2.Set();
Assert.NotNull(join); // Joined promise assigned
await join;
Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join);
Assert.True(task1.IsCompleted && !task1.IsFaulted, "Task-1 Status " + task1);
Assert.True(task2.IsCompleted && !task2.IsFaulted, "Task-2 Status " + task2);
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task ActivationSched_Task_Run_Delay()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
ManualResetEvent pause1 = new ManualResetEvent(false);
ManualResetEvent pause2 = new ManualResetEvent(false);
var finish = new TaskCompletionSource<bool>();
Task<int> task1 = null;
Task<int> task2 = null;
Task join = null;
Task wrapper = new Task(() =>
{
task1 = Task.Run(() =>
{
this.output.WriteLine("Task-1 Started");
Assert.NotEqual(scheduler, TaskScheduler.Current);
Task.Delay(1);
Assert.NotEqual(scheduler, TaskScheduler.Current);
pause1.WaitOne();
this.output.WriteLine("Task-1 Done");
return 1;
});
task2 = Task.Run(() =>
{
this.output.WriteLine("Task-2 Started");
Assert.NotEqual(scheduler, TaskScheduler.Current);
Task.Delay(1);
Assert.NotEqual(scheduler, TaskScheduler.Current);
pause2.WaitOne();
this.output.WriteLine("Task-2 Done");
return 2;
});
join = Task.WhenAll(task1, task2).ContinueWith(t =>
{
this.output.WriteLine("Join Started");
if (t.IsFaulted) throw t.Exception;
Assert.Equal(scheduler, TaskScheduler.Current);
this.output.WriteLine("Join Done");
});
finish.SetResult(true);
});
wrapper.Start(scheduler);
var timeoutLimit = TimeSpan.FromSeconds(1);
try
{
await finish.Task.WithTimeout(timeoutLimit);
}
catch (TimeoutException)
{
Assert.True(false, "Result did not arrive before timeout " + timeoutLimit);
}
pause1.Set();
pause2.Set();
Assert.NotNull(join); // Joined promise assigned
await join;
Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join);
Assert.True(task1.IsCompleted && !task1.IsFaulted, "Task-1 Status " + task1);
Assert.True(task2.IsCompleted && !task2.IsFaulted, "Task-2 Status " + task2);
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task ActivationSched_Task_Delay()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
Task wrapper = new Task(async () =>
{
Assert.Equal(scheduler, TaskScheduler.Current);
await DoDelay(1);
Assert.Equal(scheduler, TaskScheduler.Current);
await DoDelay(2);
Assert.Equal(scheduler, TaskScheduler.Current);
});
wrapper.Start(scheduler);
await wrapper;
}
private async Task DoDelay(int i)
{
try
{
this.output.WriteLine("Before Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current);
await Task.Delay(1);
this.output.WriteLine("After Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current);
}
catch (ObjectDisposedException)
{
// Ignore any problems with ObjectDisposedException if console output stream has already been closed
}
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task ActivationSched_Turn_Execution_Order_Loop()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
const int NumChains = 100;
const int ChainLength = 3;
// Can we add a unit test that basicaly checks that any turn is indeed run till completion before any other turn?
// For example, you have a long running main turn and in the middle it spawns a lot of short CWs (on Done promise) and StartNew.
// You test that no CW/StartNew runs until the main turn is fully done. And run in stress.
var resultHandles = new TaskCompletionSource<bool>[NumChains];
Task[] taskChains = new Task[NumChains];
Task[] taskChainEnds = new Task[NumChains];
bool[] executingChain = new bool[NumChains];
int[] stageComplete = new int[NumChains];
int executingGlobal = -1;
for (int i = 0; i < NumChains; i++)
{
int chainNum = i; // Capture
int sleepTime = ThreadSafeRandom.Next(100);
resultHandles[i] = new TaskCompletionSource<bool>();
taskChains[i] = new Task(() =>
{
const int taskNum = 0;
try
{
Assert.Equal(-1, executingGlobal); // "Detected unexpected other execution in chain " + chainNum + " Task " + taskNum
Assert.False(executingChain[chainNum], "Detected unexpected other execution on chain " + chainNum + " Task " + taskNum);
executingGlobal = chainNum;
executingChain[chainNum] = true;
Thread.Sleep(sleepTime);
}
finally
{
stageComplete[chainNum] = taskNum;
executingChain[chainNum] = false;
executingGlobal = -1;
}
});
Task task = taskChains[i];
for (int j = 1; j < ChainLength; j++)
{
int taskNum = j; // Capture
task = task.ContinueWith(t =>
{
if (t.IsFaulted) throw t.Exception;
this.output.WriteLine("Inside Chain {0} Task {1}", chainNum, taskNum);
try
{
Assert.Equal(-1, executingGlobal); // "Detected unexpected other execution in chain " + chainNum + " Task " + taskNum
Assert.False(executingChain[chainNum], "Detected unexpected other execution on chain " + chainNum + " Task " + taskNum);
Assert.Equal(taskNum - 1, stageComplete[chainNum]); // "Detected unexpected execution stage on chain " + chainNum + " Task " + taskNum
executingGlobal = chainNum;
executingChain[chainNum] = true;
Thread.Sleep(sleepTime);
}
finally
{
stageComplete[chainNum] = taskNum;
executingChain[chainNum] = false;
executingGlobal = -1;
}
}, scheduler);
}
taskChainEnds[chainNum] = task.ContinueWith(t =>
{
if (t.IsFaulted) throw t.Exception;
this.output.WriteLine("Inside Chain {0} Final Task", chainNum);
resultHandles[chainNum].SetResult(true);
}, scheduler);
}
for (int i = 0; i < NumChains; i++)
{
taskChains[i].Start(scheduler);
}
for (int i = 0; i < NumChains; i++)
{
TimeSpan waitCheckTime = TimeSpan.FromMilliseconds(150 * ChainLength * NumChains * WaitFactor);
try
{
await resultHandles[i].Task.WithTimeout(waitCheckTime);
}
catch (TimeoutException)
{
Assert.True(false, "Result did not arrive before timeout " + waitCheckTime);
}
bool ok = resultHandles[i].Task.Result;
try
{
// since resultHandle being complete doesn't directly imply that the final chain was completed (there's a chance for a race condition), give a small chance for it to complete.
await taskChainEnds[i].WithTimeout(TimeSpan.FromMilliseconds(10));
}
catch (TimeoutException)
{
Assert.True(false, $"Task chain end {i} should complete very shortly after after its resultHandle");
}
Assert.True(taskChainEnds[i].IsCompleted, "Task chain " + i + " should be completed");
Assert.False(taskChainEnds[i].IsFaulted, "Task chain " + i + " should not be Faulted: " + taskChainEnds[i].Exception);
Assert.Equal(ChainLength - 1, stageComplete[i]); // "Task chain " + i + " should have completed all stages"
Assert.True(ok, "Successfully waited for ResultHandle for Task chain " + i);
}
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task ActivationSched_Test1()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
await Run_ActivationSched_Test1(scheduler, false);
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task ActivationSched_Test1_Bounce()
{
TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler;
await Run_ActivationSched_Test1(scheduler, true);
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task OrleansSched_Test1()
{
UnitTestSchedulingContext context = new UnitTestSchedulingContext();
OrleansTaskScheduler orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.loggerFactory);
ActivationTaskScheduler scheduler = orleansTaskScheduler.GetWorkItemGroup(context).TaskScheduler;
await Run_ActivationSched_Test1(scheduler, false);
}
[Fact, TestCategory("Functional"), TestCategory("Scheduler")]
public async Task OrleansSched_Test1_Bounce()
{
UnitTestSchedulingContext context = new UnitTestSchedulingContext();
OrleansTaskScheduler orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.loggerFactory);
ActivationTaskScheduler scheduler = orleansTaskScheduler.GetWorkItemGroup(context).TaskScheduler;
await Run_ActivationSched_Test1(scheduler, true);
}
internal async Task Run_ActivationSched_Test1(TaskScheduler scheduler, bool bounceToThreadPool)
{
var grainId = LegacyGrainId.GetGrainId(0, Guid.NewGuid());
var silo = new MockSiloDetails
{
SiloAddress = SiloAddressUtils.NewLocalSiloAddress(23)
};
var grain = new NonReentrentStressGrainWithoutState(null);
await Task.Factory.StartNew(() => grain.OnActivateAsync(), CancellationToken.None, TaskCreationOptions.None, scheduler).Unwrap();
Task wrapped = null;
var wrapperDone = new TaskCompletionSource<bool>();
var wrappedDone = new TaskCompletionSource<bool>();
Task<Task> wrapper = new Task<Task>(() =>
{
this.output.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}",
SynchronizationContext.Current, TaskScheduler.Current);
Task t1 = grain.Test1();
Action wrappedDoneAction = () => { wrappedDone.SetResult(true); };
if (bounceToThreadPool)
{
wrapped = t1.ContinueWith(_ => wrappedDoneAction(),
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
else
{
wrapped = t1.ContinueWith(_ => wrappedDoneAction());
}
wrapperDone.SetResult(true);
return wrapped;
});
wrapper.Start(scheduler);
await wrapper;
var timeoutLimit = TimeSpan.FromSeconds(1);
try
{
await wrapperDone.Task.WithTimeout(timeoutLimit);
}
catch (TimeoutException)
{
Assert.True(false, "Result did not arrive before timeout " + timeoutLimit);
}
bool done = wrapperDone.Task.Result;
Assert.True(done, "Wrapper Task finished");
Assert.True(wrapper.IsCompleted, "Wrapper Task completed");
//done = wrapped.Wait(TimeSpan.FromSeconds(12));
//Assert.True(done, "Wrapped Task not timeout");
await wrapped;
try
{
await wrappedDone.Task.WithTimeout(timeoutLimit);
}
catch (TimeoutException)
{
Assert.True(false, "Result did not arrive before timeout " + timeoutLimit);
}
done = wrappedDone.Task.Result;
Assert.True(done, "Wrapped Task should be finished");
Assert.True(wrapped.IsCompleted, "Wrapped Task completed");
}
private void LogContext(string what)
{
lock (Lockable)
{
this.output.WriteLine(
"{0}\n"
+ " TaskScheduler.Current={1}\n"
+ " Task.Factory.Scheduler={2}\n"
+ " SynchronizationContext.Current={3}",
what,
(TaskScheduler.Current == null ? "null" : TaskScheduler.Current.ToString()),
(Task.Factory.Scheduler == null ? "null" : Task.Factory.Scheduler.ToString()),
(SynchronizationContext.Current == null ? "null" : SynchronizationContext.Current.ToString())
);
//var st = new StackTrace();
//output.WriteLine(st.ToString());
}
}
private class MockSiloDetails : ILocalSiloDetails
{
public string DnsHostName { get; }
public SiloAddress SiloAddress { get; set; }
public SiloAddress GatewayAddress { get; }
public string Name { get; set; } = Guid.NewGuid().ToString();
public string ClusterId { get; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
namespace System.Linq.Expressions.Compiler
{
internal partial class LambdaCompiler
{
[Flags]
internal enum CompilationFlags
{
EmitExpressionStart = 0x0001,
EmitNoExpressionStart = 0x0002,
EmitAsDefaultType = 0x0010,
EmitAsVoidType = 0x0020,
EmitAsTail = 0x0100, // at the tail position of a lambda, tail call can be safely emitted
EmitAsMiddle = 0x0200, // in the middle of a lambda, tail call can be emitted if it is in a return
EmitAsNoTail = 0x0400, // neither at the tail or in a return, or tail call is not turned on, no tail call is emitted
EmitExpressionStartMask = 0x000f,
EmitAsTypeMask = 0x00f0,
EmitAsTailCallMask = 0x0f00
}
/// <summary>
/// Update the flag with a new EmitAsTailCall flag
/// </summary>
private static CompilationFlags UpdateEmitAsTailCallFlag(CompilationFlags flags, CompilationFlags newValue)
{
Debug.Assert(newValue == CompilationFlags.EmitAsTail || newValue == CompilationFlags.EmitAsMiddle || newValue == CompilationFlags.EmitAsNoTail);
CompilationFlags oldValue = flags & CompilationFlags.EmitAsTailCallMask;
return flags ^ oldValue | newValue;
}
/// <summary>
/// Update the flag with a new EmitExpressionStart flag
/// </summary>
private static CompilationFlags UpdateEmitExpressionStartFlag(CompilationFlags flags, CompilationFlags newValue)
{
Debug.Assert(newValue == CompilationFlags.EmitExpressionStart || newValue == CompilationFlags.EmitNoExpressionStart);
CompilationFlags oldValue = flags & CompilationFlags.EmitExpressionStartMask;
return flags ^ oldValue | newValue;
}
/// <summary>
/// Update the flag with a new EmitAsType flag
/// </summary>
private static CompilationFlags UpdateEmitAsTypeFlag(CompilationFlags flags, CompilationFlags newValue)
{
Debug.Assert(newValue == CompilationFlags.EmitAsDefaultType || newValue == CompilationFlags.EmitAsVoidType);
CompilationFlags oldValue = flags & CompilationFlags.EmitAsTypeMask;
return flags ^ oldValue | newValue;
}
/// <summary>
/// Generates code for this expression in a value position.
/// This method will leave the value of the expression
/// on the top of the stack typed as Type.
/// </summary>
internal void EmitExpression(Expression node)
{
EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitExpressionStart);
}
/// <summary>
/// Emits an expression and discards the result. For some nodes this emits
/// more optimal code then EmitExpression/Pop
/// </summary>
private void EmitExpressionAsVoid(Expression node)
{
EmitExpressionAsVoid(node, CompilationFlags.EmitAsNoTail);
}
private void EmitExpressionAsVoid(Expression node, CompilationFlags flags)
{
Debug.Assert(node != null);
CompilationFlags startEmitted = EmitExpressionStart(node);
switch (node.NodeType)
{
case ExpressionType.Assign:
EmitAssign((AssignBinaryExpression)node, CompilationFlags.EmitAsVoidType);
break;
case ExpressionType.Block:
Emit((BlockExpression)node, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsVoidType));
break;
case ExpressionType.Throw:
EmitThrow((UnaryExpression)node, CompilationFlags.EmitAsVoidType);
break;
case ExpressionType.Goto:
EmitGotoExpression(node, UpdateEmitAsTypeFlag(flags, CompilationFlags.EmitAsVoidType));
break;
case ExpressionType.Constant:
case ExpressionType.Default:
case ExpressionType.Parameter:
// no-op
break;
default:
if (node.Type == typeof(void))
{
EmitExpression(node, UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitNoExpressionStart));
}
else
{
EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart);
_ilg.Emit(OpCodes.Pop);
}
break;
}
EmitExpressionEnd(startEmitted);
}
private void EmitExpressionAsType(Expression node, Type type, CompilationFlags flags)
{
if (type == typeof(void))
{
EmitExpressionAsVoid(node, flags);
}
else
{
// if the node is emitted as a different type, CastClass IL is emitted at the end,
// should not emit with tail calls.
if (!TypeUtils.AreEquivalent(node.Type, type))
{
EmitExpression(node);
Debug.Assert(TypeUtils.AreReferenceAssignable(type, node.Type));
_ilg.Emit(OpCodes.Castclass, type);
}
else
{
// emit the node with the flags and emit expression start
EmitExpression(node, UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart));
}
}
}
#region label block tracking
private CompilationFlags EmitExpressionStart(Expression node)
{
if (TryPushLabelBlock(node))
{
return CompilationFlags.EmitExpressionStart;
}
return CompilationFlags.EmitNoExpressionStart;
}
private void EmitExpressionEnd(CompilationFlags flags)
{
if ((flags & CompilationFlags.EmitExpressionStartMask) == CompilationFlags.EmitExpressionStart)
{
PopLabelBlock(_labelBlock.Kind);
}
}
#endregion
#region InvocationExpression
private void EmitInvocationExpression(Expression expr, CompilationFlags flags)
{
InvocationExpression node = (InvocationExpression)expr;
// Optimization: inline code for literal lambda's directly
//
// This is worth it because otherwise we end up with a extra call
// to DynamicMethod.CreateDelegate, which is expensive.
//
if (node.LambdaOperand != null)
{
EmitInlinedInvoke(node, flags);
return;
}
expr = node.Expression;
if (typeof(LambdaExpression).IsAssignableFrom(expr.Type))
{
// if the invoke target is a lambda expression tree, first compile it into a delegate
expr = Expression.Call(expr, expr.Type.GetMethod("Compile", Array.Empty<Type>()));
}
EmitMethodCall(expr, expr.Type.GetMethod("Invoke"), node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitExpressionStart);
}
private void EmitInlinedInvoke(InvocationExpression invoke, CompilationFlags flags)
{
LambdaExpression lambda = invoke.LambdaOperand;
// This is tricky: we need to emit the arguments outside of the
// scope, but set them inside the scope. Fortunately, using the IL
// stack it is entirely doable.
// 1. Emit invoke arguments
List<WriteBack> wb = EmitArguments(lambda.Type.GetMethod("Invoke"), invoke);
// 2. Create the nested LambdaCompiler
var inner = new LambdaCompiler(this, lambda, invoke);
// 3. Emit the body
// if the inlined lambda is the last expression of the whole lambda,
// tail call can be applied.
if (wb != null)
{
Debug.Assert(wb.Count > 0);
flags = UpdateEmitAsTailCallFlag(flags, CompilationFlags.EmitAsNoTail);
}
inner.EmitLambdaBody(_scope, true, flags);
// 4. Emit write-backs if needed
EmitWriteBack(wb);
}
#endregion
#region IndexExpression
private void EmitIndexExpression(Expression expr)
{
var node = (IndexExpression)expr;
// Emit instance, if calling an instance method
Type objectType = null;
if (node.Object != null)
{
EmitInstance(node.Object, out objectType);
}
// Emit indexes. We don't allow byref args, so no need to worry
// about write-backs or EmitAddress
for (int i = 0, n = node.ArgumentCount; i < n; i++)
{
Expression arg = node.GetArgument(i);
EmitExpression(arg);
}
EmitGetIndexCall(node, objectType);
}
private void EmitIndexAssignment(AssignBinaryExpression node, CompilationFlags flags)
{
Debug.Assert(!node.IsByRef);
var index = (IndexExpression)node.Left;
CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask;
// Emit instance, if calling an instance method
Type objectType = null;
if (index.Object != null)
{
EmitInstance(index.Object, out objectType);
}
// Emit indexes. We don't allow byref args, so no need to worry
// about write-backs or EmitAddress
for (int i = 0, n = index.ArgumentCount; i < n; i++)
{
Expression arg = index.GetArgument(i);
EmitExpression(arg);
}
// Emit value
EmitExpression(node.Right);
// Save the expression value, if needed
LocalBuilder temp = null;
if (emitAs != CompilationFlags.EmitAsVoidType)
{
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Stloc, temp = GetLocal(node.Type));
}
EmitSetIndexCall(index, objectType);
// Restore the value
if (emitAs != CompilationFlags.EmitAsVoidType)
{
_ilg.Emit(OpCodes.Ldloc, temp);
FreeLocal(temp);
}
}
private void EmitGetIndexCall(IndexExpression node, Type objectType)
{
if (node.Indexer != null)
{
// For indexed properties, just call the getter
MethodInfo method = node.Indexer.GetGetMethod(nonPublic: true);
EmitCall(objectType, method);
}
else
{
EmitGetArrayElement(objectType);
}
}
private void EmitGetArrayElement(Type arrayType)
{
if (arrayType.IsSZArray)
{
// For one dimensional arrays, emit load
_ilg.EmitLoadElement(arrayType.GetElementType());
}
else
{
// Multidimensional arrays, call get
_ilg.Emit(OpCodes.Call, arrayType.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance));
}
}
private void EmitSetIndexCall(IndexExpression node, Type objectType)
{
if (node.Indexer != null)
{
// For indexed properties, just call the setter
MethodInfo method = node.Indexer.GetSetMethod(nonPublic: true);
EmitCall(objectType, method);
}
else
{
EmitSetArrayElement(objectType);
}
}
private void EmitSetArrayElement(Type arrayType)
{
if (arrayType.IsSZArray)
{
// For one dimensional arrays, emit store
_ilg.EmitStoreElement(arrayType.GetElementType());
}
else
{
// Multidimensional arrays, call set
_ilg.Emit(OpCodes.Call, arrayType.GetMethod("Set", BindingFlags.Public | BindingFlags.Instance));
}
}
#endregion
#region MethodCallExpression
private void EmitMethodCallExpression(Expression expr, CompilationFlags flags)
{
MethodCallExpression node = (MethodCallExpression)expr;
EmitMethodCall(node.Object, node.Method, node, flags);
}
private void EmitMethodCallExpression(Expression expr)
{
EmitMethodCallExpression(expr, CompilationFlags.EmitAsNoTail);
}
private void EmitMethodCall(Expression obj, MethodInfo method, IArgumentProvider methodCallExpr)
{
EmitMethodCall(obj, method, methodCallExpr, CompilationFlags.EmitAsNoTail);
}
private void EmitMethodCall(Expression obj, MethodInfo method, IArgumentProvider methodCallExpr, CompilationFlags flags)
{
// Emit instance, if calling an instance method
Type objectType = null;
if (!method.IsStatic)
{
Debug.Assert(obj != null);
EmitInstance(obj, out objectType);
}
// if the obj has a value type, its address is passed to the method call so we cannot destroy the
// stack by emitting a tail call
if (obj != null && obj.Type.IsValueType)
{
EmitMethodCall(method, methodCallExpr, objectType);
}
else
{
EmitMethodCall(method, methodCallExpr, objectType, flags);
}
}
// assumes 'object' of non-static call is already on stack
private void EmitMethodCall(MethodInfo mi, IArgumentProvider args, Type objectType)
{
EmitMethodCall(mi, args, objectType, CompilationFlags.EmitAsNoTail);
}
// assumes 'object' of non-static call is already on stack
private void EmitMethodCall(MethodInfo mi, IArgumentProvider args, Type objectType, CompilationFlags flags)
{
// Emit arguments
List<WriteBack> wb = EmitArguments(mi, args);
// Emit the actual call
OpCode callOp = UseVirtual(mi) ? OpCodes.Callvirt : OpCodes.Call;
if (callOp == OpCodes.Callvirt && objectType.IsValueType)
{
// This automatically boxes value types if necessary.
_ilg.Emit(OpCodes.Constrained, objectType);
}
// The method call can be a tail call if
// 1) the method call is the last instruction before Ret
// 2) the method does not have any ByRef parameters, refer to ECMA-335 Partition III Section 2.4.
// "Verification requires that no managed pointers are passed to the method being called, since
// it does not track pointers into the current frame."
if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail && !MethodHasByRefParameter(mi))
{
_ilg.Emit(OpCodes.Tailcall);
}
if (mi.CallingConvention == CallingConventions.VarArgs)
{
int count = args.ArgumentCount;
Type[] types = new Type[count];
for (int i = 0; i < count; i++)
{
types[i] = args.GetArgument(i).Type;
}
_ilg.EmitCall(callOp, mi, types);
}
else
{
_ilg.Emit(callOp, mi);
}
// Emit write-backs for properties passed as "ref" arguments
EmitWriteBack(wb);
}
private static bool MethodHasByRefParameter(MethodInfo mi)
{
foreach (ParameterInfo pi in mi.GetParametersCached())
{
if (pi.IsByRefParameter())
{
return true;
}
}
return false;
}
private void EmitCall(Type objectType, MethodInfo method)
{
if (method.CallingConvention == CallingConventions.VarArgs)
{
throw Error.UnexpectedVarArgsCall(method);
}
OpCode callOp = UseVirtual(method) ? OpCodes.Callvirt : OpCodes.Call;
if (callOp == OpCodes.Callvirt && objectType.IsValueType)
{
_ilg.Emit(OpCodes.Constrained, objectType);
}
_ilg.Emit(callOp, method);
}
private static bool UseVirtual(MethodInfo mi)
{
// There are two factors: is the method static, virtual or non-virtual instance?
// And is the object ref or value?
// The cases are:
//
// static, ref: call
// static, value: call
// virtual, ref: callvirt
// virtual, value: call -- e.g. double.ToString must be a non-virtual call to be verifiable.
// instance, ref: callvirt -- this looks wrong, but is verifiable and gives us a free null check.
// instance, value: call
//
// We never need to generate a non-virtual call to a virtual method on a reference type because
// expression trees do not support "base.Foo()" style calling.
//
// We could do an optimization here for the case where we know that the object is a non-null
// reference type and the method is a non-virtual instance method. For example, if we had
// (new Foo()).Bar() for instance method Bar we don't need the null check so we could do a
// call rather than a callvirt. However that seems like it would not be a very big win for
// most dynamically generated code scenarios, so let's not do that for now.
if (mi.IsStatic)
{
return false;
}
if (mi.DeclaringType.IsValueType)
{
return false;
}
return true;
}
/// <summary>
/// Emits arguments to a call, and returns an array of write-backs that
/// should happen after the call.
/// </summary>
private List<WriteBack> EmitArguments(MethodBase method, IArgumentProvider args)
{
return EmitArguments(method, args, 0);
}
/// <summary>
/// Emits arguments to a call, and returns an array of write-backs that
/// should happen after the call. For emitting dynamic expressions, we
/// need to skip the first parameter of the method (the call site).
/// </summary>
private List<WriteBack> EmitArguments(MethodBase method, IArgumentProvider args, int skipParameters)
{
ParameterInfo[] pis = method.GetParametersCached();
Debug.Assert(args.ArgumentCount + skipParameters == pis.Length);
List<WriteBack> writeBacks = null;
for (int i = skipParameters, n = pis.Length; i < n; i++)
{
ParameterInfo parameter = pis[i];
Expression argument = args.GetArgument(i - skipParameters);
Type type = parameter.ParameterType;
if (type.IsByRef)
{
type = type.GetElementType();
WriteBack wb = EmitAddressWriteBack(argument, type);
if (wb != null)
{
if (writeBacks == null)
{
writeBacks = new List<WriteBack>();
}
writeBacks.Add(wb);
}
}
else
{
EmitExpression(argument);
}
}
return writeBacks;
}
private void EmitWriteBack(List<WriteBack> writeBacks)
{
if (writeBacks != null)
{
foreach (WriteBack wb in writeBacks)
{
wb(this);
}
}
}
#endregion
private void EmitConstantExpression(Expression expr)
{
ConstantExpression node = (ConstantExpression)expr;
EmitConstant(node.Value, node.Type);
}
private void EmitConstant(object value)
{
Debug.Assert(value != null);
EmitConstant(value, value.GetType());
}
private void EmitConstant(object value, Type type)
{
// Try to emit the constant directly into IL
if (!_ilg.TryEmitConstant(value, type, this))
{
_boundConstants.EmitConstant(this, value, type);
}
}
private void EmitDynamicExpression(Expression expr)
{
#if FEATURE_COMPILE_TO_METHODBUILDER
if (!(_method is DynamicMethod))
{
throw Error.CannotCompileDynamic();
}
#else
Debug.Assert(_method is DynamicMethod);
#endif
var node = (IDynamicExpression)expr;
object site = node.CreateCallSite();
Type siteType = site.GetType();
MethodInfo invoke = node.DelegateType.GetMethod("Invoke");
// site.Target.Invoke(site, args)
EmitConstant(site, siteType);
// Emit the temp as type CallSite so we get more reuse
_ilg.Emit(OpCodes.Dup);
LocalBuilder siteTemp = GetLocal(siteType);
_ilg.Emit(OpCodes.Stloc, siteTemp);
_ilg.Emit(OpCodes.Ldfld, siteType.GetField("Target"));
_ilg.Emit(OpCodes.Ldloc, siteTemp);
FreeLocal(siteTemp);
List<WriteBack> wb = EmitArguments(invoke, node, 1);
_ilg.Emit(OpCodes.Callvirt, invoke);
EmitWriteBack(wb);
}
private void EmitNewExpression(Expression expr)
{
NewExpression node = (NewExpression)expr;
if (node.Constructor != null)
{
if (node.Constructor.DeclaringType.IsAbstract)
throw Error.NonAbstractConstructorRequired();
List<WriteBack> wb = EmitArguments(node.Constructor, node);
_ilg.Emit(OpCodes.Newobj, node.Constructor);
EmitWriteBack(wb);
}
else
{
Debug.Assert(node.ArgumentCount == 0, "Node with arguments must have a constructor.");
Debug.Assert(node.Type.IsValueType, "Only value type may have constructor not set.");
LocalBuilder temp = GetLocal(node.Type);
_ilg.Emit(OpCodes.Ldloca, temp);
_ilg.Emit(OpCodes.Initobj, node.Type);
_ilg.Emit(OpCodes.Ldloc, temp);
FreeLocal(temp);
}
}
private void EmitTypeBinaryExpression(Expression expr)
{
TypeBinaryExpression node = (TypeBinaryExpression)expr;
if (node.NodeType == ExpressionType.TypeEqual)
{
EmitExpression(node.ReduceTypeEqual());
return;
}
Type type = node.Expression.Type;
// Try to determine the result statically
AnalyzeTypeIsResult result = ConstantCheck.AnalyzeTypeIs(node);
if (result == AnalyzeTypeIsResult.KnownTrue ||
result == AnalyzeTypeIsResult.KnownFalse)
{
// Result is known statically, so just emit the expression for
// its side effects and return the result
EmitExpressionAsVoid(node.Expression);
_ilg.EmitPrimitive(result == AnalyzeTypeIsResult.KnownTrue);
return;
}
if (result == AnalyzeTypeIsResult.KnownAssignable)
{
// We know the type can be assigned, but still need to check
// for null at runtime
if (type.IsNullableType())
{
EmitAddress(node.Expression, type);
_ilg.EmitHasValue(type);
return;
}
Debug.Assert(!type.IsValueType);
EmitExpression(node.Expression);
_ilg.Emit(OpCodes.Ldnull);
_ilg.Emit(OpCodes.Cgt_Un);
return;
}
Debug.Assert(result == AnalyzeTypeIsResult.Unknown);
// Emit a full runtime "isinst" check
EmitExpression(node.Expression);
if (type.IsValueType)
{
_ilg.Emit(OpCodes.Box, type);
}
_ilg.Emit(OpCodes.Isinst, node.TypeOperand);
_ilg.Emit(OpCodes.Ldnull);
_ilg.Emit(OpCodes.Cgt_Un);
}
private void EmitVariableAssignment(AssignBinaryExpression node, CompilationFlags flags)
{
var variable = (ParameterExpression)node.Left;
CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask;
if (node.IsByRef)
{
EmitAddress(node.Right, node.Right.Type);
}
else
{
EmitExpression(node.Right);
}
if (emitAs != CompilationFlags.EmitAsVoidType)
{
_ilg.Emit(OpCodes.Dup);
}
if (variable.IsByRef)
{
// Note: the stloc/ldloc pattern is a bit suboptimal, but it
// saves us from having to spill stack when assigning to a
// byref parameter. We already make this same trade-off for
// hoisted variables, see ElementStorage.EmitStore
LocalBuilder value = GetLocal(variable.Type);
_ilg.Emit(OpCodes.Stloc, value);
_scope.EmitGet(variable);
_ilg.Emit(OpCodes.Ldloc, value);
FreeLocal(value);
_ilg.EmitStoreValueIndirect(variable.Type);
}
else
{
_scope.EmitSet(variable);
}
}
private void EmitAssignBinaryExpression(Expression expr)
{
EmitAssign((AssignBinaryExpression)expr, CompilationFlags.EmitAsDefaultType);
}
private void EmitAssign(AssignBinaryExpression node, CompilationFlags emitAs)
{
switch (node.Left.NodeType)
{
case ExpressionType.Index:
EmitIndexAssignment(node, emitAs);
return;
case ExpressionType.MemberAccess:
EmitMemberAssignment(node, emitAs);
return;
case ExpressionType.Parameter:
EmitVariableAssignment(node, emitAs);
return;
default:
throw Error.InvalidLvalue(node.Left.NodeType);
}
}
private void EmitParameterExpression(Expression expr)
{
ParameterExpression node = (ParameterExpression)expr;
_scope.EmitGet(node);
if (node.IsByRef)
{
_ilg.EmitLoadValueIndirect(node.Type);
}
}
private void EmitLambdaExpression(Expression expr)
{
LambdaExpression node = (LambdaExpression)expr;
EmitDelegateConstruction(node);
}
private void EmitRuntimeVariablesExpression(Expression expr)
{
RuntimeVariablesExpression node = (RuntimeVariablesExpression)expr;
_scope.EmitVariableAccess(this, node.Variables);
}
private void EmitMemberAssignment(AssignBinaryExpression node, CompilationFlags flags)
{
Debug.Assert(!node.IsByRef);
MemberExpression lvalue = (MemberExpression)node.Left;
MemberInfo member = lvalue.Member;
// emit "this", if any
Type objectType = null;
if (lvalue.Expression != null)
{
EmitInstance(lvalue.Expression, out objectType);
}
// emit value
EmitExpression(node.Right);
LocalBuilder temp = null;
CompilationFlags emitAs = flags & CompilationFlags.EmitAsTypeMask;
if (emitAs != CompilationFlags.EmitAsVoidType)
{
// save the value so we can return it
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Stloc, temp = GetLocal(node.Type));
}
var fld = member as FieldInfo;
if ((object)fld != null)
{
_ilg.EmitFieldSet((FieldInfo)member);
}
else
{
// MemberExpression.Member can only be a FieldInfo or a PropertyInfo
Debug.Assert(member is PropertyInfo);
var prop = (PropertyInfo)member;
EmitCall(objectType, prop.GetSetMethod(nonPublic: true));
}
if (emitAs != CompilationFlags.EmitAsVoidType)
{
_ilg.Emit(OpCodes.Ldloc, temp);
FreeLocal(temp);
}
}
private void EmitMemberExpression(Expression expr)
{
MemberExpression node = (MemberExpression)expr;
// emit "this", if any
Type instanceType = null;
if (node.Expression != null)
{
EmitInstance(node.Expression, out instanceType);
}
EmitMemberGet(node.Member, instanceType);
}
// assumes instance is already on the stack
private void EmitMemberGet(MemberInfo member, Type objectType)
{
var fi = member as FieldInfo;
if ((object)fi != null)
{
if (fi.IsLiteral)
{
EmitConstant(fi.GetRawConstantValue(), fi.FieldType);
}
else
{
_ilg.EmitFieldGet(fi);
}
}
else
{
// MemberExpression.Member or MemberBinding.Member can only be a FieldInfo or a PropertyInfo
Debug.Assert(member is PropertyInfo);
var prop = (PropertyInfo)member;
EmitCall(objectType, prop.GetGetMethod(nonPublic: true));
}
}
private void EmitInstance(Expression instance, out Type type)
{
type = instance.Type;
// NB: Instance can be a ByRef type due to stack spilling introducing ref locals for
// accessing an instance of a value type. In that case, we don't have to take the
// address of the instance anymore; we just load the ref local.
if (type.IsByRef)
{
type = type.GetElementType();
Debug.Assert(instance.NodeType == ExpressionType.Parameter);
Debug.Assert(type.IsValueType);
EmitExpression(instance);
}
else if (type.IsValueType)
{
EmitAddress(instance, type);
}
else
{
EmitExpression(instance);
}
}
private void EmitNewArrayExpression(Expression expr)
{
NewArrayExpression node = (NewArrayExpression)expr;
ReadOnlyCollection<Expression> expressions = node.Expressions;
int n = expressions.Count;
if (node.NodeType == ExpressionType.NewArrayInit)
{
Type elementType = node.Type.GetElementType();
_ilg.EmitArray(elementType, n);
for (int i = 0; i < n; i++)
{
_ilg.Emit(OpCodes.Dup);
_ilg.EmitPrimitive(i);
EmitExpression(expressions[i]);
_ilg.EmitStoreElement(elementType);
}
}
else
{
for (int i = 0; i < n; i++)
{
Expression x = expressions[i];
EmitExpression(x);
_ilg.EmitConvertToType(x.Type, typeof(int), isChecked: true, locals: this);
}
_ilg.EmitArray(node.Type);
}
}
private void EmitDebugInfoExpression(Expression expr)
{
return;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "expr")]
private static void EmitExtensionExpression(Expression expr)
{
throw Error.ExtensionNotReduced();
}
#region ListInit, MemberInit
private void EmitListInitExpression(Expression expr)
{
EmitListInit((ListInitExpression)expr);
}
private void EmitMemberInitExpression(Expression expr)
{
EmitMemberInit((MemberInitExpression)expr);
}
private void EmitBinding(MemberBinding binding, Type objectType)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
EmitMemberAssignment((MemberAssignment)binding, objectType);
break;
case MemberBindingType.ListBinding:
EmitMemberListBinding((MemberListBinding)binding);
break;
case MemberBindingType.MemberBinding:
EmitMemberMemberBinding((MemberMemberBinding)binding);
break;
default:
throw Error.UnknownBindingType();
}
}
private void EmitMemberAssignment(MemberAssignment binding, Type objectType)
{
EmitExpression(binding.Expression);
FieldInfo fi = binding.Member as FieldInfo;
if (fi != null)
{
_ilg.Emit(OpCodes.Stfld, fi);
}
else
{
PropertyInfo pi = binding.Member as PropertyInfo;
if (pi != null)
{
EmitCall(objectType, pi.GetSetMethod(nonPublic: true));
}
else
{
throw Error.UnhandledBinding();
}
}
}
private void EmitMemberMemberBinding(MemberMemberBinding binding)
{
Type type = GetMemberType(binding.Member);
if (binding.Member is PropertyInfo && type.IsValueType)
{
throw Error.CannotAutoInitializeValueTypeMemberThroughProperty(binding.Member);
}
if (type.IsValueType)
{
EmitMemberAddress(binding.Member, binding.Member.DeclaringType);
}
else
{
EmitMemberGet(binding.Member, binding.Member.DeclaringType);
}
EmitMemberInit(binding.Bindings, false, type);
}
private void EmitMemberListBinding(MemberListBinding binding)
{
Type type = GetMemberType(binding.Member);
if (binding.Member is PropertyInfo && type.IsValueType)
{
throw Error.CannotAutoInitializeValueTypeElementThroughProperty(binding.Member);
}
if (type.IsValueType)
{
EmitMemberAddress(binding.Member, binding.Member.DeclaringType);
}
else
{
EmitMemberGet(binding.Member, binding.Member.DeclaringType);
}
EmitListInit(binding.Initializers, false, type);
}
private void EmitMemberInit(MemberInitExpression init)
{
EmitExpression(init.NewExpression);
LocalBuilder loc = null;
if (init.NewExpression.Type.IsValueType && init.Bindings.Count > 0)
{
loc = GetLocal(init.NewExpression.Type);
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.Emit(OpCodes.Ldloca, loc);
}
EmitMemberInit(init.Bindings, loc == null, init.NewExpression.Type);
if (loc != null)
{
_ilg.Emit(OpCodes.Ldloc, loc);
FreeLocal(loc);
}
}
// This method assumes that the instance is on the stack and is expected, based on "keepOnStack" flag
// to either leave the instance on the stack, or pop it.
private void EmitMemberInit(ReadOnlyCollection<MemberBinding> bindings, bool keepOnStack, Type objectType)
{
int n = bindings.Count;
if (n == 0)
{
// If there are no initializers and instance is not to be kept on the stack, we must pop explicitly.
if (!keepOnStack)
{
_ilg.Emit(OpCodes.Pop);
}
}
else
{
for (int i = 0; i < n; i++)
{
if (keepOnStack || i < n - 1)
{
_ilg.Emit(OpCodes.Dup);
}
EmitBinding(bindings[i], objectType);
}
}
}
private void EmitListInit(ListInitExpression init)
{
EmitExpression(init.NewExpression);
LocalBuilder loc = null;
if (init.NewExpression.Type.IsValueType)
{
loc = GetLocal(init.NewExpression.Type);
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.Emit(OpCodes.Ldloca, loc);
}
EmitListInit(init.Initializers, loc == null, init.NewExpression.Type);
if (loc != null)
{
_ilg.Emit(OpCodes.Ldloc, loc);
FreeLocal(loc);
}
}
// This method assumes that the list instance is on the stack and is expected, based on "keepOnStack" flag
// to either leave the list instance on the stack, or pop it.
private void EmitListInit(ReadOnlyCollection<ElementInit> initializers, bool keepOnStack, Type objectType)
{
int n = initializers.Count;
if (n == 0)
{
// If there are no initializers and instance is not to be kept on the stack, we must pop explicitly.
if (!keepOnStack)
{
_ilg.Emit(OpCodes.Pop);
}
}
else
{
for (int i = 0; i < n; i++)
{
if (keepOnStack || i < n - 1)
{
_ilg.Emit(OpCodes.Dup);
}
EmitMethodCall(initializers[i].AddMethod, initializers[i], objectType);
// Some add methods, ArrayList.Add for example, return non-void
if (initializers[i].AddMethod.ReturnType != typeof(void))
{
_ilg.Emit(OpCodes.Pop);
}
}
}
}
private static Type GetMemberType(MemberInfo member)
{
FieldInfo fi = member as FieldInfo;
if (fi != null) return fi.FieldType;
PropertyInfo pi = member as PropertyInfo;
if (pi != null) return pi.PropertyType;
throw Error.MemberNotFieldOrProperty(member, nameof(member));
}
#endregion
#region Expression helpers
internal static void ValidateLift(IReadOnlyList<ParameterExpression> variables, IReadOnlyList<Expression> arguments)
{
Debug.Assert(variables != null);
Debug.Assert(arguments != null);
if (variables.Count != arguments.Count)
{
throw Error.IncorrectNumberOfIndexes();
}
for (int i = 0, n = variables.Count; i < n; i++)
{
if (!TypeUtils.AreReferenceAssignable(variables[i].Type, arguments[i].Type.GetNonNullableType()))
{
throw Error.ArgumentTypesMustMatch();
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void EmitLift(ExpressionType nodeType, Type resultType, MethodCallExpression mc, ParameterExpression[] paramList, Expression[] argList)
{
Debug.Assert(TypeUtils.AreEquivalent(resultType.GetNonNullableType(), mc.Type.GetNonNullableType()));
switch (nodeType)
{
default:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
{
Label exit = _ilg.DefineLabel();
Label exitNull = _ilg.DefineLabel();
LocalBuilder anyNull = GetLocal(typeof(bool));
for (int i = 0, n = paramList.Length; i < n; i++)
{
ParameterExpression v = paramList[i];
Expression arg = argList[i];
if (arg.Type.IsNullableType())
{
_scope.AddLocal(this, v);
EmitAddress(arg, arg.Type);
_ilg.Emit(OpCodes.Dup);
_ilg.EmitHasValue(arg.Type);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Stloc, anyNull);
_ilg.EmitGetValueOrDefault(arg.Type);
_scope.EmitSet(v);
}
else
{
_scope.AddLocal(this, v);
EmitExpression(arg);
if (!arg.Type.IsValueType)
{
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Ldnull);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Stloc, anyNull);
}
_scope.EmitSet(v);
}
_ilg.Emit(OpCodes.Ldloc, anyNull);
_ilg.Emit(OpCodes.Brtrue, exitNull);
}
EmitMethodCallExpression(mc);
if (resultType.IsNullableType() && !TypeUtils.AreEquivalent(resultType, mc.Type))
{
ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type });
_ilg.Emit(OpCodes.Newobj, ci);
}
_ilg.Emit(OpCodes.Br_S, exit);
_ilg.MarkLabel(exitNull);
if (TypeUtils.AreEquivalent(resultType, mc.Type.GetNullableType()))
{
if (resultType.IsValueType)
{
LocalBuilder result = GetLocal(resultType);
_ilg.Emit(OpCodes.Ldloca, result);
_ilg.Emit(OpCodes.Initobj, resultType);
_ilg.Emit(OpCodes.Ldloc, result);
FreeLocal(result);
}
else
{
_ilg.Emit(OpCodes.Ldnull);
}
}
else
{
switch (nodeType)
{
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
_ilg.Emit(OpCodes.Ldc_I4_0);
break;
default:
throw Error.UnknownLiftType(nodeType);
}
}
_ilg.MarkLabel(exit);
FreeLocal(anyNull);
return;
}
case ExpressionType.Equal:
case ExpressionType.NotEqual:
{
if (TypeUtils.AreEquivalent(resultType, mc.Type.GetNullableType()))
{
goto default;
}
Label exit = _ilg.DefineLabel();
Label exitAllNull = _ilg.DefineLabel();
Label exitAnyNull = _ilg.DefineLabel();
LocalBuilder anyNull = GetLocal(typeof(bool));
LocalBuilder allNull = GetLocal(typeof(bool));
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Stloc, anyNull);
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.Emit(OpCodes.Stloc, allNull);
for (int i = 0, n = paramList.Length; i < n; i++)
{
ParameterExpression v = paramList[i];
Expression arg = argList[i];
_scope.AddLocal(this, v);
if (arg.Type.IsNullableType())
{
EmitAddress(arg, arg.Type);
_ilg.Emit(OpCodes.Dup);
_ilg.EmitHasValue(arg.Type);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Ldloc, anyNull);
_ilg.Emit(OpCodes.Or);
_ilg.Emit(OpCodes.Stloc, anyNull);
_ilg.Emit(OpCodes.Ldloc, allNull);
_ilg.Emit(OpCodes.And);
_ilg.Emit(OpCodes.Stloc, allNull);
_ilg.EmitGetValueOrDefault(arg.Type);
}
else
{
EmitExpression(arg);
if (!arg.Type.IsValueType)
{
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Ldnull);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Ldloc, anyNull);
_ilg.Emit(OpCodes.Or);
_ilg.Emit(OpCodes.Stloc, anyNull);
_ilg.Emit(OpCodes.Ldloc, allNull);
_ilg.Emit(OpCodes.And);
_ilg.Emit(OpCodes.Stloc, allNull);
}
else
{
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Stloc, allNull);
}
}
_scope.EmitSet(v);
}
_ilg.Emit(OpCodes.Ldloc, allNull);
_ilg.Emit(OpCodes.Brtrue, exitAllNull);
_ilg.Emit(OpCodes.Ldloc, anyNull);
_ilg.Emit(OpCodes.Brtrue, exitAnyNull);
EmitMethodCallExpression(mc);
if (resultType.IsNullableType() && !TypeUtils.AreEquivalent(resultType, mc.Type))
{
ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type });
_ilg.Emit(OpCodes.Newobj, ci);
}
_ilg.Emit(OpCodes.Br_S, exit);
_ilg.MarkLabel(exitAllNull);
_ilg.EmitPrimitive(nodeType == ExpressionType.Equal);
_ilg.Emit(OpCodes.Br_S, exit);
_ilg.MarkLabel(exitAnyNull);
_ilg.EmitPrimitive(nodeType == ExpressionType.NotEqual);
_ilg.MarkLabel(exit);
FreeLocal(anyNull);
FreeLocal(allNull);
return;
}
}
}
#endregion
}
}
| |
#region Copyright (c) Roni Schuetz - All Rights Reserved
// * --------------------------------------------------------------------- *
// * Roni Schuetz *
// * Copyright (c) 2008 All Rights reserved *
// * *
// * Shared Cache high-performance, distributed caching and *
// * replicated caching system, generic in nature, but intended to *
// * speeding up dynamic web and / or win applications by alleviating *
// * database load. *
// * *
// * This Software is written by Roni Schuetz (schuetz AT gmail DOT 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 *
// * *
// * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. *
// * --------------------------------------------------------------------- *
#endregion
// *************************************************************************
//
// Name: ManageTcpSocketConnectionPool.cs
//
// Created: 10-02-2008 SharedCache.com, rschuetz
// Modified: 10-02-2008 SharedCache.com, rschuetz : Creation
// Modified: 24-02-2008 SharedCache.com, rschuetz : updated logging part for tracking, instead of using appsetting we use precompiler definition #if TRACE
// *************************************************************************
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Net;
using System.Timers;
using System.Diagnostics;
namespace SharedCache.WinServiceCommon.Sockets
{
/// <summary>
/// Managing the various Connection Pools to each server node within the client
/// </summary>
public class ManageTcpSocketConnectionPool
{
/// <summary>
/// lock down pool upon add / receive shared cache sockets
/// </summary>
private static object bulkObject = new object();
/// <summary>
/// contains the configured host in web.config / app.config
/// </summary>
private Dictionary<string, int> configuredHosts = new Dictionary<string, int>();
/// <summary>
/// a dictonary with the relevant pool for each server node
/// </summary>
private Dictionary<string, TcpSocketConnectionPool> pools = new Dictionary<string, TcpSocketConnectionPool>();
/// <summary>
/// a Timer which validat created pools.
/// </summary>
/// Bugfix for: http://www.codeplex.com/SharedCache/WorkItem/View.aspx?WorkItemId=5847
System.Timers.Timer validatePoolTimer = null;
/// <summary>
/// Initializes a new instance of the <see cref="ManageTcpSocketConnectionPool"/> class.
/// </summary>
public ManageTcpSocketConnectionPool(bool instanceClientPools)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#if DEBUG
Debug.WriteLine(string.Format("socket connection pool created for {0}", instanceClientPools ? "client" : "server"));
#endif
#endregion Access Log
lock (bulkObject)
{
if (this.configuredHosts.Count == 0)
{
if (instanceClientPools)
{
#region reading provider data from the config file
foreach (Configuration.Client.IndexusServerSetting configEntry in Provider.Cache.IndexusDistributionCache.SharedCache.ServersList)
{
// default port!
int port = 48888;
int.TryParse(configEntry.Port, out port);
this.configuredHosts.Add(configEntry.IpAddress, port);
}
#endregion
#region upon replication the system creates also a pool for backup replication server nodes
foreach (Configuration.Client.IndexusServerSetting configEntry in Provider.Cache.IndexusDistributionCache.SharedCache.ReplicatedServersList)
{
int port = 48888;
int.TryParse(configEntry.Port, out port);
this.configuredHosts.Add(configEntry.IpAddress, port);
}
#endregion
}
else
{
#region ensure client does not configure the instance itself!!!
IPAddress ip = Handler.Network.GetFirstIPAddress();
foreach (Configuration.Server.IndexusServerSetting configEntry in Provider.Server.IndexusServerReplicationCache.CurrentProvider.ServersList)
{
// validate server does not add itself.
if (!ip.ToString().Equals(configEntry.IpAddress))
{
this.configuredHosts.Add(configEntry.IpAddress, configEntry.Port);
}
}
#endregion
}
double doubleMs = 180000;
if (instanceClientPools)
{
doubleMs = Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.SocketPoolValidationInterval.TotalMilliseconds;
}
else
{
doubleMs = Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.SocketPoolValidationInterval.TotalMilliseconds;
}
#if DEBUG
Debug.WriteLine("SocketPoolValidationInterval amount:" + doubleMs.ToString());
#endif
this.validatePoolTimer = new System.Timers.Timer();
this.validatePoolTimer.Elapsed += new ElapsedEventHandler(ValidateConnectionPools);
this.validatePoolTimer.Interval = doubleMs;
this.validatePoolTimer.Start();
}
// init each for each entry a pool
foreach (KeyValuePair<string, int> host in this.configuredHosts)
{
TcpSocketConnectionPool newPool = new TcpSocketConnectionPool();
newPool.Host = host.Key;
newPool.Port = host.Value;
pools.Add(host.Key, newPool);
int defaultPoolSize = 5;
if (instanceClientPools)
{
defaultPoolSize = Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.SocketPoolMinAvailableSize;
}
else
{
defaultPoolSize = Provider.Server.IndexusServerReplicationCache.ProviderSection.ServerSetting.SocketPoolMinAvailableSize;
}
#if DEBUG
Debug.WriteLine(string.Format("Pool size is {0} for host {1}", defaultPoolSize, host.Key));
#endif
// set tcp pool size
pools[host.Key].PoolSize = defaultPoolSize;
// enable pool
pools[host.Key].Enable();
}
}
}
/// <summary>
/// Determinates if specific pool is available.
/// </summary>
/// <param name="host">A <see cref="string"/> which defines the host.</param>
/// <returns>A <see cref="bool"/> which represents the status.</returns>
public bool Available(string host)
{
return pools[host].PoolAvailable;
}
/// <summary>
/// Validates all available pools. In case a one of the pool's is disabled
/// it will enable it automatically after it can ping specific server node.
/// </summary>
void ValidateConnectionPools(object sender, ElapsedEventArgs e)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
try
{
foreach (KeyValuePair<string, TcpSocketConnectionPool> p in pools)
{
#region Logging
//if (1 == Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.LoggingEnable)
//{
// #if TRACE
// Console.WriteLine("Validate Pool: " + host);
// #endif
// #if DEBUG
// Console.WriteLine("Validate Pool: " + p.Key);
// #endif
// Handler.LogHandler.Fatal("Validate Pool: " + p.Key);
//}
#endregion
#if DEBUG
Debug.WriteLine(string.Format("validate host: {0}", p.Key));
#endif
lock (bulkObject)
{
p.Value.Validate();
}
}
}
catch (Exception ex)
{
#if DEBUG
{
Console.WriteLine("ValidatePools throws an Exception! Message: " + ex.Message);
}
#endif
Handler.LogHandler.Fatal("ValidatePools throws an Exception!", ex);
}
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="ManageTcpSocketConnectionPool"/> is reclaimed by garbage collection.
/// </summary>
~ManageTcpSocketConnectionPool()
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
// Bugfix for: http://www.codeplex.com/SharedCache/WorkItem/View.aspx?WorkItemId=5847
if (this.validatePoolTimer != null)
{
if (this.validatePoolTimer.Enabled)
{
validatePoolTimer.Stop();
}
validatePoolTimer.Dispose();
}
foreach (KeyValuePair<string, int> host in this.configuredHosts)
{
pools[host.Key] = null;
}
}
/// <summary>
/// Gets the socket from pool.
/// </summary>
/// <param name="host">The host.</param>
/// <returns>A <see cref="SharedCacheTcpClient"/> object.</returns>
public SharedCacheTcpClient GetSocketFromPool(string host)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#endregion Access Log
#if DEBUG
Debug.WriteLine(string.Format("retrieve socket from host: {0}", host));
#endif
TcpSocketConnectionPool pool = pools[host];
return pool.GetSocket();
}
internal bool GetPoolStatus(string host)
{
return pools[host].PoolAvailable;
}
internal bool Disable(string host)
{
#if DEBUG
Debug.WriteLine(string.Format("disable host: {0}", host));
#endif
try
{
bool actualStatus = pools[host].PoolAvailable;
lock (bulkObject)
{
// need to set the attribute within the instance for enabling the pool from the validate
// method itself.
pools[host].Disable();
}
//if (1 == Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.LoggingEnable)
{
string msg = string.Empty;
if (actualStatus)
{
msg = "Server node is NOT available: {0}. Client tries to reconnect every {1}.";
}
else
{
msg = "Server node {0} is still NOT available.";
}
#if TRACE
//Console.WriteLine(msg, host, Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.SocketPoolValidationInterval.TotalMilliseconds);
#endif
#if DEBUG
//Console.WriteLine(msg, host, Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.SocketPoolValidationInterval.TotalMilliseconds);
#endif
//Handler.LogHandler.Fatal(string.Format(msg, host, Provider.Cache.IndexusDistributionCache.ProviderSection.ClientSetting.SocketPoolValidationInterval.TotalMilliseconds));
}
return true;
}
catch (Exception ex)
{
Handler.LogHandler.Fatal("Client tried to disable host " + host + ". during this step an exception appeared.",ex);
return false;
}
}
/// <summary>
/// Puts the socket to pool.
/// </summary>
/// <param name="host">The host.</param>
/// <param name="socket">The socket.</param>
public void PutSocketToPool(string host, SharedCacheTcpClient socket)
{
#region Access Log
#if TRACE
{
Handler.LogHandler.Tracking("Access Method: " + this.GetType().ToString() + "->" + ((object)MethodBase.GetCurrentMethod()).ToString() + " ;");
}
#endif
#if DEBUG
Debug.WriteLine(string.Format("put socket to pool: {0}", host));
#endif
#endregion Access Log
TcpSocketConnectionPool pool = pools[host];
pool.PutSocket(socket);
}
}
}
| |
// Copyright (C) 2013 Dmitry Yakimenko (detunized@gmail.com).
// Licensed under the terms of the MIT license. See LICENCE for details.
namespace LastPass.Test
{
static class TestData
{
public static readonly string[] ChunkIds =
{
"LPAV", "ATVR", "ENCU", "CBCU", "BBTE", "IPTE", "WMTE", "ANTE",
"DOTE", "FETE", "FUTE", "SYTE", "WOTE", "TATE", "WPTE", "SPMT",
"NMAC", "ACCT", "EQDN", "URUL", "ENDM"
};
public static readonly string BlobBase64 =
"TFBBVgAAAAMxMThBVFZSAAAAAzEwMkVOQ1UAAABGITExVkVjWFVnelFramxranB2" +
"VGZyR3c9PXxYUklhVVdQYlQzRXdRQlZCRUYxZUJTTDI3bWZ1cVViZmFCV3JCYnd5" +
"WFdFPUNCQ1UAAAABMUJCVEUAAAAMLTYyMTY5OTY2MDAwSVBURQAAAAwtNjIxNjk5" +
"NjYwMDBXTVRFAAAADC02MjE2OTk2NjAwMEFOVEUAAAAMLTYyMTY5OTY2MDAwRE9U" +
"RQAAAAwtNjIxNjk5NjYwMDBGRVRFAAAADC02MjE2OTk2NjAwMEZVVEUAAAAMLTYy" +
"MTY5OTY2MDAwU1lURQAAAAwtNjIxNjk5NjYwMDBXT1RFAAAADC02MjE2OTk2NjAw" +
"MFRBVEUAAAAMLTYyMTY5OTY2MDAwV1BURQAAAAEwU1BNVAAAAC0AAAABMAAAAAEw" +
"AAAAATAAAAABMAAAAAEwAAAAATEAAAABMQAAAAEwAAAAATBOTUFDAAAAAzEwMEFD" +
"Q1QAAAGTAAAACjE4NzI3NDU1OTYAAAAxIaUvQYPzwlMtRTrZEYftBU9068UlQ6rL" +
"OxmAxj8la1TXtePO6A6dOgmDalfC+dPq0gAAACEhP6C+06QXUEo+rzP1CV2Y8gRR" +
"6lSnhVSaB3/FJPgnYLgAAABENjg3NDc0NzAzYTJmMmY2ZTY5NjU2ZTZmNzcyZTZl" +
"NjU3NDJmNmQ2NTYxNjc2MTZlMmU2NzcyNjU2NTZlNjg2ZjZjNzQAAAAAAAAAATAA" +
"AAAAAAAAISGrnmjbXckUV+TJvuuFaiAU055QL+iRpTOLUdEfvpR55gAAADEh02Ki" +
"+p/VUgFlLbZKaV0AYtpeGsQ7Jmt+R+BRdoWkwGsXHm5blPx/YYVdf8Y9TwE7AAAA" +
"ATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ1NTk2AAAA" +
"AAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAABMQAA" +
"AAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAGJAAAACjE4NzI3NDU2MDYA" +
"AAAhIWzPDPU9FrsGRopvmOi6uvOYkcGqaqKCFprsL3G1f0FvAAAAISGG5zXlgJ5y" +
"J8fZnAWd/SNb9l/aujeXOtTHTAvQ8RuCnQAAAEo2ODc0NzQ3MDNhMmYyZjYyNjU2" +
"MzY4NzQ2NTZjNjE3MjJlNjI2OTdhMmY3NDcyNjk3Mzc0Njk2MTZlMmU2MjYxNzI3" +
"MjZmNzc3MwAAAAAAAAABMAAAAAAAAAAxIRTPYYC8d7Rvc+NXYokX3soC70wrzjEa" +
"xvytac7xJbd1K/dHU8ee7HU7u5bfNVWVuQAAACEhVq89o7tYpBLCvQO7dtjasGG7" +
"Osin9SvtokRlhNmpDVoAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAA" +
"AAAACjE4NzI3NDU2MDYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAAB" +
"MQAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA0QUNDVAAA" +
"AXUAAAAKMTg3Mjc0NTYxNgAAACEhO9e0HHKHemPXY7gLp1P722/WU9ZSQYjnTWU1" +
"CEJgA3AAAAAhIQM9xNKiBFE1UVQVYaoW6IcvoVSjbGGtS7qj1PplR/2hAAAANjY4" +
"NzQ3NDcwM2EyZjJmNzM2MzY4NzU3Mzc0NjU3MjJlNmU2MTZkNjUyZjYxNzM2ODc0" +
"NmY2ZQAAAAAAAAABMAAAAAAAAAAhIZtIAgu1kRxJC7aqw4H8RXiOC2E4NuRse0fN" +
"/IrFIYVUAAAAMSE9LwFmsD73HSRtgqo5wSX7aJposOOm2hqPIpzFvJwrJlNN1C+2" +
"gbo3ml+YhjkN5pIAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAA" +
"CjE4NzI3NDU2MTYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAABMgAA" +
"AAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA0QUNDVAAAAWsA" +
"AAAKMTg3Mjc0NTYyNgAAACEhXQIttPj6P/25RK3pzV85x1XMTwsb1HMPjCr8RLnn" +
"QOQAAAAhIQ14pX3pzuwOXfczG4+vhm1epPlgA2LtCJRV7Y/knBJ4AAAALDY4NzQ3" +
"NDcwM2EyZjJmNzI3NTZlNmY2YzY2NmY2ZTJlNmY3MjY3MmY3NDY1AAAAAAAAAAEw" +
"AAAAAAAAADEhbZ6cUQzOVkgsFB0d73mOTCJ9efy3VFBEsb0ekhyJcNcUjAPjh774" +
"+BbjywxUsco1AAAAISGD3mOMS0xWcEKRLKimTZQwwpqoMUKCjU/a/brYZbGFhwAA" +
"AAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NTYyNgAA" +
"AAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAEzAAAAATAAAAAAAAAAATEA" +
"AAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABdwAAAAoxODcyNzQ1NjM2" +
"AAAAISEb4m77GfIOvO6fYzktw4aSDOxy8gpxjuR2oD6imAeoiAAAACEh5kDr0YH/" +
"YfHah6DgyCpwbVul9y9CBylEcXENkY8LUYoAAABINjg3NDc0NzAzYTJmMmY2ODY5" +
"NmU3NDdhNzA3MjZmNjg2MTczNmI2MTJlNjI2OTdhMmY3NzYxNjQ2NTJlNjY2OTcz" +
"Njg2NTcyAAAAAAAAAAEwAAAAAAAAACEh2LKP6v5jYlQ6/0yaS4D+u2fLAxJS1BYE" +
"ebH/nwnm+NEAAAAhIbGahlE1a7dDksJcUScFfpGDWVbh6eA2FL5ZQiQJe3SOAAAA" +
"ATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ1NjM2AAAA" +
"AAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAAAAAAAATQAAAABMAAAAAAAAAABMQAA" +
"AAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAFJAAAACjE4NzI3NDU2NDYA" +
"AAAhIddUR3tvwQP0CiQGZ5nIN5AOu41QtVQQkiLlDXgC67C6AAAAAAAAADw2ODc0" +
"NzQ3MDNhMmYyZjczNjM2ODc1NmM3NDdhNjg2NTYxNmU2NTc5MmU2ZjcyNjcyZjYx" +
"NzI3NjY5NjQAAAAAAAAAATAAAAAAAAAAISEgjlPSKxJIaxzS4LtJ0h/WuXA+SzFk" +
"+xq3PIoHE01ujQAAACEhLoYYeDLOwdf2vewKK49rZ9zDR2iTxjzB5ci5L7LdIewA" +
"AAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDU2NDYA" +
"AAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAATEA" +
"AAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABcQAAAAoxODcyNzQ1NjU2" +
"AAAAMSE6dpn4QFzEtGAOF0pnukMsy7MxHQkCHkPBc2WfDpPBNd+mqJoIUr4xn9Os" +
"JLw6JHwAAAAhIa6Z2iLXCdY1FusJuahlVQ12V3AQ1xtx907dhrnLNb2RAAAAMjY4" +
"NzQ3NDcwM2EyZjJmNzM3NDcyNjU2OTYzNjgyZTYzNmY2ZDJmNzI2MTZkNmY2ZTYx" +
"AAAAAAAAAAEwAAAAAAAAACEhFjUkwX6BtmttaI8Xjeh7A4hfdzheEDvQl6ERKI/j" +
"rFMAAAAhIY41/x6H8yJBXBKtRQWNLWdH1RhXe4tsalNPqFtVEFs2AAAAATAAAAAB" +
"MAAAAAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ1NjU2AAAAAAAAAAAA" +
"AAAAAAAAATAAAAABMAAAAAAAAAAAAAAAATUAAAABMAAAAAAAAAABMQAAAAEwAAAA" +
"AAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAFnAAAACjE4NzI3NDU2NjYAAAAhIbaO" +
"iTkfVFko62wOMqoFlk31KC/H4OafgmPG3Aq9Ovg1AAAAISEI9XR+O3ru13RyvgXP" +
"IxvtUDWxbbN+9XewE/4vBxaSwQAAACg2ODc0NzQ3MDNhMmYyZjYzNmY2ZTZlMmU2" +
"ZTY1NzQyZjZjNjU2NDYxAAAAAAAAAAEwAAAAAAAAADEhLVUiK630YW+SH5XRQHQ/" +
"CTRgla8u9KY0uCtV9pw9jqppQaA8EEWIbUUxKdE9ZanFAAAAISGtYcBXZ53fKC4W" +
"W7zFZ8OzVP8HE2SX0EBle6AWtVic4wAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAA" +
"AAABMAAAAAAAAAAKMTg3Mjc0NTY2NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAA" +
"AAAAAAAAAAE2AAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcx" +
"MDRBQ0NUAAABgQAAAAoxODcyNzQ1Njc2AAAAMSHLwsXqutzkzUtQO/qEkwAFxlzV" +
"5P54THEqk12GeVRbGvasMv6m7w78Y5YKy7F0VUIAAAAhIZgyLh1/l1Zon+Sgd+3A" +
"BJ6hc2K6KzI24AwxcC7/LCTyAAAAMjY4NzQ3NDcwM2EyZjJmNjM2ZjZlNzI2Zjc5" +
"MmU2MjY5N2EyZjdhNjE2MzY4NjU3Mjc5AAAAAAAAAAEwAAAAAAAAACEhbhLO4orM" +
"Ku6oUkegA3ItB77rckAc3sQwE5t0R7q8xHQAAAAxId+80ASeTkbv+0oDEV7dfe1n" +
"oEKmVoutR6C50RUTR4s/s5fQdAt/NjqkKJ8GObagtQAAAAEwAAAAATAAAAABMAAA" +
"AAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NTY3NgAAAAAAAAAAAAAAAAAAAAEw" +
"AAAAATAAAAAAAAAAAAAAAAE3AAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAA" +
"CjEzNzMwNzcxMDRBQ0NUAAABSwAAAAoxODcyNzQ1Njg2AAAAISGeWePdN9riofiB" +
"vPXaNOxmNQTL7EkUxBTlR9ODSHHv+wAAAAAAAAAuNjg3NDc0NzAzYTJmMmY2YjY5" +
"Njg2ZTJlNmY3MjY3MmY2MzYxNmU2NDY5NjM2NQAAAAAAAAABMAAAAAAAAAAxIZla" +
"rXv+gtjIVVR/6cC9sytjKe+IjvJL2ezKP3oxEeCJOiJITo86/Furu374noD7rQAA" +
"ACEhWuB+ckZ0FcvD2FXotyKjwHPIFI5a+Yy7Sct/whk+tccAAAABMAAAAAEwAAAA" +
"ATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDU2ODYAAAAAAAAAAAAAAAAA" +
"AAABMAAAAAEwAAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAA" +
"AAAACjEzNzMwNzcxMDRBQ0NUAAABbwAAAAoxODcyNzQ1Njk2AAAAISHFwj2xbX71" +
"uPcF5SZ4bl5e0MIImDPxZqEE0t1T7j+sUQAAACEh+gZl1yfJkchbuZ3oaPGjwUNR" +
"k/np5HlQaqidnepJnvkAAAAwNjg3NDc0NzAzYTJmMmY2NzZjNmY3NjY1NzIyZTZl" +
"NjE2ZDY1MmY2YTY1NzI2MTY0AAAAAAAAAAEwAAAAAAAAACEhWejYIS8GCFp/GkGH" +
"wGdTNj/WPIkshtOCZXUuRjcBDN4AAAAxIWYXzKArUH5hAhqE+bbZvOp9cz6/mUEt" +
"Yw/n0eKACZQKC4RjdZEEXA4UllYuX3c0NwAAAAEwAAAAATAAAAABMAAAAAEwAAAA" +
"ATAAAAABMAAAAAAAAAAKMTg3Mjc0NTY5NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAA" +
"AAAAAAAAAAAAAAE4AAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMw" +
"NzcxMDRBQ0NUAAABcQAAAAoxODcyNzQ1NzA2AAAAISGorY0SSNF696WwYJcxsdFw" +
"D6m2A6ZCkFFzx3v2MBnvEwAAACEhpa8+NWZoYBtoIXi7dUGa+JQbki+uG+vuHPpp" +
"iYEcHxcAAAAyNjg3NDc0NzAzYTJmMmY2ZDYxNzk2NTcyNzQyZTZlNjE2ZDY1MmY2" +
"YTY1NzI2ZjZkNzkAAAAAAAAAATAAAAAAAAAAMSF908guDN8hOUdYwC3tYSpo4PFf" +
"yxNyzfmvW8k83zWY9Hd+QbbHHSjE5XTWAaxisfkAAAAhIdTFya25L9w4T6NH3aRm" +
"P2aMRNqVXhk+91WWKPElSpseAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEw" +
"AAAAAAAAAAoxODcyNzQ1NzA2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAAA" +
"AAAAATkAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFD" +
"Q1QAAAFHAAAACjE4NzI3NDU3MTYAAAAhIXmUu59nSkkwpim5xZUX/B42qd4Z3H3l" +
"8ZKDSxxZfqL5AAAAAAAAADo2ODc0NzQ3MDNhMmYyZjczNjE2ZTY2NmY3MjY0Nzc3" +
"NTZlNzM2MzY4MmU2ZjcyNjcyZjYxNmM2NTZiAAAAAAAAAAEwAAAAAAAAACEhlYwT" +
"HOBJy4TB4DjN4cgm/uH6ktEhYOEC33fQK/6Ew9cAAAAhIS2ehBFomoqThSf9tLV6" +
"mlsBKPU9HimyVJ1apJAuBr8qAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEw" +
"AAAAAAAAAAoxODcyNzQ1NzE2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAAA" +
"AAAAAAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA0QUND" +
"VAAAAYAAAAAKMTg3Mjc0NTcyNgAAACEhGMiPj9rwna8pqHwjeIpTwp+YcOs5ihke" +
"WGiMXBl1edMAAAAhIQAztK0yhhOnVcnIDeqfN4VELzpZqrmq5u4XU7HCgvZXAAAA" +
"QDY4NzQ3NDcwM2EyZjJmNmM2NTY4NmU2NTcyMmU2MjY5N2EyZjczNzQ2MTZlNmM2" +
"NTc5MmU2NDZmNmY2YzY1NzkAAAAAAAAAATAAAAAAAAAAMSGlEEN0n+XAbvFb0tvd" +
"UmIIsbeS1pGdnDEXHeH/d+0DZAJlNMgAYUWmVf39dp+1HTsAAAAhIemJWGnMPw2k" +
"juEmHhbeEMtY67afvWj1PfccOzEPBQs8AAAAATAAAAABMAAAAAEwAAAAATAAAAAB" +
"MAAAAAEwAAAAAAAAAAoxODcyNzQ1NzI2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAA" +
"AAAAAAAAAAAAAjEwAAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMw" +
"NzcxMDRBQ0NUAAABcAAAAAoxODcyNzQ1NzM2AAAAISGs1uDBvUMCJm1J1x+5iNEE" +
"i/i+XX0B9Yf2tadKy+U3+AAAACEhG1dTn17o1/ymRQgpn2oI+xZ36+3H3N6eXgRK" +
"hcadeWQAAAAwNjg3NDc0NzAzYTJmMmY3MjZmNmM2NjczNmY2ZTJlNmU2NTc0MmY2" +
"YTYxNjQ2NTZlAAAAAAAAAAEwAAAAAAAAACEhg9tVLX+90vps5qXkR0alKpJq7Obq" +
"E/jOwi2q6vNmy90AAAAxIWSApHuog5j4KelzaTNUloHzZX/yl1csGWvDr94aN+TN" +
"kIX0wbfFFD/3sLrIm3zo9wAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAA" +
"AAAAAAAKMTg3Mjc0NTczNgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAA" +
"AAIxMQAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA0QUND" +
"VAAAAX4AAAAKMTg3Mjc0NTc0NgAAACEhyxtMnSycw7Agyf8otQJ4l3+dBGGxmiwv" +
"hPQBVbIZChUAAAAhIeCFWsm5ZAR1oSKwDvuq968uKEWrG8yeHg/z+DjB+LSJAAAA" +
"PjY4NzQ3NDcwM2EyZjJmNjY2MTY4NjU3OTJlNmU2MTZkNjUyZjZhNmY2ZTVmNjE2" +
"ZTZiNzU2ZTY0Njk2ZTY3AAAAAAAAAAEwAAAAAAAAADEhnoNgy2MYpZqChvAvuUK6" +
"CBUyZW+13hF920UkRWeztghueq9SQpgflbmcJRZNHPH/AAAAISGSz84xg3A6AJQF" +
"9IYAiRWm+6aAo+Elx7nHUnTOSJClvwAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAA" +
"AAABMAAAAAAAAAAKMTg3Mjc0NTc0NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAA" +
"AAAAAAAAAAIxMgAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3" +
"MTA0QUNDVAAAAYwAAAAKMTg3Mjc0NTc1NgAAADEhGIdprJWxd/VPfw+rLbbq2U9E" +
"OJ8fmmafAUinE9mJh2Piw0Dt5wC1NRLcrpnUCPxtAAAAISG53FZfu7sXpOcq9n83" +
"vL85SAKSnrEO1I12DwMNs/sV6gAAADw2ODc0NzQ3MDNhMmYyZjc0NzI2NTc1NzQ2" +
"NTZjNmI2OTY1Njg2ZTJlNmY3MjY3MmY2ZDYxNzI2MzZmNzMAAAAAAAAAATAAAAAA" +
"AAAAMSF67pO4h3QqKy9FFhKpxihsjI9MG0b4ANOsekIBuXdvBg0usIZqRskzySD9" +
"m3sqM/cAAAAhIV16dEXwW0dpTkKFa2SMXToJBWjH6g6WcNdSUtOv6JUUAAAAATAA" +
"AAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ1NzU2AAAAAAAA" +
"AAAAAAAAAAAAATAAAAABMAAAAAAAAAAAAAAAAjEzAAAAATAAAAAAAAAAATEAAAAB" +
"MAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABYgAAAAoxODcyNzQ1NzY2AAAA" +
"ISE2rzBtquT4KbKDNIgBZcTpY5Wqq0OFt+65lvoBOqTuCQAAACEhRMvVlJen73am" +
"EgLBa3i4+mb7Er3+PWfNPVkXOBD46JAAAAAyNjg3NDc0NzAzYTJmMmY2YzY1NjY2" +
"NjZjNjU3MjJlNjk2ZTY2NmYyZjYzNjg2MTc5NjEAAAAAAAAAATAAAAAAAAAAISFk" +
"bW//Ga0ZSLaQuduBTr2wQg3994ZlVS23PLrmoTC/IQAAACEhmeVc7QeEZez1ql1p" +
"gi8xykwV4BZKzF7E0onW2oAOvgwAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAA" +
"ATAAAAAAAAAACjE4NzI3NDU3NjYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAA" +
"AAAAAAACMTQAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEw" +
"NEFDQ1QAAAFNAAAACjE4NzI3NDU3NzYAAAAhIZ/uatMIc0Y2ZF+LbZUuisLpWNE7" +
"sEOLNUl14Yec8qqCAAAAAAAAAEA2ODc0NzQ3MDNhMmYyZjYyNzI2MTZiNzU3Mzc3" +
"Njk2YzZjNjk2MTZkNzM2ZjZlMmU2MzZmNmQyZjYyNzI2NTc0AAAAAAAAAAEwAAAA" +
"AAAAACEhiZ6UHPLcSrKVLRzKlOuAhhPGr5H39GJ17j2ZdmtBWkcAAAAhIYsZHdIB" +
"gMIwDgqGpbmG2mrwHeHlnqCYo4d+ev8txvTiAAAAATAAAAABMAAAAAEwAAAAATAA" +
"AAABMAAAAAEwAAAAAAAAAAoxODcyNzQ1Nzc2AAAAAAAAAAAAAAAAAAAAATAAAAAB" +
"MAAAAAAAAAAAAAAAAAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzcz" +
"MDc3MTA0QUNDVAAAAZwAAAAKMTg3Mjc0NTc4NgAAADEhmciPQ/oX/XcoxHJBR5XZ" +
"aSif1w2DU56kUZIjGmyYlank2qlK0S3IUcNQwAGo6W4FAAAAISHbIP/rAq2WzcM7" +
"qfes+H2rd6xRVwiZfDsa4npC5QhAqgAAAEw2ODc0NzQ3MDNhMmYyZjZiNzU2ZTdh" +
"NjU2ZjZiNzU2ZTY1NzY2MTJlNjk2ZTY2NmYyZjczNjg2MTc3NmU1ZjZjNjE2ZTY3" +
"NmY3MzY4AAAAAAAAAAEwAAAAAAAAADEh1rZcvQLPDGfwFLS9m+xB8pkTT2s8R8hS" +
"+KkGHNkBlUuvWijoE8o/d4SZjG4aeKMXAAAAISFBViTLvTjoM4/4f47d4Eazeh4i" +
"qBE9UaeH/bEV2nbxnQAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAA" +
"AAAKMTg3Mjc0NTc4NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAIx" +
"NQAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA0QUNDVAAA" +
"AUEAAAAKMTg3Mjc0NTc5NgAAACEh9+j0st/9S+BQB2EEkgeDi2QaltidD5q7jC4D" +
"kHPkQZMAAAAAAAAANDY4NzQ3NDcwM2EyZjJmNjM3MjZmNmY2YjczMmU2MzZmNmQy" +
"ZjczNjE2ZTY0NzI2OTZlNjUAAAAAAAAAATAAAAAAAAAAISEw8Nau8j29pJuVu1Yn" +
"+5rgPeNeRWEuQwmgf9vGzA6vmAAAACEhFBedhEe9UqyYRjmWZYflGqQvkTcxFcN/" +
"QlM4e48oZ6AAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4" +
"NzI3NDU3OTYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAAAAAAAATAA" +
"AAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABgAAAAAox" +
"ODcyNzQ1ODA2AAAAISHgFLmEN8n3CujAwhp9Ovukvkz5V7+CmIjkOi+dkxKuNgAA" +
"ACEh9OBhtr31mJFvWcbHNMCAd44KqzXIvgLiHPE+sbY6z/AAAAAwNjg3NDc0NzAz" +
"YTJmMmY2YjY1NmQ2ZDY1NzIyZTZmNzI2NzJmNjg2OTZjNzQ2ZjZlAAAAAAAAAAEw" +
"AAAAAAAAADEhrP3NRn7628agNyO/QQZxNF5s6kRH2lhndFMFxVX/8pkTkIcPGcTA" +
"lYRjrVWDBu7JAAAAMSE32B39KTGTPxbh2PkQqhbi75qsIfRgD4zPw96Sq5ckf7ER" +
"pv1ra7omvV0wVbeBV84AAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAA" +
"AAAACjE4NzI3NDU4MDYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAAC" +
"MTYAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QA" +
"AAGYAAAACjE4NzI3NDU4MTYAAAAxIaZRSACBHI6LWMPcUbL9BDPJBA6ezXxodjYX" +
"eeQnS5jHd3JWW5yQ5juFLioSS+0vcgAAACEhTbCYIRlc8Vp5a6MnPhZwN61RXsZ1" +
"RLLrB/lPKTSvlyoAAABINjg3NDc0NzAzYTJmMmY3NDcyNmY2ZDcwNjI2NTcyNmU2" +
"ODYxNzI2NDJlNjM2ZjZkMmY3NDcyNjU2MTJlNjg2OTcyNzQ2ODY1AAAAAAAAAAEw" +
"AAAAAAAAADEhM3Y9D0SUShS0/StfAeN5ZCCxs0NxNSnI5HkKJsrVy/Z3XpgPuBDJ" +
"MTOCczoM5/qhAAAAISHrEm5JWCe27yo+OyGBv2YsDhh1XGM7OdB+wYRBmc2uaAAA" +
"AAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NTgxNgAA" +
"AAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAIxNwAAAAEwAAAAAAAAAAEx" +
"AAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA0QUNDVAAAAZQAAAAKMTg3Mjc0NTgy" +
"NgAAADEhIimFHCGaaVBOe0mBxijAWbsc5rn5jkSsmIoJBV8i+zCrFKH/tC4ZCtly" +
"gczOpZj9AAAAISFAbpg8zACxOEHkUeKFepaecFumI2KadyBznEhWmnlFIQAAADQ2" +
"ODc0NzQ3MDNhMmYyZjc1NmM2YzcyNjk2MzY4MmU2OTZlNjY2ZjJmNjM2MTcyNmM2" +
"NTY1AAAAAAAAAAEwAAAAAAAAADEhUIKf99JmmX098GrUfxHr6/NLv8WU9UEGlZ1W" +
"KCd/08iqfS/2MqwUXoYCZ/3K+eEGAAAAMSGVA3zC9wpvKaAdTWTDyqVQiwQ35Ov8" +
"em8JA1fpb1gZNLB3JKLRxt7WHl85Eb2KxqAAAAABMAAAAAEwAAAAATAAAAABMAAA" +
"AAEwAAAAATAAAAAAAAAACjE4NzI3NDU4MjYAAAAAAAAAAAAAAAAAAAABMAAAAAEw" +
"AAAAAAAAAAAAAAACMTgAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3" +
"MzA3NzEwNEFDQ1QAAAFwAAAACjE4NzI3NDU4MzYAAAAhIcJw1qL5OWA5gHmfeSRP" +
"a1u2OacvtgC0gN2nqh2lP2TYAAAAISHVhEe8XadXg2zF535/xOvaMJqaxuT/L7D1" +
"10cxoVuVIgAAAEA2ODc0NzQ3MDNhMmYyZjcyNjk3MDcwNjk2ZTJlNmU2MTZkNjUy" +
"ZjYyNmY2ZTY5NzQ2MTVmNjg2OTYzNmI2YzY1AAAAAAAAAAEwAAAAAAAAACEhvzjc" +
"4db86CZmTzxTpe3n4EK7H2Gvg7PnKaxv8khTx+AAAAAhIUoEgdRme2H4ahRTxfzR" +
"KTYV2+BySfdStWnvP2zsvUfvAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEw" +
"AAAAAAAAAAoxODcyNzQ1ODM2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAAA" +
"AAAAAjE5AAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRB" +
"Q0NUAAABsgAAAAoxODcyNzQ1ODU2AAAAMSHIhRWCbYpBTEn7oVMBuJH8u78b40Z2" +
"tw7qPSpOi/los3O+MN+ckeyBRQafSSmO49YAAAAhIdcAclA642w11ibw/3sVFWLi" +
"brQ+UvzSwVlhBlYuDQdnAAAAYjY4NzQ3NDcwM2EyZjJmNjE3NTY2NjQ2NTcyNjg2" +
"MTcyNzI3NTZlNmY2YzY2NzM2NDZmNzQ3NDY5NzIyZTY5NmU2NjZmMmY2NjY1NmM2" +
"OTYzNjk2MTVmNzQ2ZjcyNzA2ODc5AAAAAAAAAAEwAAAAAAAAADEh9TfrO+Fwvhby" +
"J/AXH2f1Lm+2FgRR8otkUz6ofiY8IZKuGzfcnpVgTxFtVha8Gki1AAAAISHKG4L5" +
"CqgDQtGSNcLF+0wgd6ggfqryIT4aW4ZzbJOSXwAAAAEwAAAAATAAAAABMAAAAAEw" +
"AAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NTg1NgAAAAAAAAAAAAAAAAAAAAEwAAAA" +
"ATAAAAAAAAAAAAAAAAIyMAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAox" +
"MzczMDc3MTA0QUNDVAAAAXgAAAAKMTg3Mjc0NTg2NgAAACEhQE1Ye79tC4KS/FAz" +
"PyHjDV6xuCpJuqa7nNDJxmEc7k4AAAAhIQNekQjGv4ewrI6iEdRe63wx7oygqQVx" +
"UsQ3A4+otWeXAAAAODY4NzQ3NDcwM2EyZjJmNmM2ZjYzNmI2ZDYxNmU2Yzc5NmU2" +
"MzY4MmU2ZTY1NzQyZjYxNmM2MjYxAAAAAAAAAAEwAAAAAAAAADEhplJ5oQspBCJX" +
"J96eppbg1dhBqk64ImC0Le9niB0AJRuhUWGuCwqQs7++dir4ogYkAAAAISEgTMF5" +
"pv4GQ1KpVSr2rShvLkSaBHvzFvo/hVdjNqR6zQAAAAEwAAAAATAAAAABMAAAAAEw" +
"AAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NTg2NgAAAAAAAAAAAAAAAAAAAAEwAAAA" +
"ATAAAAAAAAAAAAAAAAIyMQAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAox" +
"MzczMDc3MTA0QUNDVAAAAZoAAAAKMTg3Mjc0NTg3NgAAADEhRMdg8/tq4PEVYWVK" +
"wMo0WEN3Yur3AX7lun+Kn7eS5aFf3GzaAAJIOpniDbupf1oZAAAAISEvuWGKizfq" +
"8zJybfTlt7GGaybp50DqxCCwIw4kC/GULwAAAEo2ODc0NzQ3MDNhMmYyZjYzNjE3" +
"MjcyNmY2YzZjNzM2MzY4NmQ2OTc0NzQyZTYzNmY2ZDJmNzc2OTZjNmM3OTJlNjU2" +
"ZDYxNzI2NAAAAAAAAAABMAAAAAAAAAAxIRGwGqXCb3tWMdTM0MevrA7izlSGq7R7" +
"QdHxlBvyX+sTKwF8q/U4bgaBfGOjdYKnWwAAACEhgPjXbuVA+QuUToPd/VpkP+v/" +
"B4yv4WrA1lbhDiQlYUYAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAA" +
"AAAACjE4NzI3NDU4NzYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAAC" +
"MjIAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QA" +
"AAGIAAAACjE4NzI3NDU4ODYAAAAxIVR6nvORUDTzLM2ccDbg4X5xWSwcd7lWUkpz" +
"TQkzgdvtshGthLiBgr9KWDPGkk70qQAAACEhQV3F6awFZJ/iHgqhmCccSxPo87Lp" +
"zYADyrvDzVm3iMoAAAA4Njg3NDc0NzAzYTJmMmY2NjY1Njk2YzJlNmU2NTc0MmY2" +
"ZTYxNzQ2MTczNjg2MTVmNjg2Zjc3NjUAAAAAAAAAATAAAAAAAAAAMSGifN07AIi3" +
"wSxPhnXERybIV55e1BewQMDTczO6f+UEM5JD3LHBg9x+i8rjjaWrOzEAAAAhIQdz" +
"q3+v8HjcJKUc7xb9+6NSLWKo+w7sTAPbF8hMm3Y+AAAAATAAAAABMAAAAAEwAAAA" +
"ATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ1ODg2AAAAAAAAAAAAAAAAAAAAATAA" +
"AAABMAAAAAAAAAAAAAAAAjIzAAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAA" +
"CjEzNzMwNzcxMDRBQ0NUAAABUwAAAAoxODcyNzQ1ODk2AAAAISHcbMpS37UtrNiw" +
"y7aZoDB2jKY5VKeJbF73QFU4lJskdAAAAAAAAABGNjg3NDc0NzAzYTJmMmY2NzZj" +
"NjU2MTczNmY2ZTZhNjE2Yjc1NjI2Zjc3NzM2YjY5MmU2MjY5N2EyZjYxNzU2Nzc1" +
"NzM3NAAAAAAAAAABMAAAAAAAAAAhIeeo3o1u8KJySEwNzY1v008/rDUxNBMjjVdz" +
"j7FSbCYfAAAAISH6pvRafbbMtp1AI7hJ0fjdVPajOsrRFVqhqo1diIgbHAAAAAEw" +
"AAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NTg5NgAAAAAA" +
"AAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAABMQAAAAEw" +
"AAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAGeAAAACjE4NzI3NDU5MDYAAAAx" +
"IW61eKunz6Xb4Arymj5hAv9f56jTEJlVZPSBinxGShzXBas3bTjIGRhbkTekskND" +
"RwAAACEhz+hKrf51+vOL+g8fvuyJSPKCcx73WEAB1dUn8u+kBXsAAABONjg3NDc0" +
"NzAzYTJmMmY3NzY5NmM2YjY5NmU3MzZmNmU2YzY1NjE2ZTZlNmY2ZTJlNmU2MTZk" +
"NjUyZjYyNzU2NDJlNzc2OTZjNmM2ZDczAAAAAAAAAAEwAAAAAAAAADEhhnDGWano" +
"GhnwVsEjnH5YvPW55hjLi+5m8VPp873jbrOMVe4eSgMOMdz6R81V2Y6lAAAAISGP" +
"ckyidKNfVX0l6wB/sUr+zDonEkt8ph94HsaXXsHLLgAAAAEwAAAAATAAAAABMAAA" +
"AAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NTkwNgAAAAAAAAAAAAAAAAAAAAEw" +
"AAAAATAAAAAAAAAAAAAAAAIyNAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAA" +
"AAoxMzczMDc3MTA0QUNDVAAAAX4AAAAKMTg3Mjc0NTkxNgAAACEhIxXNy4pUbU8z" +
"w0LfG59qS38wa8sY0Ho/iV07I/hdHZ0AAAAhIdKPEper6levT1HDFcjEeXaeY8sv" +
"CTU43zixIgF49gXIAAAALjY4NzQ3NDcwM2EyZjJmNzA3MjY5NjM2NTJlNjk2ZTY2" +
"NmYyZjc1NzI2MjYxNmUAAAAAAAAAATAAAAAAAAAAMSHZiSutgWI+cIm313+M9xet" +
"6yzJPYpF8/h32rZnfM5qUO0bCsZXenRPqGSpX5pFAokAAAAxIah32aDNd/L41Lzh" +
"lLgFmiKL36FNdW4J7QoODBtBEo+haSrtiEFNuJYTZfNdEDCSaQAAAAEwAAAAATAA" +
"AAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NTkxNgAAAAAAAAAAAAAA" +
"AAAAAAEwAAAAATAAAAAAAAAAAAAAAAIyNQAAAAEwAAAAAAAAAAExAAAAATAAAAAA" +
"AAAAAAAAAAoxMzczMDc3MTA0QUNDVAAAAVkAAAAKMTg3Mjc0NTkyNgAAACEhnHKG" +
"ExBpHQpFwzERx1pvpUw9wGGmzdCy5I5JPO+LdhEAAAAAAAAATDY4NzQ3NDcwM2Ey" +
"ZjJmNzA2MTc1NjM2NTZiNzQ3NTcyNjM2Zjc0NzQ2NTJlNmY3MjY3MmY2YjYxNjQ2" +
"OTZlNWY2NzY5NjI3MzZmNmUAAAAAAAAAATAAAAAAAAAAISGAcKkcAZQQeQBS77Zg" +
"d7KT4ox6vPScCpFCAqfGxyF0DQAAACEhF7CaZZbafKaUhk+fNE+xLweUfV16+9zP" +
"HBSM2UBsWrcAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4" +
"NzI3NDU5MjYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAAAAAAAATAA" +
"AAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABeAAAAAox" +
"ODcyNzQ1OTM2AAAAMSG9wsGHAKAy1+C0KCxALbmYvKff3uz/VwB612HaOw2F+alp" +
"I80cRPAODmEmIru4GmwAAAAhIZWsd0ncx3rwoCcZ9NeSOyye3O6BLsNk4noPSdkf" +
"bpaHAAAAODY4NzQ3NDcwM2EyZjJmNzI3NTZlNzQ2NTJlNjM2ZjZkMmY2MzYxNmQ3" +
"Mjc5NmUyZTY4NjE2ZTY1AAAAAAAAAAEwAAAAAAAAACEhLMHRM5rsCrQu2F3GOVWA" +
"Z2UFCixVGpdq83tnFrIk0h8AAAAhIe44XrrijvblrbT5iPzLMxWLud83cuXoy6mt" +
"toZDlJF+AAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcy" +
"NzQ1OTM2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAAAAAAAAjI2AAAAATAA" +
"AAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABigAAAAox" +
"ODcyNzQ1OTQ2AAAAISF2yEkIfLl7Ajsf0YVp4pdwfLPebMHUjD5t1Z8zoxjeagAA" +
"ACEhspchm7eXxpyy6CNinAtGNPThM5RFe/sVdNQ19pTXl0gAAAA6Njg3NDc0NzAz" +
"YTJmMmY2Yjc1NmM2MTczNmI2YzY1Njk2ZTJlNjk2ZTY2NmYyZjZlNzk2MTczNjk2" +
"MQAAAAAAAAABMAAAAAAAAAAxIS9HwLQWni0TBZMqQKmFdZ2oSvtDRFsTdqFe8P8c" +
"Yk7NQJBt4lyYLnB63twUAeWEJwAAADEhvQVarcMhBEuu0ForhuAX8DIMl7CQfmDB" +
"io/lvJPciLI6MJixWK9Tn6vOBMuLhSpJAAAAATAAAAABMAAAAAEwAAAAATAAAAAB" +
"MAAAAAEwAAAAAAAAAAoxODcyNzQ1OTQ2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAA" +
"AAAAAAAAAAAAAjI3AAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMw" +
"NzcxMDRBQ0NUAAABggAAAAoxODcyNzQ1OTU2AAAAISEsQ5H+p6k+/lE3UtzgktRL" +
"NuBOZ78szV04ZQhWqaLAcAAAACEh+4RkoGkaAOREFTBbkr+7j2kcFXdoUX9epm6e" +
"hbaHxjcAAABCNjg3NDc0NzAzYTJmMmY3MzYzNjg2MTY1NjY2NTcyMmU2OTZlNjY2" +
"ZjJmNmM2NTczNmM2OTY1MmU2MjZmNjc2MTZlAAAAAAAAAAEwAAAAAAAAADEh2FnB" +
"pIHlJoXCCjBDYMPnFTgD93rhg/45CQphpCA7aeErTY6zBvwn+rTo4lVGsrrdAAAA" +
"ISGRjWDv3wjtjdP4P9Z5WO/HQ8XJ5oCPMXEn1raT5ls97gAAAAEwAAAAATAAAAAB" +
"MAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NTk1NgAAAAAAAAAAAAAAAAAA" +
"AAEwAAAAATAAAAAAAAAAAAAAAAIyOAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAA" +
"AAAAAAoxMzczMDc3MTA0QUNDVAAAAXYAAAAKMTg3Mjc0NTk2NgAAACEhUYoAXo4M" +
"zWu+MmrXMigKluN9UJtOrOA4WXbIWy/PbdIAAAAhIZxV+QFIyL1YG6PLx+ZnjL3p" +
"tMq1wYU6g/7sr8or8Si7AAAARjY4NzQ3NDcwM2EyZjJmNmU2MTY0NjU3MjcyNjU2" +
"ZDcwNjU2YzJlNmU2NTc0MmY2Nzc3NjU2ZTVmNzM2MzY4NmQ2OTY0NzQAAAAAAAAA" +
"ATAAAAAAAAAAISHKTNAq4v2W12jAahJnG0LAIACiJA+7gyVNYN92upz3JAAAACEh" +
"p5i1vp06RA/WhfZObM4wV3KcVliYGzHw/V4rlU0TosEAAAABMAAAAAEwAAAAATAA" +
"AAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDU5NjYAAAAAAAAAAAAAAAAAAAAB" +
"MAAAAAEwAAAAAAAAAAAAAAACMjkAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAA" +
"AAAKMTM3MzA3NzEwNEFDQ1QAAAF8AAAACjE4NzI3NDU5NzYAAAAxId4VFZGCTWXr" +
"j4xQXFpk8tcZsy3E6RGp9NbLrg9ZwQar9jrZv7ID1hwJsYXayPzdFAAAACEhF54x" +
"UhH8yMXvFHi6ZCFmLAbB2lggCDQqIknhi8HM+1sAAAA8Njg3NDc0NzAzYTJmMmY2" +
"NDZmNmY2YzY1NzkyZTY5NmU2NjZmMmY2MTZjNjU2YjVmNzA2MTcyNmI2NTcyAAAA" +
"AAAAAAEwAAAAAAAAACEhAt8Mu6ecm7T+rGwHWfz68rIDJl24ac3ZH2QsNiYtcIEA" +
"AAAhIQUx5F972yrpW+f9iPemLRfzZmEXTeddYh5FYgIIhoNqAAAAATAAAAABMAAA" +
"AAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ1OTc2AAAAAAAAAAAAAAAA" +
"AAAAATAAAAABMAAAAAAAAAAAAAAAAjMwAAAAATAAAAAAAAAAATEAAAABMAAAAAAA" +
"AAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABkgAAAAoxODcyNzQ1OTg2AAAAMSFctg/x" +
"qezfr1hwKzUCtxWN0TjN8ANA9ZbZUERX+/qLHJQup7o0Mj5XcpIpmAl0aWsAAAAh" +
"IcGbzhx5ScC7b55/yvXtxwi/yG5gx4vg2bz6w9Q6G02qAAAAQjY4NzQ3NDcwM2Ey" +
"ZjJmNmE2ZjY4NmU3MzJlNmU2MTZkNjUyZjYzNmY2Yzc1NmQ2Mjc1NzMyZTY0NmY2" +
"ZjZjNjU3OQAAAAAAAAABMAAAAAAAAAAxIWLfo4j24vstNR/p8NYSrP+xHOy05DNx" +
"vaB97a1r5gRApXnVDtAZzsOriidjgsXORwAAACEhzO+TfzZsgaSKkwVOPRk1m1WN" +
"OzkviDjC0bj/je3cKg4AAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAA" +
"AAAACjE4NzI3NDU5ODYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAAC" +
"MzEAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QA" +
"AAF+AAAACjE4NzI3NDU5OTYAAAAxIUYf7M6iePmYVtOOdv0B9Mozb8cKmIFSbYwM" +
"NOneeTpPEaP3TZIO2pkg0ga6SS2K4gAAACEhdi67SeZgy7Wr/mNaggGVaOnI0NcW" +
"u6n/jJqMqL63lUQAAAAuNjg3NDc0NzAzYTJmMmY2MjYxNzU2MzY4MmU2ZjcyNjcy" +
"ZjZkNjE3MjZjNjk2ZQAAAAAAAAABMAAAAAAAAAAhIWNxIegSHbcqsTw0CCV3gULh" +
"V6Y2LRi6Vun+cbxazWq8AAAAMSEBSbLQTX2NKTwu+0TZNUwagKnHCMTHnw+Q3PCZ" +
"t3CSOU9MPeEXl2a50drLEiRSIZAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAA" +
"ATAAAAAAAAAACjE4NzI3NDU5OTYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAA" +
"AAAAAAACMzIAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEw" +
"NEFDQ1QAAAFgAAAACjE4NzI3NDYwMDYAAAAhIUcBac23/F98Pwy/FSWJMGfEQVEr" +
"Vmz8uJiW0ndhsHbVAAAAISGqxjmXDgHposEvOwIzXMM/wIPTaXmE6K2LMu+WvRBC" +
"awAAADA2ODc0NzQ3MDNhMmYyZjY0NzU2Mjc1NzE3NTY1MmU2MzZmNmQyZjZhNjE2" +
"MzY1NzkAAAAAAAAAATAAAAAAAAAAISEaL/HykudSEtIvCV4IZLmGVpRjO42P4prW" +
"+BrhJwbCTwAAACEhGQIAi2dOCY+71CfKKLrelcbyGQX5X9LuaLYUMy9DihUAAAAB" +
"MAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDYwMDYAAAAA" +
"AAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAACMzMAAAABMAAAAAAAAAABMQAA" +
"AAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAFiAAAACjE4NzI3NDYwMTYA" +
"AAAhId82S/9iRPDUriavRfqNVUhEGZOX08ECOnuaojPykIKAAAAAISHqqFJGu5eh" +
"qOtr4bEHV5mficeDT2fVkf+LDCKWMCeZ9gAAADI2ODc0NzQ3MDNhMmYyZjczNjM2" +
"ODY5NmU2ZTY1NzIyZTZmNzI2NzJmNzA3MjY5NjM2NQAAAAAAAAABMAAAAAAAAAAh" +
"IS7XEzV9BA7EJEAwHlBxchTS64GqXT79huR1/o3vIMaCAAAAISH6Rh1DDkPHs0Sv" +
"wmSkzoS/D23FFui7SeNffUnMuO4AIgAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAA" +
"AAABMAAAAAAAAAAKMTg3Mjc0NjAxNgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAA" +
"AAAAAAAAAAIzNAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3" +
"MTA0QUNDVAAAAVsAAAAKMTg3Mjc0NjAyNgAAACEhKzg8FWTtLVnsx/q5hLxbOkcn" +
"e/ypclJgm7BN3p/zsFYAAAAAAAAAPjY4NzQ3NDcwM2EyZjJmNzQ2ZjcyNzAyZTZl" +
"NjU3NDJmNzM2ODc5NjE2ZTZlNjUyZTczNmQ2OTc0Njg2MTZkAAAAAAAAAAEwAAAA" +
"AAAAADEhQX/IAe7mSCwFyHIFWT4ckp2VqD4KkkfvzvzEJFwXI7ZNmH1SvZqvFziL" +
"U0Rkp7AGAAAAISFh6Ou1peyH/2balpLVMvjQNUPtJZo69s4hmcCl/S1m4AAAAAEw" +
"AAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjAyNgAAAAAA" +
"AAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAABMQAAAAEw" +
"AAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAFXAAAACjE4NzI3NDYwMzYAAAAh" +
"Id0gI+Cr9oVISRJI+WSG5zK2nLbTZxYUnR66RF1Gh4JaAAAAAAAAADo2ODc0NzQ3" +
"MDNhMmYyZjZkNjE2ZTc0NjUyZTYzNmY2ZDJmNjM2MTY5NjU1ZjczNzQ3MjY1Njk2" +
"MzY4AAAAAAAAAAEwAAAAAAAAACEh/QMWW3D0w5CeocXshs+ucAWyxwmiNchiwYoB" +
"6V2oOYwAAAAxIaPEUHR/4e325btZoD4F/PY9/iqT6+NTy1QlFn8sOJuO73XOru8a" +
"NRxNP5JVdjNeKgAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAK" +
"MTg3Mjc0NjAzNgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAAAAAAB" +
"MAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAGaAAAA" +
"CjE4NzI3NDYwNDYAAAAhIe3ccgsU8mUbkDYOwQv4NJ4OAyqU8VZJOTiUd+USdVtL" +
"AAAAISHPfxoXKRXWeeBvuKovJYvHIZJFiD2AXNY1IZ5bbqZ7nAAAAEo2ODc0NzQ3" +
"MDNhMmYyZjczNzc2MTZlNjk2MTc3NzM2YjY5MmU2ZjcyNjcyZjc3NjU2ZTY0NjU2" +
"YzZjNWY2NzYxNzk2YzZmNzI2NAAAAAAAAAABMAAAAAAAAABBIfQUgwe7+CAYi4L3" +
"v5Nqd3882yA1x4DsP9MHnoIuxZfMwL30DWyVMZgRdIyz+pzoUB3BuTmpyT27+iem" +
"J9TCvw4AAAAhIUczUTh5lR8H7Ktgpuqs1gxES8B9t200WVcR7Qpp9PCnAAAAATAA" +
"AAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ2MDQ2AAAAAAAA" +
"AAAAAAAAAAAAATAAAAABMAAAAAAAAAAAAAAAAjM1AAAAATAAAAAAAAAAATEAAAAB" +
"MAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABTQAAAAoxODcyNzQ2MDU2AAAA" +
"ISFois9KEuC2s4n6+S4iIfxoPyaICVq5eAnmVnRt+IjEVQAAAAAAAABANjg3NDc0" +
"NzAzYTJmMmY3MjZmNmM2NjczNmY2ZTJlNjM2ZjZkMmY3NzY5NmM2Yzc5NWY2MjYx" +
"NzI3NDY1NmM2YwAAAAAAAAABMAAAAAAAAAAhIUUANM5pwqxsxpSIR12nl8MIEH2d" +
"gzPDjs3akFpSViFaAAAAISHnnvsbor3lJDmegn0727nV7i+T4xwr4mHPdpMD+AoS" +
"qAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjA1" +
"NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAB" +
"MQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAFyAAAACjE4NzI3NDYw" +
"NjYAAAAhIT3aUadIp7a4npcPewKyUNmM571IfUBI3HonHGqhFvKDAAAAISEtgPTq" +
"ASDU7nJMFiBIQgmLNLs2Rf73uAyvCojBZznxMQAAAEI2ODc0NzQ3MDNhMmYyZjYz" +
"NmY2YzZjNjk2ZTczNzI2NTY5NjM2ODY1NmMyZTZlNjU3NDJmNzk2MTczNmQ2OTZl" +
"NjUAAAAAAAAAATAAAAAAAAAAISHyXlSAi4MAqz/VfXdgBn05h52/TMidVmsXbiye" +
"ePviSgAAACEhm1pnAzRXD1lZ7E5w8u4hWlA6ZfoAEn0OgnG4i0P7NZAAAAABMAAA" +
"AAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDYwNjYAAAAAAAAA" +
"AAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAACMzYAAAABMAAAAAAAAAABMQAAAAEw" +
"AAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAGIAAAACjE4NzI3NDYwNzYAAAAh" +
"IS6Zh5Ri+NYQTzg3DUClYCs8WHCYJMcSRjqAbtxJpiFaAAAAISE/FW6hUIGfpHVy" +
"OjQ5Y3oexM/pbESQXSzZSs7DEx45ZQAAAEg2ODc0NzQ3MDNhMmYyZjY0NjU2MzZi" +
"NmY3NzJlNmU2NTc0MmY3MjZmNmY3MzY1NzY2NTZjNzQyZTZiNzM2ODZjNjU3MjY5" +
"NmUAAAAAAAAAATAAAAAAAAAAMSGo7CEeh4bG90RwATzYPM3JH6U5RXJKMy6sZ5vL" +
"AHjrnWjSX2AMDegxFFxZA2euXssAAAAhIRQ4hn15n/NJMhOAfXcwQfD838qSTiMW" +
"3Jm9L8n03FEyAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAox" +
"ODcyNzQ2MDc2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAAAAAAAAjM3AAAA" +
"ATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABgQAA" +
"AAoxODcyNzQ2MDg2AAAAISGzuJy2/x0bzTTo5NZNRwqUmrQuRlFd3dF4BICxsjwi" +
"WgAAAAAAAABkNjg3NDc0NzAzYTJmMmY2MzZmNmU3MzY5NjQ2OTZlNjU2ODY1Njk2" +
"NDY1NmU3MjY1Njk2MzY4MmU2ZTYxNmQ2NTJmNmU2MTZkNjUyZTYzNjg3MjY5NzM3" +
"NDY5NjE2ZTczNjU2ZQAAAAAAAAABMAAAAAAAAAAxIRr+9XJWPmE4/AG7+Pb0Ks8N" +
"D8/7aC18pUrAyp9kbODPMms0fFnL/yZA/ad2xfS50wAAACEhYu5vWJSOS+ui86sl" +
"CfaoQ8oUxXGQGr6z+15FToZdk0AAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAA" +
"ATAAAAAAAAAACjE4NzI3NDYwODYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAA" +
"AAAAAAAAAAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRB" +
"Q0NUAAABYAAAAAoxODcyNzQ2MDk2AAAAISHDPPYOG+t5Z2olWjktpv9ONj9GtSrB" +
"zhEzPN4E3dORUAAAACEhNno60cEl6iYI5QvcGwalaVlou8ciQkyDcXScg6X5MtMA" +
"AAAwNjg3NDc0NzAzYTJmMmY2MjZmNjc2OTczNjk2MzY4MmU2ZTY1NzQyZjZjNmY3" +
"MjY5AAAAAAAAAAEwAAAAAAAAACEhA0cQrJycpr3/lFSJ8mRaVxxYFqaEq8SWeeGH" +
"kL0zA7oAAAAhIcq2yHDSlHc9T8KKsjYWPpHNaR/F9Gix38FLEuNHnJ+gAAAAATAA" +
"AAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ2MDk2AAAAAAAA" +
"AAAAAAAAAAAAATAAAAABMAAAAAAAAAAAAAAAAjM4AAAAATAAAAAAAAAAATEAAAAB" +
"MAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABTQAAAAoxODcyNzQ2MTA2AAAA" +
"ISERFSfjI3TjPMa0kTR1GR50OjZ/EiLvDiqW6CDzyuUuVQAAAAAAAAAwNjg3NDc0" +
"NzAzYTJmMmY2ODY1NzI3YTZmNjcyZTZlNjE2ZDY1MmY2Yzc1Njk2NzY5AAAAAAAA" +
"AAEwAAAAAAAAADEhJE3xkPvg7pMNLEHaUJwff5QT6ZLrXAqHIIOhJ+/xjI5ZMR3K" +
"gWdPoqRKWTI1hTuOAAAAISHg5oGEGzA/npjXns+NvIuIx80syiLBG8+IVOjQkcaw" +
"MwAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjEw" +
"NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAAB" +
"MQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAF8AAAACjE4NzI3NDYx" +
"MTYAAAAxIR+rniCxFedvT5iPsV+wriz/eUGqUDjSUVvgWx++Ie8SpuixV2oLJek3" +
"5QlsXpUpdAAAACEhA/oyqcYV/FLwZ/bwWmpw411m0Yw7xEIrSlTD84jBzdcAAAAs" +
"Njg3NDc0NzAzYTJmMmY2ZDYxNmU2ZTJlNjM2ZjZkMmY2MzY1NjM2OTZjNjUAAAAA" +
"AAAAATAAAAAAAAAAMSHTlqBR1p5KTloaXsqfkCtKXfnnkhBud6vb2lrKt9TgHbzz" +
"FmisdDtXdPOayMyjIA8AAAAhIRa8RGSt4sHV3kBWgWtmzffe0eQY13rGXh+aTQqu" +
"QlTbAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ2" +
"MTE2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAAAAAAAAjM5AAAAATAAAAAA" +
"AAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABgAAAAAoxODcy" +
"NzQ2MTI2AAAAMSF5MfDk4jYK0etH9leG6MO7EBSFlr5N29bfk2aH8WOf6PW1E82G" +
"hVy6jyldOud6wakAAAAhIRs3CcQDvzx4kT89JGnOSoLaYkQOJ5wcH07foV8Zl8w7" +
"AAAAMDY4NzQ3NDcwM2EyZjJmNjQ2ZjZmNmM2NTc5MmU2ZTYxNmQ2NTJmNjU3NzYx" +
"NmM2NAAAAAAAAAABMAAAAAAAAAAxISBUh/zVQKwBdHsI1zLcz9/V686lIrsDg1Y4" +
"oL21SljpYgGYgXUJomOI9PUnjj/F2QAAACEhWopo9RqMg0T6LeHA1ouIoR6s9uBn" +
"T4GdUb+8LyOSuloAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAA" +
"CjE4NzI3NDYxMjYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAACNDAA" +
"AAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAGq" +
"AAAACjE4NzI3NDYxMzYAAAAxIbMZ3DBnzDDDh7eUUesvL3gFnLLJWDwDKJdWk4iL" +
"2AcmCOXZEjAM6AOis0Dy0CZM5AAAACEhXk0HduCrtiALdG21CCdcDsw5WD09Vzlt" +
"HgBKPVjPbFkAAABaNjg3NDc0NzAzYTJmMmY2MjYxNmM2OTczNzQ3MjY1NzI2OTZk" +
"NjM2MzZjNzU3MjY1MmU2MzZmNmQyZjZhNjE3MTc1NjE2ZTVmNzc2OTZjNmI2OTZl" +
"NzM2ZjZlAAAAAAAAAAEwAAAAAAAAACEhiUn0XC5CEOI/x/ZPf8pnfBwCHVDWN6MP" +
"klIaKSK9+mYAAAAxIa1LGBP4wk8fbn9CjFbeYzwIZoX1Kgry55/SKi8vjhoSTBwK" +
"jKasZIdygJMhODEVqQAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAA" +
"AAAKMTg3Mjc0NjEzNgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAI0" +
"MQAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA0QUNDVAAA" +
"AV8AAAAKMTg3Mjc0NjE0NgAAADEhK3mh+y52pwKRaNPCkf2itmwOWCf+ihpxwkYY" +
"qRWmQUFJFaYVfWEqjf+rjkOLupx2AAAAAAAAADI2ODc0NzQ3MDNhMmYyZjcwNmY3" +
"NTcyNmY3MzJlNmU2NTc0MmY2YTY1NzI2NTZkNjk2NQAAAAAAAAABMAAAAAAAAAAh" +
"IQz4rm0x0oifUs7U79kkwk2KZZ7RWw76GLZfZM2jFDmoAAAAMSHuKArDA7E6S7MY" +
"7YYjW5oENQti+8AhNRIRmvm3ZJoDH/8AzsjP7VwZCeCNXDi5+rkAAAABMAAAAAEw" +
"AAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDYxNDYAAAAAAAAAAAAA" +
"AAAAAAABMAAAAAEwAAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAATEAAAABMAAAAAAA" +
"AAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABogAAAAoxODcyNzQ2MTU2AAAAMSG7//UM" +
"gswtSfMRaL+bnmoiL1VNggfiqWrW+ydbIPxULtrvGgel1i/fIsxZ+tKbGy0AAAAh" +
"IcjhBXk5Y2nNSIor79shd7xmBDaO7Xdnuc7SWo0fv+3IAAAAQjY4NzQ3NDcwM2Ey" +
"ZjJmNmI2NTZjNjU3MjJlNjk2ZTY2NmYyZjZlNjk2YjY5NzQ2MTJlNmM2OTZlNjQ2" +
"NzcyNjU2ZQAAAAAAAAABMAAAAAAAAAAxIRQAwLVE2YVFMOZJftKR4ERR1jI111VM" +
"xOHVfymc1Nb/VMfvKPcugRyFnToJ5FXt8gAAADEho+zPg8+KNDX5ZyozfI+foxnd" +
"4M1wfV5XyqO+3iPgbMGSgB/EuAqVCf9vPY8fgDf5AAAAATAAAAABMAAAAAEwAAAA" +
"ATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ2MTU2AAAAAAAAAAAAAAAAAAAAATAA" +
"AAABMAAAAAAAAAAAAAAAAjQyAAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAA" +
"CjEzNzMwNzcxMDRBQ0NUAAABggAAAAoxODcyNzQ2MTY2AAAAISGrWq0AxhTXoiug" +
"tHw2J/31Ec04r0hpJUGvooLiOV5ghgAAACEhdEJ1EZw4nIA/bIaL5Fb/urcMoAf8" +
"4uRmjnvkNZf61dMAAABCNjg3NDc0NzAzYTJmMmY2YTYxNzM2YjZmNmM3MzZiNjky" +
"ZTYzNmY2ZDJmNjM2ZjZlNmU2NTcyNWY2ZjcyNzQ2OTdhAAAAAAAAAAEwAAAAAAAA" +
"ADEhL1bEVgVPSRUz8DcNcIByBGss/2eixkW0Y/nqgKrSdYG0kMFd0Pfb9iNu5h4R" +
"wSnmAAAAISEi4LXgtoJUiILwN9uVsPNumBtSrq8CrPXhhCPqY+LZpgAAAAEwAAAA" +
"ATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjE2NgAAAAAAAAAA" +
"AAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAI0MwAAAAEwAAAAAAAAAAExAAAAATAA" +
"AAAAAAAAAAAAAAoxMzczMDc3MTA0QUNDVAAAAYIAAAAKMTg3Mjc0NjE3NgAAADEh" +
"qTunGI7LVuA6smQ5NUl/QAdp0BpFBZ86DxXcu9GIPjulrbfm7D8rbLlK+hyrrPUR" +
"AAAAISF/eCndbZ7sty8Fk5GacdtCSAoe4UlUJmeA0+bfRhWb1QAAAEI2ODc0NzQ3" +
"MDNhMmYyZjYzNjg2MTZkNzA2YzY5NmUyZTZmNzI2NzJmNmM3NTY1NWY3MzYzNjg3" +
"MjZmNjU2NDY1NzIAAAAAAAAAATAAAAAAAAAAISHlHxpgVAUJAiECPC2RJ6/cJl8w" +
"VbPqsL9MINg0d2HcvAAAACEhcNCDj79e3CRAemHtbExcOM0yS/eiXvyLs58RfTHV" +
"4c8AAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDYx" +
"NzYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAACNDQAAAABMAAAAAAA" +
"AAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAGAAAAACjE4NzI3" +
"NDYxODYAAAAhIQwGNLfZsRLpZCmV9LYbZUQipCsK0h/iwz/F0sdXGljHAAAAISEy" +
"nfcjxV48zNP1YQL0G+fczKb9WYYKN/yvim5CoVQWgAAAAEA2ODc0NzQ3MDNhMmYy" +
"ZjY0NmY2ZTZlNjU2YzZjNzk2MTY0NjE2ZDczMmU2MzZmNmQyZjczNjE2ZTc0Njk2" +
"ZTZmAAAAAAAAAAEwAAAAAAAAACEhr5OqXVgwE4Cm5pJ7dBbJ/5MR+odlcYi68jT8" +
"/d2ZqPwAAAAxIcqzbJKVdtdhP57PWMymBWVaLF/3OhGnBpRaGd3m9MtBhwbJDRuQ" +
"znGbA3QzZTT6EwAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAK" +
"MTg3Mjc0NjE4NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAI0NQAA" +
"AAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA0QUNDVAAAAZAA" +
"AAAKMTg3Mjc0NjE5NgAAADEh11IPQ+cUTTBgD145Il6mGe6388poazsKm27r2rgQ" +
"2I2rPR+vvH822BmmHqieiS77AAAAISFBRBjsh6QoJPEAikbmliMNGIJOiKXD0POg" +
"XU28iLWtPgAAAEA2ODc0NzQ3MDNhMmYyZjZjNjE3MjZiNjk2ZTYzNmY2ZTczNjk2" +
"NDY5NmU2NTJlNmY3MjY3MmY2YzY1NmY2YzYxAAAAAAAAAAEwAAAAAAAAADEhOp67" +
"pjeKjn3jZvND4y6Spl+0Uf5sfT4uT/6XdU7EQjL1mIc4KFKITq9u8bZyMfbvAAAA" +
"ISFDKO6UmiN55Vz/Z1nE9wgMIggkRFLSfoEWtOFxBxm4gQAAAAEwAAAAATAAAAAB" +
"MAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjE5NgAAAAAAAAAAAAAAAAAA" +
"AAEwAAAAATAAAAAAAAAAAAAAAAI0NgAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAA" +
"AAAAAAoxMzczMDc3MTA0QUNDVAAAAWgAAAAKMTg3Mjc0NjIwNgAAACEhivEANkoW" +
"2ebUjJQ1zqte5o5Lm+n7/0diEkqe0IF0gwoAAAAhIaBuyDnnjdcSg6CpOio1F0EY" +
"hTlnREYYRBn23/oNcYWtAAAAODY4NzQ3NDcwM2EyZjJmNzI3NTZlNzQ2NTZkNmY2" +
"NTZlMmU2ZTYxNmQ2NTJmNzA2OTY1NzI3MjY1AAAAAAAAAAEwAAAAAAAAACEhTp3L" +
"/Io2JJhFs4xZauBDMM7CDOZN9aEWbzO20rKqcW8AAAAhIRazdF90kyS1RTrapUfd" +
"ZCIG5h767SrwDO1O0cv+qh4HAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEw" +
"AAAAAAAAAAoxODcyNzQ2MjA2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAAA" +
"AAAAAjQ3AAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRB" +
"Q0NUAAABbgAAAAoxODcyNzQ2MjE2AAAAISFKhsuIHlq9ZK8qj7V6l34zT2Y4SaW7" +
"e8vrBQg4wUmt2QAAACEhZP+ucMFHVfuqhnkbse0AdEl+gwiMAaFzNIQ7E2Azp4gA" +
"AAAuNjg3NDc0NzAzYTJmMmY2ZDZmNmY3MjY1MmU2OTZlNjY2ZjJmNzA2NTYxNzI2" +
"YwAAAAAAAAABMAAAAAAAAAAhIfSeNtDnxF+rrgC2lqoAp5fOEYzeZoWC22pGjnLR" +
"jvflAAAAMSFGQQA1zXOD46JDl7KlJOOdNKqvf4zUEAAvCvSzYil4PoZEmpEhzORM" +
"82wjFD8ycXcAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4" +
"NzI3NDYyMTYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAACNDgAAAAB" +
"MAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAGWAAAA" +
"CjE4NzI3NDYyMjYAAAAhIfzsPBb9zw+znGr4dJ9oi+K9Kasa6HGl9KeaNzyjZnDz" +
"AAAAISHOX7VYz7NdFBpwqA5SWOlwVYg9QsxgzCQ1Pg+rnoHQDQAAAEY2ODc0NzQ3" +
"MDNhMmYyZjYxNzI2ZDczNzQ3MjZmNmU2NzY4NjE2MzZiNjU3NDc0MmU2ZTYxNmQ2" +
"NTJmNmE2MTY1NjQ2NTZlAAAAAAAAAAEwAAAAAAAAADEhQ6EOU47TD4aNTeAqrKvn" +
"0meY9qJPPxBR9Plfn/uN1Kp6ZWDuYWM0XNNG2U+suAY9AAAAMSGnFX55n8slGEuC" +
"4VixBBjncWn4DCOckmOZlXbMJGojAdxm6ItEBUkXZRfoJqCrSg8AAAABMAAAAAEw" +
"AAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDYyMjYAAAAAAAAAAAAA" +
"AAAAAAABMAAAAAEwAAAAAAAAAAAAAAACNDkAAAABMAAAAAAAAAABMQAAAAEwAAAA" +
"AAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAGYAAAACjE4NzI3NDYyMzYAAAAhIZ6M" +
"UDsd3cxd81PLuLGbefM0evo6JDhjC3mFemUTexW4AAAAISF1SZY7/6ii9QquiGk3" +
"ZSBSKy06zeI7hfepQ2HlEObtCwAAAFg2ODc0NzQ3MDNhMmYyZjczNjM2ODc1NmM2" +
"OTczNzQ2ZDY1NzQ3YTJlNjk2ZTY2NmYyZjY1NzM3MDY1NzI2MTZlN2E2MTVmNjM3" +
"NTZkNmQ2NTcyNjE3NDYxAAAAAAAAAAEwAAAAAAAAADEh3UA8lPeFoYOCGcoMqpad" +
"cfn91UaHAZ84jzzrluB/tUsNlkOKGYEEnYogobIeyY2IAAAAISFvuhLWcLczKxUv" +
"TPzCREpwVZhz5JnBiHgtFQXHzbE4bgAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAA" +
"AAABMAAAAAAAAAAKMTg3Mjc0NjIzNgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAA" +
"AAAAAAAAAAI1MAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3" +
"MTA0QUNDVAAAAXoAAAAKMTg3Mjc0NjI0NgAAADEh+6+5E2dpwHAahj8HhghS7Tiz" +
"atIe+K/38mBeat2wIGuLBl1QBuzlAz/HAM4wJs5RAAAAISFMXZCT5hUyeLF6c73d" +
"GIBFhIv2JElNHRLU9FDwTiQ8UQAAADo2ODc0NzQ3MDNhMmYyZjYyNjU2NTcyNmQ2" +
"OTZjNmM3MzJlNmU2NTc0MmY2NDYxNmU2OTY1NmM2YzY1AAAAAAAAAAEwAAAAAAAA" +
"ACEh+k828kKLO01oMkW/DYji9UXLzE0LYCbqda1NZZmdmeEAAAAhIYBS4wjSMEDX" +
"JoA5/5rvJe/qiAlVSCl3yvKpwgo23eFQAAAAATAAAAABMAAAAAEwAAAAATAAAAAB" +
"MAAAAAEwAAAAAAAAAAoxODcyNzQ2MjQ2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAA" +
"AAAAAAAAAAAAAjUxAAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMw" +
"NzcxMDRBQ0NUAAABUQAAAAoxODcyNzQ2MjU2AAAAISGW8+9kctjuPK6X5L9r6zOm" +
"lgpvvX6j0/2UR5ve7qyW3gAAAAAAAAA0Njg3NDc0NzAzYTJmMmY2NDZmNzU2NzZj" +
"NjE3MzJlNmU2MTZkNjUyZjcwNmY3Mjc0NjU3MgAAAAAAAAABMAAAAAAAAAAxIaiv" +
"pvk7dppj/nPolImh7AFR2kx4cANrGRYyAvIbeHY/KwTYM5Ck0O8Gkm1jdNxSXAAA" +
"ACEhiCOqIxGHXnB0Zoey+TP+gUovtRZQ3lU79xhLzCoOx8sAAAABMAAAAAEwAAAA" +
"ATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDYyNTYAAAAAAAAAAAAAAAAA" +
"AAABMAAAAAEwAAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAA" +
"AAAACjEzNzMwNzcxMDRBQ0NUAAABdgAAAAoxODcyNzQ2MjY2AAAAISFv+mMv2B/U" +
"Q2BdUUHBjU6866hJAgc67yKhuMoAJxXRuAAAACEhPaLJhgtFmmyF33KXEcUfCIxW" +
"BEBAZqgl4Eerx0wE0JEAAABGNjg3NDc0NzAzYTJmMmY2NDZmNmU2ZTY1NmM2Yzc5" +
"MmU2MzZmNmQyZjc0Nzk3MjY5NzE3NTY1NWY2YzYxNmU2NzZmNzM2OAAAAAAAAAAB" +
"MAAAAAAAAAAhISydgPK/e1rJplm2wN1+4yTz56+EKDmsbiq+1uYcN027AAAAISFe" +
"8CoPyaC3aS0wEwpXrZGKWIo4hlZb7bje85a6dzyf9AAAAAEwAAAAATAAAAABMAAA" +
"AAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjI2NgAAAAAAAAAAAAAAAAAAAAEw" +
"AAAAATAAAAAAAAAAAAAAAAI1MgAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAA" +
"AAoxMzczMDc3MTA0QUNDVAAAAW4AAAAKMTg3Mjc0NjI3NgAAACEh3LwiezAkEUR+" +
"j9usrYMiyyqeOYR+6PKzYRBlE22FfpoAAAAhIbBjmikiDf/gGMftxTr1uY4XR21R" +
"8UObVLnnhgIC+EkYAAAALjY4NzQ3NDcwM2EyZjJmNzM2MzY4NmY2NTZlMmU2OTZl" +
"NjY2ZjJmNmQ2MTYzNzkAAAAAAAAAATAAAAAAAAAAMSECrpe5ZtQ6RB3CYz5V5hE9" +
"KVKEIRn1Fh4c3hW4CAXQ8n10k8lnIXisyEMn+PH+8M0AAAAhIX1mKNsOAMrhn7cl" +
"E9XBmVfkUMzcrLY7PWyDTGi46Zy9AAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAA" +
"AAEwAAAAAAAAAAoxODcyNzQ2Mjc2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAAAAAA" +
"AAAAAAAAAjUzAAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcx" +
"MDRBQ0NUAAABfQAAAAoxODcyNzQ2Mjg2AAAAMSH+Pt5lvMdF2sZltKJuzRxWW5+R" +
"518B7+oeoX1pCk8Re1OAImuUvARJ06aoSsH2PQ8AAAAAAAAAQDY4NzQ3NDcwM2Ey" +
"ZjJmNzM2MzY4NzU3MDcwNjUyZTYzNmY2ZDJmNzI2ZjczNjU3NDc0NjEyZTc5NzU2" +
"ZTY0NzQAAAAAAAAAATAAAAAAAAAAMSF51wnU/8MQL0M2I1KRg/VRXoBm7EyuAPdz" +
"gicb+jPMj5uCqLGkO6yw71F7EmHYF44AAAAxIfcdgP77/uyU/+FuliVhRDQVup3h" +
"CwNBTKpcjksC8vg4nXW3n9PBJZ9csWw9ric9mAAAAAEwAAAAATAAAAABMAAAAAEw" +
"AAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjI4NgAAAAAAAAAAAAAAAAAAAAEwAAAA" +
"ATAAAAAAAAAAAAAAAAAAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3" +
"MzA3NzEwNEFDQ1QAAAGAAAAACjE4NzI3NDYyOTYAAAAhIf9jc91gmE4zEOM45EtG" +
"NTDZfJysY54eXl4Mm4gZ62F0AAAAISEThT3gw6D9nq7lbUehPOGZZScqeBBopIzr" +
"N314io+HsQAAADA2ODc0NzQ3MDNhMmYyZjY2NjU2OTZjMmU2MzZmNmQyZjY5NzM2" +
"MTYyNjU2YzZjNjUAAAAAAAAAATAAAAAAAAAAMSGTi2pOr8iisupbXnGcstLDjTmy" +
"hL1dMh/GZfOwI1ROZNnm5739s4BimxGSa2YqNC0AAAAxIb7ncD0hULxm09sIMeZy" +
"7OGBYtVHu3nRKdnhSO4ORH+g5ekRiuRrR5lZ6o6tCI2lkAAAAAEwAAAAATAAAAAB" +
"MAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjI5NgAAAAAAAAAAAAAAAAAA" +
"AAEwAAAAATAAAAAAAAAAAAAAAAI1NAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAA" +
"AAAAAAoxMzczMDc3MTA0QUNDVAAAAV8AAAAKMTg3Mjc0NjMwNgAAADEhk8jUgvJn" +
"090+fAf6MJBipK6AxFQ+ZDheQzDCeoivsc3jv0i/62miiB80RDF6UMoiAAAAAAAA" +
"ADI2ODc0NzQ3MDNhMmYyZjZkNjM2YjY1NmU3YTY5NjUyZTZlNjU3NDJmN2E2MTcy" +
"Njk2MQAAAAAAAAABMAAAAAAAAAAxIeRkk2vH0Asii+9greWOFnT9Yh7byhKdRIJH" +
"7Nt60VYt5m0Gd/0f0g3WPmxMNUCw5wAAACEhOkJc3e9C9dwhnAu0zVVBeOo3gBwu" +
"D0s9clIUYV9kvskAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAA" +
"CjE4NzI3NDYzMDYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAAAAAAA" +
"ATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABpAAA" +
"AAoxODcyNzQ2MzE2AAAAMSHqrjdVh7SyJdm/i/QdveoHr0EmFm2dKysPmxUwIyz8" +
"dStajfUR8UuecrJkDpcfE2gAAAAhIagNh8jpaaAgHvWQ6dIp/TinfIRiAtdNKzli" +
"A2Qcjj8PAAAARDY4NzQ3NDcwM2EyZjJmNzc2ODY5NzQ2NTZiNmM2ZjYzNmI2ZjJl" +
"NmU2MTZkNjUyZjZjNjE2MzY1NzkyZTY0NjE3MjY1AAAAAAAAAAEwAAAAAAAAADEh" +
"+gQF+NEN0o11e4QQcvHmVAzzlAL8378JeJHYiLx5oys3Hux8rm8V5Wmefw29sAN0" +
"AAAAMSFdcr3phRXBfJNB7mcqyGcxhq7Oa8Y0tBuseTXMXpDn+PEN2E2AxmmtG4Go" +
"lkrOmqsAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3" +
"NDYzMTYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAACNTUAAAABMAAA" +
"AAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNEFDQ1QAAAF2AAAACjE4" +
"NzI3NDYzMjYAAAAxIVK90J3XMPZAFuRp6Osn5EkFu3jHT8XBpNzVESLLl2QuyGkx" +
"H1eaoWtQu9znoH8d3AAAACEhDKRI7S5YTtlSsgQOM56/q4NWLlvLw0s+eCACoUqy" +
"2HAAAAA2Njg3NDc0NzAzYTJmMmY2ZjZiNzU2ZTY1NzY2MTJlNjI2OTdhMmY2YzY5" +
"NzM2MTZlNjQ3MjZmAAAAAAAAAAEwAAAAAAAAACEhoAKmn3YZpzOlVaWh7DH41IL7" +
"Fscmahm5cou/nr1YDMEAAAAhIVsDiiobgbm4IusJeTIpJYqUGTXar5OsoExjFCHt" +
"CVMqAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ2" +
"MzI2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAAAAAAAAjU2AAAAATAAAAAA" +
"AAAAATEAAAABMAAAAAAAAAAAAAAACjEzNzMwNzcxMDRBQ0NUAAABoAAAAAoxODcy" +
"NzQ2MzM2AAAAMSFU6SKNW6QfLGsMUOh6SDiCJTkLkqgooMJjQnu67ggENVvCNJXY" +
"/k4PLO0EVYe0F9sAAAAhISu0qI6/0edzHljLC2LY6IZyC+C5uih4/NzmxnMysCXU" +
"AAAAQDY4NzQ3NDcwM2EyZjJmNzM2MTc1NjU3MjZiNzU3NjYxNmM2OTczMmU2OTZl" +
"NjY2ZjJmNjI3MjYxNzg3NDZmNmUAAAAAAAAAATAAAAAAAAAAMSF90O1BZfKqUWt3" +
"0H6m9sQGvHoaO21DvtTQ/DglAFnIXHltZ528s1EoRElwxNHj3pAAAAAxIRwmpCAn" +
"PcbgJdgmONJ/3yan8wqRNxwva6eTfvfYJ6VyO/T1GR9ytQ/4YuKIRcFXWQAAAAEw" +
"AAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjMzNgAAAAAA" +
"AAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAI1NwAAAAEwAAAAAAAAAAExAAAA" +
"ATAAAAAAAAAAAAAAAAoxMzczMDc3MTA0QUNDVAAAAT8AAAAKMTg3Mjc0NjM0NgAA" +
"ACEhWHIlbPdrg1cxYw12zp/pT4NXK1251UvT7sQAxZvDRJ4AAAAAAAAAMjY4NzQ3" +
"NDcwM2EyZjJmNzM3MDY5NmU2YjYxMmU2OTZlNjY2ZjJmNmI2NTZlNjQ3MjYxAAAA" +
"AAAAAAEwAAAAAAAAACEhopsZrJCftw32PVUKDFNPeDazeyR+x3g9tdOF4i8EtlgA" +
"AAAhIW5MiA5bQIegxeMVVVvSIxIJMhw8jl2VOkFR5dMNk6moAAAAATAAAAABMAAA" +
"AAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ2MzQ2AAAAAAAAAAAAAAAA" +
"AAAAATAAAAABMAAAAAAAAAAAAAAAAAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAA" +
"AAAAAAoxMzczMDc3MTA0QUNDVAAAAWwAAAAKMTg3Mjc0NjM2NgAAACEhgaOpYMbJ" +
"z03Hg74f+VxVhArquOV7s3SrsaPlKKKBzHQAAAAhIT8AG2KA6BljbGz6JB1c4W+Q" +
"pevHAnl3Ry04T6OhydrRAAAAPDY4NzQ3NDcwM2EyZjJmNzA2Zjc1NzI2ZjZkNjk3" +
"NDY4NjE2ZDJlNmU2MTZkNjUyZjY1NjY3MjYxNjk2ZQAAAAAAAAABMAAAAAAAAAAh" +
"Ifjbyraq5+KMagWUJNytVJ90ZmAsh+s/Y68K4tgv6iTcAAAAISGCFBhinuNKk5m7" +
"TWJ6ZQyYoPFljt89RKIGbm3FE6PkMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAA" +
"AAABMAAAAAAAAAAKMTg3Mjc0NjM2NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAA" +
"AAAAAAAAAAI1OAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3" +
"MTA1QUNDVAAAAVEAAAAKMTg3Mjc0NjM3NgAAACEhT0031xQ/fE7hclg1kZbaqDXV" +
"+R82hh/wuo/aBkRlm0UAAAAAAAAARDY4NzQ3NDcwM2EyZjJmNjg2NTY5NjQ2NTZl" +
"NzI2NTY5NjM2ODJlNmU2NTc0MmY3Mjc5NjE2ZTZlNWY2ODYxNzk2NTczAAAAAAAA" +
"AAEwAAAAAAAAACEhPWUFEFPqutbf6MAvc7Fc8T77ELjBjqTS3fmYd3HDcAEAAAAh" +
"IaoV06azgsaZ1IP71foi65sfmwkZyDultYjBzSZohFDnAAAAATAAAAABMAAAAAEw" +
"AAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ2Mzc2AAAAAAAAAAAAAAAAAAAA" +
"ATAAAAABMAAAAAAAAAAAAAAAAAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAA" +
"AAoxMzczMDc3MTA1QUNDVAAAAX4AAAAKMTg3Mjc0NjM4NgAAACEh6nj/Gqvp52rR" +
"VczHT/rehNK9VjgvEUqxNY8IQO/4sV4AAAAhIbSNbyYuKDi8vFWoN+OBdCneJ4at" +
"SJpmSP3p6ohJ94JZAAAAPjY4NzQ3NDcwM2EyZjJmNmY2YjY1NjU2NjY1NjQ2MTZk" +
"NmY3MjY1MmU2MjY5N2EyZjY3Njk2Zjc2NjE2ZTY5AAAAAAAAAAEwAAAAAAAAADEh" +
"lbQt9/ORxb2Nat6AYieI7rj2BrxlZhomVvMexifb73pKu5ZHHmBP9y2Ob/zIbq6L" +
"AAAAISE5UbIwhatj9gc5xyOl54RdobqcmIg22iqS/zpI51KItQAAAAEwAAAAATAA" +
"AAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjM4NgAAAAAAAAAAAAAA" +
"AAAAAAEwAAAAATAAAAAAAAAAAAAAAAI1OQAAAAEwAAAAAAAAAAExAAAAATAAAAAA" +
"AAAAAAAAAAoxMzczMDc3MTA1QUNDVAAAAX4AAAAKMTg3Mjc0NjM5NgAAADEh26zB" +
"cIcYY7x6GqCqvOsF1DDLdYD0jt9NqwrScomHZ4byJtmyK1+DPlbhkhRiAEilAAAA" +
"ISHx5jHsfYubswaeDNgl2qloJBpWGJf87m+TT5O3zRbBnAAAAD42ODc0NzQ3MDNh" +
"MmYyZjY0Njk2MzZiNjk2MjZmNzM2MzZmMmU2MjY5N2EyZjdhNjE2MzY4NjE3MjY5" +
"NjE2OAAAAAAAAAABMAAAAAAAAAAhIQuOoAGzVTssrRbtg4dyDiTcHUtsx1sWDTPc" +
"IAXoRsT3AAAAISGHCH8TUm702itAbe82iWvFjdwCZj0HkPIfclWbW6417wAAAAEw" +
"AAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjM5NgAAAAAA" +
"AAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAI2MAAAAAEwAAAAAAAAAAExAAAA" +
"ATAAAAAAAAAAAAAAAAoxMzczMDc3MTA1QUNDVAAAAXYAAAAKMTg3Mjc0NjQwNgAA" +
"ACEhN5YTsEv5p9MjV/B5nPNetm726M1lsqCX/graNnGXTPcAAAAhIdhvOYLMAhx0" +
"DQGNdnyD5aPZxzJMrR0FMFvh4zMhiKyRAAAARjY4NzQ3NDcwM2EyZjJmNmI3NTZl" +
"N2E2NTZkNzU3MjYxN2E2OTZiMmU2ZTY1NzQyZjZhNmY2ODZlNmU3OTJlNmI2ZjYz" +
"NjgAAAAAAAAAATAAAAAAAAAAISFWU2xUQyWpi3pEUBjFSthhtWWORIsnZ4BadLkX" +
"3baQnAAAACEhzQVeTO7cJfirtx5qIX393cLNYdYW1ytORG01QWfWcR0AAAABMAAA" +
"AAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDY0MDYAAAAAAAAA" +
"AAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAACNjEAAAABMAAAAAAAAAABMQAAAAEw" +
"AAAAAAAAAAAAAAAKMTM3MzA3NzEwNUFDQ1QAAAGKAAAACjE4NzI3NDY0MTYAAAAx" +
"IY8zvMfWHSRx1+G5SwVzbgOlMZZk8MZHRyaddVbzwSt89lsGOij4defG9Rw1nNSP" +
"SgAAACEhpnF0CCVu/s1ReU/UcClvoIRdm6ls8iiCPfTP/iq2Ta8AAABKNjg3NDc0" +
"NzAzYTJmMmY2ODYxNzI3MjY5NzMyZTZlNjE2ZDY1MmY3MjZmNzM2MTZjNjk2ZTY0" +
"NWY2ZDYxNzI3MTc1NjE3MjY0NzQAAAAAAAAAATAAAAAAAAAAISFcwR2UwzK5wXYW" +
"nn5wBqvAxTkROjU1KEhRWXgZ8QPgGwAAACEhwt+Z3UwKxRVtjiBu2aV2B3rp4zQb" +
"UkpRb9Xnolie6VYAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAA" +
"CjE4NzI3NDY0MTYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAAAAACNjIA" +
"AAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNUFDQ1QAAAGQ" +
"AAAACjE4NzI3NDY0MjYAAAAxIcau1MQfKYFvcyd43jYAKADsjGg4JaIuQxxMOeUf" +
"Pkk7ekC7rPOMgUcUmQeqOEAvmQAAACEhVnhVvy+q5BoBlgG28yZj00hgUrpwNk08" +
"mezvGgs6P+AAAABQNjg3NDc0NzAzYTJmMmY3Mjc1NmU2ZjZjNjY3MzY0NmY3NDc0" +
"Njk3MjJlNmU2MTZkNjUyZjZlNjk2MzZiNmM2MTc1NzM1ZjY4NjE3OTY1NzMAAAAA" +
"AAAAATAAAAAAAAAAISE4S+TZaeEgkoSQJuGyZewfdFtZ7J0KUPB/P1CQ8GueegAA" +
"ACEhwVO2MK+u2tRq3d6ZeCYfy8vtsw0SRpGTZPRbWXkeWIkAAAABMAAAAAEwAAAA" +
"ATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDY0MjYAAAAAAAAAAAAAAAAA" +
"AAABMAAAAAEwAAAAAAAAAAAAAAACNjMAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAA" +
"AAAAAAAKMTM3MzA3NzEwNUFDQ1QAAAFzAAAACjE4NzI3NDY0MzYAAAAxIV4H0EZb" +
"dEL/QdJXHUFuOc36ZRh+VU5XmQGsLEtCHxX4x4wMloS0H3D8GYesBb2e9AAAAAAA" +
"AABGNjg3NDc0NzAzYTJmMmY2ZjcyNjU2OTZjNmM3OTJlNjk2ZTY2NmYyZjY0NjE2" +
"ODZjNjk2MTVmNjQ2ZjZlNmU2NTZjNmM3OQAAAAAAAAABMAAAAAAAAAAxIbLAZeQ0" +
"4zfYy6ocJ3420t18WDcoQ/8v4mNJrUEt4AtzgF+rwA0JflHE9t6HwcurYwAAACEh" +
"9lh/HLXHkvlHFXil5zSnsrpW6kX2fU9jiv1sX/Ue0OwAAAABMAAAAAEwAAAAATAA" +
"AAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDY0MzYAAAAAAAAAAAAAAAAAAAAB" +
"MAAAAAEwAAAAAAAAAAAAAAAAAAAAATAAAAAAAAAAATEAAAABMAAAAAAAAAAAAAAA" +
"CjEzNzMwNzcxMDVBQ0NUAAABiAAAAAoxODcyNzQ2NDQ2AAAAMSGrKahsenlFqPnV" +
"lmjW6pNI+96JYSUiHraJXyF4lQjs6di7u4n8AiUtFFhBSNakJNAAAAAhIadyuMaD" +
"CSh17uwbG2oGp2HezHnQls4i4MDEaXtgrEbyAAAAODY4NzQ3NDcwM2EyZjJmNzI2" +
"MTc0NjgyZTZlNjU3NDJmNmM2NTY5NjY1ZjY4NjU3MjZkNjE2ZTZlAAAAAAAAAAEw" +
"AAAAAAAAADEhBIgUGgVVgTQHqOTicVtkCMPL0FOI4VPaZmQbpjcwF/iRn21B3fCz" +
"Fsp357ehcwyaAAAAISGqE6XJGWnYtxkNfUOR6tNp+IvkccEdIGHgTJjHH0yOiQAA" +
"AAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjQ0NgAA" +
"AAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAI2NAAAAAEwAAAAAAAAAAEx" +
"AAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA1QUNDVAAAAYoAAAAKMTg3Mjc0NjQ1" +
"NgAAACEhZkA4xoPDy4bgy7ZKfe9aIRdJqTNU8wxcgChdxW/d83sAAAAhISHBtvN1" +
"YUsZY0IIE6gwJCCFgzY5CIEG4qeoYTO3y6cZAAAAOjY4NzQ3NDcwM2EyZjJmNzM2" +
"MzY4NmQ2OTY0NzQ2ZDY1NzI3NDdhMmU2ZTYxNmQ2NTJmNmI2OTcyNjEAAAAAAAAA" +
"ATAAAAAAAAAAMSEhCDNKrrqp9guf4Uiwgt7n2M+zBHHY18NCymJ5zy2S5jZ1B51J" +
"GbxzrA2+dY3YgNQAAAAxIQDSGhz+Uj/7Q5AQqV3ZxpSYSwUWn6V1dtLHnjq2OIbj" +
"WbuB+XvIhjCAPEjuJ4GWkAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAA" +
"AAAAAAAKMTg3Mjc0NjQ1NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAA" +
"AAI2NQAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA1QUND" +
"VAAAAX4AAAAKMTg3Mjc0NjQ2NgAAACEhvQQWSEN4Q9F6DpAZmDYR7rGt6hdb5jAm" +
"aNYuzrNJwJQAAAAhIescncg6gMVW7n9v/IR3uVnhg11QsWmjt13ZLWN3tk0iAAAA" +
"LjY4NzQ3NDcwM2EyZjJmNmQ2ZjZmNzI2NTJlNjI2OTdhMmY2MTZlNjk2MjYxNmMA" +
"AAAAAAAAATAAAAAAAAAAQSHEjDC/J8AM/5+IcD6QL8IYiUd2+zCWE/r4BygYvKt+" +
"AvhWz0Mk/jtAk3MJKfkK2NTd5H0XiGeFKIaZ+R51HEPNAAAAISFQImWVvnLxb4ww" +
"7plDgbfhWgWm000webb6iCd0ANjnqwAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAA" +
"AAABMAAAAAAAAAAKMTg3Mjc0NjQ2NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAA" +
"AAAAAAAAAAI2NgAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3" +
"MTA1QUNDVAAAAWYAAAAKMTg3Mjc0NjQ3NgAAACEh1UMRSOR6rSnNpoBrQ8dcU6Id" +
"ZvFAlwGyF776j2iIePEAAAAhIRJ+Is82ejxYBD89T1xLgFdLJdYkfmOFDw8kpn4h" +
"SnM0AAAANjY4NzQ3NDcwM2EyZjJmNmM2NTc1NzM2MzY4NmI2NTJlNjM2ZjZkMmY2" +
"NDYxNzA2ODZlNjU3OQAAAAAAAAABMAAAAAAAAAAhIRRhvc0h1K1Ia5XM2NL/2uv6" +
"nJs9xzw4EgEdgPO/jqNHAAAAISF4UBbivLN4vGOEJNMoNp06C+tk7/r9qUQ3llPO" +
"k6iyBQAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0" +
"NjQ3NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAI2NwAAAAEwAAAA" +
"AAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA1QUNDVAAAAV4AAAAKMTg3" +
"Mjc0NjQ4NgAAACEhNDsGOVJdXNVJJYTl5KraHxdsxIog6NQuymajYSXkeVgAAAAh" +
"IU6tnMOtDTKlxZkrL4ocYAfFhgTDV3/UHNld+ie9LHeoAAAALjY4NzQ3NDcwM2Ey" +
"ZjJmNjM3MjZmNmU2OTZlMmU2ZTY1NzQyZjYzNzk3MjY5NmMAAAAAAAAAATAAAAAA" +
"AAAAISHB6qFDZ5CLTuSTEZkt2lKxSYkWwXiSFXBEUC92WRowHwAAACEhpMuL0lvS" +
"xLjDtwYHXcluFCm6zxL+5lsRZAGKMyVtuDoAAAABMAAAAAEwAAAAATAAAAABMAAA" +
"AAEwAAAAATAAAAAAAAAACjE4NzI3NDY0ODYAAAAAAAAAAAAAAAAAAAABMAAAAAEw" +
"AAAAAAAAAAAAAAACNjgAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3" +
"MzA3NzEwNUFDQ1QAAAF6AAAACjE4NzI3NDY0OTYAAAAxIQaQDPg3JmzYujNUhwdk" +
"x8uKsB5E2YxKXSNVgX/j/T4kN+bsKxoE173N7N3UuW3vBwAAACEhmoKCnmzdmcBm" +
"OwfLFHBQS51W+53P246QhgIUXrQUbnEAAAA6Njg3NDc0NzAzYTJmMmY3Mzc0NjU3" +
"NTYyNjU3MjJlNjM2ZjZkMmY2MTZjNjk1ZjY3Njk2MjczNmY2ZQAAAAAAAAABMAAA" +
"AAAAAAAhIdAikrlhzlhz8r33P2Stw/Zn4RXVv0sE5DnGbY2/Y7PEAAAAISHsr7jL" +
"jaATZw6veoWRfmHiBNFbZjhKWRpc1qCMLI/djQAAAAEwAAAAATAAAAABMAAAAAEw" +
"AAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjQ5NgAAAAAAAAAAAAAAAAAAAAEwAAAA" +
"ATAAAAAAAAAAAAAAAAI2OQAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAox" +
"MzczMDc3MTA1QUNDVAAAAYIAAAAKMTg3Mjc0NjUwNgAAADEhdj8sGtoiaRhR2ukP" +
"VM2EqRlS8rw7vOnAN6HKek9LJEqzPlEPyzNlsQpwJF8Ruu17AAAAISG1AUGnPJRu" +
"ZwhuOzelbQFTZl0ekVmENixE18fpdRWkYAAAAEI2ODc0NzQ3MDNhMmYyZjZiNjU3" +
"Mjc0N2E2ZDYxNmU2ZTJlNjI2OTdhMmY2YTYxNzk2NDZmNmU1ZjZiNzU2ZTdhNjUA" +
"AAAAAAAAATAAAAAAAAAAISHKnHE7GVST7ukUNNcWxUiMhlcljy/X31n5OCqVdODb" +
"EwAAACEhcDIPTXpUMoxulC2fHPNr0eqUHvzEdpEYPi6IaJ/W4koAAAABMAAAAAEw" +
"AAAAATAAAAABMAAAAAEwAAAAATAAAAAAAAAACjE4NzI3NDY1MDYAAAAAAAAAAAAA" +
"AAAAAAABMAAAAAEwAAAAAAAAAAAAAAACNzAAAAABMAAAAAAAAAABMQAAAAEwAAAA" +
"AAAAAAAAAAAKMTM3MzA3NzEwNUFDQ1QAAAGeAAAACjE4NzI3NDY1MTYAAAAxISbs" +
"q/LHUzxe9WZcGips3Wth3v8SZPEwH/MmwWCGTo7HXG7uexsrRHSkzHVWDNGWjQAA" +
"ACEh1xU+wdTpc+Kv1M61y33JISYaZZOZQuFEhrXnkd3lknkAAABONjg3NDc0NzAz" +
"YTJmMmY2Nzc1NzQ2YjZmNzc3MzZiNjk3MjYxNzUyZTZmNzI2NzJmNjQ2ZjcyNjEy" +
"ZTc3Njk2YzZjNjk2MTZkNzM2ZjZlAAAAAAAAAAEwAAAAAAAAADEhdk7n/+SQFAL7" +
"2dz2bep6hKa+1RxqVtMMOjNn0KVgFaWyEhY9F6+BzhRjqtApGET7AAAAISEJsfL0" +
"LEAMyrJ+JDZQ8sMmZ3aQtZpUCSF2aZzIC/uiIAAAAAEwAAAAATAAAAABMAAAAAEw" +
"AAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjUxNgAAAAAAAAAAAAAAAAAAAAEwAAAA" +
"ATAAAAAAAAAAAAAAAAI3MQAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAox" +
"MzczMDc3MTA1QUNDVAAAAYQAAAAKMTg3Mjc0NjUyNgAAACEhCH2dW2TvT05XAoqC" +
"i5GtSXCKhtCLcIp2oEhtK6NaBAoAAAAhIZC18+hzJxeUCkBwWy75C1pYz2+OOLZ0" +
"K2ctNl1Vo2GcAAAARDY4NzQ3NDcwM2EyZjJmNjI3NTYzNmI3MjY5NjQ2NzY1MmU2" +
"ZTY1NzQyZjZjNjE3NTcyNjU3NDc0NjEyZTc2NjU3NTZkAAAAAAAAAAEwAAAAAAAA" +
"ADEhMz3QU9XsQ9YRGZf5WndY4i6M65cZp/dXdPPfkYRjhECB8OwbPozZZr3GAlL0" +
"mniTAAAAISH35JWqSpN0G/ryr8wN4cm8JQx39xSv/WwDd481RWMLZgAAAAEwAAAA" +
"ATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjUyNgAAAAAAAAAA" +
"AAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAI3MgAAAAEwAAAAAAAAAAExAAAAATAA" +
"AAAAAAAAAAAAAAoxMzczMDc3MTA1QUNDVAAAAVsAAAAKMTg3Mjc0NjUzNgAAACEh" +
"rZAymsLlKg8EmVqRzZuf4n9Bc3Ag/O28MQFRuYjaZzUAAAAAAAAAPjY4NzQ3NDcw" +
"M2EyZjJmNjM3NTZkNmQ2OTZlNjc3Mzc3NjU2ODZlNjU3MjJlNjI2OTdhMmY2MTcw" +
"NzI2OTZjAAAAAAAAAAEwAAAAAAAAADEhywe4mNI06dhIJhx68RLj2Zzj3gYbi3cR" +
"U+fBf9RkIRW5OTGWRxfC5rIepNfY5gXtAAAAISFwTCUl/eIsU0NqyrhI+E3HLMDP" +
"GqBohKWb3ALCab+K4QAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAA" +
"AAAKMTg3Mjc0NjUzNgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAAA" +
"AAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNUFDQ1QAAAFN" +
"AAAACjE4NzI3NDY1NDYAAAAhIZohkZeduize24bhEB34LGC5MKD8ZKivHChDMSnI" +
"CbE7AAAAAAAAAEA2ODc0NzQ3MDNhMmYyZjY3NzI2MTY0NzkyZTYyNjk3YTJmNmQ2" +
"ZjY4NjE2ZDZkNjU2NDVmNjI3MjYxNmI3NTczAAAAAAAAAAEwAAAAAAAAACEhUIgb" +
"cpIZAQJxF9rxK6XtDWFiyR84IBR7vlpBHx7fmkoAAAAhIR9DUEY85kTttQlzgFgZ" +
"qcnAKW1FNA76tVl2q/o0p+6DAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEw" +
"AAAAAAAAAAoxODcyNzQ2NTQ2AAAAAAAAAAAAAAAAAAAAATAAAAABMAAAAAAAAAAA" +
"AAAAAAAAAAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA1QUND" +
"VAAAAXwAAAAKMTg3Mjc0NjU1NgAAADEhruEMVK972nEfSiAWnnvmpgnBiONiM3JT" +
"g29++iaGwyaR5x7D2C7/+0G/WrTGvV04AAAAISFEPu/XMRbV0DBbJiFUs3C0/nm2" +
"pYJT8tu+Ho+QdOAtDgAAADw2ODc0NzQ3MDNhMmYyZjY3NmY3NDc0NmM2OTY1NjIy" +
"ZTZlNjE2ZDY1MmY2NTZjNjk3MzYxNjI2NTc0NjgAAAAAAAAAATAAAAAAAAAAISF9" +
"4WILdSHxrR6qzEEMy07FURJnAp770+ppyJM/KG4wqwAAACEhwEs7wyKYcIJ05lS8" +
"+gIWX7uWA8yMhCFlBxrdl/LAWmAAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAA" +
"ATAAAAAAAAAACjE4NzI3NDY1NTYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAA" +
"AAAAAAACNzMAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEw" +
"NUFDQ1QAAAF4AAAACjE4NzI3NDY1NjYAAAAhISrRosN67ZDNH2xyB3d4ywdJaAD8" +
"s34SagHcl2TGk150AAAAISF8S/LT9cg1/b0QErA5SPznZmnshsvfjePbLpTKHVRQ" +
"aAAAADg2ODc0NzQ3MDNhMmYyZjY0NjE2MzY4Njc2OTczNmM2MTczNmY2ZTJlNmY3" +
"MjY3MmY2MTZjNzY2MQAAAAAAAAABMAAAAAAAAAAxIakkKSxfhSFpGH0hU7sjoZJ/" +
"JEk2XFuvU26H15BZYZC5K22lBRKNp2MROQkzTr5RHwAAACEhk1UjSMVmdD40Ilkw" +
"TFe6iEXFZ0HFU/kV14EOVGGOko4AAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAA" +
"ATAAAAAAAAAACjE4NzI3NDY1NjYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAA" +
"AAAAAAACNzQAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEw" +
"NUFDQ1QAAAGeAAAACjE4NzI3NDY1NzYAAAAhIWV5XeJcLDDr88ffAGB3fAMXUDTZ" +
"H5VxZ9+jaKHbwOSLAAAAISFC0s+hSulEiuF//bbQ/+5tz+1k2aV2H2ZYLakrwvqN" +
"gAAAAD42ODc0NzQ3MDNhMmYyZjcyNjk2MzY1MmU2OTZlNjY2ZjJmNjc2OTZmNzY2" +
"MTZlNmU3OTVmNjU2MjY1NzI3NAAAAAAAAAABMAAAAAAAAABBISrH3GQCdKEtSu3j" +
"8JGQAmt0bb3N5rMndYdPdpZ04dB3P0PjBqyAW6cGg/ycoNJlIRI6iykCa+aiJB1w" +
"JiomzcwAAAAxIYi6OcqI1uilWb3yE6T/lSyJZfZGoZM2GTaPK2u7OvuCA4BbdZvh" +
"XytlitWmRYsFigAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAK" +
"MTg3Mjc0NjU3NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAI3NQAA" +
"AAEwAAAAAAAAAAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA1QUNDVAAAAWMA" +
"AAAKMTg3Mjc0NjU4NgAAACEhPxthU1wxY1Vfg9FtdzPeaM16ul3vD9ewKUwi0LYx" +
"P4YAAAAAAAAARjY4NzQ3NDcwM2EyZjJmNjc2YzZmNzY2NTcyNmQ2MzZiNjU2ZTdh" +
"Njk2NTJlNjk2ZTY2NmYyZjZiNjE3NDY1NmM3OTZlNmUAAAAAAAAAATAAAAAAAAAA" +
"MSG7r/Ki2TpMoKgYPY6hvy4pkYnySbIRetT2uKIOT0Y08ldKqJpFHpvtZ+jjw7RY" +
"QWIAAAAhIS8zsOjIHPVGtEMzb496ThecPslNg9xnysv7txkZNvrWAAAAATAAAAAB" +
"MAAAAAEwAAAAATAAAAABMAAAAAEwAAAAAAAAAAoxODcyNzQ2NTg2AAAAAAAAAAAA" +
"AAAAAAAAATAAAAABMAAAAAAAAAAAAAAAAAAAAAEwAAAAAAAAAAExAAAAATAAAAAA" +
"AAAAAAAAAAoxMzczMDc3MTA1QUNDVAAAAWQAAAAKMTg3Mjc0NjU5NgAAACEhEbPb" +
"uJsF57lzoIq6F2FKQhgRRAHvN0KIcSuzs8n/jpYAAAAhIekaX0ey4afkTz5BHXGv" +
"A2UOsZh8CYt56eKNR1hLPyJvAAAANDY4NzQ3NDcwM2EyZjJmNzM2OTcwNjU3MzJl" +
"NjM2ZjZkMmY2YTZmNjU3OTJlNmQ2NTc0N2EAAAAAAAAAATAAAAAAAAAAISFFsZHh" +
"NE2jfzflVu2rCoI9yYXShSD22+bIYCqX1bJn2AAAACEhmFKfi0Y4UQ4dVKQLnZWw" +
"LfrmyXG44I9R2KD/547mCsoAAAABMAAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAA" +
"AAAAAAAACjE4NzI3NDY1OTYAAAAAAAAAAAAAAAAAAAABMAAAAAEwAAAAAAAAAAAA" +
"AAACNzYAAAABMAAAAAAAAAABMQAAAAEwAAAAAAAAAAAAAAAKMTM3MzA3NzEwNUFD" +
"Q1QAAAFoAAAACjE4NzI3NDY2MDYAAAAhIUHNGYLU9wBDjFH4cQd5wpL8cvIG1uJF" +
"Z47PcbT4zNJYAAAAISHUq0bIfBWiDXXoroCW6B3zQk0zfiBsrIi+A0CQZQ0HnAAA" +
"ADg2ODc0NzQ3MDNhMmYyZjYyNjU3MjZlNjk2NTcyMmU2ZjcyNjcyZjY3NjE2NzY1" +
"NWY2ODYxNjE2NwAAAAAAAAABMAAAAAAAAAAhIcqK9nXa9CORzJLL17L0HQCur+St" +
"+FnhL4oQAfk9z5uiAAAAISGcPvE/fXdL9HU69fCNLk6kmu4L/Hb7N/K9584AVe+o" +
"qQAAAAEwAAAAATAAAAABMAAAAAEwAAAAATAAAAABMAAAAAAAAAAKMTg3Mjc0NjYw" +
"NgAAAAAAAAAAAAAAAAAAAAEwAAAAATAAAAAAAAAAAAAAAAI3NwAAAAEwAAAAAAAA" +
"AAExAAAAATAAAAAAAAAAAAAAAAoxMzczMDc3MTA1RVFETgAAACUAAAABMQAAABw2" +
"MTZkNjU3MjY5NzQ3MjYxNjQ2NTJlNjM2ZjZkRVFETgAAACkAAAABMQAAACA3NDY0" +
"NjE2ZDY1NzI2OTc0NzI2MTY0NjUyZTYzNmY2ZEVRRE4AAAArAAAAATIAAAAiNjI2" +
"MTZlNmI2ZjY2NjE2ZDY1NzI2OTYzNjEyZTYzNmY2ZEVRRE4AAAAZAAAAATIAAAAQ" +
"NjI2ZjY2NjEyZTYzNmY2ZEVRRE4AAAAZAAAAATIAAAAQNmQ2MjZlNjEyZTYzNmY2" +
"ZEVRRE4AAAAdAAAAATIAAAAUNzU3MzY1NjM2NjZmMmU2MzZmNmRFUUROAAAAHQAA" +
"AAEzAAAAFDczNzA3MjY5NmU3NDJlNjM2ZjZkRVFETgAAACMAAAABMwAAABo3Mzcw" +
"NzI2OTZlNzQ3MDYzNzMyZTYzNmY2ZEVRRE4AAAAdAAAAATMAAAAUNmU2NTc4NzQ2" +
"NTZjMmU2MzZmNmRFUUROAAAAHwAAAAE0AAAAFjc5NmY3NTc0NzU2MjY1MmU2MzZm" +
"NmRFUUROAAAAHQAAAAE0AAAAFDY3NmY2ZjY3NmM2NTJlNjM2ZjZkRVFETgAAABsA" +
"AAABNQAAABI2MTcwNzA2YzY1MmU2MzZmNmRFUUROAAAAHQAAAAE1AAAAFDY5NjM2" +
"YzZmNzU2NDJlNjM2ZjZkRVFETgAAACUAAAABNgAAABw3NzY1NmM2YzczNjY2MTcy" +
"Njc2ZjJlNjM2ZjZkRVFETgAAABUAAAABNgAAAAw3NzY2MmU2MzZmNmRFUUROAAAA" +
"LwAAAAE3AAAAJjczNmY3NTc0Njg2NTcyNmU2MzZmNmQ3MDYxNmU3OTJlNjM2ZjZk" +
"RVFETgAAACUAAAABNwAAABw3MzZmNzU3NDY4NjU3MjZlNjM2ZjJlNjM2ZjZkRVFE" +
"TgAAACwAAAACMTIAAAAiNjE2MzYzNmY3NTZlNzQ2ZjZlNmM2OTZlNjUyZTYzNmY2" +
"ZEVRRE4AAAAaAAAAAjEyAAAAEDYzNjk3NDY5MmU2MzZmNmRFUUROAAAAIgAAAAIx" +
"MgAAABg2MzY5NzQ2OTYyNjE2ZTZiMmU2MzZmNmRFUUROAAAAJAAAAAIxMgAAABo2" +
"MzY5NzQ2OTYzNjE3MjY0NzMyZTYzNmY2ZEVRRE4AAAAaAAAAAjIyAAAAEDYzNmU2" +
"NTc0MmU2MzZmNmRFUUROAAAAHgAAAAIyMgAAABQ2MzZlNjU3NDc0NzYyZTYzNmY2" +
"ZEVRRE4AAAAYAAAAAjIyAAAADjYzNmY2ZDJlNjM2ZjZkRVFETgAAACIAAAACMjIA" +
"AAAYNjQ2Zjc3NmU2YzZmNjE2NDJlNjM2ZjZkRVFETgAAABoAAAACMjIAAAAQNmU2" +
"NTc3NzMyZTYzNmY2ZEVRRE4AAAAeAAAAAjIyAAAAFDczNjU2MTcyNjM2ODJlNjM2" +
"ZjZkRVFETgAAAB4AAAACMjIAAAAUNzU3MDZjNmY2MTY0MmU2MzZmNmRFUUROAAAA" +
"LgAAAAIzMgAAACQ2MjYxNmU2MTZlNjE3MjY1NzA3NTYyNmM2OTYzMmU2MzZmNmRF" +
"UUROAAAAGAAAAAIzMgAAAA42NzYxNzAyZTYzNmY2ZEVRRE4AAAAgAAAAAjMyAAAA" +
"FjZmNmM2NDZlNjE3Njc5MmU2MzZmNmRFUUROAAAAJAAAAAIzMgAAABo3MDY5NzA2" +
"NTcyNmM2OTZkNjUyZTYzNmY2ZEVRRE4AAAAaAAAAAjQyAAAAEDYyNjk2ZTY3MmU2" +
"MzZmNmRFUUROAAAAIAAAAAI0MgAAABY2ODZmNzQ2ZDYxNjk2YzJlNjM2ZjZkRVFE" +
"TgAAABoAAAACNDIAAAAQNmM2OTc2NjUyZTYzNmY2ZEVRRE4AAAAkAAAAAjQyAAAA" +
"GjZkNjk2MzcyNmY3MzZmNjY3NDJlNjM2ZjZkRVFETgAAABgAAAACNDIAAAAONmQ3" +
"MzZlMmU2MzZmNmRFUUROAAAAIgAAAAI0MgAAABg3MDYxNzM3MzcwNmY3Mjc0MmU2" +
"ZTY1NzRFUUROAAAAHAAAAAI1MgAAABI3NTYxMzI2NzZmMmU2MzZmNmRFUUROAAAA" +
"GAAAAAI1MgAAAA43NTYxNmMyZTYzNmY2ZEVRRE4AAAAeAAAAAjUyAAAAFDc1NmU2" +
"OTc0NjU2NDJlNjM2ZjZkRVFETgAAACIAAAACODIAAAAYNmY3NjY1NzI3NDc1NzI2" +
"NTJlNjM2ZjZkRVFETgAAABwAAAACODIAAAASNzk2MTY4NmY2ZjJlNjM2ZjZkRVFE" +
"TgAAACQAAAACOTIAAAAaN2E2ZjZlNjU2MTZjNjE3MjZkMmU2MzZmNmRFUUROAAAA" +
"IgAAAAI5MgAAABg3YTZmNmU2NTZjNjE2MjczMmU2MzZmNmRFUUROAAAAGwAAAAM4" +
"NDIAAAAQNjE3NjZmNmUyZTYzNmY2ZEVRRE4AAAAjAAAAAzg0MgAAABg3OTZmNzU3" +
"MjYxNzY2ZjZlMmU2MzZmNmRFUUROAAAALAAAAAQxNDc0AAAAIDMxMzgzMDMwNjM2" +
"ZjZlNzQ2MTYzNzQ3MzJlNjM2ZjZkRVFETgAAACoAAAAEMTQ3NAAAAB4zODMwMzA2" +
"MzZmNmU3NDYxNjM3NDczMmU2MzZmNmRFUUROAAAAIAAAAAQyMDAwAAAAFDYxNmQ2" +
"MTdhNmY2ZTJlNjM2ZjZkRVFETgAAACQAAAAEMjAwMAAAABg2MTZkNjE3YTZmNmUy" +
"ZTYzNmYyZTc1NmJFUUROAAAAMgAAAAQyMDEwAAAAJjY1Nzg3MDcyNjU3MzczMmQ3" +
"MzYzNzI2OTcwNzQ3MzJlNjM2ZjZkRVFETgAAACoAAAAEMjAxMAAAAB42ZDY1NjQ2" +
"MzZmNjg2NTYxNmM3NDY4MmU2MzZmNmRFUUROAAAAGgAAAAQyMDEyAAAADjYzNmY3" +
"ODJlNjM2ZjZkRVFETgAAABoAAAAEMjAxMgAAAA42MzZmNzgyZTZlNjU3NEVRRE4A" +
"AAAqAAAABDIwMTIAAAAeNjM2Zjc4NjI3NTczNjk2ZTY1NzM3MzJlNjM2ZjZkRVFE" +
"TgAAADIAAAAEMjAyMgAAACY2ZDc5NmU2ZjcyNzQ2ZjZlNjE2MzYzNmY3NTZlNzQy" +
"ZTYzNmY2ZEVRRE4AAAAgAAAABDIwMjIAAAAUNmU2ZjcyNzQ2ZjZlMmU2MzZmNmRF" +
"UUROAAAAIgAAAAQyMDMyAAAAFjc2NjU3MjY5N2E2ZjZlMmU2MzZmNmRFUUROAAAA" +
"IgAAAAQyMDMyAAAAFjc2NjU3MjY5N2E2ZjZlMmU2ZTY1NzRFUUROAAAAIgAAAAQy" +
"MDQyAAAAFjZjNmY2NzZkNjU2OTZlMmU2MzZmNmRFUUROAAAAHAAAAAQyMDQyAAAA" +
"EDZjNmY2NzZkNjUyZTY5NmVFUUROAAAAIgAAAAQyMDUyAAAAFjcyNjE2Yjc1NzQ2" +
"NTZlMmU2MzZmNmRFUUROAAAAGgAAAAQyMDUyAAAADjYyNzU3OTJlNjM2ZjZkRVFE" +
"TgAAACQAAAAEMjA2MgAAABg3MzY5NzI2OTc1NzM3ODZkMmU2MzZmNmRFUUROAAAA" +
"IAAAAAQyMDYyAAAAFDczNjk3MjY5NzU3MzJlNjM2ZjZkRVFETgAAABgAAAAEMjA3" +
"MgAAAAw2NTYxMmU2MzZmNmRFUUROAAAAIAAAAAQyMDcyAAAAFDZmNzI2OTY3Njk2" +
"ZTJlNjM2ZjZkRVFETgAAACYAAAAEMjA3MgAAABo3MDZjNjE3OTM0NjY3MjY1NjUy" +
"ZTYzNmY2ZEVRRE4AAAA0AAAABDIwNzIAAAAoNzQ2OTYyNjU3MjY5NzU2ZDYxNmM2" +
"YzY5NjE2ZTYzNjUyZTYzNmY2ZFVSVUwAAAAoAAAAGjY3NmY2ZjY3NmM2NTJlNjM2" +
"ZjZkMmY2MTJmAAAAATAAAAABMFVSVUwAAAAkAAAAFjZjNmY2NzZkNjU2OTZlMmU2" +
"MzZmNmQAAAABMQAAAAEwVVJVTAAAADoAAAAsNzM2OTc0NjU3MzJlNjc2ZjZmNjc2" +
"YzY1MmU2MzZmNmQyZjczNjk3NDY1MmYAAAABMAAAAAEwVVJVTAAAACIAAAAUNzc2" +
"NTY1NjI2Yzc5MmU2MzZmNmQAAAABMQAAAAEwVVJVTAAAABwAAAAONzc2OTc4MmU2" +
"MzZmNmQAAAABMQAAAAEwVVJVTAAAAB4AAAAQNzc2NTYyNzMyZTYzNmY2ZAAAAAEx" +
"AAAAATBVUlVMAAAAKAAAABo2ODZmNmQ2NTczNzQ2NTYxNjQyZTYzNmY2ZAAAAAEx" +
"AAAAATBVUlVMAAAAKAAAABo3NzZmNzI2NDcwNzI2NTczNzMyZTYzNmY2ZAAAAAEx" +
"AAAAATBVUlVMAAAAIAAAABI2YTY5NmQ2NDZmMmU2MzZmNmQAAAABMQAAAAEwVVJV" +
"TAAAACgAAAAaNzc2NTYyNzM3NDYxNzI3NDczMmU2MzZmNmQAAAABMQAAAAEwVVJV" +
"TAAAACgAAAAaNzM2ZTYxNzA3MDYxNjc2NTczMmU2MzZmNmQAAAABMQAAAAEwVVJV" +
"TAAAACwAAAAeNjM2YzZmNzU2NDYxNjM2MzY1NzM3MzJlNmU2NTc0AAAAATEAAAAB" +
"MFVSVUwAAAAkAAAAFjc3NjU2MjZlNmY2NDY1MmU2MzZmNmQAAAABMQAAAAEwVVJV" +
"TAAAACwAAAAeNmY2ZTZkNjk2MzcyNmY3MzZmNjY3NDJlNjM2ZjZkAAAAATEAAAAB" +
"MFVSVUwAAAAoAAAAGjY4NjU3MjZmNmI3NTYxNzA3MDJlNjM2ZjZkAAAAATEAAAAB" +
"MFVSVUwAAAAaAAAADDZlNmY3NjJlNzI3NQAAAAExAAAAATBFTkRNAAAAAk9L";
public static readonly byte[] Blob = BlobBase64.Decode64();
public static readonly byte[] EncryptionKey = "p8utF7ZB8yD06SrtrD4hsdvEOiBU1Y19cr2dhG9DWZg=".Decode64();
public static readonly string EncryptedPrivateKey =
"fc61ba57136d7ebb627e659a1e1f0ac68686bf4a7774dcc90a80b16383cfe7ef" +
"4523386da9e62c30e01fcb2d07fccfbf79e30497c72e3b41be1cf4c36cf24b74" +
"f8ffe41cd4ed301bf56f1229eb7c87ff50d61ecd2f8bedc538a379b983e13ace" +
"0472a908893e5b413ae573f2a9e453b3730fe42324525238f9179cc1a93977a8" +
"93748ecfc1bc09df440dc030e804feb3f2f9b4a0c79222a22335fcc9f7f54da7" +
"b229cab3f01e955c68a80d67aeea3932507a8b76d6195aaa0c7502b484f24f10" +
"bca93012f2d6084f3f6143fd3d3eca2613036b56da10a5acd6e4e1066d0ef667" +
"a46e591bde42adf84c8193f9993a52ee1c9724e49f74323ad8e7d24d5bdd7eed" +
"7ae7543e6ec9a288f5bec84490168f40ea2b5e9ba14ddcd5533cc063cf4c0cee" +
"a7f47f57280480ca869f1066048cfa2517a1e41f2c9f807dbc77d3de3a281b15" +
"97976f65bbd9ea576755d65b14a58420b3bedb378bc204f438cc244cec5de6e1" +
"9c645d3271bb83447515bdb18bbd16bed4c937a395077b6e99fb5cfe8504f258" +
"a329d2c738cdd9206a27cb8d51d44db166f47ef40f3fa812d493ef12e6bf7001" +
"236ca1ec3bb9b3033f9de7cb39d3f3fe1356d8f6228fb02f2c22e5d3a14bbff9" +
"7708ef94f180a6c04541f2eed04141521876c2a901f2df7ee26873114066da72" +
"1fbe0634154ed5f080542840dd5e56b64f2039b85ca5e4cad5e75392689b215f" +
"830f58374dbbd32c1d32e140b1f1ba3af5d806c61bed6067c72070f74d3443fc" +
"4019fa5f8349f2068a7cd3db2b5d1cd05a51d7203155142a109124948ea51850" +
"c6747b03e8a348b76741808ae8b24539538afab2c574f62c356263723cc3f840" +
"b35f814933764c5e0b5ac7960ee2bec12912754a36d2900899050276161f4abd" +
"4da9754d2f62c51e4f3bb1c7eeb970008eca65590e983eed6481cdae06b5707a" +
"b29975d117d42dd49d527ce1077af2485cc040aa3805b8372bf27860a13b2763" +
"5572021e36009c1224593cbccda3e3442fd3565872c2f90180a747ac4333af58" +
"037068efc8674409ff233fdaecfd727daec246d40ed72831d89b005e5e311002" +
"94da55beb9a8398cba5b1a4a411d9f90a7725453551d21640d8436ee78e1a476" +
"c99b54089f564368e08783c1e4529a2ee6a32f9fb19727f4858ba0953d65a7e7" +
"aa747748f3a4935391d0d136cd5ef801858d5b4ab2911034d717f1078c1974bd" +
"7cccf529ebe4bc7a39a54470fcd39799d4ec333cceeb48e59ef1cf363761e3b1" +
"00c6523fd5e531fcf27923ddc71eafb63fd275a897e9c3aef32db9d6daabfe98" +
"c61066f2b32a10d76370b436072873b508035f3e7f8b5480ecb28d81e2c58aa2" +
"045930106e449daa3bebc6053c2a072209ff5844af5a6a875d076982d073128a" +
"3080d4147dd893e6b6e64814b323be54e87256927045accc14be00f0ad19baf6" +
"5fa246f795ece6618e21cc4b07bf51cc37767723e36dfe2018dc5eaac60fe021" +
"931dda5f0d2a1157736eff3687459ab9b81aeaa4b693f3516d4c9e4e8ed1b742" +
"61018a5d0c9a445d66c8505bae1787ef448f22e0fb5fff1b0e4dc45f0335f658" +
"2b574d0e0c116ef2be8f3e07923deb886f9b48efb5ba02c54a2fa059251bd48e" +
"78c675242d5078293a90ff5d8e81a2d163763176bf1db0c87845e2b5dc7b40b9" +
"418ea3900c414d480d86d4385dd3aa3496ce6d67c551f906fcd46e7246bf088d" +
"639e4d1a3677f50f4a3c2ab7df809ac88b76748842af4a4c3cc77ca10de71da2" +
"0a2b9dfde0d9057317b687aa7c6195a8d2595e37027fc012ae1dc7b4aea185d4" +
"91832d90e3724a5b2acd5220b166b168cbdf3a0cfaff2acbc45d631fd86ca43f" +
"9ba57d3591fa4a2a55abdbe6166e36c1136d0dc7861a26e88cbbb65b70fe1a1f" +
"062957211d38e9ff677fdb773e373650f527e8892f0afea25def92282671a33b" +
"affd5a68fc552047513660bef99de98e8cfdbb9a2151379efc1ea1a89cfb067e" +
"408c7742733584959205b095e4ec97c4182381ae283400cb2aa7f251249cf3cf" +
"1c0ff7c311a740a7a25971d3ec56c4db14f15991066c5dd1aa0c85958a3e82e1" +
"5217087663c8fddee68ea6e62798c9abfdf7996c317c35424b9dea8b438bf493" +
"6cf08f019b8f5ad738536f438821d841b6d86d8a3dde06dd3c2a37af8ed617a0" +
"bed014da0643811478d2867494724252521efb41230b813c7be5d30c3d7845be" +
"af690c8f0a909087ed8eb774b0eb57171075584e08bf9a51854cd0610284dc9a" +
"fe86ce5b3fd8eaa85fcf50cb1b833a641fba908396438a45ae8cf0fc606bd7dd" +
"171dd82e0576b65338e3d3705f66f874a5b0780c48f78b7411a333f49b861a77" +
"9af2127f8b0481f326e692be96af15fcea1de840626f8f761b16b1afe7d6af2c" +
"8ad2d34839bce0212bc9dd74df4b079b886a58a800fe8f7c5356cd8be92400d0" +
"80e1fcbe3cdc9ddfd3c845bd9aedc894697b6757baf40cb2ecfa207f682cab2d" +
"387d4df33548c36b1695577a816c4dcf3ca7c00a97da4722c8d63c6862af3e83" +
"0e86f5ab4d43fc57c13fb6d88b0ec5c9034921901278fdde457043f7b16e50db" +
"2eb5e85618cc03485be48438eed60e125a21dcb478d6df811e010bd0ed9cdf42" +
"6ed51410f1747edf1ab42f283921e5e6ed273b1226e3b3f66eb3716e943f5e78" +
"9ba25f8137e7d57c915cbd43dc4694d0910e511d8dfcb95410decb836445dd5c" +
"a0c0c96990a1cd378cf30a04d37e53ca0bbdd43ff191e4a38787933fa0acece0" +
"29987f250e2883842d9b714a55841fb6809cadcdaa25eba5b0f9544bf3c54665" +
"2dc97ae8653119fd072bc68ee900b7a8450d932f50ac9559db17b57fe1408bc1" +
"bc93d7889b7a58236b7c4017f048e9f460d4d962c87ec5cb541b5c1ceb587f41" +
"f44803808e05b33618ff4ef32eb44a1752372da4b9b023013a7290d1449a1c0e" +
"bea88373db1cbaf51455e3a9e076ca340d8c1f1ff3bd1a58034c18c9aadbda81" +
"032c88bb38b8e02b24983b3852a57cfa0ac1a6c745817ac463f8f3032099b434" +
"a94f35f123c8c56c1f111b5692ece492a4e2772e1c01726e5fe803ac63237dfd" +
"a595d42c7dfb0968f49f6bb5fb77f13bd3b9de50c3486cf64be1cf289e92f583" +
"4b3d0bd5d02412f73f639da12a7e2cccb49d64940a11f1bfa12f8d03b1d6e6ce" +
"052c54d0fd12d08fa5a934c9acb6938adf4cbe5c5a93bcdcc4b6e399067f31fb" +
"05469052de1476ba3e36bdb758caf0de004d6bedab85aca69cfc4cada2bc120a" +
"b6f582954ee8cf3db91990fa225dcbd71f45846274691bece6651eacad8a1550" +
"7f734095ab7a7f97c383a8d698f3c339537f1a5d858da964c9dfa2e681705e74" +
"3d7e6fcf6023daf2bcc6d00fe33ce68166fba31a32ebe4a1b4d1e792a9db76b8" +
"50710ae7d0f3007ab15b94e1a3b97f9cb165457e706d19e40081ce917be0cbbf" +
"5b78fb81701939efef4f57350c2dbf2fa05ff469aa48b2cac1f496de48cc55c8" +
"c2d6db524687475335dd9169a496a4c2";
public static readonly byte[] RsaD = (
"oCZKcCWHrddSg44/MMadv3nW6VdMiR4Tpw13yvdO2XgFUX8Rt2o/mL1g+KYD" +
"F+Zu74bF2Jzj7asNxJM2CwZ2ayckE0w6Ew99GXwyMTHp18F5POEQvmvQO5Fm" +
"fpYClnjQiQ3pOaeCPXzKP6dlzEdQHUKkUvc+vAvSU02XwWCGpBTNmJNKiFSN" +
"+kHolIvM3Gn5GoFdp9m1HJlTWCoJl0oJND0ko+jozUvNEcmgtrsIC6YLypBN" +
"rZCHrdmgVi1WEtdfKowzcCQyYP9u4dctLOGBqSS5Uz4Ldw3MzL2R8y8Nbo2H" +
"OVgXqw7TM9zIdnZxkVs6yqzJ2FEiXI4KcK7J4iD3rQ==").Decode64();
public static readonly byte[] RsaDP = (
"oT8Dc/I+r2VX5xeyVt3VYrC7ExcVxx9tUsFm5b90S1CnfLRMzcOSTXM6z60Q" +
"bK0w1Q5hmblAViGbJr3twtqwYP7WDrfTOInnE28zXgItrRHCuFltwZmWOXxv" +
"wHjolcQV51o9gHs08XIV1BdHqHnNLph9qm5hfFJq2HWUn+8poT8=").Decode64();
public static readonly byte[] RsaDQ = (
"s6RccDP6SzSFDh63CobUHB5poehNsao5xwg9MLvdOa9PV9DR2qdj4HXvlRrY" +
"FCuhlafCPgYiTLZBM7COlipR9OneMuNw17YRfI3ROmqVcZLYKhBByZLdzypN" +
"TGNbcHyMGxj7nu2QJnWyLLCPWe1F7tco0V/bFMBO7Xjk0q0NBB0=").Decode64();
public static readonly byte[] RsaExponent = "AQAB".Decode64();
public static readonly byte[] RsaInverseQ = (
"tFK0dzELJnDl0tj5URPAycY1kXIWa4eMSNXo6KTsGYoCe0ZXjO/zwKKTVlPN" +
"JJmPZwnXQaN2YtwykrKGikx1ZvdnVfIx+i2FFVdPuGc9LAnmeTbhTC3T0vkK" +
"L4SqTnCjIpXmSwlV/aPhOOW9EGxK2LSKoD5jreOQatWmpN8Ry18=").Decode64();
public static readonly byte[] RsaModulus = (
"zufyGpNKMoL7WK2TyQ++OQjrWaJVhaxHyfI8sV/HZqhhJSFEtlL94/SvG5rd" +
"SKn24CENXYr4uHWAsSlcNUEndSUfxUyZeWobJUkzGqRDP+bknR+BEJS6LUbE" +
"44ttz9eU5mFr4SN44G2xKfX8F5+xNwwdZk7YzzT/F5zcAeD2nxV4kIVg2Dxm" +
"rl3yry+2reNq3oTGH7/iBXz9X1RsR6jxIfryJHUycuIt2ze2hjInVMUYBMdP" +
"kt0qUDpT7yBU40yGKIjj05Vlte0ZLbTcdv18aX4kWess8NOwT6n7zpxDPWrM" +
"BQhiL19o/CyogdaMd2tii3V7lgxSmLG671zmExgOeQ==").Decode64();
public static readonly byte[] RsaP = (
"/LXZfJ811wtpvxfRHzE0Ds2x3v3bRRGUKFLHQ1ZJ4kpAX8UXigVTk5P8kKXU" +
"uo6KIub++nC90xCXlKcbVtFNsPYYVobBUel07jrTAVaBvkJr5Kw1xNiXmOxc" +
"w8hlIDlGS2LX776aKn4LtMfd3Nte2WY7PcOmUXtoEl5L3BmM2W8=").Decode64();
public static readonly byte[] RsaQ = (
"0Zl0W6Cz920jJqy4RzwNwlaQ133n/+PnimMHROy69aNy90JgElhtyFnW54S/" +
"9hl+eqRPVBbcw7lLCTSKi4VrZpcy22j1y9aDXJ3Baovq3yjHt8XvgoX44ZVI" +
"EVu5r0tI9yd0LDIhG0Dy1uTT69JjEHni/3ccNto3Ua4soEDmEpc=").Decode64();
public class Account
{
public Account(string id, string name, string username, string password, string url, string group)
{
Id = id;
Name = name;
Username = username;
Password = password;
Url = url;
Group = group;
}
public string Id { get; private set; }
public string Name { get; private set; }
public string Username { get; private set; }
public string Password { get; private set; }
public string Url { get; private set; }
public string Group { get; private set; }
}
public static readonly Account[] Accounts = new[] {
new Account("1872745596", "Muller, Morar and Wisoky", "branson_cormier", "8jgLCzQSkB2rTZ1OtF9sNGpc", "http://nienow.net/meagan.greenholt", "three"),
new Account("1872745606", "goyette.net", "kris_quigley@baileyjewe.biz", "S5@3^wPv!6JsFj", "http://bechtelar.biz/tristian.barrows", "four"),
new Account("1872745616", "Ward Inc", "angela_emard", "zp8N@KoWyS0IYu7VR$dvBF!t", "http://schuster.name/ashton", "one"),
new Account("1872745626", "stehr.com", "bailee_marvin@mohrlegros.net", "cupiditate", "http://runolfon.org/te", "three"),
new Account("1872745636", "kiehn.biz", "freda", "et", "http://hintzprohaska.biz/wade.fisher", "one"),
new Account("1872745646", "Jacobs and Sons", "johnnie.hand", "gzyl6714", "http://schultzheaney.org/arvid", ""),
new Account("1872745656", "Larkin, Kautzer and Wiegand", "hilton", "zguovmdr8703", "http://streich.com/ramona", "one"),
new Account("1872745666", "Conn Inc", "malvina_paucek@nikolausveum.net", "numquam", "http://conn.net/leda", "four"),
new Account("1872745676", "Block, Sanford and Connelly", "marilie_wolff", "zKcy?U*aCGS^gf@Z", "http://conroy.biz/zachery", "two"),
new Account("1872745686", "gradyrenner.org", "oswald@ryan.info", "ojgwad28", "http://kihn.org/candice", ""),
new Account("1872745696", "lesch.net", "nicholas", "Pkc72Lmr1qwI%sNV^d4@GtX", "http://glover.name/jerad", "two"),
new Account("1872745706", "sipes.biz", "kaitlyn.bernier@reichel.net", "in", "http://mayert.name/jeromy", "two"),
new Account("1872745716", "Hintz-Herman", "prince.moriette", "0hebvIS@s^BwMc", "http://sanfordwunsch.org/alek", ""),
new Account("1872745726", "Hammes-Kassulke", "brooke@gloverhintz.net", "paokcs08", "http://lehner.biz/stanley.dooley", "four"),
new Account("1872745736", "hermann.com", "jasper_dickens", "Ppj2b!rIMLu*@ElTCZU", "http://rolfson.net/jaden", "one"),
new Account("1872745746", "Veum and Sons", "marquise@quitzonbrown.com", "owsg728", "http://fahey.name/jon_ankunding", "one"),
new Account("1872745756", "Balistreri, Emard and Mayert", "verona@willmswhite.info", "wnydas6714", "http://treutelkiehn.org/marcos", "two"),
new Account("1872745766", "lindkeler.net", "ed", "quia", "http://leffler.info/chaya", "one"),
new Account("1872745776", "nikolaus.biz", "leonard", "oW9fdvJLkp#%I", "http://brakuswilliamson.com/bret", ""),
new Account("1872745786", "bartonherzog.net", "dock@vonrueden.net", "beatae", "http://kunzeokuneva.info/shawn_langosh", "three"),
new Account("1872745796", "howe.org", "chad@walker.biz", "zexfir7951", "http://crooks.com/sandrine", ""),
new Account("1872745806", "shields.info", "modesto@kunzenicolas.com", "*JDSdp@VyR8f5FOALW", "http://kemmer.org/hilton", "three"),
new Account("1872745816", "kihnabernathy.com", "mafalda.treutel@gislason.name", "hwuoxizq18", "http://trompbernhard.com/trea.hirthe", "two"),
new Account("1872745826", "Gislason and Sons", "torrey@kshlerin.info", "OfZrTFAIq?Uyl9X$", "http://ullrich.info/carlee", "four"),
new Account("1872745836", "simonis.com", "marco.cronin", "upokmxct57", "http://rippin.name/bonita_hickle", "four"),
new Account("1872745856", "Howell, Beer and Yundt", "raegan@cruickshankgreenholt.org", "dHPFrtOjieum4L", "http://aufderharrunolfsdottir.info/felicia_torphy", "two"),
new Account("1872745866", "Gottlieb-Ernser", "ivory.moore@paucek.com", "fugit", "http://lockmanlynch.net/alba", "four"),
new Account("1872745876", "Emmerich and Sons", "lacey.bernier@hansenboyer.com", "aqzkolu6021", "http://carrollschmitt.com/willy.emard", "three"),
new Account("1872745886", "Gerlach, Kirlin and Roberts", "maiya@bayergusikowski.org", "nhit3214", "http://feil.net/natasha_howe", "one"),
new Account("1872745896", "ryan.net", "rubie@fahey.org", "aihw^uFgXnC%R", "http://gleasonjakubowski.biz/august", ""),
new Account("1872745906", "Jewess, Wolf and Volkman", "kristin_blanda@howekuhlman.biz", "nacro5213", "http://wilkinsonleannon.name/bud.willms", "two"),
new Account("1872745916", "Ritchie Group", "nathen_ortiz@turner.biz", "XfmN@G%ebsK1Jc$q", "http://price.info/urban", "two"),
new Account("1872745926", "wiegand.info", "lavon_greenholt", "fzedpuq30", "http://paucekturcotte.org/kadin_gibson", ""),
new Account("1872745936", "Rohan, Schneider and Daniel", "zella.effertz", "wksei21", "http://runte.com/camryn.hane", "one"),
new Account("1872745946", "boyle.name", "gennaro_goldner@kovacek.biz", "eaJD#Kb6UAis@M*8jhILk", "http://kulasklein.info/nyasia", "four"),
new Account("1872745956", "Pouros-Funk", "maudie@fahey.org", "wahkvms6871", "http://schaefer.info/leslie.bogan", "three"),
new Account("1872745966", "Parisian-Legros", "holly", "et", "http://naderrempel.net/gwen_schmidt", "four"),
new Account("1872745976", "Rosenbaum-Schulist", "jordy.krajcik", "xqzflsy843", "http://dooley.info/alek_parker", "four"),
new Account("1872745986", "christiansen.info", "phoebe@larson.info", "bilvs07", "http://johns.name/columbus.dooley", "two"),
new Account("1872745996", "Hauck, Thiel and VonRueden", "leif", "QVx?JvZ46e1FBmsAi", "http://bauch.org/marlin", "one"),
new Account("1872746006", "Sipes and Sons", "leland", "ecgs1758", "http://dubuque.com/jacey", "one"),
new Account("1872746016", "Osinski LLC", "rhoda", "nhwo705", "http://schinner.org/price", "four"),
new Account("1872746026", "daniel.name", "santina@wiegand.net", "dolorem", "http://torp.net/shyanne.smitham", ""),
new Account("1872746036", "darekutch.name", "ali", "U*kgl8u1p#QO9xWNnEd0b3", "http://mante.com/caie_streich", ""),
new Account("1872746046", "grimes.com", "eunice_satterfield@baileymante.net", "ipsam", "http://swaniawski.org/wendell_gaylord", "three"),
new Account("1872746056", "conn.name", "sandrine", "rv%XVjo#2Id?@4L", "http://rolfson.com/willy_bartell", ""),
new Account("1872746066", "Kozey-Spinka", "brando.kshlerin", "consequatur", "http://collinsreichel.net/yasmine", "three"),
new Account("1872746076", "Daugherty LLC", "horacio_schulist@davis.net", "sbxzn64", "http://deckow.net/roosevelt.kshlerin", "four"),
new Account("1872746086", "Lubowitz LLC", "maxine@ebertmckenzie.biz", "qrcl02", "http://considineheidenreich.name/name.christiansen", ""),
new Account("1872746096", "mante.name", "jayne", "xnekizj90", "http://bogisich.net/lori", "four"),
new Account("1872746106", "Mante LLC", "antonio.turner@sauertorphy.com", "ckomnf175", "http://herzog.name/luigi", ""),
new Account("1872746116", "Greenholt-Hodkiewicz", "moriah@mccullough.org", "udaxo7451", "http://mann.com/cecile", "three"),
new Account("1872746126", "Rosenbaum, Sipes and Leffler", "keshaun@schroeder.info", "recusandae", "http://dooley.name/ewald", "two"),
new Account("1872746136", "Fadel, Ferry and Kohler", "sister", "sUxoLNhl8Kty*Ve76b45G", "http://balistrerimcclure.com/jaquan_wilkinson", "two"),
new Account("1872746146", "Schaden-Rosenbaum", "godfrey", "oDVcsx*m!0Rb@NjSyqdGIl", "http://pouros.net/jeremie", ""),
new Account("1872746156", "Monahan, Reinger and McKenzie", "christophe.kub@luettgen.name", "fLqj&e$TyNo8gd7!", "http://keler.info/nikita.lindgren", "four"),
new Account("1872746166", "bednar.info", "roselyn@hickle.com", "*2tiEP&Ic7dT", "http://jaskolski.com/conner_ortiz", "two"),
new Account("1872746176", "Jewess, Wolf and Feil", "hal", "doloribus", "http://champlin.org/lue_schroeder", "three"),
new Account("1872746186", "Kunze-Hettinger", "camilla_pagac", "elpbzT08Dvo6NyQF3wPEr", "http://donnellyadams.com/santino", "one"),
new Account("1872746196", "Jacobs, Toy and Schultz", "billy_boehm@will.biz", "g5X*hRwlmcL6ZM", "http://larkinconsidine.org/leola", "one"),
new Account("1872746206", "sanford.com", "joy@abbott.org", "rfolun872", "http://runtemoen.name/pierre", "three"),
new Account("1872746216", "upton.net", "susana.gaylord", "WR4KxbU^@$Vpi%QH9Mv#T", "http://moore.info/pearl", "three"),
new Account("1872746226", "wiegand.biz", "ashleigh_gutmann", "t7C&j!Ox21oha5sX*f", "http://armstronghackett.name/jaeden", "three"),
new Account("1872746236", "schneider.net", "eunice.sauer@ledner.org", "U%EFVGnxw2fQ^t*", "http://schulistmetz.info/esperanza_cummerata", "two"),
new Account("1872746246", "Swift-Stoltenberg", "katelin_rempel", "labore", "http://beermills.net/danielle", "two"),
new Account("1872746256", "Heathcote Group", "hope.waters@parisianbruen.info", "EhG7zBTb8OseI", "http://douglas.name/porter", ""),
new Account("1872746266", "hilpert.com", "phyllis.lemke", "est", "http://donnelly.com/tyrique_langosh", "one"),
new Account("1872746276", "daviswolff.name", "martine@ryan.com", "incidunt", "http://schoen.info/macy", "one"),
new Account("1872746286", "Bahringer, Prohaska and Mills", "merritt_reilly@lynch.info", "dyX^xZ3HTKsqFIMeA", "http://schuppe.com/rosetta.yundt", ""),
new Account("1872746296", "ledner.name", "billie.lueilwitz@kertzmann.org", "Zi5K6tXh91mJG3EnjBD4r", "http://feil.com/isabelle", "four"),
new Account("1872746306", "jerdecormier.com", "renee.towne@ruecker.net", "vuzoskg85", "http://mckenzie.net/zaria", ""),
new Account("1872746316", "harbervandervort.org", "elta_haag@okuneva.net", "2?GVri70HkKceU*m#CZ3x", "http://whiteklocko.name/lacey.dare", "one"),
new Account("1872746326", "gulgowskimann.org", "chaz_brakus", "explicabo", "http://okuneva.biz/lisandro", "two"),
new Account("1872746336", "padbergconn.info", "lenore@ullrich.net", "ORrNKnhuqd7xeULa^YDk", "http://sauerkuvalis.info/braxton", "one"),
new Account("1872746346", "davis.com", "margarett", "debitis", "http://spinka.info/kendra", ""),
new Account("1872746366", "Gerlach Inc", "krystel_boyer", "qui", "http://pouromitham.name/efrain", "three"),
new Account("1872746376", "cummerata.net", "rudy.flatley", "mzqvakic527", "http://heidenreich.net/ryann_hayes", ""),
new Account("1872746386", "schowalter.name", "hyman.satterfield", "pjts564", "http://okeefedamore.biz/giovani", "one"),
new Account("1872746396", "McLaughlin-Fadel", "fanny_sporer", "kyti64", "http://dickibosco.biz/zachariah", "four"),
new Account("1872746406", "Gerlach-Nienow", "treva.block", "csnxhldi893", "http://kunzemurazik.net/johnny.koch", "two"),
new Account("1872746416", "O'Reilly-Trantow", "grayson", "non", "http://harris.name/rosalind_marquardt", "three"),
new Account("1872746426", "Larkin-Konopelski", "josianne_walker", "bwms78", "http://runolfsdottir.name/nicklaus_hayes", "two"),
new Account("1872746436", "Swaniawski, Will and Gaylord", "jeramie.ohara@nader.org", "quia", "http://oreilly.info/dahlia_donnelly", ""),
new Account("1872746446", "emmerichgaylord.name", "diana@hansenbeahan.net", "omnis", "http://rath.net/leif_hermann", "three"),
new Account("1872746456", "armstrong.org", "genesis@rosenbaumlueilwitz.biz", "zHeu%^kxj9Y0Qr4@m*3!ov", "http://schmidtmertz.name/kira", "one"),
new Account("1872746466", "Waelchi Group", "trace.heaney@heidenreichbernier.com", "whljnru03", "http://moore.biz/anibal", "two"),
new Account("1872746476", "fahey.org", "ward_okuneva", "qjnz18", "http://leuschke.com/daphney", "two"),
new Account("1872746486", "koelpin.info", "dylan.klocko", "vdjlot364", "http://cronin.net/cyril", "three"),
new Account("1872746496", "Murphy-Breitenberg", "marcia_kreiger", "dacyz723", "http://steuber.com/ali_gibson", "three"),
new Account("1872746506", "andersondicki.org", "ceasar@lind.com", "nvymdsk14", "http://kertzmann.biz/jaydon_kunze", "four"),
new Account("1872746516", "watersreichel.net", "adella_price@beahanblock.biz", "maiores", "http://gutkowskirau.org/dora.williamson", "four"),
new Account("1872746526", "torphy.biz", "osborne_hackett@davis.org", "wkdcu1265", "http://buckridge.net/lauretta.veum", "four"),
new Account("1872746536", "Moen-Hermiston", "hildegard@hahn.com", "zbag942", "http://cummingswehner.biz/april", ""),
new Account("1872746546", "Gaylord-Lowe", "jerrell", "quasi", "http://grady.biz/mohammed_brakus", ""),
new Account("1872746556", "Bechtelar, Wyman and Thompson", "shanie@batz.biz", "vel", "http://gottlieb.name/elisabeth", "four"),
new Account("1872746566", "jacobs.info", "lon_champlin@cristlittel.name", "aut", "http://dachgislason.org/alva", "two"),
new Account("1872746576", "ankunding.com", "reina_runolfon@altenwerthhilll.net", "@g&aWsoTeJEFhHK5wr#4", "http://rice.info/giovanny_ebert", "two"),
new Account("1872746586", "Okuneva-Schmitt", "esperanza@kshlerin.com", "djwhba31", "http://glovermckenzie.info/katelynn", ""),
new Account("1872746596", "jones.name", "elvera", "ewoqt49", "http://sipes.com/joey.metz", "two"),
new Account("1872746606", "Tromp-Roob", "brisa.mcdermott", "vcnkg254", "http://bernier.org/gage_haag", "three")
};
}
}
| |
/*******************************************************************************
* Copyright (c) 2009-2012 by Thomas Jahn
* Questions? Mail me at lithander@gmx.de!
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
namespace Vectrics
{
public struct LineSegment2D
{
public static LineSegment2D Zero = new LineSegment2D();
public static LineSegment2D Void = new LineSegment2D(Vector2D.Void, Vector2D.Void);
public bool IsVoid
{
get { return Start.IsVoid || End.IsVoid; }
}
[Flags]
public enum Relation
{
NoConnection = 0x0,
StartConnects = 0x1,
EndConnects = 0x2,
OtherStartConnects = 0x4,
OtherEndConnects = 0x8,
Intersection = 0xF
};
public Vector2D Start;
public Vector2D End;
/**
* A new vector covering the distance from start to end.
*/
public Vector2D StartToEnd
{
get
{
return End - Start;
}
set
{
End = Start + value;
}
}
/**
* A new vector covering the distance from start to end.
*/
public Vector2D EndToStart
{
get
{
return Start - End;
}
set
{
Start = End - value;
}
}
public Vector2D Center
{
get
{
return 0.5f * (Start + End);
}
set
{
Vector2D delta = value - Center;
Start += delta;
End += delta;
}
}
//start -> end normalized
public Vector2D Direction
{
get { return (End - Start).SafeNormalized(); }
}
public LineSegment2D(Vector2D startPoint, Vector2D endPoint)
{
Start = startPoint;
End = endPoint;
}
public LineSegment2D(float x, float y, float x2, float y2)
{
Start = new Vector2D(x, y);
End = new Vector2D(x2, y2);
}
public float Length
{
get
{
return StartToEnd.Length;
}
}
public float LengthSquared
{
get
{
return StartToEnd.LengthSquared;
}
}
public static bool operator ==(LineSegment2D a, LineSegment2D b)
{
return (a.Start == b.Start && a.End == b.End);
}
public static bool operator !=(LineSegment2D a, LineSegment2D b)
{
return (a.Start != b.Start || a.End == b.End);
}
public override bool Equals(Object obj)
{
// Check for null values and compare run-time types.
if (obj == null || GetType() != obj.GetType())
return false;
LineSegment2D l = (LineSegment2D)obj;
return (Start == l.Start && End == l.End);
}
public override int GetHashCode()
{
return Start.GetHashCode() ^ End.GetHashCode();
}
public enum Side
{
Left = -1,
Colinear = 0,
Right = 1
}
public Side GetSide(Vector2D pt)
{
return (Side)Math.Sign(StartToEnd.Cross(pt - Start));
/*
//its the basic idea of the crossproduct in R3 with a garuanteed 0 for z.
return (Side)Math.Sign(Start.X * (End.Y - pt.Y) + End.X * (pt.Y - Start.Y) + pt.X * (Start.Y - End.Y));*/
}
/**
* Compare this line segment to another and return true if the lines have an intersection.
*/
/*
public bool IsIntersecting(LineSegment2D other)
{
//line_this = start + a * direction
//line_other = other.start + b * direction
//start.x + a * direction.x = other.start.x + b * other.direction.x;
//start.y + a * direction.y = other.start.y + b * other.direction.y;
//solve to a...
Vector2D v = Vector;
Vector2D ov = other.Vector;
Vector2D s = Start - other.Start;
float denom = v.Cross(ov);
float a = ov.Cross(s) / denom;
float b = v.Cross(s) / denom;
//The equations apply to lines, if the intersection of line segments is required then it is only necessary to test if ua and ub lie between 0 and 1.
//Whichever one lies within that range then the corresponding line segment contains the intersection point.
//If both lie within the range of 0 to 1 then the intersection point is within both line segments.
return (a > 0 && a < 1 && b > 0 && b < 1);
}
*/
/**
* Compare this line segment to another and return true if the lines have an intersection.
*/
public bool IsIntersecting(LineSegment2D other)
{
int a = (int)GetSide(other.Start) * (int)GetSide(other.End);
int b = (int)other.GetSide(Start) * (int)other.GetSide(End);
return a == -1 && b == -1;
}
/**
* Compare this line segment to another and return true if the lines are parallel.
*/
public bool IsParallel(LineSegment2D other, float tolerance = 0)
{
return Math.Abs(StartToEnd.Cross(other.StartToEnd)) <= tolerance;
}
/**
* Get information on how the two lines interact.
*/
public Relation GetRelation(LineSegment2D other, float tolerance = 0)
{
//see IsIntersecting...
Vector2D v = StartToEnd;
Vector2D ov = other.StartToEnd;
Vector2D s = Start - other.Start;
float denom = v.Cross(ov);
float a = ov.Cross(s) / denom;
float b = v.Cross(s) / denom;
Relation result = Relation.NoConnection;
if (Math.Abs(a - 1) < tolerance && (b >= 0 && b <= 1)) //touching - a is 1 and b in range
result = result | Relation.EndConnects;
if (Math.Abs(a) < tolerance && (b >= 0 && b <= 1)) //touching - a is 0 and b in range
result = result | Relation.StartConnects;
if (Math.Abs(b) < tolerance && (a >= 0 && a <= 1)) //touching - b is 1 and a in range
result = result | Relation.OtherStartConnects;
if (Math.Abs(b - 1) < tolerance && (a >= 0 && a <= 1)) //touching - b is 0 and a in range
result = result | Relation.OtherEndConnects;
if (a > tolerance && (a - 1) < tolerance && b > tolerance && (b - 1) < tolerance)
result = result | Relation.Intersection;
return result;
}
/**
* Returns the sample ratio where this line would intersect the other. Segment boundaries are not considered.
*/
public float GetIntersectionRatio(LineSegment2D other)
{
//see IsIntersecting...
Vector2D ov = other.StartToEnd;
Vector2D s = Start - other.Start;
float denom = StartToEnd.Cross(ov);
return ov.Cross(s) / denom;
}
public float GetIntersectionRatio(Vector2D start, Vector2D dir)
{
//see IsIntersecting...
Vector2D s = Start - start;
float denom = StartToEnd.Cross(dir);
return dir.Cross(s) / denom;
}
/**
* Returns a new vector v at the position where the lines would intersect. Segment boundaries are not considered.
*/
public Vector2D Intersect(LineSegment2D other)
{
return Start + StartToEnd * GetIntersectionRatio(other);
}
/**
* Project the vector v on this line segment and return the ratio.
* return = 0 v = start
* return = 1 v = end
* return < 0 v is on the backward extension of AB
* return > 1 v is on the forward extension of AB
* 0< return <1 v is interior to AB
*/
public float GetSnapRatio(Vector2D v)
{
/*
Let the point be C (Cx,Cy) and the line be AB (Ax,Ay) to (Bx,By).
Let P be the point of perpendicular projection of C on AB. The parameter
r, which indicates P's position along AB, is computed by the dot product
of AC and AB divided by the square of the length of AB:
(1) AC dot AB
r = ---------
||AB||^2
*/
return StartToEnd.Dot(v - Start) / LengthSquared;
}
/**
* Returns a new vector on this line segment at the given 'ratio'. A ratio of 0 returns v1 and a ratio of 1 returns v2.
*/
public Vector2D Sample(float r)
{
return Start + StartToEnd * r;
}
/**
* Returns the point on this line segment that is closest to the vector.
*/
public Vector2D Snapped(Vector2D v)
{
Vector2D toEnd = End - Start;
float sr = toEnd.Dot(v - Start) / toEnd.LengthSquared;
return Start + toEnd * CgMath.Saturate(sr);
}
/**
* Returns the point on this line segment that is closest to the vector.
*/
public Vector2D SnapDelta(Vector2D v)
{
Vector2D toEnd = End - Start;
float sr = toEnd.Dot(v - Start) / toEnd.LengthSquared;
return Start + toEnd * CgMath.Saturate(sr) - v;
}
/**
* Returns the distance of the vector to its closest point on this line segment.
*/
public float Distance(Vector2D v)
{
return SnapDelta(v).Length;
}
/**
* Returns the square of the distance of the vector to its closest point on this line segment.
*/
public float DistanceSquared(Vector2D v)
{
return SnapDelta(v).LengthSquared;
}
/**
* Returns the square of the distance of the vector to its closest point on this line segment.
*/
public float Distance(LineSegment2D other)
{
if (IsIntersecting(other))
return 0;//early out
//see IsIntersecting...
Vector2D v = StartToEnd;
Vector2D ov = other.StartToEnd;
Vector2D s = Start - other.Start;
float denom = v.Cross(ov);
if(denom == 0) //lines are parallel
return Direction.OrthogonalizedClockwise().Dot(s);
float a = CgMath.Saturate(ov.Cross(s) / denom);
float b = CgMath.Saturate(v.Cross(s) / denom);
return Math.Min(other.Distance(Sample(a)), this.Distance(other.Sample(b)));
}
public float DistanceSquared(LineSegment2D other)
{
//see IsIntersecting...
Vector2D v = StartToEnd;
Vector2D ov = other.StartToEnd;
Vector2D s = Start - other.Start;
float denom = v.Cross(ov);
if (denom == 0) //lines are parallel
{
float d = Direction.OrthogonalizedClockwise().Dot(s);
return d * d;
}
float a = CgMath.Saturate(ov.Cross(s) / denom);
float b = CgMath.Saturate(v.Cross(s) / denom);
return Math.Min(other.DistanceSquared(Sample(a)), this.DistanceSquared(other.Sample(b)));
}
public override string ToString()
{
return "(" + Start.ToString() + "->" + End.ToString() + ")";
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.Generic;
using System.Management.Automation.Language;
namespace Microsoft.PowerShell
{
public partial class PSConsoleReadLine
{
private char _lastWordDelimiter = char.MinValue;
private bool _shouldAppend = false;
/// <summary>
/// Returns the position of the beginning of the next word as delimited by white space and delimiters.
/// </summary>
private int ViFindNextWordPoint(string wordDelimiters)
{
return ViFindNextWordPoint(_current, wordDelimiters);
}
/// <summary>
/// Returns the position of the beginning of the next word as delimited by white space and delimiters.
/// </summary>
private int ViFindNextWordPoint(int i, string wordDelimiters)
{
if (IsAtEndOfLine(i))
{
return i;
}
if (InWord(i, wordDelimiters))
{
return ViFindNextWordFromWord(i, wordDelimiters);
}
if (IsDelimiter(i, wordDelimiters))
{
return ViFindNextWordFromDelimiter(i, wordDelimiters);
}
return ViFindNextWordFromWhiteSpace(i, wordDelimiters);
}
private int ViFindNextWordFromWhiteSpace(int i, string wordDelimiters)
{
while (!IsAtEndOfLine(i) && IsWhiteSpace(i))
{
i++;
}
return i;
}
private int ViFindNextWordFromDelimiter(int i, string wordDelimiters)
{
while (!IsAtEndOfLine(i) && IsDelimiter(i, wordDelimiters))
{
i++;
}
if (IsAtEndOfLine(i))
{
if (IsDelimiter(i, wordDelimiters))
{
_shouldAppend = true;
return i + 1;
}
return i;
}
while (!IsAtEndOfLine(i) && IsWhiteSpace(i))
{
i++;
}
return i;
}
private bool IsAtEndOfLine(int i)
{
return i >= (_buffer.Length - 1);
}
private bool IsPastEndOfLine(int i)
{
return i > (_buffer.Length - 1);
}
private int ViFindNextWordFromWord(int i, string wordDelimiters)
{
while (!IsAtEndOfLine(i) && InWord(i, wordDelimiters))
{
i++;
}
if (IsAtEndOfLine(i) && InWord(i, wordDelimiters))
{
_shouldAppend = true;
return i + 1;
}
if (IsDelimiter(i, wordDelimiters))
{
_lastWordDelimiter = _buffer[i];
return i;
}
while (!IsAtEndOfLine(i) && IsWhiteSpace(i))
{
i++;
}
if (IsAtEndOfLine(i) && !InWord(i, wordDelimiters))
{
return i + 1;
}
_lastWordDelimiter = _buffer[i-1];
return i;
}
/// <summary>
/// Returns true of the character at the given position is white space.
/// </summary>
private bool IsWhiteSpace(int i)
{
return char.IsWhiteSpace(_buffer[i]);
}
/// <summary>
/// Returns the beginning of the current/next word as defined by wordDelimiters and whitespace.
/// </summary>
private int ViFindPreviousWordPoint(string wordDelimiters)
{
return ViFindPreviousWordPoint(_current, wordDelimiters);
}
/// <summary>
/// Returns the beginning of the current/next word as defined by wordDelimiters and whitespace.
/// </summary>
/// <param name="i">Current cursor location.</param>
/// <param name="wordDelimiters">Characters used to delimit words.</param>
/// <returns>Location of the beginning of the previous word.</returns>
private int ViFindPreviousWordPoint(int i, string wordDelimiters)
{
if (i == 0)
{
return i;
}
if (IsWhiteSpace(i))
{
return FindPreviousWordFromWhiteSpace(i, wordDelimiters);
}
else if (InWord(i, wordDelimiters))
{
return FindPreviousWordFromWord(i, wordDelimiters);
}
return FindPreviousWordFromDelimiter(i, wordDelimiters);
}
/// <summary>
/// Knowing that you're starting with a word, find the previous start of the next word.
/// </summary>
private int FindPreviousWordFromWord(int i, string wordDelimiters)
{
i--;
if (InWord(i, wordDelimiters))
{
while (i > 0 && InWord(i, wordDelimiters))
{
i--;
}
if (i == 0 && InWord(i, wordDelimiters))
{
return i;
}
return i + 1;
}
if (IsWhiteSpace(i))
{
while (i > 0 && IsWhiteSpace(i))
{
i--;
}
if (i == 0)
{
return i;
}
if (InWord(i, wordDelimiters) && InWord(i-1, wordDelimiters))
{
return FindPreviousWordFromWord(i, wordDelimiters);
}
if (IsDelimiter(i - 1, wordDelimiters))
{
FindPreviousWordFromDelimiter(i, wordDelimiters);
}
return i;
}
while (i > 0 && IsDelimiter(i, wordDelimiters))
{
i--;
}
if (i == 0 && IsDelimiter(i, wordDelimiters))
{
return i;
}
return i + 1;
}
/// <summary>
/// Returns true if the cursor is on a word delimiter
/// </summary>
private bool IsDelimiter(int i, string wordDelimiters)
{
return wordDelimiters.IndexOf(_buffer[i]) >= 0;
}
/// <summary>
/// Returns true if <paramref name="c"/> is in the set of <paramref name="wordDelimiters"/>.
/// </summary>
private bool IsDelimiter(char c, string wordDelimiters)
{
foreach (char delimiter in wordDelimiters)
{
if (c == delimiter)
{
return true;
}
}
return false;
}
/// <summary>
/// Returns the cursor position of the beginning of the previous word when starting on a delimiter
/// </summary>
private int FindPreviousWordFromDelimiter(int i, string wordDelimiters)
{
i--;
if (IsDelimiter(i, wordDelimiters))
{
while (i > 0 && IsDelimiter(i, wordDelimiters))
{
i--;
}
if (i == 0 && !IsDelimiter(i, wordDelimiters))
{
return i + 1;
}
if (!IsWhiteSpace(i))
{
return i + 1;
}
return i;
}
return ViFindPreviousWordPoint(i, wordDelimiters);
}
/// <summary>
/// Returns the cursor position of the beginning of the previous word when starting on white space
/// </summary>
private int FindPreviousWordFromWhiteSpace(int i, string wordDelimiters)
{
while (IsWhiteSpace(i) && i > 0)
{
i--;
}
int j = i - 1;
if (j < 0 || !InWord(i, wordDelimiters) || char.IsWhiteSpace(_buffer[j]))
{
return i;
}
return (ViFindPreviousWordPoint(i, wordDelimiters));
}
/// <summary>
/// Returns the cursor position of the previous word, ignoring all delimiters other what white space
/// </summary>
private int ViFindPreviousGlob()
{
int i = _current;
if (i == 0)
{
return 0;
}
i--;
return ViFindPreviousGlob(i);
}
/// <summary>
/// Returns the cursor position of the previous word from i, ignoring all delimiters other what white space
/// </summary>
private int ViFindPreviousGlob(int i)
{
if (i <= 0)
{
return 0;
}
if (!IsWhiteSpace(i))
{
while (i > 0 && !IsWhiteSpace(i))
{
i--;
}
if (!IsWhiteSpace(i))
{
return i;
}
return i + 1;
}
while (i > 0 && IsWhiteSpace(i))
{
i--;
}
if (i == 0)
{
return i;
}
return ViFindPreviousGlob(i);
}
/// <summary>
/// Finds the next work, using only white space as the word delimiter.
/// </summary>
private int ViFindNextGlob()
{
int i = _current;
return ViFindNextGlob(i);
}
private int ViFindNextGlob(int i)
{
if (i >= _buffer.Length)
{
return i;
}
while (!IsAtEndOfLine(i) && !IsWhiteSpace(i))
{
i++;
}
if (IsAtEndOfLine(i) && !IsWhiteSpace(i))
{
return i + 1;
}
while (!IsAtEndOfLine(i) && IsWhiteSpace(i))
{
i++;
}
if (IsAtEndOfLine(i) && IsWhiteSpace(i))
{
return i + 1;
}
return i;
}
/// <summary>
/// Finds the end of the current/next word as defined by whitespace.
/// </summary>
private int ViFindEndOfGlob()
{
return ViFindGlobEnd(_current);
}
/// <summary>
/// Find the end of the current/next word as defined by wordDelimiters and whitespace.
/// </summary>
private int ViFindNextWordEnd(string wordDelimiters)
{
int i = _current;
return ViFindNextWordEnd(i, wordDelimiters);
}
/// <summary>
/// Find the end of the current/next word as defined by wordDelimiters and whitespace.
/// </summary>
private int ViFindNextWordEnd(int i, string wordDelimiters)
{
if (IsAtEndOfLine(i))
{
return i;
}
if (IsDelimiter(i, wordDelimiters) && !IsDelimiter(i + 1, wordDelimiters))
{
i++;
if (IsAtEndOfLine(i))
{
return i;
}
}
else if (InWord(i, wordDelimiters) && !InWord(i + 1, wordDelimiters))
{
i++;
if (IsAtEndOfLine(i))
{
return i;
}
}
while (!IsAtEndOfLine(i) && IsWhiteSpace(i))
{
i++;
}
if (IsAtEndOfLine(i))
{
return i;
}
if (IsDelimiter(i, wordDelimiters))
{
while (!IsAtEndOfLine(i) && IsDelimiter(i, wordDelimiters))
{
i++;
}
if (!IsDelimiter(i, wordDelimiters))
{
return i - 1;
}
}
else
{
while (!IsAtEndOfLine(i) && InWord(i, wordDelimiters))
{
i++;
}
if (!InWord(i, wordDelimiters))
{
return i - 1;
}
}
return i;
}
/// <summary>
/// Return the last character in a white space defined word after skipping contiguous white space.
/// </summary>
private int ViFindGlobEnd(int i)
{
if (IsAtEndOfLine(i))
{
return i;
}
i++;
if (IsAtEndOfLine(i))
{
return i;
}
while (!IsAtEndOfLine(i) && IsWhiteSpace(i))
{
i++;
}
if (IsAtEndOfLine(i))
{
return i;
}
while (!IsAtEndOfLine(i) && !IsWhiteSpace(i))
{
i++;
}
if (IsWhiteSpace(i))
{
return i - 1;
}
return i;
}
private int ViFindEndOfPreviousGlob()
{
int i = _current;
return ViFindEndOfPreviousGlob(i);
}
private int ViFindEndOfPreviousGlob(int i)
{
if (IsWhiteSpace(i))
{
while (i > 0 && IsWhiteSpace(i))
{
i--;
}
return i;
}
while (i > 0 && !IsWhiteSpace(i))
{
i--;
}
return ViFindEndOfPreviousGlob(i);
}
}
}
| |
using System.Security;
using System.Security.Claims;
using System.Security.Principal;
namespace Odachi.Security
{
public static class PrincipalExtensions
{
/// <summary>
/// Returns whether principal has been granted a permission.
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <returns>True when permission is granted, false otherwise</returns>
public static bool HasPermission(this ClaimsPrincipal principal, Permission permission)
{
foreach (var claim in principal.Claims)
{
if (claim.Type != Permission.PermissionClaim)
continue;
if (permission.Matches(claim.Value))
return true;
}
return false;
}
/// <summary>
/// Returns whether principal has been granted a permission.
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="arg0">The first permission argument</param>
/// <returns>True when permission is granted, false otherwise</returns>
public static bool HasPermission(this ClaimsPrincipal principal, Permission permission, object arg0)
{
foreach (var claim in principal.Claims)
{
if (claim.Type != Permission.PermissionClaim)
continue;
if (permission.Matches(claim.Value, arg0))
return true;
}
return false;
}
/// <summary>
/// Returns whether principal has been granted a permission.
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="arg0">The first permission argument</param>
/// <param name="arg1">The second permission argument</param>
/// <returns>True when permission is granted, false otherwise</returns>
public static bool HasPermission(this ClaimsPrincipal principal, Permission permission, object arg0, object arg1)
{
foreach (var claim in principal.Claims)
{
if (claim.Type != Permission.PermissionClaim)
continue;
if (permission.Matches(claim.Value, arg0, arg1))
return true;
}
return false;
}
/// <summary>
/// Returns whether principal has been granted a permission.
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="args">Permission arguments</param>
/// <returns>True when permission is granted, false otherwise</returns>
public static bool HasPermission(this ClaimsPrincipal principal, Permission permission, params object[] args)
{
foreach (var claim in principal.Claims)
{
if (claim.Type != Permission.PermissionClaim)
continue;
if (permission.Matches(claim.Value, args))
return true;
}
return false;
}
/// <summary>
/// Throws exception when principal has not been granted a permission.
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
public static void DemandPermission(this ClaimsPrincipal principal, Permission permission)
{
if (!HasPermission(principal, permission))
throw new SecurityException("Principal '" + principal.Identity.Name + "' doesn't have permission '" + permission.Template + "'");
}
/// <summary>
/// Throws exception when principal has not been granted a permission.
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="arg0">The first permission argument</param>
public static void DemandPermission(this ClaimsPrincipal principal, Permission permission, object arg0)
{
if (!HasPermission(principal, permission, arg0))
throw new SecurityException("Principal '" + principal.Identity.Name + "' doesn't have permission '" + permission.Template + "'+1");
}
/// <summary>
/// Throws exception when principal has not been granted a permission.
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="arg0">The first permission argument</param>
/// <param name="arg1">The second permission argument</param>
public static void DemandPermission(this ClaimsPrincipal principal, Permission permission, object arg0, object arg1)
{
if (!HasPermission(principal, permission, arg0, arg1))
throw new SecurityException("Principal '" + principal.Identity.Name + "' doesn't have permission '" + permission.Template + "'+2");
}
/// <summary>
/// Throws exception when principal has not been granted a permission.
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="args">Permission arguments</param>
public static void DemandPermission(this ClaimsPrincipal principal, Permission permission, params object[] args)
{
if (!HasPermission(principal, permission, args))
throw new SecurityException("Principal '" + principal.Identity.Name + "' doesn't have permission '" + permission.Template + "'+" + args.Length);
}
/// <summary>
/// Returns whether principal has been granted a permission (assumes principal is ClaimsPrincipal).
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <returns>True when permission is granted, false otherwise</returns>
public static bool HasPermission(this IPrincipal principal, Permission permission)
{
return ((ClaimsPrincipal)principal).HasPermission(permission);
}
/// <summary>
/// Returns whether principal has been granted a permission (assumes principal is ClaimsPrincipal).
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="arg0">The first permission argument</param>
/// <returns>True when permission is granted, false otherwise</returns>
public static bool HasPermission(this IPrincipal principal, Permission permission, object arg0)
{
return ((ClaimsPrincipal)principal).HasPermission(permission, arg0);
}
/// <summary>
/// Returns whether principal has been granted a permission (assumes principal is ClaimsPrincipal).
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="arg0">The first permission argument</param>
/// <param name="arg1">The second permission argument</param>
/// <returns>True when permission is granted, false otherwise</returns>
public static bool HasPermission(this IPrincipal principal, Permission permission, object arg0, object arg1)
{
return ((ClaimsPrincipal)principal).HasPermission(permission, arg0, arg1);
}
/// <summary>
/// Returns whether principal has been granted a permission (assumes principal is ClaimsPrincipal).
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="args">Permission arguments</param>
/// <returns>True when permission is granted, false otherwise</returns>
public static bool HasPermission(this IPrincipal principal, Permission permission, params object[] args)
{
return ((ClaimsPrincipal)principal).HasPermission(permission, args);
}
/// <summary>
/// Throws exception when principal has not been granted a permission (assumes principal is ClaimsPrincipal).
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
public static void DemandPermission(this IPrincipal principal, Permission permission)
{
((ClaimsPrincipal)principal).DemandPermission(permission);
}
/// <summary>
/// Throws exception when principal has not been granted a permission (assumes principal is ClaimsPrincipal).
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="arg0">The first permission argument</param>
public static void DemandPermission(this IPrincipal principal, Permission permission, object arg0)
{
((ClaimsPrincipal)principal).DemandPermission(permission, arg0);
}
/// <summary>
/// Throws exception when principal has not been granted a permission (assumes principal is ClaimsPrincipal).
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="arg0">The first permission argument</param>
/// <param name="arg1">The second permission argument</param>
public static void DemandPermission(this IPrincipal principal, Permission permission, object arg0, object arg1)
{
((ClaimsPrincipal)principal).DemandPermission(permission, arg0, arg1);
}
/// <summary>
/// Throws exception when principal has not been granted a permission (assumes principal is ClaimsPrincipal).
/// </summary>
/// <param name="principal">The principal</param>
/// <param name="permission">The permission</param>
/// <param name="args">Permission arguments</param>
public static void DemandPermission(this IPrincipal principal, Permission permission, params object[] args)
{
((ClaimsPrincipal)principal).DemandPermission(permission, args);
}
}
}
| |
using UnityEngine;
using System.Collections;
public class TimedEvents : GenericEvents
{
#region Functions
public override string GetEventType() { return GenericEventNames.Timed; }
#endregion
#region Events
public class TimedEvent_Base : ICutsceneEventInterface { }
public class TimedEvent_FollowCurve : TimedEvent_Base
{
#region Functions
public void FollowCurve(GameObject follower, Curve curve)
{
follower.transform.position = curve.GetPosition(m_InterpolationTime);
follower.transform.forward = curve.GetForwardDirection(m_InterpolationTime, true);
}
public void FollowCurve(GameObject follower, Curve curve, Transform lookAtTarget)
{
follower.transform.position = curve.GetPosition(m_InterpolationTime);
follower.transform.LookAt(lookAtTarget);
}
public void FollowCurve(string follower, string curve)
{
GameObject gameObj = GameObject.Find(follower);
GameObject curveGo = GameObject.Find(curve);
if (gameObj != null && curveGo != null)
{
gameObj.transform.position = curveGo.GetComponent<Curve>().GetPosition(m_InterpolationTime);
gameObj.transform.forward = curveGo.GetComponent<Curve>().GetForwardDirection(m_InterpolationTime, true);
}
}
public void FollowCurve(string follower, string curve, string lookAtTarget)
{
GameObject gameObj = GameObject.Find(follower);
GameObject curveGo = GameObject.Find(curve);
if (gameObj != null && curveGo != null)
{
gameObj.transform.position = curveGo.GetComponent<Curve>().GetPosition(m_InterpolationTime);
gameObj.transform.forward = curveGo.GetComponent<Curve>().GetForwardDirection(m_InterpolationTime, true);
GameObject lookAtGo = GameObject.Find(lookAtTarget);
if (lookAtGo != null)
{
gameObj.transform.LookAt(lookAtGo.transform);
}
}
}
public override bool IsFireAndForget() { return false; }
#endregion
}
public class TimedEvent_FadeLight : TimedEvent_Base
{
#region Functions
public void FadeLight(Light light, Color startColor, Color endColor)
{
light.color = Color.Lerp(startColor, endColor, m_InterpolationTime);
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "startColor")
{
param.colorData = Color.white;
}
}
public override bool IsFireAndForget() { return false; }
#endregion
}
public class TimedEvent_FadeLightIntensity : TimedEvent_Base
{
#region Functions
public void FadeLightIntensity(Light light, float startIntensity, float endIntensity)
{
light.intensity = Mathf.Lerp(startIntensity, endIntensity, m_InterpolationTime);
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "startIntensity")
{
param.floatData = 1;
}
}
public override bool IsFireAndForget() { return false; }
#endregion
}
public class TimedEvent_FadeRenderer : TimedEvent_Base
{
#region Functions
public void FadeRenderer(Renderer renderer, Color startColor, Color endColor)
{
if (Application.isPlaying)
{
renderer.material.color = Color.Lerp(startColor, endColor, m_InterpolationTime);
}
else
{
renderer.sharedMaterial.color = Color.Lerp(startColor, endColor, m_InterpolationTime);
}
}
public void FadeRenderer(Renderer renderer, Color startColor, Color endColor, int materialIndex)
{
Material[] mats = Application.isPlaying ? renderer.materials : renderer.sharedMaterials;
mats[materialIndex].color = Color.Lerp(startColor, endColor, m_InterpolationTime);
renderer.materials = mats;
}
public void FadeRenderer(string renderer, Color startColor, Color endColor)
{
Renderer rendComp = GetComponentFromString<Renderer>(renderer);
if (rendComp != null)
{
FadeRenderer(rendComp, startColor, endColor);
}
}
public void FadeRenderer(string renderer, Color startColor, Color endColor, int materialIndex)
{
Renderer rendComp = GetComponentFromString<Renderer>(renderer);
if (rendComp != null)
{
FadeRenderer(rendComp, startColor, endColor, materialIndex);
}
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "startColor")
{
param.colorData = Color.white;
}
}
public override bool IsFireAndForget() { return false; }
#endregion
}
public class TimedEvent_FadeGUITexture : TimedEvent_Base
{
#region Functions
public void FadeGUITexture(GUITexture guiTexture, Color startColor, Color endColor)
{
guiTexture.color = Color.Lerp(startColor, endColor, m_InterpolationTime);
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "startColor")
{
param.colorData = Color.white;
}
}
public override bool IsFireAndForget() { return false; }
#endregion
}
public class TimedEvent_FadeAudio : TimedEvent_Base
{
#region Functions
public void FadeAudio(AudioSource source, float startVolume, float endVolume)
{
source.volume = Mathf.Lerp(startVolume, endVolume, m_InterpolationTime);
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "startVolume")
{
param.floatData = 1;
}
}
public override bool IsFireAndForget() { return false; }
#endregion
}
public class TimedEvent_Rotate : TimedEvent_Base
{
#region Functions
public void Rotate(Transform transform, Vector3 startRotation, Vector3 endRotation)
{
transform.localRotation = Quaternion.Euler(Vector3.Lerp(startRotation, endRotation, Mathf.Clamp01(m_InterpolationTime)));
}
public void Rotate(Transform transform, Vector3 startRotation, Transform endRotation)
{
transform.localRotation = Quaternion.Euler(Vector3.Lerp(startRotation, endRotation.rotation.eulerAngles, Mathf.Clamp01(m_InterpolationTime)));
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "endRotation")
{
param.vec3Data = new Vector3(90, 90, 90);
}
}
public override bool IsFireAndForget() { return false; }
#endregion
}
public class TimedEvent_Translate : TimedEvent_Base
{
#region Functions
public void Translate(Transform transform, Vector3 startPosition, Vector3 endPosition)
{
transform.localPosition = Vector3.Lerp(startPosition, endPosition, Mathf.Clamp01(m_InterpolationTime));
}
public void Translate(Transform transform, Vector3 startPosition, Transform endPosition)
{
transform.localPosition = Vector3.Lerp(startPosition, endPosition.position, Mathf.Clamp01(m_InterpolationTime));
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "endPosition")
{
param.vec3Data = new Vector3(10, 0, 0);
}
}
public override bool IsFireAndForget() { return false; }
#endregion
}
public class TimedEvent_Scale : TimedEvent_Base
{
#region Functions
public void Scale(Transform transform, Vector3 startScale, Vector3 endScale)
{
transform.localScale = Vector3.Lerp(startScale, endScale, Mathf.Clamp01(m_InterpolationTime));
}
public void Scale(Transform transform, Vector3 startScale, Transform endScale)
{
transform.localScale = Vector3.Lerp(startScale, endScale.localScale, Mathf.Clamp01(m_InterpolationTime));
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "startScale")
{
param.vec3Data = Vector3.one;
}
}
public override bool IsFireAndForget() { return false; }
#endregion
}
public class TimedEvent_CameraFOV : TimedEvent_Base
{
#region Functions
public void CameraFOV(Camera camera, float startFov, float endFov)
{
camera.fieldOfView = Mathf.Lerp(startFov, endFov, Mathf.Clamp01(m_InterpolationTime));
}
public override void UseParamDefaultValue(CutsceneEvent ce, CutsceneEventParam param)
{
if (param.Name == "startFov")
{
param.floatData = 60;
}
else if (param.Name == "endFov")
{
param.floatData = 90;
}
}
public override bool IsFireAndForget() { return false; }
#endregion
}
#endregion
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
[CanEditMultipleObjects]
[CustomEditor(typeof(tk2dSprite))]
class tk2dSpriteEditor : Editor
{
// Serialized properties are going to be far too much hassle
private tk2dBaseSprite[] targetSprites = new tk2dBaseSprite[0];
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
private Renderer[] renderers = new Renderer[0];
#endif
public override void OnInspectorGUI()
{
DrawSpriteEditorGUI();
}
public void OnSceneGUI()
{
if (tk2dPreferences.inst.enableSpriteHandles == false || !tk2dEditorUtility.IsEditable(target)) {
return;
}
tk2dSprite spr = (tk2dSprite)target;
var sprite = spr.CurrentSprite;
if (sprite == null) {
return;
}
Transform t = spr.transform;
Bounds b = spr.GetUntrimmedBounds();
Rect localRect = new Rect(b.min.x, b.min.y, b.size.x, b.size.y);
// Draw rect outline
Handles.color = new Color(1,1,1,0.5f);
tk2dSceneHelper.DrawRect (localRect, t);
Handles.BeginGUI ();
// Resize handles
if (tk2dSceneHelper.RectControlsToggle ()) {
EditorGUI.BeginChangeCheck ();
Rect resizeRect = tk2dSceneHelper.RectControl (999888, localRect, t);
if (EditorGUI.EndChangeCheck ()) {
tk2dUndo.RecordObjects(new Object[] {t, spr}, "Resize");
spr.ReshapeBounds(new Vector3(resizeRect.xMin, resizeRect.yMin) - new Vector3(localRect.xMin, localRect.yMin),
new Vector3(resizeRect.xMax, resizeRect.yMax) - new Vector3(localRect.xMax, localRect.yMax));
tk2dUtil.SetDirty(spr);
}
}
// Rotate handles
if (!tk2dSceneHelper.RectControlsToggle ()) {
EditorGUI.BeginChangeCheck();
float theta = tk2dSceneHelper.RectRotateControl (888999, localRect, t, new List<int>());
if (EditorGUI.EndChangeCheck()) {
tk2dUndo.RecordObject (t, "Rotate");
if (Mathf.Abs(theta) > Mathf.Epsilon) {
t.Rotate(t.forward, theta, Space.World);
}
}
}
Handles.EndGUI ();
// Sprite selecting
tk2dSceneHelper.HandleSelectSprites();
// Move targeted sprites
tk2dSceneHelper.HandleMoveSprites(t, localRect);
if (GUI.changed) {
tk2dUtil.SetDirty(target);
}
}
protected T[] GetTargetsOfType<T>( Object[] objects ) where T : UnityEngine.Object {
List<T> ts = new List<T>();
foreach (Object o in objects) {
T s = o as T;
if (s != null)
ts.Add(s);
}
return ts.ToArray();
}
protected void OnEnable()
{
targetSprites = GetTargetsOfType<tk2dBaseSprite>( targets );
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
List<Renderer> rs = new List<Renderer>();
foreach (var v in targetSprites) {
if (v != null && v.GetComponent<Renderer>() != null) {
rs.Add(v.GetComponent<Renderer>());
}
}
renderers = rs.ToArray();
#endif
}
void OnDestroy()
{
targetSprites = new tk2dBaseSprite[0];
tk2dSpriteThumbnailCache.Done();
tk2dGrid.Done();
tk2dEditorSkin.Done();
}
// Callback and delegate
void SpriteChangedCallbackImpl(tk2dSpriteCollectionData spriteCollection, int spriteId, object data)
{
tk2dUndo.RecordObjects(targetSprites, "Sprite Change");
foreach (tk2dBaseSprite s in targetSprites) {
s.SetSprite(spriteCollection, spriteId);
s.EditMode__CreateCollider();
tk2dUtil.SetDirty(s);
}
}
tk2dSpriteGuiUtility.SpriteChangedCallback _spriteChangedCallbackInstance = null;
tk2dSpriteGuiUtility.SpriteChangedCallback spriteChangedCallbackInstance {
get {
if (_spriteChangedCallbackInstance == null) {
_spriteChangedCallbackInstance = new tk2dSpriteGuiUtility.SpriteChangedCallback( SpriteChangedCallbackImpl );
}
return _spriteChangedCallbackInstance;
}
}
protected void DrawSpriteEditorGUI()
{
Event ev = Event.current;
tk2dSpriteGuiUtility.SpriteSelector( targetSprites[0].Collection, targetSprites[0].spriteId, spriteChangedCallbackInstance, null );
if (targetSprites[0].Collection != null)
{
if (tk2dPreferences.inst.displayTextureThumbs) {
tk2dBaseSprite sprite = targetSprites[0];
tk2dSpriteDefinition def = sprite.GetCurrentSpriteDef();
if (sprite.Collection.version < 1 || def.texelSize == Vector2.zero)
{
string message = "";
message = "No thumbnail data.";
if (sprite.Collection.version < 1)
message += "\nPlease rebuild Sprite Collection.";
tk2dGuiUtility.InfoBox(message, tk2dGuiUtility.WarningLevel.Info);
}
else
{
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(" ");
int tileSize = 128;
Rect r = GUILayoutUtility.GetRect(tileSize, tileSize, GUILayout.ExpandWidth(false));
tk2dGrid.Draw(r);
tk2dSpriteThumbnailCache.DrawSpriteTextureInRect(r, def, Color.white);
GUILayout.EndHorizontal();
r = GUILayoutUtility.GetLastRect();
if (ev.type == EventType.MouseDown && ev.button == 0 && r.Contains(ev.mousePosition)) {
tk2dSpriteGuiUtility.SpriteSelectorPopup( sprite.Collection, sprite.spriteId, spriteChangedCallbackInstance, null );
}
}
}
Color newColor = EditorGUILayout.ColorField("Color", targetSprites[0].color);
if (newColor != targetSprites[0].color) {
tk2dUndo.RecordObjects(targetSprites, "Sprite Color");
foreach (tk2dBaseSprite s in targetSprites) {
s.color = newColor;
}
}
GUILayout.Space(8);
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
int sortingOrder = EditorGUILayout.IntField("Sorting Order In Layer", targetSprites[0].SortingOrder);
if (sortingOrder != targetSprites[0].SortingOrder) {
tk2dUndo.RecordObjects(targetSprites, "Sorting Order In Layer");
foreach (tk2dBaseSprite s in targetSprites) {
s.SortingOrder = sortingOrder;
}
}
#else
if (renderers.Length > 0) {
string sortingLayerName = tk2dEditorUtility.SortingLayerNamePopup("Sorting Layer", renderers[0].sortingLayerName);
if (sortingLayerName != renderers[0].sortingLayerName) {
tk2dUndo.RecordObjects(renderers, "Sorting Layer");
foreach (Renderer r in renderers) {
r.sortingLayerName = sortingLayerName;
}
}
int sortingOrder = EditorGUILayout.IntField("Order In Layer", targetSprites[0].SortingOrder);
if (sortingOrder != targetSprites[0].SortingOrder) {
tk2dUndo.RecordObjects(targetSprites, "Order In Layer");
tk2dUndo.RecordObjects(renderers, "Order In Layer");
foreach (tk2dBaseSprite s in targetSprites) {
s.SortingOrder = sortingOrder;
}
}
}
#endif
GUILayout.Space(8);
Vector3 newScale = EditorGUILayout.Vector3Field("Scale", targetSprites[0].scale);
if (newScale != targetSprites[0].scale)
{
tk2dUndo.RecordObjects(targetSprites, "Sprite Scale");
foreach (tk2dBaseSprite s in targetSprites) {
s.scale = newScale;
s.EditMode__CreateCollider();
}
}
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("HFlip", EditorStyles.miniButton))
{
tk2dUndo.RecordObjects(targetSprites, "Sprite HFlip");
foreach (tk2dBaseSprite sprite in targetSprites) {
sprite.EditMode__CreateCollider();
Vector3 scale = sprite.scale;
scale.x *= -1.0f;
sprite.scale = scale;
}
GUI.changed = true;
}
if (GUILayout.Button("VFlip", EditorStyles.miniButton))
{
tk2dUndo.RecordObjects(targetSprites, "Sprite VFlip");
foreach (tk2dBaseSprite sprite in targetSprites) {
Vector3 s = sprite.scale;
s.y *= -1.0f;
sprite.scale = s;
GUI.changed = true;
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button(new GUIContent("Reset Scale", "Set scale to 1"), EditorStyles.miniButton))
{
tk2dUndo.RecordObjects(targetSprites, "Sprite Reset Scale");
foreach (tk2dBaseSprite sprite in targetSprites) {
Vector3 s = sprite.scale;
s.x = Mathf.Sign(s.x);
s.y = Mathf.Sign(s.y);
s.z = Mathf.Sign(s.z);
sprite.scale = s;
GUI.changed = true;
}
}
if (GUILayout.Button(new GUIContent("Bake Scale", "Transfer scale from transform.scale -> sprite"), EditorStyles.miniButton))
{
foreach (tk2dBaseSprite sprite in targetSprites) {
tk2dScaleUtility.Bake(sprite.transform);
}
GUI.changed = true;
}
GUIContent pixelPerfectButton = new GUIContent("1:1", "Make Pixel Perfect for camera");
if ( GUILayout.Button(pixelPerfectButton, EditorStyles.miniButton ))
{
if (tk2dPixelPerfectHelper.inst) tk2dPixelPerfectHelper.inst.Setup();
tk2dUndo.RecordObjects(targetSprites, "Sprite Pixel Perfect");
foreach (tk2dBaseSprite sprite in targetSprites) {
sprite.MakePixelPerfect();
}
GUI.changed = true;
}
EditorGUILayout.EndHorizontal();
}
else
{
tk2dGuiUtility.InfoBox("Please select a sprite collection.", tk2dGuiUtility.WarningLevel.Error);
}
bool needUpdatePrefabs = false;
if (GUI.changed)
{
foreach (tk2dBaseSprite sprite in targetSprites) {
if (PrefabUtility.GetPrefabType(sprite) == PrefabType.Prefab)
needUpdatePrefabs = true;
tk2dUtil.SetDirty(sprite);
}
}
// This is a prefab, and changes need to be propagated. This isn't supported in Unity 3.4
if (needUpdatePrefabs)
{
// Rebuild prefab instances
tk2dBaseSprite[] allSprites = Resources.FindObjectsOfTypeAll(typeof(tk2dBaseSprite)) as tk2dBaseSprite[];
foreach (var spr in allSprites)
{
if (PrefabUtility.GetPrefabType(spr) == PrefabType.PrefabInstance)
{
Object parent = PrefabUtility.GetPrefabParent(spr.gameObject);
bool found = false;
foreach (tk2dBaseSprite sprite in targetSprites) {
if (sprite.gameObject == parent) {
found = true;
break;
}
}
if (found) {
// Reset all prefab states
var propMod = PrefabUtility.GetPropertyModifications(spr);
PrefabUtility.ResetToPrefabState(spr);
PrefabUtility.SetPropertyModifications(spr, propMod);
spr.ForceBuild();
}
}
}
}
}
protected void WarnSpriteRenderType(tk2dSpriteDefinition sprite) {
if (sprite.positions.Length != 4 || sprite.complexGeometry) {
EditorGUILayout.HelpBox("Sprite type incompatible with Render Mesh setting.\nPlease use Default Render Mesh.", MessageType.Error);
}
}
static void PerformActionOnGlobalSelection(string actionName, System.Action<GameObject> action) {
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo(actionName);
#else
int undoGroup = Undo.GetCurrentGroup();
#endif
foreach (GameObject go in Selection.gameObjects) {
if (go.GetComponent<tk2dBaseSprite>() != null) {
action(go);
}
}
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.CollapseUndoOperations(undoGroup);
#endif
}
static void ConvertSpriteType(GameObject go, System.Type targetType) {
tk2dBaseSprite spr = go.GetComponent<tk2dBaseSprite>();
System.Type sourceType = spr.GetType();
if (sourceType != targetType) {
tk2dBatchedSprite batchedSprite = new tk2dBatchedSprite();
tk2dStaticSpriteBatcherEditor.FillBatchedSprite(batchedSprite, go);
if (targetType == typeof(tk2dSprite)) batchedSprite.type = tk2dBatchedSprite.Type.Sprite;
else if (targetType == typeof(tk2dTiledSprite)) batchedSprite.type = tk2dBatchedSprite.Type.TiledSprite;
else if (targetType == typeof(tk2dSlicedSprite)) batchedSprite.type = tk2dBatchedSprite.Type.SlicedSprite;
else if (targetType == typeof(tk2dClippedSprite)) batchedSprite.type = tk2dBatchedSprite.Type.ClippedSprite;
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
if (spr.collider != null) {
Object.DestroyImmediate(spr.collider);
}
Object.DestroyImmediate(spr, true);
#else
{
Collider[] colliders = spr.GetComponents<Collider>();
foreach (Collider c in colliders) {
Undo.DestroyObjectImmediate(c);
}
Collider2D[] collider2Ds = spr.GetComponents<Collider2D>();
foreach (Collider2D c in collider2Ds) {
Undo.DestroyObjectImmediate(c);
}
}
Undo.DestroyObjectImmediate(spr);
#endif
bool sourceHasDimensions = sourceType == typeof(tk2dSlicedSprite) || sourceType == typeof(tk2dTiledSprite);
bool targetHasDimensions = targetType == typeof(tk2dSlicedSprite) || targetType == typeof(tk2dTiledSprite);
// Some minor fixups
if (!sourceHasDimensions && targetHasDimensions) {
batchedSprite.Dimensions = new Vector2(100, 100);
}
if (targetType == typeof(tk2dClippedSprite)) {
batchedSprite.ClippedSpriteRegionBottomLeft = Vector2.zero;
batchedSprite.ClippedSpriteRegionTopRight = Vector2.one;
}
if (targetType == typeof(tk2dSlicedSprite)) {
batchedSprite.SlicedSpriteBorderBottomLeft = new Vector2(0.1f, 0.1f);
batchedSprite.SlicedSpriteBorderTopRight = new Vector2(0.1f, 0.1f);
}
tk2dStaticSpriteBatcherEditor.RestoreBatchedSprite(go, batchedSprite);
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
{
tk2dBaseSprite tmpSprite = go.GetComponent<tk2dBaseSprite>();
if (tmpSprite != null) {
Undo.RegisterCreatedObjectUndo( tmpSprite, "Convert Sprite Type" );
}
}
#endif
}
}
// This is used by derived classes only
protected bool DrawCreateBoxColliderCheckbox(bool value) {
tk2dBaseSprite sprite = target as tk2dBaseSprite;
bool newCreateBoxCollider = EditorGUILayout.Toggle("Create Box Collider", value);
if (newCreateBoxCollider != value) {
tk2dUndo.RecordObjects(targetSprites, "Create Box Collider");
if (!newCreateBoxCollider) {
var boxCollider = sprite.GetComponent<BoxCollider>();
if (boxCollider != null) {
DestroyImmediate(boxCollider);
}
#if !STRIP_PHYSICS_3D
sprite.boxCollider = null;
#endif
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
#if !STRIP_PHYSICS_2D
var boxCollider2D = sprite.GetComponent<BoxCollider2D>();
if (boxCollider2D != null) {
DestroyImmediate(boxCollider2D);
}
sprite.boxCollider2D = null;
#endif
#endif
}
}
return newCreateBoxCollider;
}
[MenuItem("CONTEXT/tk2dBaseSprite/Convert to Sprite")]
static void DoConvertSprite() { PerformActionOnGlobalSelection( "Convert to Sprite", (go) => ConvertSpriteType(go, typeof(tk2dSprite)) ); }
[MenuItem("CONTEXT/tk2dBaseSprite/Convert to Sliced Sprite")]
static void DoConvertSlicedSprite() { PerformActionOnGlobalSelection( "Convert to Sliced Sprite", (go) => ConvertSpriteType(go, typeof(tk2dSlicedSprite)) ); }
[MenuItem("CONTEXT/tk2dBaseSprite/Convert to Tiled Sprite")]
static void DoConvertTiledSprite() { PerformActionOnGlobalSelection( "Convert to Tiled Sprite", (go) => ConvertSpriteType(go, typeof(tk2dTiledSprite)) ); }
[MenuItem("CONTEXT/tk2dBaseSprite/Convert to Clipped Sprite")]
static void DoConvertClippedSprite() { PerformActionOnGlobalSelection( "Convert to Clipped Sprite", (go) => ConvertSpriteType(go, typeof(tk2dClippedSprite)) ); }
[MenuItem("CONTEXT/tk2dBaseSprite/Add animator", true, 10000)]
static bool ValidateAddAnimator() {
if (Selection.activeGameObject == null) return false;
return Selection.activeGameObject.GetComponent<tk2dSpriteAnimator>() == null;
}
[MenuItem("CONTEXT/tk2dBaseSprite/Add animator", false, 10000)]
static void DoAddAnimator() {
tk2dSpriteAnimation anim = null;
int clipId = -1;
if (!tk2dSpriteAnimatorEditor.GetDefaultSpriteAnimation(out anim, out clipId)) {
EditorUtility.DisplayDialog("Create Sprite Animation", "Unable to create animated sprite as no SpriteAnimations have been found.", "Ok");
return;
}
else {
PerformActionOnGlobalSelection("Add animator", delegate(GameObject go) {
tk2dSpriteAnimator animator = go.GetComponent<tk2dSpriteAnimator>();
if (animator == null) {
animator = go.AddComponent<tk2dSpriteAnimator>();
animator.Library = anim;
animator.DefaultClipId = clipId;
tk2dSpriteAnimationClip clip = anim.GetClipById(clipId);
animator.SetSprite( clip.frames[0].spriteCollection, clip.frames[0].spriteId );
}
});
}
}
[MenuItem("CONTEXT/tk2dBaseSprite/Add AttachPoint", false, 10002)]
static void DoRemoveAnimator() {
PerformActionOnGlobalSelection("Add AttachPoint", delegate(GameObject go) {
tk2dSpriteAttachPoint ap = go.GetComponent<tk2dSpriteAttachPoint>();
if (ap == null) {
go.AddComponent<tk2dSpriteAttachPoint>();
}
});
}
[MenuItem(tk2dMenu.createBase + "Sprite", false, 1290)]
static void DoCreateSpriteObject()
{
tk2dSpriteGuiUtility.GetSpriteCollectionAndCreate( (sprColl) => {
GameObject go = tk2dEditorUtility.CreateGameObjectInScene("Sprite");
tk2dSprite sprite = go.AddComponent<tk2dSprite>();
sprite.SetSprite(sprColl, sprColl.FirstValidDefinitionIndex);
sprite.GetComponent<Renderer>().material = sprColl.FirstValidDefinition.material;
sprite.Build();
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create Sprite");
} );
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Xunit;
namespace System.Collections.ObjectModel.Tests
{
/// <summary>
/// Tests the public properties and constructor in ObservableCollection<T>.
/// </summary>
public class ReadOnlyObservableCollectionTests
{
[Fact]
public static void Ctor_Tests()
{
string[] anArray = new string[] { "one", "two", "three", "four", "five" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>(readOnlyCol, anArray);
helper.InitialItems_Tests();
IList<string> readOnlyColAsIList = readOnlyCol;
Assert.True(readOnlyColAsIList.IsReadOnly, "ReadOnlyObservableCollection should be readOnly.");
}
[Fact]
public static void Ctor_Tests_Negative()
{
ReadOnlyObservableCollection<string> collection;
Assert.Throws<ArgumentNullException>(() => collection = new ReadOnlyObservableCollection<string>(null));
}
[Fact]
public static void GetItemTests()
{
string[] anArray = new string[] { "one", "two", "three", "four", "five" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>(readOnlyCol, anArray);
helper.Item_get_Tests();
}
[Fact]
public static void GetItemTests_Negative()
{
string[] anArray = new string[] { "one", "two", "three", "four", "five" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>(readOnlyCol, anArray);
helper.Item_get_Tests_Negative();
}
/// <summary>
/// Tests that contains returns true when the item is in the collection
/// and false otherwise.
/// </summary>
[Fact]
public static void ContainsTests()
{
string[] anArray = new string[] { "one", "two", "three", "four", "five" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
for (int i = 0; i < anArray.Length; i++)
{
string item = anArray[i];
Assert.True(readOnlyCol.Contains(item), "ReadOnlyCol did not contain item: " + anArray[i] + " at index: " + i);
}
Assert.False(readOnlyCol.Contains("randomItem"), "ReadOnlyCol should not have contained non-existent item");
Assert.False(readOnlyCol.Contains(null), "ReadOnlyCol should not have contained null");
}
/// <summary>
/// Tests that the collection can be copied into a destination array.
/// </summary>
[Fact]
public static void CopyToTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
string[] aCopy = new string[anArray.Length];
readOnlyCol.CopyTo(aCopy, 0);
for (int i = 0; i < anArray.Length; ++i)
Assert.Equal(anArray[i], aCopy[i]);
// copy observable collection starting in middle, where array is larger than source.
aCopy = new string[anArray.Length + 2];
int offsetIndex = 1;
readOnlyCol.CopyTo(aCopy, offsetIndex);
for (int i = 0; i < aCopy.Length; i++)
{
string value = aCopy[i];
if (i == 0)
Assert.True(null == value, "Should not have a value since we did not start copying there.");
else if (i == (aCopy.Length - 1))
Assert.True(null == value, "Should not have a value since the collection is shorter than the copy array..");
else
{
int indexInCollection = i - offsetIndex;
Assert.Equal(readOnlyCol[indexInCollection], aCopy[i]);
}
}
}
/// <summary>
/// Tests that:
/// ArgumentOutOfRangeException is thrown when the Index is >= collection.Count
/// or Index < 0.
/// ArgumentException when the destination array does not have enough space to
/// contain the source Collection.
/// ArgumentNullException when the destination array is null.
/// </summary>
[Fact]
public static void CopyToTest_Negative()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
foreach (var index in iArrInvalidValues)
{
string[] aCopy = new string[anArray.Length];
Assert.Throws<ArgumentOutOfRangeException>(() => readOnlyCol.CopyTo(aCopy, index));
}
int[] iArrLargeValues = new Int32[] { anArray.Length, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
foreach (var index in iArrLargeValues)
{
string[] aCopy = new string[anArray.Length];
AssertExtensions.Throws<ArgumentException>("destinationArray", null, () => readOnlyCol.CopyTo(aCopy, index));
}
Assert.Throws<ArgumentNullException>(() => readOnlyCol.CopyTo(null, 1));
string[] copy = new string[anArray.Length - 1];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => readOnlyCol.CopyTo(copy, 0));
copy = new string[0];
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => readOnlyCol.CopyTo(copy, 0));
}
/// <summary>
/// Tests that the index of an item can be retrieved when the item is
/// in the collection and -1 otherwise.
/// </summary>
[Fact]
public static void IndexOfTest()
{
string[] anArray = new string[] { "one", "two", "three", "four" };
ReadOnlyObservableCollection<string> readOnlyCollection =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
for (int i = 0; i < anArray.Length; ++i)
Assert.Equal(i, readOnlyCollection.IndexOf(anArray[i]));
Assert.Equal(-1, readOnlyCollection.IndexOf("seven"));
Assert.Equal(-1, readOnlyCollection.IndexOf(null));
// testing that the first occurrence is the index returned.
ObservableCollection<int> intCol = new ObservableCollection<int>();
for (int i = 0; i < 4; ++i)
intCol.Add(i % 2);
ReadOnlyObservableCollection<int> intReadOnlyCol = new ReadOnlyObservableCollection<int>(intCol);
Assert.Equal(0, intReadOnlyCol.IndexOf(0));
Assert.Equal(1, intReadOnlyCol.IndexOf(1));
IList colAsIList = (IList)intReadOnlyCol;
var index = colAsIList.IndexOf("stringObj");
Assert.Equal(-1, index);
}
/// <summary>
/// Tests that a ReadOnlyDictionary cannot be modified. That is, that
/// Add, Remove, Clear does not work.
/// </summary>
[Fact]
public static void CannotModifyDictionaryTests_Negative()
{
string[] anArray = new string[] { "one", "two", "three", "four", "five" };
ReadOnlyObservableCollection<string> readOnlyCol =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray));
IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>();
IList<string> readOnlyColAsIList = readOnlyCol;
Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Add("seven"));
Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Insert(0, "nine"));
Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Remove("one"));
Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Clear());
helper.VerifyReadOnlyCollection(readOnlyCol, anArray);
}
[Fact]
// skip the test on desktop as "new ObservableCollection<int>()" returns 0 length collection
// skip the test on UapAot as the requires Reflection on internal framework types.
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot)]
public static void DebuggerAttribute_Tests()
{
ReadOnlyObservableCollection<int> col = new ReadOnlyObservableCollection<int>(new ObservableCollection<int>(new[] {1, 2, 3, 4}));
DebuggerAttributes.ValidateDebuggerDisplayReferences(col);
DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(col);
PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden);
int[] items = itemProperty.GetValue(info.Instance) as int[];
Assert.Equal(col, items);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public static void DebuggerAttribute_NullCollection_ThrowsArgumentNullException()
{
TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(ReadOnlyObservableCollection<int>), null));
ArgumentNullException argumentNullException = Assert.IsType<ArgumentNullException>(ex.InnerException);
}
}
internal class IReadOnlyList_T_Test<T>
{
private readonly IReadOnlyList<T> _collection;
private readonly T[] _expectedItems;
/// <summary>
/// Initializes a new instance of the IReadOnlyList_T_Test.
/// </summary>
/// <param name="collection">The collection to run the tests on.</param>
/// <param name="expectedItems">The items expected to be in the collection.</param>
public IReadOnlyList_T_Test(IReadOnlyList<T> collection, T[] expectedItems)
{
_collection = collection;
_expectedItems = expectedItems;
}
public IReadOnlyList_T_Test()
{
}
/// <summary>
/// This verifies that the collection contains the expected items.
/// </summary>
public void InitialItems_Tests()
{
// Verify Count returns the expected value
Assert.Equal(_expectedItems.Length, _collection.Count);
// Verify the initial items in the collection
VerifyReadOnlyCollection(_collection, _expectedItems);
}
/// <summary>
/// Runs all of the valid tests on get Item.
/// </summary>
public void Item_get_Tests()
{
// Verify get_Item with valid item on Collection
Verify_get(_collection, _expectedItems);
}
/// <summary>
/// Runs all of the argument checking(invalid) tests on get Item.
/// </summary>
public void Item_get_Tests_Negative()
{
// Verify get_Item with index=Int32.MinValue
Assert.Throws<ArgumentOutOfRangeException>(() => { T item = _collection[Int32.MinValue]; });
// Verify that the collection was not mutated
VerifyReadOnlyCollection(_collection, _expectedItems);
// Verify get_Item with index=-1
Assert.Throws<ArgumentOutOfRangeException>(() => { T item = _collection[-1]; });
// Verify that the collection was not mutated
VerifyReadOnlyCollection(_collection, _expectedItems);
if (_expectedItems.Length == 0)
{
// Verify get_Item with index=0 on Empty collection
Assert.Throws<ArgumentOutOfRangeException>(() => { T item = _collection[0]; });
// Verify that the collection was not mutated
VerifyReadOnlyCollection(_collection, _expectedItems);
}
else
{
// Verify get_Item with index=Count on Empty collection
Assert.Throws<ArgumentOutOfRangeException>(() => { T item = _collection[_expectedItems.Length]; });
// Verify that the collection was not mutated
VerifyReadOnlyCollection(_collection, _expectedItems);
}
}
#region Helper Methods
/// <summary>
/// Verifies that the items in the collection match the expected items.
/// </summary>
internal void VerifyReadOnlyCollection(IReadOnlyList<T> collection, T[] items)
{
Verify_get(collection, items);
VerifyGenericEnumerator(collection, items);
VerifyEnumerator(collection, items);
}
/// <summary>
/// Verifies that you can get all items that should be in the collection.
/// </summary>
private void Verify_get(IReadOnlyList<T> collection, T[] items)
{
Assert.Equal(items.Length, collection.Count);
for (int i = 0; i < items.Length; i++)
{
int itemsIndex = i;
Assert.Equal(items[itemsIndex], collection[i]);
}
}
/// <summary>
/// Verifies that the generic enumerator retrieves the correct items.
/// </summary>
private void VerifyGenericEnumerator(IReadOnlyList<T> collection, T[] expectedItems)
{
IEnumerator<T> enumerator = collection.GetEnumerator();
int iterations = 0;
int expectedCount = expectedItems.Length;
// There is a sequential order to the collection, so we're testing for that.
while ((iterations < expectedCount) && enumerator.MoveNext())
{
T currentItem = enumerator.Current;
T tempItem;
// Verify we have not gotten more items then we expected
Assert.True(iterations < expectedCount,
"Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) than are in the expectedElements(" + expectedCount + " items)");
// Verify Current returned the correct value
Assert.Equal(currentItem, expectedItems[iterations]);
// Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
Assert.Equal(currentItem, tempItem);
}
iterations++;
}
Assert.Equal(expectedCount, iterations);
for (int i = 0; i < 3; i++)
{
Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations");
}
enumerator.Dispose();
}
/// <summary>
/// Verifies that the non-generic enumerator retrieves the correct items.
/// </summary>
private void VerifyEnumerator(IReadOnlyList<T> collection, T[] expectedItems)
{
IEnumerator enumerator = collection.GetEnumerator();
int iterations = 0;
int expectedCount = expectedItems.Length;
// There is no sequential order to the collection, so we're testing that all the items
// in the readonlydictionary exist in the array.
bool[] itemsVisited = new bool[expectedCount];
bool itemFound;
while ((iterations < expectedCount) && enumerator.MoveNext())
{
object currentItem = enumerator.Current;
object tempItem;
// Verify we have not gotten more items then we expected
Assert.True(iterations < expectedCount,
"Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) then are in the expectedElements(" + expectedCount + " items)");
// Verify Current returned the correct value
itemFound = false;
for (int i = 0; i < itemsVisited.Length; ++i)
{
if (!itemsVisited[i] && expectedItems[i].Equals(currentItem))
{
itemsVisited[i] = true;
itemFound = true;
break;
}
}
Assert.True(itemFound, "Err_1432pauy Current returned unexpected value=" + currentItem);
// Verify Current always returns the same value every time it is called
for (int i = 0; i < 3; i++)
{
tempItem = enumerator.Current;
Assert.Equal(currentItem, tempItem);
}
iterations++;
}
for (int i = 0; i < expectedCount; ++i)
{
Assert.True(itemsVisited[i], "Err_052848ahiedoi Expected Current to return true for item: " + expectedItems[i] + "index: " + i);
}
Assert.Equal(expectedCount, iterations);
for (int i = 0; i < 3; i++)
{
Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations");
}
}
#endregion
}
}
| |
// 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 FluentAssertions;
using Microsoft.NET.TestFramework;
using Microsoft.NET.TestFramework.Assertions;
using Microsoft.NET.TestFramework.Commands;
using NuGet.Packaging.Core;
using NuGet.Versioning;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Xml.Linq;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.NET.Publish.Tests
{
public class GivenThatWeWantToStoreAProjectWithDependencies : SdkTest
{
private static readonly string _libPrefix = FileConstants.DynamicLibPrefix;
private static string _runtimeOs;
private static string _runtimeLibOs;
private static string _runtimeRid;
private static string _testArch;
private static string _tfm = "netcoreapp1.0";
static GivenThatWeWantToStoreAProjectWithDependencies()
{
var rid = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment.GetRuntimeIdentifier();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
_runtimeOs = "win7";
_runtimeLibOs = "win";
_testArch = rid.Substring(rid.LastIndexOf("-") + 1);
_runtimeRid = "win7-" + _testArch;
}
else
{
_runtimeOs = "unix";
_runtimeLibOs = "unix";
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// microsoft.netcore.coredistools only has assets for osx.10.10
_runtimeRid = "osx.10.10-x64";
}
else if (rid.Contains("ubuntu"))
{
// microsoft.netcore.coredistools only has assets for ubuntu.14.04-x64
_runtimeRid = "ubuntu.14.04-x64";
}
else
{
_runtimeRid = rid;
}
}
}
public GivenThatWeWantToStoreAProjectWithDependencies(ITestOutputHelper log) : base(log)
{
}
[Fact]
public void compose_dependencies()
{
TestAsset simpleDependenciesAsset = _testAssetsManager
.CopyTestAsset("SimpleStore")
.WithSource();
var storeCommand = new ComposeStoreCommand(Log, simpleDependenciesAsset.TestRoot, "SimpleStore.xml");
var OutputFolder = Path.Combine(simpleDependenciesAsset.TestRoot, "outdir");
var WorkingDir = Path.Combine(simpleDependenciesAsset.TestRoot, "w");
storeCommand
.Execute($"/p:RuntimeIdentifier={_runtimeRid}", $"/p:TargetFramework={_tfm}", $"/p:ComposeDir={OutputFolder}", $"/p:ComposeWorkingDir={WorkingDir}", "/p:DoNotDecorateComposeDir=true", "/p:PreserveComposeWorkingDir=true")
.Should()
.Pass();
DirectoryInfo storeDirectory = new DirectoryInfo(OutputFolder);
List<string> files_on_disk = new List<string> {
"artifact.xml",
$"runtime.{_runtimeRid}.microsoft.netcore.coredistools/1.0.1-prerelease-00001/runtimes/{_runtimeRid}/native/{_libPrefix}coredistools{FileConstants.DynamicLibSuffix}",
$"runtime.{_runtimeRid}.microsoft.netcore.coredistools/1.0.1-prerelease-00001/runtimes/{_runtimeRid}/native/coredistools.h"
};
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && _testArch != "x86")
{
files_on_disk.Add($"runtime.{_runtimeRid}.runtime.native.system/4.4.0-beta-24821-02/runtimes/{_runtimeRid}/native/System.Native.a");
files_on_disk.Add($"runtime.{_runtimeRid}.runtime.native.system/4.4.0-beta-24821-02/runtimes/{_runtimeRid}/native/System.Native{FileConstants.DynamicLibSuffix}");
}
storeDirectory.Should().OnlyHaveFiles(files_on_disk);
//valid artifact.xml
var knownpackage = new HashSet<PackageIdentity>();
knownpackage.Add(new PackageIdentity("Microsoft.NETCore.Targets", NuGetVersion.Parse("1.2.0-beta-24821-02")));
knownpackage.Add(new PackageIdentity("System.Private.Uri", NuGetVersion.Parse("4.4.0-beta-24821-02")));
knownpackage.Add(new PackageIdentity("Microsoft.NETCore.CoreDisTools", NuGetVersion.Parse("1.0.1-prerelease-00001")));
knownpackage.Add(new PackageIdentity($"runtime.{_runtimeOs}.System.Private.Uri", NuGetVersion.Parse("4.4.0-beta-24821-02")));
knownpackage.Add(new PackageIdentity("Microsoft.NETCore.Platforms", NuGetVersion.Parse("1.2.0-beta-24821-02")));
knownpackage.Add(new PackageIdentity($"runtime.{_runtimeRid}.Microsoft.NETCore.CoreDisTools", NuGetVersion.Parse("1.0.1-prerelease-00001")));
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && _testArch != "x86")
{
knownpackage.Add(new PackageIdentity("runtime.native.System", NuGetVersion.Parse("4.4.0-beta-24821-02")));
knownpackage.Add(new PackageIdentity($"runtime.{_runtimeRid}.runtime.native.System", NuGetVersion.Parse("4.4.0-beta-24821-02")));
}
var artifact = Path.Combine(OutputFolder, "artifact.xml");
HashSet<PackageIdentity> packagescomposed = ParseStoreArtifacts(artifact);
packagescomposed.Count.Should().Be(knownpackage.Count);
foreach (var pkg in packagescomposed)
{
knownpackage.Should().Contain(elem => elem.Equals(pkg), "package {0}, version {1} was not expected to be stored", pkg.Id, pkg.Version);
}
}
[Fact]
public void compose_with_fxfiles()
{
TestAsset simpleDependenciesAsset = _testAssetsManager
.CopyTestAsset("SimpleStore")
.WithSource();
var storeCommand = new ComposeStoreCommand(Log, simpleDependenciesAsset.TestRoot, "SimpleStore.xml");
var OutputFolder = Path.Combine(simpleDependenciesAsset.TestRoot, "outdir");
var WorkingDir = Path.Combine(simpleDependenciesAsset.TestRoot, "w");
storeCommand
.Execute($"/p:RuntimeIdentifier={_runtimeRid}", $"/p:TargetFramework={_tfm}", $"/p:ComposeDir={OutputFolder}", $"/p:ComposeWorkingDir={WorkingDir}", "/p:DoNotDecorateComposeDir=true", "/p:SkipRemovingSystemFiles=true", "/p:CreateProfilingSymbols=false")
.Should()
.Pass();
DirectoryInfo storeDirectory = new DirectoryInfo(OutputFolder);
List<string> files_on_disk = new List<string> {
"artifact.xml",
$"runtime.{_runtimeRid}.microsoft.netcore.coredistools/1.0.1-prerelease-00001/runtimes/{_runtimeRid}/native/{_libPrefix}coredistools{FileConstants.DynamicLibSuffix}",
$"runtime.{_runtimeRid}.microsoft.netcore.coredistools/1.0.1-prerelease-00001/runtimes/{_runtimeRid}/native/coredistools.h",
$"runtime.{_runtimeOs}.system.private.uri/4.4.0-beta-24821-02/runtimes/{_runtimeLibOs}/lib/netstandard1.0/System.Private.Uri.dll"
};
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && _testArch != "x86")
{
files_on_disk.Add($"runtime.{_runtimeRid}.runtime.native.system/4.4.0-beta-24821-02/runtimes/{_runtimeRid}/native/System.Native.a");
files_on_disk.Add($"runtime.{_runtimeRid}.runtime.native.system/4.4.0-beta-24821-02/runtimes/{_runtimeRid}/native/System.Native{FileConstants.DynamicLibSuffix}");
}
storeDirectory.Should().OnlyHaveFiles(files_on_disk);
}
[Fact]
public void compose_dependencies_noopt()
{
TestAsset simpleDependenciesAsset = _testAssetsManager
.CopyTestAsset("SimpleStore")
.WithSource();
var storeCommand = new ComposeStoreCommand(Log, simpleDependenciesAsset.TestRoot, "SimpleStore.xml");
var OutputFolder = Path.Combine(simpleDependenciesAsset.TestRoot, "outdir");
var WorkingDir = Path.Combine(simpleDependenciesAsset.TestRoot, "w");
storeCommand
.Execute($"/p:RuntimeIdentifier={_runtimeRid}", $"/p:TargetFramework={_tfm}", $"/p:ComposeDir={OutputFolder}", $"/p:DoNotDecorateComposeDir=true", "/p:SkipOptimization=true", $"/p:ComposeWorkingDir={WorkingDir}", "/p:PreserveComposeWorkingDir=true")
.Should()
.Pass();
DirectoryInfo storeDirectory = new DirectoryInfo(OutputFolder);
List<string> files_on_disk = new List<string> {
"artifact.xml",
$"runtime.{_runtimeRid}.microsoft.netcore.coredistools/1.0.1-prerelease-00001/runtimes/{_runtimeRid}/native/{_libPrefix}coredistools{FileConstants.DynamicLibSuffix}",
$"runtime.{_runtimeRid}.microsoft.netcore.coredistools/1.0.1-prerelease-00001/runtimes/{_runtimeRid}/native/coredistools.h",
$"runtime.{_runtimeOs}.system.private.uri/4.4.0-beta-24821-02/runtimes/{_runtimeLibOs}/lib/netstandard1.0/System.Private.Uri.dll"
};
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && _testArch != "x86")
{
files_on_disk.Add($"runtime.{_runtimeRid}.runtime.native.system/4.4.0-beta-24821-02/runtimes/{_runtimeRid}/native/System.Native.a");
files_on_disk.Add($"runtime.{_runtimeRid}.runtime.native.system/4.4.0-beta-24821-02/runtimes/{_runtimeRid}/native/System.Native{FileConstants.DynamicLibSuffix}");
}
storeDirectory.Should().OnlyHaveFiles(files_on_disk);
}
[Fact]
public void store_nativeonlyassets()
{
TestAsset simpleDependenciesAsset = _testAssetsManager
.CopyTestAsset("UnmanagedStore")
.WithSource();
var storeCommand = new ComposeStoreCommand(Log, simpleDependenciesAsset.TestRoot);
var OutputFolder = Path.Combine(simpleDependenciesAsset.TestRoot, "outdir");
var WorkingDir = Path.Combine(simpleDependenciesAsset.TestRoot, "w");
storeCommand
.Execute($"/p:RuntimeIdentifier={_runtimeRid}", $"/p:TargetFramework={_tfm}", $"/p:ComposeWorkingDir={WorkingDir}", $"/p:ComposeDir={OutputFolder}", $"/p:DoNotDecorateComposeDir=true")
.Should()
.Pass();
DirectoryInfo storeDirectory = new DirectoryInfo(OutputFolder);
List<string> files_on_disk = new List<string> {
"artifact.xml",
$"runtime.{_runtimeRid}.microsoft.netcore.coredistools/1.0.1-prerelease-00001/runtimes/{_runtimeRid}/native/{_libPrefix}coredistools{FileConstants.DynamicLibSuffix}",
$"runtime.{_runtimeRid}.microsoft.netcore.coredistools/1.0.1-prerelease-00001/runtimes/{_runtimeRid}/native/coredistools.h"
};
storeDirectory.Should().OnlyHaveFiles(files_on_disk);
}
[Fact]
public void compose_multifile()
{
TestAsset simpleDependenciesAsset = _testAssetsManager
.CopyTestAsset("TargetManifests", "multifile")
.WithSource();
var storeCommand = new ComposeStoreCommand(Log, simpleDependenciesAsset.TestRoot, "NewtonsoftFilterProfile.xml");
var OutputFolder = Path.Combine(simpleDependenciesAsset.TestRoot, "o");
var WorkingDir = Path.Combine(simpleDependenciesAsset.TestRoot, "w");
var additonalproj1 = Path.Combine(simpleDependenciesAsset.TestRoot, "NewtonsoftMultipleVersions.xml");
var additonalproj2 = Path.Combine(simpleDependenciesAsset.TestRoot, "FluentAssertions.xml");
storeCommand
.Execute($"/p:RuntimeIdentifier={_runtimeRid}", $"/p:TargetFramework={_tfm}", $"/p:Additionalprojects={additonalproj1}%3b{additonalproj2}", $"/p:ComposeDir={OutputFolder}", $"/p:ComposeWorkingDir={WorkingDir}", "/p:DoNotDecorateComposeDir=true", "/p:CreateProfilingSymbols=false")
.Should()
.Pass();
DirectoryInfo storeDirectory = new DirectoryInfo(OutputFolder);
List<string> files_on_disk = new List<string> {
"artifact.xml",
@"newtonsoft.json/9.0.2-beta2/lib/netstandard1.1/Newtonsoft.Json.dll",
@"newtonsoft.json/9.0.1/lib/netstandard1.0/Newtonsoft.Json.dll",
@"fluentassertions.json/4.12.0/lib/netstandard1.3/FluentAssertions.Json.dll"
};
storeDirectory.Should().HaveFiles(files_on_disk);
var knownpackage = new HashSet<PackageIdentity>();
knownpackage.Add(new PackageIdentity("Newtonsoft.Json", NuGetVersion.Parse("9.0.1")));
knownpackage.Add(new PackageIdentity("Newtonsoft.Json", NuGetVersion.Parse("9.0.2-beta2")));
knownpackage.Add(new PackageIdentity("FluentAssertions.Json", NuGetVersion.Parse("4.12.0")));
var artifact = Path.Combine(OutputFolder, "artifact.xml");
var packagescomposed = ParseStoreArtifacts(artifact);
packagescomposed.Count.Should().BeGreaterThan(0);
foreach (var pkg in knownpackage)
{
packagescomposed.Should().Contain(elem => elem.Equals(pkg), "package {0}, version {1} was not expected to be stored", pkg.Id, pkg.Version);
}
}
[Fact]
public void It_uses_star_versions_correctly()
{
TestAsset targetManifestsAsset = _testAssetsManager
.CopyTestAsset("TargetManifests")
.WithSource();
var outputFolder = Path.Combine(targetManifestsAsset.TestRoot, "o");
var workingDir = Path.Combine(targetManifestsAsset.TestRoot, "w");
new ComposeStoreCommand(Log, targetManifestsAsset.TestRoot, "StarVersion.xml")
.Execute($"/p:RuntimeIdentifier={_runtimeRid}", $"/p:TargetFramework={_tfm}", $"/p:ComposeDir={outputFolder}", $"/p:ComposeWorkingDir={workingDir}", "/p:DoNotDecorateComposeDir=true", "/p:CreateProfilingSymbols=false")
.Should()
.Pass();
var artifactFile = Path.Combine(outputFolder, "artifact.xml");
var storeArtifacts = ParseStoreArtifacts(artifactFile);
var nugetPackage = storeArtifacts.Single(p => string.Equals(p.Id, "NuGet.Common", StringComparison.OrdinalIgnoreCase));
// nuget.org/packages/NuGet.Common currently contains:
// 4.0.0
// 4.0.0-rtm-2283
// 4.0.0-rtm-2265
// 4.0.0-rc3
// 4.0.0-rc2
// 4.0.0-rc-2048
//
// and the StarVersion.xml uses Version="4.0.0-*",
// so we expect a version greater than 4.0.0-rc2, since there is
// a higher version on the feed that meets the criteria
nugetPackage.Version.Should().BeGreaterThan(NuGetVersion.Parse("4.0.0-rc2"));
// work around https://github.com/dotnet/sdk/issues/1045. The unnecessary assets getting
// put in the store folder cause long path issues, so delete them
foreach (var runtimeFolder in new DirectoryInfo(outputFolder).GetDirectories("runtime.*"))
{
runtimeFolder.Delete(true);
}
}
[Fact]
public void It_creates_profiling_symbols()
{
if (UsingFullFrameworkMSBuild)
{
// Disabled on full framework MSBuild until CI machines have VS with bundled .NET Core / .NET Standard versions
// See https://github.com/dotnet/sdk/issues/1077
return;
}
TestAsset targetManifestsAsset = _testAssetsManager
.CopyTestAsset("TargetManifests")
.WithSource();
var outputFolder = Path.Combine(targetManifestsAsset.TestRoot, "o");
var workingDir = Path.Combine(targetManifestsAsset.TestRoot, "w");
new ComposeStoreCommand(Log, targetManifestsAsset.TestRoot, "NewtonsoftFilterProfile.xml")
.Execute(
$"/p:RuntimeIdentifier={_runtimeRid}",
"/p:TargetFramework=netcoreapp2.0",
$"/p:ComposeDir={outputFolder}",
$"/p:ComposeWorkingDir={workingDir}",
"/p:DoNotDecorateComposeDir=true",
"/p:PreserveComposeWorkingDir=true")
.Should()
.Pass();
var symbolFileExtension = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "ni.pdb" : ".map";
var symbolsFolder = new DirectoryInfo(Path.Combine(outputFolder, "symbols"));
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// profiling symbols are not supported on OSX
symbolsFolder.Should().NotExist();
return;
}
var newtonsoftSymbolsFolder = symbolsFolder.Sub("newtonsoft.json").Sub("9.0.1").Sub("lib").Sub("netstandard1.0");
newtonsoftSymbolsFolder.Should().Exist();
var newtonsoftSymbolsFiles = newtonsoftSymbolsFolder.GetFiles().ToArray();
newtonsoftSymbolsFiles.Length.Should().Be(1);
newtonsoftSymbolsFiles[0].Name.Should().StartWith("Newtonsoft.Json").And.EndWith(symbolFileExtension);
}
private static HashSet<PackageIdentity> ParseStoreArtifacts(string path)
{
return new HashSet<PackageIdentity>(
from element in XDocument.Load(path).Root.Elements("Package")
select new PackageIdentity(
element.Attribute("Id").Value,
NuGetVersion.Parse(element.Attribute("Version").Value)));
}
}
}
| |
//*******************************************************
//
// Delphi DataSnap Framework
//
// Copyright(c) 1995-2011 Embarcadero Technologies, Inc.
//
//*******************************************************
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace Embarcadero.Datasnap.WindowsPhone7
{
/**
*
* Implements a JSON array.
*
*/
public class TJSONArray : TJSONValue
{
protected List<TJSONValue> Elements;
/**
* Parse the passed String into a new TJSONArray
* @param JSONString
* @return TJSONArray
*/
public static TJSONArray Parse(String JSONString)
{
return new TJSONArray(JArray.Parse(JSONString));
}
/**
* Initialized the instance with a TJSONValueList
* @param JSONValues
*/
public TJSONArray(List<TJSONValue> JSONValues)
: base()
{
Elements = JSONValues;
}
public override String ToString()
{
return asJSONArray().ToString(Newtonsoft.Json.Formatting.None);
}
/**
* Initialized the instance
*/
public TJSONArray()
: base()
{
Elements = new List<TJSONValue>();
}
/**
* Initialized the instance with a JSONArray;
* @param json
*/
public TJSONArray(JArray json)
: base()
{
Elements = buildElements(json);
}
protected List<TJSONValue> buildElements(JArray arr)
{
try
{
List<TJSONValue> res = new List<TJSONValue>();
for (int i = 0; i < arr.Count; i++)
{
switch (arr[i].Type)
{
case JTokenType.Null: { res.Add(new TJSONNull()); break; }
case JTokenType.String: { res.Add(new TJSONString(arr.Value<string>(i))); break; }
case JTokenType.Float: { res.Add(new TJSONNumber(arr.Value<float>(i))); break; }
case JTokenType.Integer: { res.Add(new TJSONNumber(arr.Value<long>(i))); break; }
case JTokenType.Array: { res.Add(new TJSONArray(arr.Value<JArray>(i))); break; }
case JTokenType.Object: { res.Add(new TJSONObject(arr.Value<JObject>(i))); break; }
case JTokenType.Boolean: { if (arr.Value<Boolean>(i)) res.Add(new TJSONTrue()); else res.Add(new TJSONFalse()); break; }
}
}
return res;
}
catch (Exception)
{
return null;
}
}
/**
*Converts into JSONArray
*/
public JArray asJSONArray()
{
JArray arr = new JArray();
foreach (TJSONValue v in Elements)
arr.Add(v.getInternalObject());
return arr;
}
public override Object getInternalObject()
{
return asJSONArray();
}
/**
* Adds a TJSonValue
* @param value a TJSONValue
* @returns a itlsef
*/
public TJSONArray add(TJSONValue value)
{
Elements.Add(value);
return this;
}
public TJSONArray add(int value)
{
JArray app = (JArray)getInternalObject();
app.Add(value);
Elements = buildElements(app);
return this;
}
public TJSONArray add(long value)
{
JArray app = (JArray)getInternalObject();
app.Add(value);
Elements = buildElements(app);
return this;
}
public TJSONArray add(bool value)
{
JArray app = (JArray)getInternalObject();
app.Add(value);
Elements = buildElements(app);
return this;
}
public TJSONArray add(double value)
{
JArray app = (JArray)getInternalObject();
try
{
app.Add(value);
}
catch (Exception e)
{
throw new DBXException(e.Message);
}
Elements = buildElements(app);
return this;
}
public TJSONArray add(String value)
{
JArray app = (JArray)getInternalObject();
app.Add(value);
Elements = buildElements(app);
return this;
}
public TJSONArray add(Object value)
{
JArray app = (JArray)getInternalObject();
app.Add(value);
Elements = buildElements(app);
return this;
}
/**
* Returns a string value by the index
* @param index the index of the value
* @return the value as string
*/
public String getString(int index)
{
TJSONValue p;
return ((p = get(index)) == null) ? null : ((TJSONString)p).getValue();
}
/**
* Returns a double value by the index
* @param index the index of the value
* @return the value as double
*/
public Double? getDouble(int index)
{
TJSONValue p = get(index);
if (p == null)
return null;
Double? d = ((TJSONNumber)p).getValue();
if (d.HasValue)
return d.Value;
return null;
}
/**
* Returns a TJSONObject value by the index
* @param index the index of the value
* @return the value as TSJONObject
*/
public TJSONObject getJSONObject(int index)
{
TJSONValue p;
return ((p = get(index)) == null) ? null : (TJSONObject)p;
}
/**
* Returns an integer value by the index
* @param index the index of the value
* @return the value as integer
*/
public long? getInt(int index)
{
TJSONValue p = get(index);
if (p == null)
return null;
long? d = ((TJSONNumber)p).getValueInt();
if (d.HasValue)
return d.Value;
return null;
}
/**
* Returns a boolean value by the index
* @param index the index of the value
* @return the value as boolean
*/
public Boolean? getBoolean(int index)
{
TJSONValue p = get(index);
if (p == null)
return null;
if (p is TJSONTrue)
return true;
else
return false;
}
/**
* Returns a {@link TJSONArray} value by the index
* @param index
* @return TJSONArray
*/
public TJSONArray getJSONArray(int index)
{
TJSONValue p;
return ((p = get(index)) == null) ? null : (TJSONArray)p;
}
/**
* Returns a {@link TJSONValue} value by the index
* @param index
* @return TJSONValue
*/
public TJSONValue get(int index)
{
return Elements[index];
}
/**
* Convert into a formatted json string.
*/
public TJSONString getAsJsonString(int index)
{
return (TJSONString)get(index);
}
/**
* Returns a TJSONObject value by the index
* @param index
* @return TJSONObject
*/
public TJSONObject getAsJsonObject(int index)
{
return (TJSONObject)get(index);
}
/**
* Returns a {@link TJSONArray} value by the index
* @param index
* @return TJSONArray
*/
public TJSONArray getAsJsonArray(int index)
{
return (TJSONArray)get(index);
}
/**
* Remove a element by the index
* @param index the index of the value
* @returns a itlsef
*/
public TJSONArray remove(int index)
{
Elements.RemoveAt(index);
return this;
}
/**
* Return the size of the element
*/
public long size()
{
return Elements.Count;
}
public override JSONValueType getJsonValueType()
{
return JSONValueType.JSONArray;
}
}
}
| |
//
// StringExtensions.cs
//
// Author:
// Craig Fowler <craig@csf-dev.com>
//
// Copyright (c) 2015 CSF Software Limited
//
// 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.RegularExpressions;
using System.Text;
using System.Globalization;
namespace CSF
{
/// <summary>
/// Extension methods for the string type.
/// </summary>
public static class StringExtensions
{
#region constants
private const string FirstCharacterPattern = @"\b(\w)";
private static readonly Regex FirstCharacterFinder = new Regex(FirstCharacterPattern, RegexOptions.Compiled);
#endregion
#region extension methods
/// <summary>
/// Capitalizes the specified string.
/// </summary>
/// <remarks>
/// <para>
/// The definition of this operation is to firstly convert the entire string to lowercase. Then, the first
/// character of every word is replaced with its uppercase equivalent.
/// </para>
/// </remarks>
/// <param name='value'>
/// The string to be capitalized.
/// </param>
public static string Capitalize(this string value)
{
return value.Capitalize(CultureInfo.CurrentCulture);
}
/// <summary>
/// Capitalizes the specified string.
/// </summary>
/// <remarks>
/// <para>
/// The definition of this operation is to firstly convert the entire string to lowercase. Then, the first
/// character of every word is replaced with its uppercase equivalent.
/// </para>
/// </remarks>
/// <param name='value'>
/// The string to be capitalized.
/// </param>
/// <param name='culture'>
/// The culture to use for any lowercase/uppercase transformations.
/// </param>
public static string Capitalize(this string value, CultureInfo culture)
{
if(value == null)
{
throw new ArgumentNullException(nameof(value));
}
if(culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
string lowercaseVersion = value.ToLower(culture);
StringBuilder output = new StringBuilder(lowercaseVersion);
var matches = FirstCharacterFinder.Matches(lowercaseVersion);
foreach(Match match in matches)
{
output.Replace(match.Value, match.Value.ToUpper(culture), match.Index, 1);
}
return output.ToString();
}
/// <summary>
/// Capitalizes the specified string using the invariant culture.
/// </summary>
/// <remarks>
/// <para>
/// The definition of this operation is to firstly convert the entire string to lowercase. Then, the first
/// character of every word is replaced with its uppercase equivalent.
/// </para>
/// </remarks>
/// <param name='value'>
/// The string to be capitalized.
/// </param>
public static string CapitalizeInvariant(this string value)
{
return value.Capitalize(CultureInfo.InvariantCulture);
}
/// <summary>
/// Parses the string as an enumeration member.
/// </summary>
/// <returns>
/// The enumeration member represented by the <paramref name="value"/>.
/// </returns>
/// <param name='value'>
/// The string value to parse.
/// </param>
/// <typeparam name='TEnum'>
/// The target enumeration type.
/// </typeparam>
/// <exception cref="ArgumentNullException">
/// If the <paramref name="value"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the <paramref name="value"/> does not represent an enumeration constant of the target type.
/// </exception>
/// <exception cref="InvalidOperationException">
/// If the target type is not an enumeration type.
/// </exception>
public static TEnum ParseAs<TEnum>(this string value) where TEnum : struct
{
return ParseAs<TEnum>(value, false);
}
/// <summary>
/// Parses the string as an enumeration member.
/// </summary>
/// <returns>
/// The enumeration member represented by the <paramref name="value"/>.
/// </returns>
/// <param name='value'>
/// The string value to parse.
/// </param>
/// <param name='ignoreCase'>
/// A value that indicates whether the case of the <paramref name="value"/> should be ignored or not.
/// </param>
/// <typeparam name='TEnum'>
/// The target enumeration type.
/// </typeparam>
/// <exception cref="ArgumentNullException">
/// If the <paramref name="value"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the <paramref name="value"/> does not represent an enumeration constant of the target type.
/// </exception>
/// <exception cref="InvalidOperationException">
/// If the target type is not an enumeration type.
/// </exception>
public static TEnum ParseAs<TEnum>(this string value, bool ignoreCase) where TEnum : struct
{
if(value == null)
{
throw new ArgumentNullException(nameof(value));
}
var output = TryParseAs<TEnum>(value, ignoreCase);
if(!output.HasValue)
{
throw new RequiresDefinedEnumerationConstantException(typeof(TEnum), value);
}
return output.Value;
}
/// <summary>
/// Attempts to parse the string as an enumeration member, returning a null reference if parsing fails.
/// </summary>
/// <returns>
/// The enumeration member represented by the <paramref name="value"/>, or a null reference.
/// </returns>
/// <param name='value'>
/// The string value to parse.
/// </param>
/// <typeparam name='TEnum'>
/// The target enumeration type.
/// </typeparam>
/// <exception cref="InvalidOperationException">
/// If the target type is not an enumeration type.
/// </exception>
public static TEnum? TryParseAs<TEnum>(this string value) where TEnum : struct
{
return TryParseAs<TEnum>(value, false);
}
/// <summary>
/// Attempts to parse the string as an enumeration member, returning a null reference if parsing fails.
/// </summary>
/// <returns>
/// The enumeration member represented by the <paramref name="value"/>, or a null reference.
/// </returns>
/// <param name='value'>
/// The string value to parse.
/// </param>
/// <param name='ignoreCase'>
/// A value that indicates whether the case of the <paramref name="value"/> should be ignored or not.
/// </param>
/// <typeparam name='TEnum'>
/// The target enumeration type.
/// </typeparam>
/// <exception cref="InvalidOperationException">
/// If the target type is not an enumeration type.
/// </exception>
public static TEnum? TryParseAs<TEnum>(this string value, bool ignoreCase) where TEnum : struct
{
if(value == null)
{
return null;
}
TEnum output;
var enumType = typeof(TEnum);
EnumExtensions.RequireEnum(enumType);
if(Enum.TryParse<TEnum>(value, ignoreCase, out output))
{
return output;
}
else
{
return null;
}
}
#endregion
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
namespace Revit.SDK.Samples.VisibilityControl.CS
{
partial class VisibilityCtrlForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.visibilityCtrlGroupBox = new System.Windows.Forms.GroupBox();
this.allCategoriesListView = new System.Windows.Forms.ListView();
this.cancelButton = new System.Windows.Forms.Button();
this.okBotton = new System.Windows.Forms.Button();
this.pickOneRadioButton = new System.Windows.Forms.RadioButton();
this.isolategroupBox = new System.Windows.Forms.GroupBox();
this.windowSelectRadioButton = new System.Windows.Forms.RadioButton();
this.isolateButton = new System.Windows.Forms.Button();
this.checkAllButton = new System.Windows.Forms.Button();
this.checkNoneButton = new System.Windows.Forms.Button();
this.visibilityCtrlGroupBox.SuspendLayout();
this.isolategroupBox.SuspendLayout();
this.SuspendLayout();
//
// visibilityCtrlGroupBox
//
this.visibilityCtrlGroupBox.Controls.Add(this.checkNoneButton);
this.visibilityCtrlGroupBox.Controls.Add(this.checkAllButton);
this.visibilityCtrlGroupBox.Controls.Add(this.allCategoriesListView);
this.visibilityCtrlGroupBox.Controls.Add(this.cancelButton);
this.visibilityCtrlGroupBox.Controls.Add(this.okBotton);
this.visibilityCtrlGroupBox.Location = new System.Drawing.Point(12, 12);
this.visibilityCtrlGroupBox.Name = "visibilityCtrlGroupBox";
this.visibilityCtrlGroupBox.Size = new System.Drawing.Size(620, 339);
this.visibilityCtrlGroupBox.TabIndex = 3;
this.visibilityCtrlGroupBox.TabStop = false;
this.visibilityCtrlGroupBox.Text = "Category visibility";
//
// allCategoriesListView
//
this.allCategoriesListView.CheckBoxes = true;
this.allCategoriesListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.allCategoriesListView.Location = new System.Drawing.Point(6, 19);
this.allCategoriesListView.Name = "allCategoriesListView";
this.allCategoriesListView.Size = new System.Drawing.Size(527, 314);
this.allCategoriesListView.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.allCategoriesListView.TabIndex = 5;
this.allCategoriesListView.UseCompatibleStateImageBehavior = false;
this.allCategoriesListView.View = System.Windows.Forms.View.Details;
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Location = new System.Drawing.Point(539, 310);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(75, 23);
this.cancelButton.TabIndex = 4;
this.cancelButton.Text = "&Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
//
// okBotton
//
this.okBotton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.okBotton.Location = new System.Drawing.Point(539, 281);
this.okBotton.Name = "okBotton";
this.okBotton.Size = new System.Drawing.Size(75, 23);
this.okBotton.TabIndex = 1;
this.okBotton.Text = "&OK";
this.okBotton.UseVisualStyleBackColor = true;
//
// pickOneRadioButton
//
this.pickOneRadioButton.AutoSize = true;
this.pickOneRadioButton.Checked = true;
this.pickOneRadioButton.Location = new System.Drawing.Point(6, 19);
this.pickOneRadioButton.Name = "pickOneRadioButton";
this.pickOneRadioButton.Size = new System.Drawing.Size(66, 17);
this.pickOneRadioButton.TabIndex = 2;
this.pickOneRadioButton.TabStop = true;
this.pickOneRadioButton.Text = "PickOne";
this.pickOneRadioButton.UseVisualStyleBackColor = true;
//
// isolategroupBox
//
this.isolategroupBox.Controls.Add(this.windowSelectRadioButton);
this.isolategroupBox.Controls.Add(this.pickOneRadioButton);
this.isolategroupBox.Controls.Add(this.isolateButton);
this.isolategroupBox.Location = new System.Drawing.Point(364, 357);
this.isolategroupBox.Name = "isolategroupBox";
this.isolategroupBox.Size = new System.Drawing.Size(268, 49);
this.isolategroupBox.TabIndex = 2;
this.isolategroupBox.TabStop = false;
this.isolategroupBox.Text = "Isolate element(s)";
//
// windowSelectRadioButton
//
this.windowSelectRadioButton.AutoSize = true;
this.windowSelectRadioButton.Location = new System.Drawing.Point(78, 19);
this.windowSelectRadioButton.Name = "windowSelectRadioButton";
this.windowSelectRadioButton.Size = new System.Drawing.Size(94, 17);
this.windowSelectRadioButton.TabIndex = 2;
this.windowSelectRadioButton.TabStop = true;
this.windowSelectRadioButton.Text = "WindowSelect";
this.windowSelectRadioButton.UseVisualStyleBackColor = true;
//
// isolateButton
//
this.isolateButton.DialogResult = System.Windows.Forms.DialogResult.Yes;
this.isolateButton.Location = new System.Drawing.Point(187, 16);
this.isolateButton.Name = "isolateButton";
this.isolateButton.Size = new System.Drawing.Size(75, 23);
this.isolateButton.TabIndex = 3;
this.isolateButton.Text = "&Isolate";
this.isolateButton.UseVisualStyleBackColor = true;
this.isolateButton.Click += new System.EventHandler(this.isolateButton_Click);
//
// checkAllButton
//
this.checkAllButton.Location = new System.Drawing.Point(539, 223);
this.checkAllButton.Name = "checkAllButton";
this.checkAllButton.Size = new System.Drawing.Size(75, 23);
this.checkAllButton.TabIndex = 6;
this.checkAllButton.Text = "Check All";
this.checkAllButton.UseVisualStyleBackColor = true;
this.checkAllButton.Click += new System.EventHandler(this.checkAllButton_Click);
//
// checkNoneButton
//
this.checkNoneButton.Location = new System.Drawing.Point(539, 252);
this.checkNoneButton.Name = "checkNoneButton";
this.checkNoneButton.Size = new System.Drawing.Size(75, 23);
this.checkNoneButton.TabIndex = 6;
this.checkNoneButton.Text = "Check None";
this.checkNoneButton.UseVisualStyleBackColor = true;
this.checkNoneButton.Click += new System.EventHandler(this.checkNoneButton_Click);
//
// VisibilityCtrlForm
//
this.AcceptButton = this.okBotton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.cancelButton;
this.ClientSize = new System.Drawing.Size(644, 418);
this.Controls.Add(this.visibilityCtrlGroupBox);
this.Controls.Add(this.isolategroupBox);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "VisibilityCtrlForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Visibility Controller";
this.Load += new System.EventHandler(this.VisibilityCtrlForm_Load);
this.visibilityCtrlGroupBox.ResumeLayout(false);
this.isolategroupBox.ResumeLayout(false);
this.isolategroupBox.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox visibilityCtrlGroupBox;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button okBotton;
private System.Windows.Forms.RadioButton pickOneRadioButton;
private System.Windows.Forms.GroupBox isolategroupBox;
private System.Windows.Forms.RadioButton windowSelectRadioButton;
private System.Windows.Forms.Button isolateButton;
private System.Windows.Forms.ListView allCategoriesListView;
private System.Windows.Forms.Button checkNoneButton;
private System.Windows.Forms.Button checkAllButton;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial class SolutionCrawlerRegistrationService
{
private partial class WorkCoordinator
{
private const int MinimumDelayInMS = 50;
private readonly Registration _registration;
private readonly LogAggregator _logAggregator;
private readonly IAsynchronousOperationListener _listener;
private readonly IOptionService _optionService;
private readonly CancellationTokenSource _shutdownNotificationSource;
private readonly CancellationToken _shutdownToken;
private readonly SimpleTaskQueue _eventProcessingQueue;
// points to processor task
private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor;
private readonly SemanticChangeProcessor _semanticChangeProcessor;
public WorkCoordinator(
IAsynchronousOperationListener listener,
IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders,
Registration registration)
{
_logAggregator = new LogAggregator();
_registration = registration;
_listener = listener;
_optionService = _registration.GetService<IOptionService>();
_optionService.OptionChanged += OnOptionChanged;
// event and worker queues
_shutdownNotificationSource = new CancellationTokenSource();
_shutdownToken = _shutdownNotificationSource.Token;
_eventProcessingQueue = new SimpleTaskQueue(TaskScheduler.Default);
var activeFileBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS);
var allFilesWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS);
var entireProjectWorkerBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS);
_documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor(
listener, analyzerProviders, _registration,
activeFileBackOffTimeSpanInMS, allFilesWorkerBackOffTimeSpanInMS, entireProjectWorkerBackOffTimeSpanInMS, _shutdownToken);
var semanticBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS);
var projectBackOffTimeSpanInMS = _optionService.GetOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS);
_semanticChangeProcessor = new SemanticChangeProcessor(listener, _registration, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpanInMS, projectBackOffTimeSpanInMS, _shutdownToken);
// if option is on
if (_optionService.GetOption(InternalSolutionCrawlerOptions.SolutionCrawler))
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
}
public int CorrelationId
{
get { return _registration.CorrelationId; }
}
public void Shutdown(bool blockingShutdown)
{
_optionService.OptionChanged -= OnOptionChanged;
// detach from the workspace
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
// cancel any pending blocks
_shutdownNotificationSource.Cancel();
_documentAndProjectWorkerProcessor.Shutdown();
SolutionCrawlerLogger.LogWorkCoordinatorShutdown(CorrelationId, _logAggregator);
if (blockingShutdown)
{
var shutdownTask = Task.WhenAll(
_eventProcessingQueue.LastScheduledTask,
_documentAndProjectWorkerProcessor.AsyncProcessorTask,
_semanticChangeProcessor.AsyncProcessorTask);
shutdownTask.Wait(TimeSpan.FromSeconds(5));
if (!shutdownTask.IsCompleted)
{
SolutionCrawlerLogger.LogWorkCoordinatorShutdownTimeout(CorrelationId);
}
}
}
private void OnOptionChanged(object sender, OptionChangedEventArgs e)
{
// if solution crawler got turned off or on.
if (e.Option == InternalSolutionCrawlerOptions.SolutionCrawler)
{
var value = (bool)e.Value;
if (value)
{
_registration.Workspace.WorkspaceChanged += OnWorkspaceChanged;
_registration.Workspace.DocumentOpened += OnDocumentOpened;
_registration.Workspace.DocumentClosed += OnDocumentClosed;
}
else
{
_registration.Workspace.WorkspaceChanged -= OnWorkspaceChanged;
_registration.Workspace.DocumentOpened -= OnDocumentOpened;
_registration.Workspace.DocumentClosed -= OnDocumentClosed;
}
SolutionCrawlerLogger.LogOptionChanged(CorrelationId, value);
return;
}
// Changing the UseV2Engine option is a no-op as we have a single engine now.
if (e.Option == Diagnostics.InternalDiagnosticsOptions.UseDiagnosticEngineV2)
{
_documentAndProjectWorkerProcessor.ChangeDiagnosticsEngine((bool)e.Value);
}
ReanalyzeOnOptionChange(sender, e);
}
private void ReanalyzeOnOptionChange(object sender, OptionChangedEventArgs e)
{
// otherwise, let each analyzer decide what they want on option change
ISet<DocumentId> set = null;
foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers)
{
if (analyzer.NeedsReanalysisOnOptionChanged(sender, e))
{
set = set ?? _registration.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet();
this.Reanalyze(analyzer, set);
}
}
}
public void Reanalyze(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority = false)
{
var asyncToken = _listener.BeginAsyncOperation("Reanalyze");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(analyzer, documentIds, highPriority), _shutdownToken).CompletesAsyncOperation(asyncToken);
SolutionCrawlerLogger.LogReanalyze(CorrelationId, analyzer, documentIds, highPriority);
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args)
{
// guard us from cancellation
try
{
ProcessEvents(args, _listener.BeginAsyncOperation("OnWorkspaceChanged"));
}
catch (OperationCanceledException oce)
{
if (NotOurShutdownToken(oce))
{
throw;
}
// it is our cancellation, ignore
}
catch (AggregateException ae)
{
ae = ae.Flatten();
// If we had a mix of exceptions, don't eat it
if (ae.InnerExceptions.Any(e => !(e is OperationCanceledException)) ||
ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken))
{
// We had a cancellation with a different token, so don't eat it
throw;
}
// it is our cancellation, ignore
}
}
private bool NotOurShutdownToken(OperationCanceledException oce)
{
return oce.CancellationToken == _shutdownToken;
}
private void ProcessEvents(WorkspaceChangeEventArgs args, IAsyncToken asyncToken)
{
SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind);
// TODO: add telemetry that record how much it takes to process an event (max, min, average and etc)
switch (args.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
case WorkspaceChangeKind.SolutionRemoved:
case WorkspaceChangeKind.SolutionCleared:
ProcessSolutionEvent(args, asyncToken);
break;
case WorkspaceChangeKind.ProjectAdded:
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
case WorkspaceChangeKind.ProjectRemoved:
ProcessProjectEvent(args, asyncToken);
break;
case WorkspaceChangeKind.DocumentAdded:
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
case WorkspaceChangeKind.DocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
ProcessDocumentEvent(args, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void OnDocumentOpened(object sender, DocumentEventArgs e)
{
var asyncToken = _listener.BeginAsyncOperation("OnDocumentOpened");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentOpened), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void OnDocumentClosed(object sender, DocumentEventArgs e)
{
var asyncToken = _listener.BeginAsyncOperation("OnDocumentClosed");
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(e.Document, InvocationReasons.DocumentClosed), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.DocumentAdded:
EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.DocumentRemoved:
EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.DocumentReloaded:
case WorkspaceChangeKind.DocumentChanged:
EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, asyncToken);
break;
case WorkspaceChangeKind.AdditionalDocumentAdded:
case WorkspaceChangeKind.AdditionalDocumentRemoved:
case WorkspaceChangeKind.AdditionalDocumentChanged:
case WorkspaceChangeKind.AdditionalDocumentReloaded:
// If an additional file has changed we need to reanalyze the entire project.
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void ProcessProjectEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.ProjectAdded:
OnProjectAdded(e.NewSolution.GetProject(e.ProjectId));
EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.ProjectRemoved:
EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.ProjectChanged:
case WorkspaceChangeKind.ProjectReloaded:
EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken)
{
switch (e.Kind)
{
case WorkspaceChangeKind.SolutionAdded:
OnSolutionAdded(e.NewSolution);
EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, asyncToken);
break;
case WorkspaceChangeKind.SolutionRemoved:
EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, asyncToken);
break;
case WorkspaceChangeKind.SolutionCleared:
EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, asyncToken);
break;
case WorkspaceChangeKind.SolutionChanged:
case WorkspaceChangeKind.SolutionReloaded:
EnqueueEvent(e.OldSolution, e.NewSolution, asyncToken);
break;
default:
throw ExceptionUtilities.Unreachable;
}
}
private void OnSolutionAdded(Solution solution)
{
var asyncToken = _listener.BeginAsyncOperation("OnSolutionAdded");
_eventProcessingQueue.ScheduleTask(() =>
{
var semanticVersionTrackingService = solution.Workspace.Services.GetService<ISemanticVersionTrackingService>();
if (semanticVersionTrackingService != null)
{
semanticVersionTrackingService.LoadInitialSemanticVersions(solution);
}
}, _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void OnProjectAdded(Project project)
{
var asyncToken = _listener.BeginAsyncOperation("OnProjectAdded");
_eventProcessingQueue.ScheduleTask(() =>
{
var semanticVersionTrackingService = project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>();
if (semanticVersionTrackingService != null)
{
semanticVersionTrackingService.LoadInitialSemanticVersions(project);
}
}, _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForSolutionAsync(solution, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, IAsyncToken asyncToken)
{
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemForDocumentAsync(solution, documentId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, IAsyncToken asyncToken)
{
// document changed event is the special one.
_eventProcessingQueue.ScheduleTask(
() => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken).CompletesAsyncOperation(asyncToken);
}
private async Task EnqueueWorkItemAsync(Document document, InvocationReasons invocationReasons, SyntaxNode changedMember = null)
{
// we are shutting down
_shutdownToken.ThrowIfCancellationRequested();
var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false);
var currentMember = GetSyntaxPath(changedMember);
// call to this method is serialized. and only this method does the writing.
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(document.Id, document.Project.Language, invocationReasons,
isLowPriority, currentMember, _listener.BeginAsyncOperation("WorkItem")));
// enqueue semantic work planner
if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged))
{
// must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later.
// due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual.
_semanticChangeProcessor.Enqueue(document, currentMember);
}
}
private SyntaxPath GetSyntaxPath(SyntaxNode changedMember)
{
// using syntax path might be too expansive since it will be created on every keystroke.
// but currently, we have no other way to track a node between two different tree (even for incrementally parsed one)
if (changedMember == null)
{
return null;
}
return new SyntaxPath(changedMember);
}
private async Task EnqueueWorkItemAsync(Project project, InvocationReasons invocationReasons)
{
foreach (var documentId in project.DocumentIds)
{
var document = project.GetDocument(documentId);
await EnqueueWorkItemAsync(document, invocationReasons).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds, bool highPriority)
{
var solution = _registration.CurrentSolution;
foreach (var documentId in documentIds)
{
var document = solution.GetDocument(documentId);
if (document == null)
{
continue;
}
var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, _shutdownToken).ConfigureAwait(false);
var invocationReasons = highPriority ? InvocationReasons.ReanalyzeHighPriority : InvocationReasons.Reanalyze;
_documentAndProjectWorkerProcessor.Enqueue(
new WorkItem(documentId, document.Project.Language, invocationReasons,
isLowPriority, analyzer, _listener.BeginAsyncOperation("WorkItem")));
}
}
private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution)
{
var solutionChanges = newSolution.GetChanges(oldSolution);
// TODO: Async version for GetXXX methods?
foreach (var addedProject in solutionChanges.GetAddedProjects())
{
await EnqueueWorkItemAsync(addedProject, InvocationReasons.DocumentAdded).ConfigureAwait(false);
}
foreach (var projectChanges in solutionChanges.GetProjectChanges())
{
await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedProject in solutionChanges.GetRemovedProjects())
{
await EnqueueWorkItemAsync(removedProject, InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges)
{
await EnqueueProjectConfigurationChangeWorkItemAsync(projectChanges).ConfigureAwait(false);
foreach (var addedDocumentId in projectChanges.GetAddedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.NewProject.GetDocument(addedDocumentId), InvocationReasons.DocumentAdded).ConfigureAwait(false);
}
foreach (var changedDocumentId in projectChanges.GetChangedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(changedDocumentId), projectChanges.NewProject.GetDocument(changedDocumentId))
.ConfigureAwait(continueOnCapturedContext: false);
}
foreach (var removedDocumentId in projectChanges.GetRemovedDocuments())
{
await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(removedDocumentId), InvocationReasons.DocumentRemoved).ConfigureAwait(false);
}
}
private async Task EnqueueProjectConfigurationChangeWorkItemAsync(ProjectChanges projectChanges)
{
var oldProject = projectChanges.OldProject;
var newProject = projectChanges.NewProject;
// TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document?
var projectConfigurationChange = InvocationReasons.Empty;
if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions))
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged);
}
if (projectChanges.GetAddedMetadataReferences().Any() ||
projectChanges.GetAddedProjectReferences().Any() ||
projectChanges.GetAddedAnalyzerReferences().Any() ||
projectChanges.GetRemovedMetadataReferences().Any() ||
projectChanges.GetRemovedProjectReferences().Any() ||
projectChanges.GetRemovedAnalyzerReferences().Any() ||
!object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions) ||
!object.Equals(oldProject.AssemblyName, newProject.AssemblyName) ||
!object.Equals(oldProject.Name, newProject.Name) ||
!object.Equals(oldProject.AnalyzerOptions, newProject.AnalyzerOptions))
{
projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged);
}
if (!projectConfigurationChange.IsEmpty)
{
await EnqueueWorkItemAsync(projectChanges.NewProject, projectConfigurationChange).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument)
{
var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>();
if (differenceService != null)
{
var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false);
if (differenceResult != null)
{
await EnqueueWorkItemAsync(newDocument, differenceResult.ChangeType, differenceResult.ChangedMember).ConfigureAwait(false);
}
}
}
private Task EnqueueWorkItemForDocumentAsync(Solution solution, DocumentId documentId, InvocationReasons invocationReasons)
{
var document = solution.GetDocument(documentId);
return EnqueueWorkItemAsync(document, invocationReasons);
}
private Task EnqueueWorkItemForProjectAsync(Solution solution, ProjectId projectId, InvocationReasons invocationReasons)
{
var project = solution.GetProject(projectId);
return EnqueueWorkItemAsync(project, invocationReasons);
}
private async Task EnqueueWorkItemForSolutionAsync(Solution solution, InvocationReasons invocationReasons)
{
foreach (var projectId in solution.ProjectIds)
{
await EnqueueWorkItemForProjectAsync(solution, projectId, invocationReasons).ConfigureAwait(false);
}
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId)
{
var oldProject = oldSolution.GetProject(projectId);
var newProject = newSolution.GetProject(projectId);
await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false);
}
private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId)
{
var oldProject = oldSolution.GetProject(documentId.ProjectId);
var newProject = newSolution.GetProject(documentId.ProjectId);
await EnqueueWorkItemAsync(oldProject.GetDocument(documentId), newProject.GetDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false);
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> workers)
{
var solution = _registration.CurrentSolution;
var list = new List<WorkItem>();
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
list.Add(new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, false, EmptyAsyncToken.Instance));
}
}
_documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(workers, list);
}
internal void WaitUntilCompletion_ForTestingPurposesOnly()
{
_documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly();
}
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers.Wrappers
{
using System;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Replaces a string in the output of another layout with another string.
/// </summary>
/// <example>
/// ${replace:searchFor=\\n+:replaceWith=-:regex=true:inner=${message}}
/// </example>
[LayoutRenderer("replace")]
[AppDomainFixedOutput]
[ThreadAgnostic]
[ThreadSafe]
public sealed class ReplaceLayoutRendererWrapper : WrapperLayoutRendererBase
{
private RegexHelper _regexHelper;
private MatchEvaluator _groupMatchEvaluator;
/// <summary>
/// Gets or sets the text to search for.
/// </summary>
/// <value>The text search for.</value>
/// <docgen category='Search/Replace Options' order='10' />
[DefaultValue(null)]
public string SearchFor { get; set; }
/// <summary>
/// Gets or sets a value indicating whether regular expressions should be used.
/// </summary>
/// <value>A value of <c>true</c> if regular expressions should be used otherwise, <c>false</c>.</value>
/// <docgen category='Search/Replace Options' order='10' />
[DefaultValue(false)]
public bool Regex { get; set; }
/// <summary>
/// Gets or sets the replacement string.
/// </summary>
/// <value>The replacement string.</value>
/// <docgen category='Search/Replace Options' order='10' />
[DefaultValue(null)]
public string ReplaceWith { get; set; }
/// <summary>
/// Gets or sets the group name to replace when using regular expressions.
/// Leave null or empty to replace without using group name.
/// </summary>
/// <value>The group name.</value>
/// <docgen category='Search/Replace Options' order='10' />
[DefaultValue(null)]
public string ReplaceGroupName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to ignore case.
/// </summary>
/// <value>A value of <c>true</c> if case should be ignored when searching; otherwise, <c>false</c>.</value>
/// <docgen category='Search/Replace Options' order='10' />
[DefaultValue(false)]
public bool IgnoreCase { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to search for whole words.
/// </summary>
/// <value>A value of <c>true</c> if whole words should be searched for; otherwise, <c>false</c>.</value>
/// <docgen category='Search/Replace Options' order='10' />
[DefaultValue(false)]
public bool WholeWords { get; set; }
/// <summary>
/// Compile the <see cref="Regex"/>? This can improve the performance, but at the costs of more memory usage. If <c>false</c>, the Regex Cache is used.
/// </summary>
/// <docgen category='Rule Matching Options' order='10' />
[DefaultValue(false)]
public bool CompileRegex { get; set; }
/// <summary>
/// Initializes the layout renderer.
/// </summary>
protected override void InitializeLayoutRenderer()
{
base.InitializeLayoutRenderer();
_regexHelper = new RegexHelper()
{
IgnoreCase = IgnoreCase,
WholeWords = WholeWords,
CompileRegex = CompileRegex,
};
if (Regex)
_regexHelper.RegexPattern = SearchFor;
else
_regexHelper.SearchText = SearchFor;
if (!string.IsNullOrEmpty(ReplaceGroupName) && _regexHelper.Regex?.GetGroupNames()?.Contains(ReplaceGroupName) == false)
{
InternalLogger.Warn("Replace-LayoutRenderer assigned unknown ReplaceGroupName: {0}", ReplaceGroupName);
}
}
/// <summary>
/// Post-processes the rendered message.
/// </summary>
/// <param name="text">The text to be post-processed.</param>
/// <returns>Post-processed text.</returns>
protected override string Transform(string text)
{
if (string.IsNullOrEmpty(ReplaceGroupName))
{
return _regexHelper.Replace(text, ReplaceWith);
}
else
{
if (_groupMatchEvaluator == null)
_groupMatchEvaluator = m => ReplaceNamedGroup(ReplaceGroupName, ReplaceWith, m);
return _regexHelper.Regex?.Replace(text, _groupMatchEvaluator) ?? text;
}
}
/// <summary>
/// This class was created instead of simply using a lambda expression so that the "ThreadAgnosticAttributeTest" will pass
/// </summary>
[ThreadAgnostic]
[Obsolete("This class should not be used. Marked obsolete on NLog 4.7")]
public class Replacer
{
private readonly string _text;
private readonly string _replaceGroupName;
private readonly string _replaceWith;
internal Replacer(string text, string replaceGroupName, string replaceWith)
{
_text = text;
_replaceGroupName = replaceGroupName;
_replaceWith = replaceWith;
}
internal string EvaluateMatch(Match match)
{
return ReplaceNamedGroup(_replaceGroupName, _replaceWith, match);
}
}
/// <summary>
/// A match evaluator for Regular Expression based replacing
/// </summary>
/// <param name="input">Input string.</param>
/// <param name="groupName">Group name in the regex.</param>
/// <param name="replacement">Replace value.</param>
/// <param name="match">Match from regex.</param>
/// <returns>Groups replaced with <paramref name="replacement"/>.</returns>
[Obsolete("This method should not be used. Marked obsolete on NLog 4.7")]
public static string ReplaceNamedGroup(string input, string groupName, string replacement, Match match)
{
return ReplaceNamedGroup(groupName, replacement, match);
}
internal static string ReplaceNamedGroup(string groupName, string replacement, Match match)
{
var sb = new StringBuilder(match.Value);
var matchLength = match.Length;
var captures = match.Groups[groupName].Captures.OfType<Capture>().OrderByDescending(c => c.Index);
foreach (var capt in captures)
{
matchLength += replacement.Length - capt.Length;
sb.Remove(capt.Index - match.Index, capt.Length);
sb.Insert(capt.Index - match.Index, replacement);
}
var end = matchLength;
sb.Remove(end, sb.Length - end);
return sb.ToString();
}
}
}
| |
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 FoxyEcomm.Services.Identity.Areas.HelpPage.ModelDescriptions;
using FoxyEcomm.Services.Identity.Areas.HelpPage.Models;
namespace FoxyEcomm.Services.Identity.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);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.