context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Concurrency;
namespace Orleans.Streams
{
internal class PersistentStreamPullingAgent : SystemTarget, IPersistentStreamPullingAgent
{
private static readonly IBackoffProvider DefaultBackoffProvider = new ExponentialBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1));
private readonly string streamProviderName;
private readonly IStreamProviderRuntime providerRuntime;
private readonly IStreamPubSub pubSub;
private readonly Dictionary<StreamId, StreamConsumerCollection> pubSubCache;
private readonly SafeRandom safeRandom;
private readonly TimeSpan queueGetPeriod;
private readonly TimeSpan initQueueTimeout;
private readonly TimeSpan maxDeliveryTime;
private readonly Logger logger;
private readonly CounterStatistic numReadMessagesCounter;
private readonly CounterStatistic numSentMessagesCounter;
private int numMessages;
private IQueueAdapter queueAdapter;
private IQueueCache queueCache;
private IQueueAdapterReceiver receiver;
private IStreamFailureHandler streamFailureHandler;
private IDisposable timer;
internal readonly QueueId QueueId;
internal PersistentStreamPullingAgent(
GrainId id,
string strProviderName,
IStreamProviderRuntime runtime,
IStreamPubSub streamPubSub,
QueueId queueId,
TimeSpan queueGetPeriod,
TimeSpan initQueueTimeout,
TimeSpan maxDeliveryTime)
: base(id, runtime.ExecutingSiloAddress, true)
{
if (runtime == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: runtime reference should not be null");
if (strProviderName == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: strProviderName should not be null");
QueueId = queueId;
streamProviderName = strProviderName;
providerRuntime = runtime;
pubSub = streamPubSub;
pubSubCache = new Dictionary<StreamId, StreamConsumerCollection>();
safeRandom = new SafeRandom();
this.queueGetPeriod = queueGetPeriod;
this.initQueueTimeout = initQueueTimeout;
this.maxDeliveryTime = maxDeliveryTime;
numMessages = 0;
logger = providerRuntime.GetLogger(GrainId + "-" + streamProviderName);
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_01,
"Created {0} {1} for Stream Provider {2} on silo {3} for Queue {4}.",
GetType().Name, GrainId.ToDetailedString(), streamProviderName, Silo, QueueId.ToStringWithHashCode());
numReadMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_READ_MESSAGES, strProviderName));
numSentMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_SENT_MESSAGES, strProviderName));
}
/// <summary>
/// Take responsibility for a new queues that was assigned to me via a new range.
/// We first store the new queue in our internal data structure, try to initialize it and start a pumping timer.
/// ERROR HANDLING:
/// The resposibility to handle initializatoion and shutdown failures is inside the INewQueueAdapterReceiver code.
/// The agent will call Initialize once and log an error. It will not call initiliaze again.
/// The receiver itself may attempt later to recover from this error and do initialization again.
/// The agent will assume initialization has succeeded and will subsequently start calling pumping receive.
/// Same applies to shutdown.
/// </summary>
/// <param name="qAdapter"></param>
/// <param name="queueAdapterCache"></param>
/// <param name="failureHandler"></param>
/// <returns></returns>
public async Task Initialize(Immutable<IQueueAdapter> qAdapter, Immutable<IQueueAdapterCache> queueAdapterCache, Immutable<IStreamFailureHandler> failureHandler)
{
if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null");
if (failureHandler.Value == null) throw new ArgumentNullException("failureHandler", "Init: streamDeliveryFailureHandler should not be null");
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_02, "Init of {0} {1} on silo {2} for queue {3}.",
GetType().Name, GrainId.ToDetailedString(), Silo, QueueId.ToStringWithHashCode());
// Remove cast once we cleanup
queueAdapter = qAdapter.Value;
streamFailureHandler = failureHandler.Value;
try
{
receiver = queueAdapter.CreateReceiver(QueueId);
}
catch (Exception exc)
{
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_02, String.Format("Exception while calling IQueueAdapter.CreateNewReceiver."), exc);
return;
}
try
{
if (queueAdapterCache.Value != null)
{
queueCache = queueAdapterCache.Value.CreateQueueCache(QueueId);
}
}
catch (Exception exc)
{
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_23, String.Format("Exception while calling IQueueAdapterCache.CreateQueueCache."), exc);
return;
}
try
{
var task = OrleansTaskExtentions.SafeExecute(() => receiver.Initialize(initQueueTimeout));
task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_03, String.Format("QueueAdapterReceiver {0} failed to Initialize.", QueueId.ToStringWithHashCode()));
await task;
}
catch
{
// Just ignore this exception and proceed as if Initialize has succeeded.
// We already logged individual exceptions for individual calls to Initialize. No need to log again.
}
// Setup a reader for a new receiver.
// Even if the receiver failed to initialise, treat it as OK and start pumping it. It's receiver responsibility to retry initialization.
var randomTimerOffset = safeRandom.NextTimeSpan(queueGetPeriod);
timer = providerRuntime.RegisterTimer(AsyncTimerCallback, QueueId, randomTimerOffset, queueGetPeriod);
logger.Info((int) ErrorCode.PersistentStreamPullingAgent_04, "Taking queue {0} under my responsibility.", QueueId.ToStringWithHashCode());
}
public async Task Shutdown()
{
// Stop pulling from queues that are not in my range anymore.
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_05, "Shutdown of {0} responsible for queue: {1}", GetType().Name, QueueId.ToStringWithHashCode());
if (timer != null)
{
var tmp = timer;
timer = null;
tmp.Dispose();
}
var unregisterTasks = new List<Task>();
var meAsStreamProducer = this.AsReference<IStreamProducerExtension>();
foreach (var streamId in pubSubCache.Keys)
{
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_06, "Unregister PersistentStreamPullingAgent Producer for stream {0}.", streamId);
unregisterTasks.Add(pubSub.UnregisterProducer(streamId, streamProviderName, meAsStreamProducer));
}
try
{
var task = OrleansTaskExtentions.SafeExecute(() => receiver.Shutdown(initQueueTimeout));
task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_07,
String.Format("QueueAdapterReceiver {0} failed to Shutdown.", QueueId));
await task;
}
catch
{
// Just ignore this exception and proceed as if Shutdown has succeeded.
// We already logged individual exceptions for individual calls to Shutdown. No need to log again.
}
try
{
await Task.WhenAll(unregisterTasks);
}
catch (Exception exc)
{
logger.Warn((int)ErrorCode.PersistentStreamPullingAgent_08,
"Failed to unregister myself as stream producer to some streams taht used to be in my responsibility.", exc);
}
}
public Task AddSubscriber(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
IStreamFilterPredicateWrapper filter)
{
if (logger.IsVerbose) logger.Verbose((int)ErrorCode.PersistentStreamPullingAgent_09, "AddSubscriber: Stream={0} Subscriber={1}.", streamId, streamConsumer);
// cannot await here because explicit consumers trigger this call, so it could cause a deadlock.
AddSubscriber_Impl(subscriptionId, streamId, streamConsumer, null, filter)
.LogException(logger, ErrorCode.PersistentStreamPullingAgent_26,
String.Format("Failed to add subscription for stream {0}." , streamId))
.Ignore();
return TaskDone.Done;
}
// Called by rendezvous when new remote subscriber subscribes to this stream.
private async Task AddSubscriber_Impl(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
StreamSequenceToken token,
IStreamFilterPredicateWrapper filter)
{
IQueueCacheCursor cursor = null;
// if not cache, then we can't get cursor and there is no reason to ask consumer for token.
if (queueCache != null)
{
try
{
StreamSequenceToken consumerToken = await streamConsumer.GetSequenceToken(subscriptionId);
// Set cursor if not cursor is set, or if subscription provides new token
consumerToken = consumerToken ?? token;
if (token != null)
{
cursor = queueCache.GetCacheCursor(streamId.Guid, streamId.Namespace, consumerToken);
}
}
catch (DataNotAvailableException dataNotAvailableException)
{
// notify consumer that the data is not available, if we can.
streamConsumer.ErrorInStream(subscriptionId, dataNotAvailableException).Ignore();
}
}
AddSubscriberToSubscriptionCache(subscriptionId, streamId, streamConsumer, cursor, filter);
}
// Called by rendezvous when new remote subscriber subscribes to this stream or when registering a new stream with the pubsub system.
private void AddSubscriberToSubscriptionCache(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
IQueueCacheCursor newCursor,
IStreamFilterPredicateWrapper filter)
{
StreamConsumerCollection streamDataCollection;
if (!pubSubCache.TryGetValue(streamId, out streamDataCollection))
{
streamDataCollection = new StreamConsumerCollection();
pubSubCache.Add(streamId, streamDataCollection);
}
StreamConsumerData data;
if (!streamDataCollection.TryGetConsumer(subscriptionId, out data))
data = streamDataCollection.AddConsumer(subscriptionId, streamId, streamConsumer, filter);
// if we have a new cursor, use it
if (newCursor != null)
{
data.Cursor = newCursor;
} // else if we don't yet have a cursor, get a cursor at the end of the cash (null sequence token).
else if (data.Cursor == null && queueCache != null)
{
data.Cursor = queueCache.GetCacheCursor(streamId.Guid, streamId.Namespace, null);
}
if (data.State == StreamConsumerDataState.Inactive)
RunConsumerCursor(data, filter).Ignore(); // Start delivering events if not actively doing so
}
public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId)
{
RemoveSubscriber_Impl(subscriptionId, streamId);
return TaskDone.Done;
}
public void RemoveSubscriber_Impl(GuidId subscriptionId, StreamId streamId)
{
StreamConsumerCollection streamData;
if (!pubSubCache.TryGetValue(streamId, out streamData)) return;
// remove consumer
bool removed = streamData.RemoveConsumer(subscriptionId);
if (removed && logger.IsVerbose) logger.Verbose((int)ErrorCode.PersistentStreamPullingAgent_10, "Removed Consumer: subscription={0}, for stream {1}.", subscriptionId, streamId);
if (streamData.Count == 0)
pubSubCache.Remove(streamId);
}
private async Task AsyncTimerCallback(object state)
{
try
{
var myQueueId = (QueueId)(state);
if (timer == null) return; // timer was already removed, last tick
IQueueAdapterReceiver rcvr = receiver;
int maxCacheAddCount = queueCache != null ? queueCache.MaxAddCount : QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG;
// loop through the queue until it is empty.
while (true)
{
if (queueCache != null && queueCache.IsUnderPressure())
{
// Under back pressure. Exit the loop. Will attempt again in the next timer callback.
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_24, String.Format("Stream cache is under pressure. Backing off."));
return;
}
// Retrive one multiBatch from the queue. Every multiBatch has an IEnumerable of IBatchContainers, each IBatchContainer may have multiple events.
IList<IBatchContainer> multiBatch = await rcvr.GetQueueMessagesAsync(maxCacheAddCount);
if (multiBatch == null || multiBatch.Count == 0) return; // queue is empty. Exit the loop. Will attempt again in the next timer callback.
if (queueCache != null)
{
queueCache.AddToCache(multiBatch);
}
numMessages += multiBatch.Count;
numReadMessagesCounter.IncrementBy(multiBatch.Count);
if (logger.IsVerbose2) logger.Verbose2((int)ErrorCode.PersistentStreamPullingAgent_11, "Got {0} messages from queue {1}. So far {2} msgs from this queue.",
multiBatch.Count, myQueueId.ToStringWithHashCode(), numMessages);
foreach (var group in multiBatch.Where(m => m != null)
.GroupBy(container => new Tuple<Guid, string>(container.StreamGuid, container.StreamNamespace)))
{
var streamId = StreamId.GetStreamId(group.Key.Item1, queueAdapter.Name, group.Key.Item2);
StreamConsumerCollection streamData;
if (pubSubCache.TryGetValue(streamId, out streamData))
StartInactiveCursors(streamId, streamData); // if this is an existing stream, start any inactive cursors
else
RegisterStream(streamId, group.First().SequenceToken).Ignore(); ; // if this is a new stream register as producer of stream in pub sub system
}
}
}
catch (Exception exc)
{
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_12,
String.Format("Exception while PersistentStreamPullingAgentGrain.AsyncTimerCallback"), exc);
}
}
private async Task RegisterStream(StreamId streamId, StreamSequenceToken firstToken)
{
var streamData = new StreamConsumerCollection();
pubSubCache.Add(streamId, streamData);
// Create a fake cursor to point into a cache.
// That way we will not purge the event from the cache, until we talk to pub sub.
// This will help ensure the "casual consistency" between pre-existing subscripton (of a potentially new already subscribed consumer)
// and later production.
var pinCursor = queueCache.GetCacheCursor(streamId.Guid, streamId.Namespace, firstToken);
try
{
await RegisterAsStreamProducer(streamId, firstToken);
}finally
{
// Cleanup the fake pinning cursor.
pinCursor.Dispose();
}
}
private void StartInactiveCursors(StreamId streamId, StreamConsumerCollection streamData)
{
// if stream is already registered, just wake inactive consumers
// get list of inactive consumers
var inactiveStreamConsumers = streamData.AllConsumersForStream(streamId)
.Where(consumer => consumer.State == StreamConsumerDataState.Inactive)
.ToList();
// for each inactive stream
foreach (StreamConsumerData consumerData in inactiveStreamConsumers)
RunConsumerCursor(consumerData, consumerData.Filter).Ignore();
}
private async Task RunConsumerCursor(StreamConsumerData consumerData, IStreamFilterPredicateWrapper filterWrapper)
{
try
{
// double check in case of interleaving
if (consumerData.State == StreamConsumerDataState.Active ||
consumerData.Cursor == null) return;
consumerData.State = StreamConsumerDataState.Active;
while (consumerData.Cursor != null && consumerData.Cursor.MoveNext())
{
IBatchContainer batch = null;
Exception ex;
Task deliveryTask;
bool deliveryFailed = false;
try
{
batch = consumerData.Cursor.GetCurrent(out ex);
}
catch (DataNotAvailableException dataNotAvailable)
{
ex = dataNotAvailable;
}
// Apply filtering to this batch, if applicable
if (filterWrapper != null && batch != null)
{
try
{
// Apply batch filter to this input batch, to see whether we should deliver it to this consumer.
if (!batch.ShouldDeliver(
consumerData.StreamId,
filterWrapper.FilterData,
filterWrapper.ShouldReceive)) continue; // Skip this batch -- nothing to do
}
catch (Exception exc)
{
var message = string.Format("Ignoring exception while trying to evaluate subscription filter function {0} on stream {1} in PersistentStreamPullingAgentGrain.RunConsumerCursor", filterWrapper, consumerData.StreamId);
logger.Warn((int) ErrorCode.PersistentStreamPullingAgent_13, message, exc);
}
}
if (batch != null)
{
deliveryTask = AsyncExecutorWithRetries.ExecuteWithRetries(i => DeliverBatchToConsumer(consumerData, batch),
AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => !(exception is DataNotAvailableException), maxDeliveryTime, DefaultBackoffProvider);
}
else if (ex == null)
{
deliveryTask = consumerData.StreamConsumer.CompleteStream(consumerData.SubscriptionId);
}
else
{
// If data is not avialable, bring cursor current
if (ex is DataNotAvailableException)
{
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId.Guid,
consumerData.StreamId.Namespace, null);
}
// Notify client of error.
deliveryTask = consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId, ex);
}
try
{
numSentMessagesCounter.Increment();
await deliveryTask;
}
catch (Exception exc)
{
var message = string.Format("Exception while trying to deliver msgs to stream {0} in PersistentStreamPullingAgentGrain.RunConsumerCursor", consumerData.StreamId);
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_14, message, exc);
deliveryFailed = true;
}
// if we failed to deliver a batch
if (deliveryFailed && batch != null)
{
// notify consumer of delivery error, if we can.
consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId, new StreamEventDeliveryFailureException(consumerData.StreamId)).Ignore();
// record that there was a delivery failure
await streamFailureHandler.OnDeliveryFailure(consumerData.SubscriptionId, streamProviderName,
consumerData.StreamId, batch.SequenceToken);
// if configured to fault on delivery failure and this is not an implicit subscription, fault and remove the subscription
if (streamFailureHandler.ShouldFaultSubsriptionOnError && !SubscriptionMarker.IsImplicitSubscription(consumerData.SubscriptionId.Guid))
{
try
{
// notify consumer of faulted subscription, if we can.
consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId,
new FaultedSubscriptionException(consumerData.SubscriptionId, consumerData.StreamId))
.Ignore();
// mark subscription as faulted.
await pubSub.FaultSubscription(consumerData.StreamId, consumerData.SubscriptionId);
}
finally
{
// remove subscription
RemoveSubscriber_Impl(consumerData.SubscriptionId, consumerData.StreamId);
}
return;
}
}
}
consumerData.State = StreamConsumerDataState.Inactive;
}
catch (Exception exc)
{
// RunConsumerCursor is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_15, "Ignored RunConsumerCursor Error", exc);
throw;
}
}
private async Task DeliverBatchToConsumer(StreamConsumerData consumerData, IBatchContainer batch)
{
StreamSequenceToken newToken = await consumerData.StreamConsumer.DeliverBatch(consumerData.SubscriptionId, batch.AsImmutable());
if (newToken != null)
{
consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId.Guid, consumerData.StreamId.Namespace, newToken);
}
}
private async Task RegisterAsStreamProducer(StreamId streamId, StreamSequenceToken streamStartToken)
{
try
{
if (pubSub == null) throw new NullReferenceException("Found pubSub reference not set up correctly in RetreaveNewStream");
IStreamProducerExtension meAsStreamProducer = this.AsReference<IStreamProducerExtension>();
ISet<PubSubSubscriptionState> streamData = await pubSub.RegisterProducer(streamId, streamProviderName, meAsStreamProducer);
if (logger.IsVerbose) logger.Verbose((int)ErrorCode.PersistentStreamPullingAgent_16, "Got back {0} Subscribers for stream {1}.", streamData.Count, streamId);
var addSubscriptionTasks = new List<Task>(streamData.Count);
foreach (PubSubSubscriptionState item in streamData)
{
addSubscriptionTasks.Add(AddSubscriber_Impl(item.SubscriptionId, item.Stream, item.Consumer, streamStartToken, item.Filter));
}
await Task.WhenAll(addSubscriptionTasks);
}
catch (Exception exc)
{
// RegisterAsStreamProducer is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_17, "Ignored RegisterAsStreamProducer Error", exc);
throw;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace jcMSA.Posts.WebAPI.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type OrganizationRequest.
/// </summary>
public partial class OrganizationRequest : BaseRequest, IOrganizationRequest
{
/// <summary>
/// Constructs a new OrganizationRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public OrganizationRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified Organization using POST.
/// </summary>
/// <param name="organizationToCreate">The Organization to create.</param>
/// <returns>The created Organization.</returns>
public System.Threading.Tasks.Task<Organization> CreateAsync(Organization organizationToCreate)
{
return this.CreateAsync(organizationToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified Organization using POST.
/// </summary>
/// <param name="organizationToCreate">The Organization to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Organization.</returns>
public async System.Threading.Tasks.Task<Organization> CreateAsync(Organization organizationToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<Organization>(organizationToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified Organization.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified Organization.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<Organization>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified Organization.
/// </summary>
/// <returns>The Organization.</returns>
public System.Threading.Tasks.Task<Organization> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified Organization.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The Organization.</returns>
public async System.Threading.Tasks.Task<Organization> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<Organization>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified Organization using PATCH.
/// </summary>
/// <param name="organizationToUpdate">The Organization to update.</param>
/// <returns>The updated Organization.</returns>
public System.Threading.Tasks.Task<Organization> UpdateAsync(Organization organizationToUpdate)
{
return this.UpdateAsync(organizationToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified Organization using PATCH.
/// </summary>
/// <param name="organizationToUpdate">The Organization to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated Organization.</returns>
public async System.Threading.Tasks.Task<Organization> UpdateAsync(Organization organizationToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<Organization>(organizationToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IOrganizationRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IOrganizationRequest Expand(Expression<Func<Organization, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IOrganizationRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IOrganizationRequest Select(Expression<Func<Organization, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="organizationToInitialize">The <see cref="Organization"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(Organization organizationToInitialize)
{
if (organizationToInitialize != null && organizationToInitialize.AdditionalData != null)
{
if (organizationToInitialize.Extensions != null && organizationToInitialize.Extensions.CurrentPage != null)
{
organizationToInitialize.Extensions.AdditionalData = organizationToInitialize.AdditionalData;
object nextPageLink;
organizationToInitialize.AdditionalData.TryGetValue("[email protected]", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
organizationToInitialize.Extensions.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
}
}
}
}
| |
//
// ColorSelector.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Drawing;
using Xwt.Backends;
using System.Collections.Generic;
namespace Xwt
{
[BackendType (typeof(IColorSelectorBackend))]
public class ColorSelector: Widget
{
protected new class WidgetBackendHost: Widget.WidgetBackendHost, IColorSelectorEventSink
{
protected override IBackend OnCreateBackend ()
{
var b = base.OnCreateBackend ();
if (b == null)
b = new DefaultColorSelectorBackend ();
return b;
}
public void OnColorChanged ()
{
((ColorSelector)Parent).OnColorChanged (EventArgs.Empty);
}
}
public ColorSelector ()
{
}
protected override Xwt.Backends.BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
IColorSelectorBackend Backend {
get { return (IColorSelectorBackend) BackendHost.Backend; }
}
/// <summary>
/// Gets or sets the selected color
/// </summary>
public Color Color {
get { return Backend.Color; }
set { Backend.Color = value; }
}
public bool SupportsAlpha {
get { return Backend.SupportsAlpha; }
set { Backend.SupportsAlpha = value; }
}
protected virtual void OnColorChanged (EventArgs args)
{
if (colorChanged != null)
colorChanged (this, args);
}
EventHandler colorChanged;
public event EventHandler ColorChanged {
add {
BackendHost.OnBeforeEventAdd (ColorSelectorEvent.ColorChanged, colorChanged);
colorChanged += value;
}
remove {
colorChanged -= value;
BackendHost.OnAfterEventRemove (ColorSelectorEvent.ColorChanged, colorChanged);
}
}
}
class DefaultColorSelectorBackend: XwtWidgetBackend, IColorSelectorBackend
{
HueBox hsBox;
LightBox lightBox;
ColorSelectionBox colorBox;
SpinButton hueEntry;
SpinButton satEntry;
SpinButton lightEntry;
SpinButton redEntry;
SpinButton greenEntry;
SpinButton blueEntry;
SpinButton alphaEntry;
HSlider alphaSlider;
HSeparator alphaSeparator;
Color currentColor;
bool loadingEntries;
List<Widget> alphaControls = new List<Widget> ();
bool enableColorChangedEvent;
public DefaultColorSelectorBackend ()
{
HBox box = new HBox ();
Table selBox = new Table ();
hsBox = new HueBox ();
hsBox.Light = 0.5;
lightBox = new LightBox ();
hsBox.SelectionChanged += delegate {
lightBox.Hue = hsBox.SelectedColor.Hue;
lightBox.Saturation = hsBox.SelectedColor.Saturation;
};
colorBox = new ColorSelectionBox () { MinHeight = 20 };
selBox.Add (hsBox, 0, 0);
selBox.Add (lightBox, 1, 0);
box.PackStart (selBox);
const int entryWidth = 40;
VBox entryBox = new VBox ();
Table entryTable = new Table ();
entryTable.Add (new Label (Application.TranslationCatalog.GetString("Color:")), 0, 0);
entryTable.Add (colorBox, 1, 0, colspan:4);
entryTable.Add (new HSeparator (), 0, 1, colspan:5);
int r = 2;
entryTable.Add (new Label (Application.TranslationCatalog.GetString("Hue:")), 0, r);
entryTable.Add (hueEntry = new SpinButton () {
MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 360, Digits = 0, IncrementValue = 1 }, 1, r++);
entryTable.Add (new Label (Application.TranslationCatalog.GetString("Saturation:")), 0, r);
entryTable.Add (satEntry = new SpinButton () {
MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 100, Digits = 0, IncrementValue = 1 }, 1, r++);
entryTable.Add (new Label (Application.TranslationCatalog.GetString("Light:")), 0, r);
entryTable.Add (lightEntry = new SpinButton () {
MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 100, Digits = 0, IncrementValue = 1 }, 1, r++);
r = 2;
entryTable.Add (new Label (Application.TranslationCatalog.GetString("Red:")), 3, r);
entryTable.Add (redEntry = new SpinButton () {
MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 255, Digits = 0, IncrementValue = 1 }, 4, r++);
entryTable.Add (new Label (Application.TranslationCatalog.GetString("Green:")), 3, r);
entryTable.Add (greenEntry = new SpinButton () {
MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 255, Digits = 0, IncrementValue = 1 }, 4, r++);
entryTable.Add (new Label (Application.TranslationCatalog.GetString("Blue:")), 3, r);
entryTable.Add (blueEntry = new SpinButton () {
MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 255, Digits = 0, IncrementValue = 1 }, 4, r++);
Label label;
entryTable.Add (alphaSeparator = new HSeparator (), 0, r++, colspan:5);
entryTable.Add (label = new Label (Application.TranslationCatalog.GetString("Opacity:")), 0, r);
entryTable.Add (alphaSlider = new HSlider () {
MinimumValue = 0, MaximumValue = 255, }, 1, r, colspan: 3);
entryTable.Add (alphaEntry = new SpinButton () {
MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 255, Digits = 0, IncrementValue = 1 }, 4, r);
alphaControls.Add (alphaSeparator);
alphaControls.Add (label);
alphaControls.Add (alphaEntry);
entryBox.PackStart (entryTable);
box.PackStart (entryBox);
Content = box;
hsBox.SelectionChanged += HandleColorBoxSelectionChanged;
lightBox.SelectionChanged += HandleColorBoxSelectionChanged;
hueEntry.ValueChanged += HandleHslChanged;
satEntry.ValueChanged += HandleHslChanged;
lightEntry.ValueChanged += HandleHslChanged;
redEntry.ValueChanged += HandleRgbChanged;
greenEntry.ValueChanged += HandleRgbChanged;
blueEntry.ValueChanged += HandleRgbChanged;
alphaEntry.ValueChanged += HandleAlphaChanged;
alphaSlider.ValueChanged += HandleAlphaChanged;
Color = Colors.White;
}
void HandleAlphaChanged (object sender, EventArgs e)
{
if (loadingEntries)
return;
if (sender == alphaSlider)
alphaEntry.Value = alphaSlider.Value;
if (sender == alphaEntry)
alphaSlider.Value = alphaEntry.Value;
int a = Convert.ToInt32 (alphaEntry.Value);
currentColor = currentColor.WithAlpha ((double)a / 255d);
LoadColorBoxSelection ();
HandleColorChanged ();
}
void HandleHslChanged (object sender, EventArgs e)
{
if (loadingEntries)
return;
int h = Convert.ToInt32 (hueEntry.Value);
int s = Convert.ToInt32 (satEntry.Value);
int l = Convert.ToInt32 (lightEntry.Value);
currentColor = Color.FromHsl ((double)h / 360d, (double)s / 100d, (double)l / 100d, currentColor.Alpha);
LoadColorBoxSelection ();
LoadRgbEntries ();
HandleColorChanged ();
}
void HandleRgbChanged (object sender, EventArgs e)
{
if (loadingEntries)
return;
int r = Convert.ToInt32 (redEntry.Value);
int g = Convert.ToInt32 (greenEntry.Value);
int b = Convert.ToInt32 (blueEntry.Value);
currentColor = new Color ((double)r / 255d, (double)g / 255d, (double)b / 255d, currentColor.Alpha);
LoadColorBoxSelection ();
LoadHslEntries ();
HandleColorChanged ();
}
void HandleColorBoxSelectionChanged (object sender, EventArgs args)
{
currentColor = Color.FromHsl (
hsBox.SelectedColor.Hue,
hsBox.SelectedColor.Saturation,
lightBox.Light,
currentColor.Alpha);
colorBox.Color = currentColor;
LoadHslEntries ();
LoadRgbEntries ();
HandleColorChanged ();
}
void LoadAlphaEntry ()
{
alphaEntry.Value = ((int)(currentColor.Alpha * 255));
alphaSlider.Value = ((int)(currentColor.Alpha * 255));
}
void LoadHslEntries ()
{
loadingEntries = true;
hueEntry.Value = ((int)(currentColor.Hue * 360));
satEntry.Value = ((int)(currentColor.Saturation * 100));
lightEntry.Value = ((int)(currentColor.Light * 100));
loadingEntries = false;
}
void LoadRgbEntries ()
{
loadingEntries = true;
redEntry.Value = ((int)(currentColor.Red * 255));
greenEntry.Value = ((int)(currentColor.Green * 255));
blueEntry.Value = ((int)(currentColor.Blue * 255));
loadingEntries = false;
}
void LoadColorBoxSelection ()
{
hsBox.SelectedColor = currentColor;
lightBox.Light = currentColor.Light;
lightBox.Hue = hsBox.SelectedColor.Hue;
lightBox.Saturation = hsBox.SelectedColor.Saturation;
colorBox.Color = currentColor;
}
#region IColorSelectorBackend implementation
public Color Color {
get {
return currentColor;
}
set {
currentColor = value;
LoadColorBoxSelection ();
LoadRgbEntries ();
LoadHslEntries ();
LoadAlphaEntry ();
}
}
public bool SupportsAlpha {
get {
return alphaControls [0].Visible;
}
set {
foreach (var w in alphaControls)
w.Visible = value;
}
}
#endregion
protected new IColorSelectorEventSink EventSink {
get { return (IColorSelectorEventSink)base.EventSink; }
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is ColorSelectorEvent) {
switch ((ColorSelectorEvent)eventId) {
case ColorSelectorEvent.ColorChanged: enableColorChangedEvent = true; break;
}
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is ColorSelectorEvent) {
switch ((ColorSelectorEvent)eventId) {
case ColorSelectorEvent.ColorChanged: enableColorChangedEvent = false; break;
}
}
}
void HandleColorChanged ()
{
if (enableColorChangedEvent)
Application.Invoke (EventSink.OnColorChanged);
}
}
class HueBox: Canvas
{
const int size = 150;
const int padding = 3;
bool buttonDown;
Point selection;
Image colorBox;
double light;
public double Light {
get {
return light;
}
set {
light = value;
if (colorBox != null) {
colorBox.Dispose ();
colorBox = null;
}
QueueDraw ();
}
}
public Color SelectedColor {
get { return GetColor ((int)selection.X, (int)selection.Y); }
set {
selection.X = (size - 1) * value.Hue;
selection.Y = (size - 1) * (1 - value.Saturation);
QueueDraw ();
}
}
public HueBox ()
{
MinWidth = size + padding * 2;
MinHeight = size + padding * 2;
}
protected override void OnDraw (Context ctx, Rectangle dirtyRect)
{
if (colorBox == null) {
using (var ib = new ImageBuilder (size, size)) {
for (int i=0; i<size; i++) {
for (int j=0; j<size; j++) {
ib.Context.Rectangle (i, j, 1, 1);
ib.Context.SetColor (GetColor (i,j));
ib.Context.Fill ();
}
}
if (ParentWindow != null)
colorBox = ib.ToBitmap (this); // take screen scale factor into account
else
colorBox = ib.ToBitmap ();
}
}
ctx.DrawImage (colorBox, padding, padding);
ctx.SetLineWidth (1);
ctx.SetColor (Colors.Black);
ctx.Rectangle (selection.X + padding - 2 + 0.5, selection.Y + padding - 2 + 0.5, 4, 4);
ctx.Stroke ();
}
Color GetColor (int x, int y)
{
return Color.FromHsl ((double)x / (double)(size-1), (double)(size - 1 - y) / (double)(size-1), Light);
}
protected override void OnButtonPressed (ButtonEventArgs args)
{
base.OnButtonPressed (args);
buttonDown = true;
selection = new Point (args.X - padding, args.Y - padding);
OnSelectionChanged ();
QueueDraw ();
}
protected override void OnButtonReleased (ButtonEventArgs args)
{
base.OnButtonReleased (args);
buttonDown = false;
QueueDraw ();
}
protected override void OnMouseMoved (MouseMovedEventArgs args)
{
base.OnMouseMoved (args);
if (buttonDown) {
QueueDraw ();
selection = new Point (args.X - padding, args.Y - padding);
OnSelectionChanged ();
}
}
void OnSelectionChanged ()
{
if (selection.X < 0)
selection.X = 0;
if (selection.Y < 0)
selection.Y = 0;
if (selection.X >= size)
selection.X = size - 1;
if (selection.Y >= size)
selection.Y = size - 1;
if (SelectionChanged != null)
SelectionChanged (this, EventArgs.Empty);
}
public event EventHandler SelectionChanged;
}
class LightBox: Canvas
{
const int padding = 3;
double light;
double saturation;
double hue;
bool buttonPressed;
public double Hue {
get {
return hue;
}
set {
hue = value;
QueueDraw ();
}
}
public double Saturation {
get {
return saturation;
}
set {
saturation = value;
QueueDraw ();
}
}
public double Light {
get {
return light;
}
set {
light = value;
QueueDraw ();
}
}
public LightBox ()
{
MinWidth = 20;
MinHeight = 20;
}
protected override void OnDraw (Context ctx, Rectangle dirtyRect)
{
double width = Size.Width - padding * 2;
int range = (int)Size.Height - padding * 2;
for (int n=0; n < range; n++) {
ctx.Rectangle (padding, padding + n, width, 1);
ctx.SetColor (Color.FromHsl (hue, saturation, (double)(range - n - 1) / (double)(range - 1)));
ctx.Fill ();
}
ctx.Rectangle (0.5, padding + (int)(((double)range) * (1-light)) + 0.5 - 2, Size.Width - 1, 4);
ctx.SetColor (Colors.Black);
ctx.SetLineWidth (1);
ctx.Stroke ();
}
protected override void OnButtonPressed (ButtonEventArgs args)
{
base.OnButtonPressed (args);
buttonPressed = true;
OnSelectionChanged ((int)args.Y - padding);
QueueDraw ();
}
protected override void OnButtonReleased (ButtonEventArgs args)
{
base.OnButtonReleased (args);
buttonPressed = false;
QueueDraw ();
}
protected override void OnMouseMoved (MouseMovedEventArgs args)
{
base.OnMouseMoved (args);
if (buttonPressed) {
OnSelectionChanged ((int)args.Y - padding);
QueueDraw ();
}
}
void OnSelectionChanged (int y)
{
int range = (int)Size.Height - padding * 2;
if (y < 0)
y = 0;
if (y >= range)
y = range - 1;
light = 1 - ((double) y / (double)(range - 1));
if (SelectionChanged != null)
SelectionChanged (this, EventArgs.Empty);
}
public event EventHandler SelectionChanged;
}
class ColorSelectionBox: Canvas
{
Color color;
public Color Color {
get {
return color;
}
set {
color = value;
QueueDraw ();
}
}
protected override void OnDraw (Context ctx, Rectangle dirtyRect)
{
ctx.Rectangle (Bounds);
ctx.SetColor (Colors.White);
ctx.Fill ();
ctx.MoveTo (0, 0);
ctx.LineTo (Size.Width, 0);
ctx.LineTo (0, Size.Height);
ctx.LineTo (0, 0);
ctx.SetColor (Colors.Black);
ctx.Fill ();
ctx.Rectangle (Bounds);
ctx.SetColor (color);
ctx.Fill ();
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.BusinessEntities.BusinessEntities
File: MarketDepth.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.BusinessEntities
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using StockSharp.Messages;
using StockSharp.Localization;
/// <summary>
/// Order book.
/// </summary>
[System.Runtime.Serialization.DataContract]
[Serializable]
public class MarketDepth : Cloneable<MarketDepth>, IEnumerable<QuoteChange>
{
/// <summary>
/// Create order book.
/// </summary>
/// <param name="security">Security.</param>
public MarketDepth(Security security)
{
Security = security ?? throw new ArgumentNullException(nameof(security));
}
private int _maxDepth = 100;
/// <summary>
/// The maximum depth of order book.
/// </summary>
/// <remarks>
/// The default value is 100. If the exceeded the maximum depth the event <see cref="MarketDepth.QuoteOutOfDepth"/> will triggered.
/// </remarks>
[DisplayNameLoc(LocalizedStrings.Str1660Key)]
[Browsable(false)]
[Obsolete]
public int MaxDepth
{
get => _maxDepth;
set
{
if (value < 1)
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str480);
_maxDepth = value;
}
}
/// <summary>
/// Security.
/// </summary>
public Security Security { get; }
/// <summary>
/// Whether to use aggregated quotes <see cref="QuoteChange.InnerQuotes"/> at the join of the volumes with the same price.
/// </summary>
/// <remarks>
/// The default is disabled for performance.
/// </remarks>
public bool UseAggregatedQuotes { get; set; }
/// <summary>
/// Last change time.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.ServerTimeKey,
Description = LocalizedStrings.Str168Key,
GroupName = LocalizedStrings.CommonKey,
Order = 2)]
public DateTimeOffset LastChangeTime { get; set; }
/// <summary>
/// The order book local time stamp.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str203Key,
Description = LocalizedStrings.Str204Key,
GroupName = LocalizedStrings.CommonKey,
Order = 3)]
public DateTimeOffset LocalTime { get; set; }
/// <summary>
/// Sequence number.
/// </summary>
/// <remarks>Zero means no information.</remarks>
public long SeqNum { get; set; }
/// <summary>
/// Determines the message is generated from the specified <see cref="Messages.DataType"/>.
/// </summary>
public Messages.DataType BuildFrom { get; set; }
/// <summary>
/// Get the array of bids sorted by descending price. The first (best) bid will be the maximum price.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str281Key,
Description = LocalizedStrings.Str282Key,
GroupName = LocalizedStrings.CommonKey,
Order = 0)]
[Obsolete("Use Bids2 property.")]
public Quote[] Bids => Bids2.Select(c => c.ToQuote(Sides.Buy, Security)).ToArray();
/// <summary>
/// Get the array of asks sorted by ascending price. The first (best) ask will be the minimum price.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str283Key,
Description = LocalizedStrings.Str284Key,
GroupName = LocalizedStrings.CommonKey,
Order = 1)]
[Obsolete("Use Asks2 property.")]
public Quote[] Asks => Asks2.Select(c => c.ToQuote(Sides.Sell, Security)).ToArray();
private QuoteChange[] _bids2 = Array.Empty<QuoteChange>();
/// <summary>
/// Get the array of bids sorted by descending price. The first (best) bid will be the maximum price.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str281Key,
Description = LocalizedStrings.Str282Key,
GroupName = LocalizedStrings.CommonKey,
Order = 0)]
public QuoteChange[] Bids2
{
get => _bids2;
private set => _bids2 = value ?? throw new ArgumentNullException(nameof(value));
}
private QuoteChange[] _asks2 = Array.Empty<QuoteChange>();
/// <summary>
/// Get the array of asks sorted by ascending price. The first (best) ask will be the minimum price.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str283Key,
Description = LocalizedStrings.Str284Key,
GroupName = LocalizedStrings.CommonKey,
Order = 1)]
public QuoteChange[] Asks2
{
get => _asks2;
private set => _asks2 = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Trading security currency.
/// </summary>
[DisplayNameLoc(LocalizedStrings.CurrencyKey)]
public CurrencyTypes? Currency { get; set; }
/// <summary>
/// The best bid. If the order book does not contain bids, will be returned <see langword="null" />.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str291Key)]
[Obsolete("Use BestBid2 property.")]
public Quote BestBid => BestBid2?.ToQuote(Sides.Buy, Security);
/// <summary>
/// The best ask. If the order book does not contain asks, will be returned <see langword="null" />.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str292Key)]
[Obsolete("Use BestAsk2 property.")]
public Quote BestAsk => BestAsk2?.ToQuote(Sides.Sell, Security);
/// <summary>
/// The best bid. If the order book does not contain bids, will be returned <see langword="null" />.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str291Key)]
public QuoteChange? BestBid2 { get; private set; }
/// <summary>
/// The best ask. If the order book does not contain asks, will be returned <see langword="null" />.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str292Key)]
public QuoteChange? BestAsk2 { get; private set; }
/// <summary>
/// The best pair. If the order book is empty, will be returned <see langword="null" />.
/// </summary>
[DisplayNameLoc(LocalizedStrings.BestPairKey)]
public MarketDepthPair BestPair => GetPair(0);
/// <summary>
/// To get the total price size by bids.
/// </summary>
[DisplayNameLoc(LocalizedStrings.TotalBidsPriceKey)]
public decimal TotalBidsPrice => _bids2.Length > 0 ? Security.ShrinkPrice(_bids2.Sum(b => b.Price)) : 0;
/// <summary>
/// To get the total price size by offers.
/// </summary>
[DisplayNameLoc(LocalizedStrings.TotalAsksPriceKey)]
public decimal TotalAsksPrice => _asks2.Length > 0 ? Security.ShrinkPrice(_asks2.Sum(a => a.Price)) : 0;
/// <summary>
/// Get bids total volume.
/// </summary>
[DisplayNameLoc(LocalizedStrings.TotalBidsVolumeKey)]
public decimal TotalBidsVolume => _bids2.Sum(b => b.Volume);
/// <summary>
/// Get asks total volume.
/// </summary>
[DisplayNameLoc(LocalizedStrings.TotalAsksVolumeKey)]
public decimal TotalAsksVolume => _asks2.Sum(a => a.Volume);
/// <summary>
/// Get total volume.
/// </summary>
[DisplayNameLoc(LocalizedStrings.TotalVolumeKey)]
public decimal TotalVolume => TotalBidsVolume + TotalAsksVolume;
/// <summary>
/// To get the total price size.
/// </summary>
[DisplayNameLoc(LocalizedStrings.TotalPriceKey)]
public decimal TotalPrice => TotalBidsPrice + TotalAsksPrice;
/// <summary>
/// Total quotes count (bids + asks).
/// </summary>
[DisplayNameLoc(LocalizedStrings.TotalQuotesCountKey)]
public int Count => _bids2.Length + _asks2.Length;
private int _depth;
/// <summary>
/// Depth of book.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str1197Key)]
public int Depth
{
get => _depth;
private set
{
if (_depth == value)
return;
_depth = value;
#pragma warning disable 612
DepthChanged?.Invoke();
#pragma warning restore 612
}
}
/// <summary>
/// Event on exceeding the maximum allowable depth of quotes.
/// </summary>
[Obsolete]
#pragma warning disable 67
public event Action<Quote> QuoteOutOfDepth;
#pragma warning restore 67
/// <summary>
/// Depth <see cref="Depth"/> changed.
/// </summary>
[Obsolete]
public event Action DepthChanged;
/// <summary>
/// Quotes changed.
/// </summary>
[Obsolete]
public event Action QuotesChanged;
/// <summary>
/// To reduce the order book to the required depth.
/// </summary>
/// <param name="newDepth">New order book depth.</param>
public void Decrease(int newDepth)
{
var currentDepth = Depth;
if (newDepth < 0)
throw new ArgumentOutOfRangeException(nameof(newDepth), newDepth, LocalizedStrings.Str481);
else if (newDepth > currentDepth)
throw new ArgumentOutOfRangeException(nameof(newDepth), newDepth, LocalizedStrings.Str482Params.Put(currentDepth));
Bids2 = Decrease(_bids2, newDepth);
Asks2 = Decrease(_asks2, newDepth);
UpdateDepthAndTime();
RaiseQuotesChanged();
}
private static QuoteChange[] Decrease(QuoteChange[] quotes, int newDepth)
{
if (quotes is null)
throw new ArgumentNullException(nameof(quotes));
if (newDepth <= quotes.Length)
Array.Resize(ref quotes, newDepth);
return quotes;
}
/// <summary>
/// To get a quote by the direction <see cref="Sides"/> and the depth index.
/// </summary>
/// <param name="orderDirection">Orders side.</param>
/// <param name="depthIndex">Depth index. Zero index means the best quote.</param>
/// <returns>Quote. If a quote does not exist for specified depth, then the <see langword="null" /> will be returned.</returns>
public QuoteChange? GetQuote(Sides orderDirection, int depthIndex)
{
return GetQuotesInternal(orderDirection).ElementAtOr(depthIndex);
}
/// <summary>
/// To get a quote by the price.
/// </summary>
/// <param name="price">Quote price.</param>
/// <returns>Found quote. If there is no quote in the order book for the passed price, then the <see langword="null" /> will be returned.</returns>
public QuoteChange? GetQuote(decimal price)
{
var quotes = GetQuotes(price);
var i = GetQuoteIndex(quotes, price);
return i < 0 ? default : quotes[i];
}
/// <summary>
/// To get quotes by the direction <see cref="Sides"/>.
/// </summary>
/// <param name="orderDirection">Orders side.</param>
/// <returns>Quotes.</returns>
public QuoteChange[] GetQuotes(Sides orderDirection)
{
return orderDirection == Sides.Buy ? Bids2 : Asks2;
}
/// <summary>
/// To get the best quote by the direction <see cref="Sides"/>.
/// </summary>
/// <param name="orderDirection">Order side.</param>
/// <returns>The best quote. If the order book is empty, then the <see langword="null" /> will be returned.</returns>
public QuoteChange? GetBestQuote(Sides orderDirection)
{
return orderDirection == Sides.Buy ? BestBid2 : BestAsk2;
}
/// <summary>
/// To get a pair of quotes (bid + offer) by the depth index.
/// </summary>
/// <param name="depthIndex">Depth index. Zero index means the best pair of quotes.</param>
/// <returns>The pair of quotes. If the index is larger than book order depth <see cref="MarketDepth.Depth"/>, then the <see langword="null" /> is returned.</returns>
public MarketDepthPair GetPair(int depthIndex)
{
if (depthIndex < 0)
throw new ArgumentOutOfRangeException(nameof(depthIndex), depthIndex, LocalizedStrings.Str483);
var bid = GetQuote(Sides.Buy, depthIndex);
var ask = GetQuote(Sides.Sell, depthIndex);
if (bid == null && ask == null)
return null;
return new MarketDepthPair(Security, bid, ask);
}
/// <summary>
/// To get a pair of quotes for a given book depth.
/// </summary>
/// <param name="depth">Book depth. The counting is from the best quotes.</param>
/// <returns>Spread.</returns>
public IEnumerable<MarketDepthPair> GetTopPairs(int depth)
{
if (depth < 0)
throw new ArgumentOutOfRangeException(nameof(depth), depth, LocalizedStrings.Str484);
var retVal = new List<MarketDepthPair>();
for (var i = 0; i < depth; i++)
{
var single = GetPair(i);
if (single != null)
retVal.Add(single);
else
break;
}
return retVal;
}
/// <summary>
/// To get quotes for a given book depth.
/// </summary>
/// <param name="depth">Book depth. Quotes are in order of price increasing from bids to offers.</param>
/// <returns>Spread.</returns>
public IEnumerable<QuoteChange> GetTopQuotes(int depth)
{
if (depth < 0)
throw new ArgumentOutOfRangeException(nameof(depth), depth, LocalizedStrings.Str484);
var retVal = new List<QuoteChange>();
for (var i = depth - 1; i >= 0; i--)
{
var single = GetQuote(Sides.Buy, i);
if (single != null)
retVal.Add(single.Value);
}
for (var i = 0; i < depth; i++)
{
var single = GetQuote(Sides.Sell, i);
if (single != null)
retVal.Add(single.Value);
else
break;
}
return retVal;
}
/// <summary>
/// Update the order book by new quotes.
/// </summary>
/// <param name="quotes">The new quotes.</param>
/// <param name="lastChangeTime">Last change time.</param>
/// <returns>Market depth.</returns>
/// <remarks>
/// The old quotes will be removed from the book.
/// </remarks>
[Obsolete]
public MarketDepth Update(IEnumerable<Quote> quotes, DateTimeOffset lastChangeTime = default)
{
if (quotes == null)
throw new ArgumentNullException(nameof(quotes));
var bids = Enumerable.Empty<Quote>();
var asks = Enumerable.Empty<Quote>();
foreach (var group in quotes.GroupBy(q => q.OrderDirection))
{
if (group.Key == Sides.Buy)
bids = group;
else
asks = group;
}
return Update(bids, asks, false, lastChangeTime);
}
/// <summary>
/// Update the order book by new bids and asks.
/// </summary>
/// <param name="bids">The new bids.</param>
/// <param name="asks">The new asks.</param>
/// <param name="isSorted">Are quotes sorted. This parameter is used for optimization in order to prevent re-sorting.</param>
/// <param name="lastChangeTime">Last change time.</param>
/// <returns>Market depth.</returns>
/// <remarks>
/// The old quotes will be removed from the book.
/// </remarks>
[Obsolete]
public MarketDepth Update(IEnumerable<Quote> bids, IEnumerable<Quote> asks, bool isSorted = false, DateTimeOffset lastChangeTime = default)
{
if (bids == null)
throw new ArgumentNullException(nameof(bids));
if (asks == null)
throw new ArgumentNullException(nameof(asks));
if (!isSorted)
{
bids = bids.OrderBy(q => 0 - q.Price);
asks = asks.OrderBy(q => q.Price);
}
var bidsArr = bids.Select(EntitiesExtensions.ToQuoteChange).ToArray();
var asksArr = asks.Select(EntitiesExtensions.ToQuoteChange).ToArray();
//if (AutoVerify)
//{
// if (!Verify(bidsArr, asksArr))
// throw new ArgumentException(LocalizedStrings.Str485);
//}
//Truncate(bidsArr, asksArr, lastChangeTime);
return Update(bidsArr, asksArr, lastChangeTime);
}
/// <summary>
/// To update the order book. The version without checks and blockings.
/// </summary>
/// <param name="bids">Sorted bids.</param>
/// <param name="asks">Sorted asks.</param>
/// <param name="lastChangeTime">Change time.</param>
/// <returns>Market depth.</returns>
public MarketDepth Update(QuoteChange[] bids, QuoteChange[] asks, DateTimeOffset lastChangeTime)
{
if (bids is null)
throw new ArgumentNullException(nameof(bids));
if (asks is null)
throw new ArgumentNullException(nameof(asks));
_bids2 = bids.ToArray();
_asks2 = asks.ToArray();
UpdateDepthAndTime(lastChangeTime, false);
RaiseQuotesChanged();
return this;
}
/// <summary>
/// To refresh the quote. If a quote with the same price is already in the order book, it is updated as passed. Otherwise, it automatically rebuilds the order book.
/// </summary>
/// <param name="quote">The new quote.</param>
/// <param name="side">Side.</param>
public void UpdateQuote(QuoteChange quote, Sides side)
{
SetQuote(quote, side, false);
}
/// <summary>
/// Add buy quote.
/// </summary>
/// <param name="price">Buy price.</param>
/// <param name="volume">Buy volume.</param>
public void AddBid(decimal price, decimal volume)
{
AddQuote(new QuoteChange
{
Price = price,
Volume = volume,
}, Sides.Buy);
}
/// <summary>
/// Add sell quote.
/// </summary>
/// <param name="price">Sell price.</param>
/// <param name="volume">Sell volume.</param>
public void AddAsk(decimal price, decimal volume)
{
AddQuote(new QuoteChange
{
Price = price,
Volume = volume,
}, Sides.Sell);
}
/// <summary>
/// To add the quote. If a quote with the same price is already in the order book, they are combined into the <see cref="QuoteChange.InnerQuotes"/>.
/// </summary>
/// <param name="quote">The new quote.</param>
/// <param name="side">Side.</param>
public void AddQuote(QuoteChange quote, Sides side)
{
SetQuote(quote, side, true);
}
private void SetQuote(QuoteChange quote, Sides side, bool isAggregate)
{
//CheckQuote(quote);
//Quote outOfDepthQuote = null;
//lock (_syncRoot)
//{
var quotes = GetQuotes(side);
var index = GetQuoteIndex(quotes, quote.Price);
if (index != -1)
{
if (isAggregate)
{
var existedQuote = quotes[index];
//if (UseAggregatedQuotes)
//{
// if (existedQuote is not AggregatedQuote aggQuote)
// {
// aggQuote = new AggregatedQuote
// {
// Price = quote.Price,
// Security = quote.Security,
// OrderDirection = quote.OrderDirection
// };
// aggQuote.InnerQuotes.Add(existedQuote);
// quotes[index] = aggQuote;
// }
// aggQuote.InnerQuotes.Add(quote);
//}
//else
existedQuote.Volume += quote.Volume;
}
else
{
quotes[index] = quote;
}
}
else
{
for (index = 0; index < quotes.Length; index++)
{
var currentPrice = quotes[index].Price;
if (side == Sides.Buy)
{
if (quote.Price > currentPrice)
break;
}
else
{
if (quote.Price < currentPrice)
break;
}
}
Array.Resize(ref quotes, quotes.Length + 1);
if (index < (quotes.Length - 1))
Array.Copy(quotes, index, quotes, index + 1, quotes.Length - 1 - index);
quotes[index] = quote;
//if (quotes.Length > MaxDepth)
//{
// outOfDepthQuote = quotes[quotes.Length - 1];
// quotes = RemoveAt(quotes, quotes.Length - 1);
//}
if (side == Sides.Buy)
Bids2 = quotes;
else
Asks2 = quotes;
}
UpdateDepthAndTime();
//if (quotes.Length > MaxDepth)
// throw new InvalidOperationException(LocalizedStrings.Str486Params.Put(MaxDepth, quotes.Length));
//}
RaiseQuotesChanged();
//if (outOfDepthQuote != null)
// QuoteOutOfDepth?.Invoke(outOfDepthQuote);
}
#region IEnumerable<QuoteChange>
/// <summary>
/// To get the enumerator object.
/// </summary>
/// <returns>The enumerator object.</returns>
public IEnumerator<QuoteChange> GetEnumerator()
{
return Bids2.Reverse().Concat(Asks2).Cast<QuoteChange>().GetEnumerator();
}
/// <summary>
/// To get the enumerator object.
/// </summary>
/// <returns>The enumerator object.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
/// <summary>
/// To get all pairs from the order book.
/// </summary>
/// <returns>Pairs from which the order book is composed.</returns>
public IEnumerable<MarketDepthPair> ToPairs()
{
return GetTopPairs(Depth);
}
/// <summary>
/// Remove the quote.
/// </summary>
/// <param name="quote">The quote to remove.</param>
/// <param name="lastChangeTime">Order book change time.</param>
[Obsolete]
public void Remove(Quote quote, DateTimeOffset lastChangeTime = default)
{
if (quote == null)
throw new ArgumentNullException(nameof(quote));
Remove(quote.OrderDirection, quote.Price, quote.Volume, lastChangeTime);
}
/// <summary>
/// Remove the volume for the price.
/// </summary>
/// <param name="price">Remove the quote for the price.</param>
/// <param name="volume">The volume to be deleted. If it is not specified, then all the quote is removed.</param>
/// <param name="lastChangeTime">Order book change time.</param>
public void Remove(decimal price, decimal volume = 0, DateTimeOffset lastChangeTime = default)
{
var dir = GetDirection(price);
if (dir == null)
throw new ArgumentOutOfRangeException(nameof(price), price, LocalizedStrings.Str487);
Remove((Sides)dir, price, volume, lastChangeTime);
}
/// <summary>
/// Remove the volume for the price.
/// </summary>
/// <param name="direction">Order side.</param>
/// <param name="price">Remove the quote for the price.</param>
/// <param name="volume">The volume to be deleted. If it is not specified, then all the quote is removed.</param>
/// <param name="lastChangeTime">Order book change time.</param>
public void Remove(Sides direction, decimal price, decimal volume = 0, DateTimeOffset lastChangeTime = default)
{
if (price <= 0)
throw new ArgumentOutOfRangeException(nameof(price), price, LocalizedStrings.Str488);
if (volume < 0)
throw new ArgumentOutOfRangeException(nameof(volume), volume, LocalizedStrings.Str489);
var quotes = GetQuotesInternal(direction);
var index = GetQuoteIndex(quotes, price);
if (index == -1)
throw new ArgumentOutOfRangeException(nameof(price), price, LocalizedStrings.Str487);
var quote = quotes[index];
decimal leftVolume;
if (volume > 0)
{
if (quote.Volume < volume)
throw new ArgumentOutOfRangeException(nameof(volume), volume, LocalizedStrings.Str490Params.Put(quote));
leftVolume = quote.Volume - volume;
//if (UseAggregatedQuotes)
//{
// if (quote is AggregatedQuote aggQuote)
// {
// while (volume > 0)
// {
// var innerQuote = aggQuote.InnerQuotes.First();
// if (innerQuote.Volume > volume)
// {
// innerQuote.Volume -= volume;
// break;
// }
// else
// {
// aggQuote.InnerQuotes.Remove(innerQuote);
// volume -= innerQuote.Volume;
// }
// }
// }
//}
}
else
leftVolume = 0;
if (leftVolume == 0)
{
quotes = RemoveAt(quotes, index);
if (direction == Sides.Buy)
Bids2 = quotes;
else
Asks2 = quotes;
UpdateDepthAndTime(lastChangeTime);
}
else
{
quote.Volume = leftVolume;
UpdateTime(lastChangeTime);
}
RaiseQuotesChanged();
}
private static QuoteChange[] RemoveAt(QuoteChange[] quotes, int index)
{
var newQuotes = new QuoteChange[quotes.Length - 1];
if (index > 0)
Array.Copy(quotes, 0, newQuotes, 0, index);
if (index < (quotes.Length - 1))
Array.Copy(quotes, index + 1, newQuotes, index, quotes.Length - index - 1);
return newQuotes;
}
private static int GetQuoteIndex(QuoteChange[] quotes, decimal price)
{
var stop = quotes.Length - 1;
if (stop < 0)
return -1;
var first = quotes[0];
var cmp = decimal.Compare(price, first.Price);
if (cmp == 0)
return 0;
var last = quotes[stop];
var desc = first.Price - last.Price > 0m;
if (desc)
cmp = -cmp;
if (cmp < 0)
return -1;
cmp = decimal.Compare(price, last.Price);
if (desc)
cmp = -cmp;
if (cmp > 0)
return -1;
if (cmp == 0)
return stop;
var start = 0;
while (stop - start >= 0)
{
var mid = (start + stop) >> 1;
cmp = decimal.Compare(price, quotes[mid].Price);
if (desc)
cmp = -cmp;
if (cmp > 0)
start = mid + 1;
else if (cmp < 0)
stop = mid - 1;
else
return mid;
}
return -1;
}
private QuoteChange[] GetQuotesInternal(Sides direction)
{
return direction == Sides.Buy ? _bids2 : _asks2;
}
private QuoteChange[] GetQuotes(decimal price)
{
var dir = GetDirection(price);
if (dir == null)
return Array.Empty<QuoteChange>();
else
return dir == Sides.Buy ? _bids2 : _asks2;
}
private Sides? GetDirection(decimal price)
{
if (BestBid2 != null && BestBid2.Value.Price >= price)
return Sides.Buy;
else if (BestAsk2 != null && BestAsk2.Value.Price <= price)
return Sides.Sell;
else
return null;
}
private void UpdateDepthAndTime(DateTimeOffset lastChangeTime = default, bool depthChangedEventNeeded = true)
{
if (depthChangedEventNeeded)
{
Depth = _bids2.Length > _asks2.Length ? _bids2.Length : _asks2.Length;
}
else
{
_depth = _bids2.Length > _asks2.Length ? _bids2.Length : _asks2.Length;
}
BestBid2 = _bids2.Length > 0 ? _bids2[0] : null;
BestAsk2 = _asks2.Length > 0 ? _asks2[0] : null;
UpdateTime(lastChangeTime);
}
private void UpdateTime(DateTimeOffset lastChangeTime)
{
if (lastChangeTime != default)
{
LastChangeTime = lastChangeTime;
}
}
private void RaiseQuotesChanged()
{
#pragma warning disable 612
QuotesChanged?.Invoke();
#pragma warning restore 612
}
/// <summary>
/// Create a copy of <see cref="MarketDepth"/>.
/// </summary>
/// <returns>Copy.</returns>
public override MarketDepth Clone()
{
return new MarketDepth(Security)
{
//MaxDepth = MaxDepth,
//UseAggregatedQuotes = UseAggregatedQuotes,
//AutoVerify = AutoVerify,
Currency = Currency,
LocalTime = LocalTime,
LastChangeTime = LastChangeTime,
_bids2 = _bids2.ToArray(),
_asks2 = _asks2.ToArray(),
SeqNum = SeqNum,
BuildFrom = BuildFrom,
};
}
/// <inheritdoc />
public override string ToString()
{
return this.Select(q => q.ToString()).Join(Environment.NewLine);
}
}
}
| |
using System;
using Bearded.Utilities.Monads;
using Bearded.Utilities.Testing;
using FluentAssertions;
using Xunit;
using Xunit.Sdk;
namespace Bearded.Utilities.Tests.Monads;
public sealed class ResultTests
{
public sealed class ResultOrDefault
{
public sealed class WithEagerDefault
{
[Fact]
public void ReturnsDefaultOnFailure()
{
var result = Result.Failure<int, string>("something went wrong");
result.ResultOrDefault(100).Should().Be(100);
}
[Fact]
public void ReturnsResultOnSuccess()
{
var result = Result.Success<int, string>(200);
result.ResultOrDefault(100).Should().Be(200);
}
}
public sealed class WithLazyDefault
{
[Fact]
public void ReturnsDefaultOnFailure()
{
var result = Result.Failure<int, string>("something went wrong");
result.ResultOrDefault(() => 100).Should().Be(100);
}
[Fact]
public void ReturnsResultOnSuccess()
{
var result = Result.Success<int, string>(200);
result.ResultOrDefault(() => 100).Should().Be(200);
}
}
}
public sealed class ResultOrThrow
{
[Fact]
public void TrowsOnFailure()
{
var result = Result.Failure<int, string>("something went wrong");
Action assertion = () => result.ResultOrThrow(_ => new ApplicationException());
assertion.Should().Throw<ApplicationException>();
}
[Fact]
public void ReturnsResultOnSuccess()
{
var result = Result.Success<int, string>(200);
result.ResultOrThrow(_ => new ApplicationException()).Should().Be(200);
}
}
public sealed class AsMaybe
{
[Fact]
public void ReturnsNothingOnFailure()
{
var result = Result.Failure<int, string>("something went wrong");
result.AsMaybe().Should().BeNothing();
}
[Fact]
public void ReturnsJustResultOnSuccess()
{
var result = Result.Success<int, string>(200);
result.AsMaybe().Should().BeJust(200);
}
}
public sealed class Select
{
[Fact]
public void MapsFailureToFailure()
{
var result = Result.Failure<int, string>("something went wrong");
result.Select(i => i * 2).Should().Be(Result.Failure<int, string>("something went wrong"));
}
[Fact]
public void MapsSuccessToSuccess()
{
var result = Result.Success<int, string>(100);
result.Select(i => i * 2).Should().Be(Result.Success<int, string>(200));
}
}
public sealed class SelectMany
{
[Fact]
public void MapsFailureToFailure()
{
var result = Result.Failure<int, string>("something went wrong");
result.SelectMany<int>(i => Result.Success(i * 2)).Should().Be(Result.Failure<int, string>("something went wrong"));
}
[Fact]
public void MapsSuccessToSuccess()
{
var result = Result.Success<int, string>(100);
result.SelectMany<int>(i => Result.Success(i * 2)).Should().Be(Result.Success<int, string>(200));
}
[Fact]
public void MapsSuccessToFailure()
{
var result = Result.Success<int, string>(100);
result.SelectMany<int>(i => Result.Failure("something went wrong"))
.Should().Be(Result.Failure<int, string>("something went wrong"));
}
}
public sealed class Match
{
public sealed class WithOneParameter
{
[Fact]
public void DoesNotCallOnSuccessWithFailure()
{
var result = Result.Failure<int, string>("something went wrong");
result.Match(onSuccess: _ => throw new XunitException("Wrong method called"));
}
[Fact]
public void CallsOnSuccessWithResultOnSuccess()
{
var result = Result.Success<int, string>(100);
var isCalled = false;
result.Match(
onSuccess: r =>
{
r.Should().Be(100);
isCalled = true;
});
isCalled.Should().BeTrue("onSuccess should have been called");
}
}
public sealed class WithTwoParameters
{
[Fact]
public void CallsOnFailureWithErrorOnFailure()
{
var result = Result.Failure<int, string>("something went wrong");
var isCalled = false;
result.Match(
onSuccess: r => throw new XunitException("Wrong method called"),
onFailure: error =>
{
error.Should().Be("something went wrong");
isCalled = true;
});
isCalled.Should().BeTrue("onFailure should have been called");
}
[Fact]
public void CallsOnSuccessWithResultOnSuccess()
{
var result = Result.Success<int, string>(100);
var isCalled = false;
result.Match(
onSuccess: r =>
{
r.Should().Be(100);
isCalled = true;
},
onFailure: _ => throw new XunitException("Wrong method called"));
isCalled.Should().BeTrue("onSuccess should have been called");
}
}
public sealed class Returning
{
[Fact]
public void CallsOnFailureWithErrorOnFailureAndReturnsItsValue()
{
var result = Result.Failure<int, string>("something went wrong");
const string expectedResult = "expected result";
var actualResult = result.Match(
onSuccess: _ => throw new XunitException("Wrong method called"),
onFailure: error =>
{
error.Should().Be("something went wrong");
return expectedResult;
});
actualResult.Should().Be(expectedResult, "onFailure should have been called");
}
[Fact]
public void CallsOnSuccessWithResultOnSuccessAndReturnsItsValue()
{
var result = Result.Success<int, string>(100);
const string expectedReturn = "expected result";
var actualReturn = result.Match(
onSuccess: r =>
{
r.Should().Be(100);
return expectedReturn;
},
onFailure: _ => throw new XunitException("Wrong method called"));
actualReturn.Should().Be(expectedReturn, "onSuccess should have been called");
}
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Monitoring.V3.Snippets
{
using Google.Api;
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using apis = Google.Cloud.Monitoring.V3;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>Generated snippets</summary>
public class GeneratedMetricServiceClientSnippets
{
/// <summary>Snippet for ListMonitoredResourceDescriptorsAsync</summary>
public async Task ListMonitoredResourceDescriptorsAsync()
{
// Snippet: ListMonitoredResourceDescriptorsAsync(ProjectName,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response =
metricServiceClient.ListMonitoredResourceDescriptorsAsync(name);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MonitoredResourceDescriptor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListMonitoredResourceDescriptorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MonitoredResourceDescriptor> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MonitoredResourceDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListMonitoredResourceDescriptors</summary>
public void ListMonitoredResourceDescriptors()
{
// Snippet: ListMonitoredResourceDescriptors(ProjectName,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
// Make the request
PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response =
metricServiceClient.ListMonitoredResourceDescriptors(name);
// Iterate over all response items, lazily performing RPCs as required
foreach (MonitoredResourceDescriptor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListMonitoredResourceDescriptorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MonitoredResourceDescriptor> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MonitoredResourceDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListMonitoredResourceDescriptorsAsync</summary>
public async Task ListMonitoredResourceDescriptorsAsync_RequestObject()
{
// Snippet: ListMonitoredResourceDescriptorsAsync(ListMonitoredResourceDescriptorsRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest
{
ProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response =
metricServiceClient.ListMonitoredResourceDescriptorsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MonitoredResourceDescriptor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListMonitoredResourceDescriptorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MonitoredResourceDescriptor> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MonitoredResourceDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListMonitoredResourceDescriptors</summary>
public void ListMonitoredResourceDescriptors_RequestObject()
{
// Snippet: ListMonitoredResourceDescriptors(ListMonitoredResourceDescriptorsRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest
{
ProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response =
metricServiceClient.ListMonitoredResourceDescriptors(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (MonitoredResourceDescriptor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListMonitoredResourceDescriptorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MonitoredResourceDescriptor item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MonitoredResourceDescriptor> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MonitoredResourceDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetMonitoredResourceDescriptorAsync</summary>
public async Task GetMonitoredResourceDescriptorAsync()
{
// Snippet: GetMonitoredResourceDescriptorAsync(MonitoredResourceDescriptorName,CallSettings)
// Additional: GetMonitoredResourceDescriptorAsync(MonitoredResourceDescriptorName,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]");
// Make the request
MonitoredResourceDescriptor response = await metricServiceClient.GetMonitoredResourceDescriptorAsync(name);
// End snippet
}
/// <summary>Snippet for GetMonitoredResourceDescriptor</summary>
public void GetMonitoredResourceDescriptor()
{
// Snippet: GetMonitoredResourceDescriptor(MonitoredResourceDescriptorName,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]");
// Make the request
MonitoredResourceDescriptor response = metricServiceClient.GetMonitoredResourceDescriptor(name);
// End snippet
}
/// <summary>Snippet for GetMonitoredResourceDescriptorAsync</summary>
public async Task GetMonitoredResourceDescriptorAsync_RequestObject()
{
// Snippet: GetMonitoredResourceDescriptorAsync(GetMonitoredResourceDescriptorRequest,CallSettings)
// Additional: GetMonitoredResourceDescriptorAsync(GetMonitoredResourceDescriptorRequest,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
// Make the request
MonitoredResourceDescriptor response = await metricServiceClient.GetMonitoredResourceDescriptorAsync(request);
// End snippet
}
/// <summary>Snippet for GetMonitoredResourceDescriptor</summary>
public void GetMonitoredResourceDescriptor_RequestObject()
{
// Snippet: GetMonitoredResourceDescriptor(GetMonitoredResourceDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest
{
MonitoredResourceDescriptorName = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"),
};
// Make the request
MonitoredResourceDescriptor response = metricServiceClient.GetMonitoredResourceDescriptor(request);
// End snippet
}
/// <summary>Snippet for ListMetricDescriptorsAsync</summary>
public async Task ListMetricDescriptorsAsync()
{
// Snippet: ListMetricDescriptorsAsync(ProjectName,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response =
metricServiceClient.ListMetricDescriptorsAsync(name);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MetricDescriptor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListMetricDescriptorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MetricDescriptor item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MetricDescriptor> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MetricDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListMetricDescriptors</summary>
public void ListMetricDescriptors()
{
// Snippet: ListMetricDescriptors(ProjectName,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
// Make the request
PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response =
metricServiceClient.ListMetricDescriptors(name);
// Iterate over all response items, lazily performing RPCs as required
foreach (MetricDescriptor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListMetricDescriptorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MetricDescriptor item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MetricDescriptor> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MetricDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListMetricDescriptorsAsync</summary>
public async Task ListMetricDescriptorsAsync_RequestObject()
{
// Snippet: ListMetricDescriptorsAsync(ListMetricDescriptorsRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ListMetricDescriptorsRequest request = new ListMetricDescriptorsRequest
{
ProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response =
metricServiceClient.ListMetricDescriptorsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((MetricDescriptor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListMetricDescriptorsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MetricDescriptor item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MetricDescriptor> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MetricDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListMetricDescriptors</summary>
public void ListMetricDescriptors_RequestObject()
{
// Snippet: ListMetricDescriptors(ListMetricDescriptorsRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ListMetricDescriptorsRequest request = new ListMetricDescriptorsRequest
{
ProjectName = new ProjectName("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response =
metricServiceClient.ListMetricDescriptors(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (MetricDescriptor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListMetricDescriptorsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (MetricDescriptor item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<MetricDescriptor> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (MetricDescriptor item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetMetricDescriptorAsync</summary>
public async Task GetMetricDescriptorAsync()
{
// Snippet: GetMetricDescriptorAsync(MetricDescriptorName,CallSettings)
// Additional: GetMetricDescriptorAsync(MetricDescriptorName,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
MetricDescriptor response = await metricServiceClient.GetMetricDescriptorAsync(name);
// End snippet
}
/// <summary>Snippet for GetMetricDescriptor</summary>
public void GetMetricDescriptor()
{
// Snippet: GetMetricDescriptor(MetricDescriptorName,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
MetricDescriptor response = metricServiceClient.GetMetricDescriptor(name);
// End snippet
}
/// <summary>Snippet for GetMetricDescriptorAsync</summary>
public async Task GetMetricDescriptorAsync_RequestObject()
{
// Snippet: GetMetricDescriptorAsync(GetMetricDescriptorRequest,CallSettings)
// Additional: GetMetricDescriptorAsync(GetMetricDescriptorRequest,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
// Make the request
MetricDescriptor response = await metricServiceClient.GetMetricDescriptorAsync(request);
// End snippet
}
/// <summary>Snippet for GetMetricDescriptor</summary>
public void GetMetricDescriptor_RequestObject()
{
// Snippet: GetMetricDescriptor(GetMetricDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
GetMetricDescriptorRequest request = new GetMetricDescriptorRequest
{
MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
// Make the request
MetricDescriptor response = metricServiceClient.GetMetricDescriptor(request);
// End snippet
}
/// <summary>Snippet for CreateMetricDescriptorAsync</summary>
public async Task CreateMetricDescriptorAsync()
{
// Snippet: CreateMetricDescriptorAsync(ProjectName,MetricDescriptor,CallSettings)
// Additional: CreateMetricDescriptorAsync(ProjectName,MetricDescriptor,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
MetricDescriptor metricDescriptor = new MetricDescriptor();
// Make the request
MetricDescriptor response = await metricServiceClient.CreateMetricDescriptorAsync(name, metricDescriptor);
// End snippet
}
/// <summary>Snippet for CreateMetricDescriptor</summary>
public void CreateMetricDescriptor()
{
// Snippet: CreateMetricDescriptor(ProjectName,MetricDescriptor,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
MetricDescriptor metricDescriptor = new MetricDescriptor();
// Make the request
MetricDescriptor response = metricServiceClient.CreateMetricDescriptor(name, metricDescriptor);
// End snippet
}
/// <summary>Snippet for CreateMetricDescriptorAsync</summary>
public async Task CreateMetricDescriptorAsync_RequestObject()
{
// Snippet: CreateMetricDescriptorAsync(CreateMetricDescriptorRequest,CallSettings)
// Additional: CreateMetricDescriptorAsync(CreateMetricDescriptorRequest,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
ProjectName = new ProjectName("[PROJECT]"),
MetricDescriptor = new MetricDescriptor(),
};
// Make the request
MetricDescriptor response = await metricServiceClient.CreateMetricDescriptorAsync(request);
// End snippet
}
/// <summary>Snippet for CreateMetricDescriptor</summary>
public void CreateMetricDescriptor_RequestObject()
{
// Snippet: CreateMetricDescriptor(CreateMetricDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
ProjectName = new ProjectName("[PROJECT]"),
MetricDescriptor = new MetricDescriptor(),
};
// Make the request
MetricDescriptor response = metricServiceClient.CreateMetricDescriptor(request);
// End snippet
}
/// <summary>Snippet for DeleteMetricDescriptorAsync</summary>
public async Task DeleteMetricDescriptorAsync()
{
// Snippet: DeleteMetricDescriptorAsync(MetricDescriptorName,CallSettings)
// Additional: DeleteMetricDescriptorAsync(MetricDescriptorName,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
await metricServiceClient.DeleteMetricDescriptorAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteMetricDescriptor</summary>
public void DeleteMetricDescriptor()
{
// Snippet: DeleteMetricDescriptor(MetricDescriptorName,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
// Make the request
metricServiceClient.DeleteMetricDescriptor(name);
// End snippet
}
/// <summary>Snippet for DeleteMetricDescriptorAsync</summary>
public async Task DeleteMetricDescriptorAsync_RequestObject()
{
// Snippet: DeleteMetricDescriptorAsync(DeleteMetricDescriptorRequest,CallSettings)
// Additional: DeleteMetricDescriptorAsync(DeleteMetricDescriptorRequest,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
// Make the request
await metricServiceClient.DeleteMetricDescriptorAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteMetricDescriptor</summary>
public void DeleteMetricDescriptor_RequestObject()
{
// Snippet: DeleteMetricDescriptor(DeleteMetricDescriptorRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest
{
MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"),
};
// Make the request
metricServiceClient.DeleteMetricDescriptor(request);
// End snippet
}
/// <summary>Snippet for ListTimeSeriesAsync</summary>
public async Task ListTimeSeriesAsync()
{
// Snippet: ListTimeSeriesAsync(ProjectName,string,TimeInterval,ListTimeSeriesRequest.Types.TimeSeriesView,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
string filter = "";
TimeInterval interval = new TimeInterval();
ListTimeSeriesRequest.Types.TimeSeriesView view = ListTimeSeriesRequest.Types.TimeSeriesView.Full;
// Make the request
PagedAsyncEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeriesAsync(name, filter, interval, view);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TimeSeries item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTimeSeriesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TimeSeries item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TimeSeries> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TimeSeries item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTimeSeries</summary>
public void ListTimeSeries()
{
// Snippet: ListTimeSeries(ProjectName,string,TimeInterval,ListTimeSeriesRequest.Types.TimeSeriesView,string,int?,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
string filter = "";
TimeInterval interval = new TimeInterval();
ListTimeSeriesRequest.Types.TimeSeriesView view = ListTimeSeriesRequest.Types.TimeSeriesView.Full;
// Make the request
PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeries(name, filter, interval, view);
// Iterate over all response items, lazily performing RPCs as required
foreach (TimeSeries item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTimeSeriesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TimeSeries item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TimeSeries> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TimeSeries item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTimeSeriesAsync</summary>
public async Task ListTimeSeriesAsync_RequestObject()
{
// Snippet: ListTimeSeriesAsync(ListTimeSeriesRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ListTimeSeriesRequest request = new ListTimeSeriesRequest
{
ProjectName = new ProjectName("[PROJECT]"),
Filter = "",
Interval = new TimeInterval(),
View = ListTimeSeriesRequest.Types.TimeSeriesView.Full,
};
// Make the request
PagedAsyncEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeriesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TimeSeries item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTimeSeriesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TimeSeries item in page)
{
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TimeSeries> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TimeSeries item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTimeSeries</summary>
public void ListTimeSeries_RequestObject()
{
// Snippet: ListTimeSeries(ListTimeSeriesRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ListTimeSeriesRequest request = new ListTimeSeriesRequest
{
ProjectName = new ProjectName("[PROJECT]"),
Filter = "",
Interval = new TimeInterval(),
View = ListTimeSeriesRequest.Types.TimeSeriesView.Full,
};
// Make the request
PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response =
metricServiceClient.ListTimeSeries(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (TimeSeries item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTimeSeriesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TimeSeries item in page)
{
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TimeSeries> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TimeSeries item in singlePage)
{
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CreateTimeSeriesAsync</summary>
public async Task CreateTimeSeriesAsync()
{
// Snippet: CreateTimeSeriesAsync(ProjectName,IEnumerable<TimeSeries>,CallSettings)
// Additional: CreateTimeSeriesAsync(ProjectName,IEnumerable<TimeSeries>,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
IEnumerable<TimeSeries> timeSeries = new List<TimeSeries>();
// Make the request
await metricServiceClient.CreateTimeSeriesAsync(name, timeSeries);
// End snippet
}
/// <summary>Snippet for CreateTimeSeries</summary>
public void CreateTimeSeries()
{
// Snippet: CreateTimeSeries(ProjectName,IEnumerable<TimeSeries>,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
ProjectName name = new ProjectName("[PROJECT]");
IEnumerable<TimeSeries> timeSeries = new List<TimeSeries>();
// Make the request
metricServiceClient.CreateTimeSeries(name, timeSeries);
// End snippet
}
/// <summary>Snippet for CreateTimeSeriesAsync</summary>
public async Task CreateTimeSeriesAsync_RequestObject()
{
// Snippet: CreateTimeSeriesAsync(CreateTimeSeriesRequest,CallSettings)
// Additional: CreateTimeSeriesAsync(CreateTimeSeriesRequest,CancellationToken)
// Create client
MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync();
// Initialize request argument(s)
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
ProjectName = new ProjectName("[PROJECT]"),
TimeSeries = { },
};
// Make the request
await metricServiceClient.CreateTimeSeriesAsync(request);
// End snippet
}
/// <summary>Snippet for CreateTimeSeries</summary>
public void CreateTimeSeries_RequestObject()
{
// Snippet: CreateTimeSeries(CreateTimeSeriesRequest,CallSettings)
// Create client
MetricServiceClient metricServiceClient = MetricServiceClient.Create();
// Initialize request argument(s)
CreateTimeSeriesRequest request = new CreateTimeSeriesRequest
{
ProjectName = new ProjectName("[PROJECT]"),
TimeSeries = { },
};
// Make the request
metricServiceClient.CreateTimeSeries(request);
// End snippet
}
}
}
| |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright (c) 2003-2012 by AG-Software *
* All Rights Reserved. *
* Contact information for AG-Software is available at http://www.ag-software.de *
* *
* Licence: *
* The agsXMPP SDK is released under a dual licence *
* agsXMPP can be used under either of two licences *
* *
* A commercial licence which is probably the most appropriate for commercial *
* corporate use and closed source projects. *
* *
* The GNU Public License (GPL) is probably most appropriate for inclusion in *
* other open source projects. *
* *
* See README.html for details. *
* *
* For general enquiries visit our website at: *
* http://www.ag-software.de *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
using System;
using System.Text;
using System.Collections;
using agsXMPP.Exceptions;
using agsXMPP.Collections;
#if STRINGPREP
using agsXMPP.Idn;
#endif
namespace agsXMPP
{
/// <summary>
/// Class for building and handling XMPP Id's (JID's)
/// </summary>
public class Jid : IComparable, IEquatable<Jid>
{
/*
14 possible invalid forms of JIDs and some variations on valid JIDs with invalid lengths, viz:
jidforms = [
"",
"@",
"@/resource",
"@domain",
"@domain/",
"@domain/resource",
"nodename@",
"/",
"nodename@domain/",
"nodename@/",
"@/",
"nodename/",
"/resource",
"nodename@/resource",
]
TODO
Each allowable portion of a JID (node identifier, domain identifier, and resource identifier) MUST NOT
be more than 1023 bytes in length, resulting in a maximum total size
(including the '@' and '/' separators) of 3071 bytes.
stringprep with libIDN
m_User ==> nodeprep
m_Server ==> nameprep
m_Resource ==> resourceprep
*/
// !!!
// use this internal variables only if you know what you are doing
// !!!
internal string m_Jid = null;
internal string m_User = null;
internal string m_Server = null;
internal string m_Resource = null;
/// <summary>
/// Create a new JID object from a string. The input string must be a valid jabberId and already prepared with stringprep.
/// Otherwise use one of the other constructors with escapes the node and prepares the gives balues with the stringprep
/// profiles
/// </summary>
/// <param name="jid">XMPP ID, in string form examples: user@server/Resource, user@server</param>
public Jid(string jid)
{
m_Jid = jid;
Parse(jid);
}
/// <summary>
/// builds a new Jid object
/// </summary>
/// <param name="user">XMPP User part</param>
/// <param name="server">XMPP Domain part</param>
/// <param name="resource">XMPP Resource part</param>
public Jid(string user, string server, string resource)
{
#if !STRINGPREP
if (user != null)
{
user = EscapeNode(user);
m_User = user.ToLower();
}
if (server != null)
m_Server = server.ToLower();
if (resource != null)
m_Resource = resource;
#else
if (user != null)
{
user = EscapeNode(user);
m_User = Stringprep.NodePrep(user);
}
if (server != null)
m_Server = Stringprep.NamePrep(server);
if (resource != null)
m_Resource = Stringprep.ResourcePrep(resource);
#endif
BuildJid();
}
/// <summary>
/// Parses a JabberId from a string. If we parse a jid we assume it's correct and already prepared via stringprep.
/// </summary>
/// <param name="fullJid">jis to parse as string</param>
/// <returns>true if the jid could be parsed, false if an error occured</returns>
public bool Parse(string fullJid)
{
string user = null;
string server = null;
string resource = null;
try
{
if (fullJid == null || fullJid.Length == 0)
{
return false;
}
m_Jid = fullJid;
int atPos = m_Jid.IndexOf('@');
int slashPos = m_Jid.IndexOf('/');
// some more validations
// @... or /...
if (atPos == 0 || slashPos == 0)
return false;
// nodename@
if (atPos + 1 == fullJid.Length)
return false;
// @/ at followed by resource separator
if (atPos + 1 == slashPos)
return false;
if (atPos == -1)
{
user = null;
if (slashPos == -1)
{
// JID Contains only the Server
server = m_Jid;
}
else
{
// JID Contains only the Server and Resource
server = m_Jid.Substring(0, slashPos);
resource = m_Jid.Substring(slashPos + 1);
}
}
else
{
if (slashPos == -1)
{
// We have no resource
// Devide User and Server (user@server)
server = m_Jid.Substring(atPos + 1);
user = m_Jid.Substring(0, atPos);
}
else
{
// We have all
user = m_Jid.Substring(0, atPos);
server = m_Jid.Substring(atPos + 1, slashPos - atPos - 1);
resource = m_Jid.Substring(slashPos + 1);
}
}
if (user != null)
this.m_User = user;
if (server != null)
this.m_Server = server;
if (resource != null)
this.m_Resource = resource;
return true;
}
catch (Exception)
{
return false;
}
}
internal void BuildJid()
{
m_Jid = BuildJid(m_User, m_Server, m_Resource);
}
private string BuildJid(string user, string server, string resource)
{
StringBuilder sb = new StringBuilder();
if (user != null)
{
sb.Append(user);
sb.Append("@");
}
sb.Append(server);
if (resource != null)
{
sb.Append("/");
sb.Append(resource);
}
return sb.ToString();
}
public override string ToString()
{
return m_Jid;
}
/// <summary>
/// the user part of the JabberId.
/// </summary>
public string User
{
get
{
return m_User;
}
set
{
// first Encode the user/node
string tmpUser = EscapeNode(value);
#if !STRINGPREP
if (value != null)
m_User = tmpUser.ToLower();
else
m_User = null;
#else
if (value != null)
m_User = Stringprep.NodePrep(tmpUser);
else
m_User = null;
#endif
BuildJid();
}
}
/// <summary>
/// Only Server
/// </summary>
public string Server
{
get
{
return m_Server;
}
set
{
#if !STRINGPREP
if (value != null)
m_Server = value.ToLower();
else
m_Server = null;
#else
if (value != null)
m_Server = Stringprep.NamePrep(value);
else
m_Server = null;
#endif
BuildJid();
}
}
/// <summary>
/// Only the Resource field.
/// null for none
/// </summary>
public string Resource
{
get
{
return m_Resource;
}
set
{
#if !STRINGPREP
if (value != null)
m_Resource = value;
else
m_Resource = null;
#else
if (value != null)
m_Resource = Stringprep.ResourcePrep(value);
else
m_Resource = null;
#endif
BuildJid();
}
}
/// <summary>
/// The Bare Jid only (user@server).
/// </summary>
public string Bare
{
get
{
return BuildJid(m_User, m_Server, null);
}
}
#region << Overrides >>
/// <summary>
/// This compares the full Jid by default
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return Equals(obj, new FullJidComparer());
}
public override int GetHashCode()
{
int hcode = 0;
if (m_User !=null)
hcode ^= m_User.GetHashCode();
if (m_Server != null)
hcode ^= m_Server.GetHashCode();
if (m_Resource != null)
hcode ^= m_Resource.GetHashCode();
return hcode;
}
#endregion
public bool Equals(object other, System.Collections.IComparer comparer)
{
if (comparer.Compare(other, this) == 0)
return true;
else
return false;
}
/*
public static bool operator !=(Jid jid1, Jid jid2)
{
return !jid1.Equals(jid2, new FullJidComparer());
}
public static bool operator ==(Jid jid1, Jid jid2)
{
return jid1.Equals(jid2, new FullJidComparer());
}
*/
#region << implicit operators >>
static public implicit operator Jid(string value)
{
if (value == null) {
return null;
}
return new Jid(value);
}
static public implicit operator string(Jid jid)
{
if (jid == null) {
return null;
}
return jid.ToString();
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
if (obj is Jid)
{
Jid jid = obj as Jid;
FullJidComparer comparer = new FullJidComparer();
return comparer.Compare(obj, this);
}
throw new ArgumentException("object is not a Jid");
}
#endregion
#region IEquatable<Jid> Members
public bool Equals(Jid other)
{
FullJidComparer comparer = new FullJidComparer();
if (comparer.Compare(other, this) == 0)
return true;
else
return false;
}
#endregion
#region << XEP-0106: JID Escaping >>
/// <summary>
/// <para>
/// Escape a node according to XEP-0106
/// </para>
/// <para>
/// <a href="http://www.xmpp.org/extensions/xep-0106.html">http://www.xmpp.org/extensions/xep-0106.html</a>
/// </para>
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public static string EscapeNode(string node)
{
if (node == null)
return null;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < node.Length; i++)
{
/*
<space> \20
" \22
& \26
' \27
/ \2f
: \3a
< \3c
> \3e
@ \40
\ \5c
*/
char c = node[i];
switch (c)
{
case ' ': sb.Append(@"\20"); break;
case '"': sb.Append(@"\22"); break;
case '&': sb.Append(@"\26"); break;
case '\'': sb.Append(@"\27"); break;
case '/': sb.Append(@"\2f"); break;
case ':': sb.Append(@"\3a"); break;
case '<': sb.Append(@"\3c"); break;
case '>': sb.Append(@"\3e"); break;
case '@': sb.Append(@"\40"); break;
case '\\': sb.Append(@"\5c"); break;
default: sb.Append(c); break;
}
}
return sb.ToString();
}
/// <summary>
/// <para>
/// unescape a node according to XEP-0106
/// </para>
/// <para>
/// <a href="http://www.xmpp.org/extensions/xep-0106.html">http://www.xmpp.org/extensions/xep-0106.html</a>
/// </para>
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public static string UnescapeNode(string node)
{
if (node == null)
return null;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < node.Length; i++)
{
char c1 = node[i];
if (c1 == '\\' && i + 2 < node.Length)
{
i += 1;
char c2 = node[i];
i += 1;
char c3 = node[i];
if (c2 == '2')
{
switch (c3)
{
case '0':
sb.Append(' ');
break;
case '2':
sb.Append('"');
break;
case '6':
sb.Append('&');
break;
case '7':
sb.Append('\'');
break;
case 'f':
sb.Append('/');
break;
}
}
else if (c2 == '3')
{
switch (c3)
{
case 'a':
sb.Append(':');
break;
case 'c':
sb.Append('<');
break;
case 'e':
sb.Append('>');
break;
}
}
else if (c2 == '4')
{
if (c3 == '0')
sb.Append("@");
}
else if (c2 == '5')
{
if (c3 == 'c')
sb.Append("\\");
}
}
else
sb.Append(c1);
}
return sb.ToString();
}
#endregion
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.IO;
using System.Text;
#if ODATALIB_ASYNC
using System.Threading.Tasks;
#endif
using Microsoft.Data.Edm;
using Microsoft.Data.OData.Metadata;
#endregion Namespaces
/// <summary>
/// Base class for OData parameter writers that verifies a proper sequence of write calls on the writer.
/// </summary>
internal abstract class ODataParameterWriterCore : ODataParameterWriter, IODataReaderWriterListener, IODataOutputInStreamErrorListener
{
/// <summary>The output context to write to.</summary>
private readonly ODataOutputContext outputContext;
/// <summary>The function import whose parameters will be written.</summary>
private readonly IEdmFunctionImport functionImport;
/// <summary>Stack of writer scopes to keep track of the current context of the writer.</summary>
private Stack<ParameterWriterState> scopes = new Stack<ParameterWriterState>();
/// <summary>Parameter names that have already been written, used to detect duplicate writes on a parameter.</summary>
private HashSet<string> parameterNamesWritten = new HashSet<string>(EqualityComparer<string>.Default);
/// <summary>Checker to detect duplicate property names on complex parameter values.</summary>
private DuplicatePropertyNamesChecker duplicatePropertyNamesChecker;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="outputContext">The output context to write to.</param>
/// <param name="functionImport">The function import whose parameters will be written.</param>
protected ODataParameterWriterCore(ODataOutputContext outputContext, IEdmFunctionImport functionImport)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(outputContext != null, "outputContext != null");
Debug.Assert(
outputContext.MessageWriterSettings.Version.HasValue && outputContext.MessageWriterSettings.Version.Value >= ODataVersion.V3,
"Parameter writer only writes to V3 or above.");
this.outputContext = outputContext;
this.functionImport = functionImport;
this.scopes.Push(ParameterWriterState.Start);
}
/// <summary>
/// An enumeration representing the current state of the writer.
/// </summary>
private enum ParameterWriterState
{
/// <summary>The writer is at the start; nothing has been written yet.</summary>
Start,
/// <summary>
/// The writer is in a state where the next parameter can be written.
/// The writer enters this state after WriteStart() or after the previous parameter is written.
/// </summary>
CanWriteParameter,
/// <summary>One of the create writer method has been called and the created sub writer is not in Completed state.</summary>
ActiveSubWriter,
/// <summary>The writer has completed; nothing can be written anymore.</summary>
Completed,
/// <summary>An error had occured while writing the payload; nothing can be written anymore.</summary>
Error
}
/// <summary>Checker to detect duplicate property names on complex parameter values.</summary>
protected DuplicatePropertyNamesChecker DuplicatePropertyNamesChecker
{
get
{
return this.duplicatePropertyNamesChecker ?? (this.duplicatePropertyNamesChecker = new DuplicatePropertyNamesChecker(false /*allowDuplicateProperties*/, false /*isResponse*/));
}
}
/// <summary>
/// The current state of the writer.
/// </summary>
private ParameterWriterState State
{
get { return this.scopes.Peek(); }
}
/// <summary>
/// Flushes the write buffer to the underlying stream.
/// </summary>
public sealed override void Flush()
{
this.VerifyCanFlush(true /*synchronousCall*/);
// make sure we switch to writer state Error if an exception is thrown during flushing.
this.InterceptException(this.FlushSynchronously);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously flushes the write buffer to the underlying stream.
/// </summary>
/// <returns>A task instance that represents the asynchronous operation.</returns>
public sealed override Task FlushAsync()
{
this.VerifyCanFlush(false /*synchronousCall*/);
// make sure we switch to writer state Error if an exception is thrown during flushing.
return this.FlushAsynchronously().FollowOnFaultWith(t => this.EnterErrorScope());
}
#endif
/// <summary>
/// Start writing a parameter payload.
/// </summary>
public sealed override void WriteStart()
{
this.VerifyCanWriteStart(true /*synchronousCall*/);
this.InterceptException(() => this.WriteStartImplementation());
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously start writing a parameter payload.
/// </summary>
/// <returns>A task instance that represents the asynchronous write operation.</returns>
public sealed override Task WriteStartAsync()
{
this.VerifyCanWriteStart(false /*synchronousCall*/);
return TaskUtils.GetTaskForSynchronousOperation(() => this.InterceptException(() => this.WriteStartImplementation()));
}
#endif
/// <summary>
/// Start writing a value parameter.
/// </summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <param name="parameterValue">The value of the parameter to write.</param>
public sealed override void WriteValue(string parameterName, object parameterValue)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference expectedTypeReference = this.VerifyCanWriteValueParameter(true /*synchronousCall*/, parameterName, parameterValue);
this.InterceptException(() => this.WriteValueImplementation(parameterName, parameterValue, expectedTypeReference));
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously start writing a value parameter.
/// </summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <param name="parameterValue">The value of the parameter to write.</param>
/// <returns>A task instance that represents the asynchronous write operation.</returns>
public sealed override Task WriteValueAsync(string parameterName, object parameterValue)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference expectedTypeReference = this.VerifyCanWriteValueParameter(false /*synchronousCall*/, parameterName, parameterValue);
return TaskUtils.GetTaskForSynchronousOperation(() => this.InterceptException(() => this.WriteValueImplementation(parameterName, parameterValue, expectedTypeReference)));
}
#endif
/// <summary>
/// Creates an <see cref="ODataCollectionWriter"/> to write the value of a collection parameter.
/// </summary>
/// <param name="parameterName">The name of the collection parameter to write.</param>
/// <returns>The newly created <see cref="ODataCollectionWriter"/>.</returns>
public sealed override ODataCollectionWriter CreateCollectionWriter(string parameterName)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference itemTypeReference = this.VerifyCanCreateCollectionWriter(true /*synchronousCall*/, parameterName);
return this.InterceptException(() => this.CreateCollectionWriterImplementation(parameterName, itemTypeReference));
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously creates an <see cref="ODataCollectionWriter"/> to write the value of a collection parameter.
/// </summary>
/// <param name="parameterName">The name of the collection parameter to write.</param>
/// <returns>A running task for the created writer.</returns>
public sealed override Task<ODataCollectionWriter> CreateCollectionWriterAsync(string parameterName)
{
ExceptionUtils.CheckArgumentStringNotNullOrEmpty(parameterName, "parameterName");
IEdmTypeReference itemTypeReference = this.VerifyCanCreateCollectionWriter(false /*synchronousCall*/, parameterName);
return TaskUtils.GetTaskForSynchronousOperation(
() => this.InterceptException(() => this.CreateCollectionWriterImplementation(parameterName, itemTypeReference)));
}
#endif
/// <summary>
/// Finish writing a parameter payload.
/// </summary>
public sealed override void WriteEnd()
{
this.VerifyCanWriteEnd(true /*synchronousCall*/);
this.InterceptException(() => this.WriteEndImplementation());
if (this.State == ParameterWriterState.Completed)
{
// Note that we intentionally go through the public API so that if the Flush fails the writer moves to the Error state.
this.Flush();
}
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously finish writing a parameter payload.
/// </summary>
/// <returns>A task instance that represents the asynchronous write operation.</returns>
public sealed override Task WriteEndAsync()
{
this.VerifyCanWriteEnd(false /*synchronousCall*/);
return TaskUtils.GetTaskForSynchronousOperation(() => this.InterceptException(() => this.WriteEndImplementation()))
.FollowOnSuccessWithTask(
task =>
{
if (this.State == ParameterWriterState.Completed)
{
// Note that we intentionally go through the public API so that if the Flush fails the writer moves to the Error state.
return this.FlushAsync();
}
else
{
return TaskUtils.CompletedTask;
}
});
}
#endif
/// <summary>
/// This method notifies the implementer of this interface that the created reader is in Exception state.
/// </summary>
void IODataReaderWriterListener.OnException()
{
Debug.Assert(this.State == ParameterWriterState.ActiveSubWriter, "this.State == ParameterWriterState.ActiveSubWriter");
this.ReplaceScope(ParameterWriterState.Error);
}
/// <summary>
/// This method notifies the implementer of this interface that the created reader is in Completed state.
/// </summary>
void IODataReaderWriterListener.OnCompleted()
{
Debug.Assert(this.State == ParameterWriterState.ActiveSubWriter, "this.State == ParameterWriterState.ActiveSubWriter");
this.ReplaceScope(ParameterWriterState.CanWriteParameter);
}
/// <summary>
/// This method notifies the listener, that an in-stream error is to be written.
/// </summary>
/// <remarks>
/// This listener can choose to fail, if the currently written payload doesn't support in-stream error at this position.
/// If the listener returns, the writer should not allow any more writing, since the in-stream error is the last thing in the payload.
/// </remarks>
void IODataOutputInStreamErrorListener.OnInStreamError()
{
// The parameter payload is writen by the client and read by the server, we do not support
// writing an in-stream error payload in this scenario.
throw new ODataException(Strings.ODataParameterWriter_InStreamErrorNotSupported);
}
/// <summary>
/// Check if the object has been disposed; called from all public API methods. Throws an ObjectDisposedException if the object
/// has already been disposed.
/// </summary>
protected abstract void VerifyNotDisposed();
/// <summary>
/// Flush the output.
/// </summary>
protected abstract void FlushSynchronously();
#if ODATALIB_ASYNC
/// <summary>
/// Flush the output.
/// </summary>
/// <returns>Task representing the pending flush operation.</returns>
protected abstract Task FlushAsynchronously();
#endif
/// <summary>
/// Start writing an OData payload.
/// </summary>
protected abstract void StartPayload();
/// <summary>
/// Writes a value parameter (either primitive or complex).
/// </summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <param name="parameterValue">The value of the parameter to write.</param>
/// <param name="expectedTypeReference">The expected type reference of the parameter value.</param>
protected abstract void WriteValueParameter(string parameterName, object parameterValue, IEdmTypeReference expectedTypeReference);
/// <summary>
/// Creates a format specific <see cref="ODataCollectionWriter"/> to write the value of a collection parameter.
/// </summary>
/// <param name="parameterName">The name of the collection parameter to write.</param>
/// <param name="expectedItemType">The type reference of the expected item type or null if no expected item type exists.</param>
/// <returns>The newly created <see cref="ODataCollectionWriter"/>.</returns>
protected abstract ODataCollectionWriter CreateFormatCollectionWriter(string parameterName, IEdmTypeReference expectedItemType);
/// <summary>
/// Finish writing an OData payload.
/// </summary>
protected abstract void EndPayload();
/// <summary>
/// Verifies that calling WriteStart is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCanWriteStart(bool synchronousCall)
{
this.VerifyNotDisposed();
this.VerifyCallAllowed(synchronousCall);
if (this.State != ParameterWriterState.Start)
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteStart);
}
}
/// <summary>
/// Start writing a parameter payload - implementation of the actual functionality.
/// </summary>
private void WriteStartImplementation()
{
Debug.Assert(this.State == ParameterWriterState.Start, "this.State == ParameterWriterState.Start");
this.InterceptException(this.StartPayload);
this.EnterScope(ParameterWriterState.CanWriteParameter);
}
/// <summary>
/// Verifies that the parameter with name <paramref name="parameterName"/> can be written and returns the
/// type reference of the parameter.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
/// <param name="parameterName">The name of the parameter to be written.</param>
/// <returns>The type reference of the parameter; null if no function import was specified to the writer.</returns>
private IEdmTypeReference VerifyCanWriteParameterAndGetTypeReference(bool synchronousCall, string parameterName)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
this.VerifyNotDisposed();
this.VerifyCallAllowed(synchronousCall);
this.VerifyNotInErrorOrCompletedState();
if (this.State != ParameterWriterState.CanWriteParameter)
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteParameter);
}
if (this.parameterNamesWritten.Contains(parameterName))
{
throw new ODataException(Strings.ODataParameterWriterCore_DuplicatedParameterNameNotAllowed(parameterName));
}
this.parameterNamesWritten.Add(parameterName);
return this.GetParameterTypeReference(parameterName);
}
/// <summary>
/// Verify that calling WriteValue is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
/// <param name="parameterName">The name of the parameter to be written.</param>
/// <param name="parameterValue">The value of the parameter to write.</param>
/// <returns>The type reference of the parameter; null if no function import was specified to the writer.</returns>
private IEdmTypeReference VerifyCanWriteValueParameter(bool synchronousCall, string parameterName, object parameterValue)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
IEdmTypeReference parameterTypeReference = this.VerifyCanWriteParameterAndGetTypeReference(synchronousCall, parameterName);
if (parameterTypeReference != null && !parameterTypeReference.IsODataPrimitiveTypeKind() && !parameterTypeReference.IsODataComplexTypeKind())
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteValueOnNonValueTypeKind(parameterName, parameterTypeReference.TypeKind()));
}
if (parameterValue != null && (!EdmLibraryExtensions.IsPrimitiveType(parameterValue.GetType()) || parameterValue is Stream) && !(parameterValue is ODataComplexValue))
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteValueOnNonSupportedValueType(parameterName, parameterValue.GetType()));
}
return parameterTypeReference;
}
/// <summary>
/// Verify that calling CreateCollectionWriter is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
/// <param name="parameterName">The name of the parameter to be written.</param>
/// <returns>The expected item type of the items in the collection or null if no item type is available.</returns>
private IEdmTypeReference VerifyCanCreateCollectionWriter(bool synchronousCall, string parameterName)
{
Debug.Assert(!string.IsNullOrEmpty(parameterName), "!string.IsNullOrEmpty(parameterName)");
IEdmTypeReference parameterTypeReference = this.VerifyCanWriteParameterAndGetTypeReference(synchronousCall, parameterName);
if (parameterTypeReference != null && !parameterTypeReference.IsNonEntityODataCollectionTypeKind())
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotCreateCollectionWriterOnNonCollectionTypeKind(parameterName, parameterTypeReference.TypeKind()));
}
return parameterTypeReference == null ? null : parameterTypeReference.GetCollectionItemType();
}
/// <summary>
/// Gets the type reference of the parameter in question. Returns null if no function import was specified to the writer.
/// </summary>
/// <param name="parameterName">The name of the parameter in question.</param>
/// <returns>The type reference of the parameter; null if no function import was specified to the writer.</returns>
private IEdmTypeReference GetParameterTypeReference(string parameterName)
{
if (this.functionImport != null)
{
IEdmFunctionParameter parameter = this.functionImport.FindParameter(parameterName);
if (parameter == null)
{
throw new ODataException(Strings.ODataParameterWriterCore_ParameterNameNotFoundInFunctionImport(parameterName, this.functionImport.Name));
}
return parameter.Type;
}
return null;
}
/// <summary>
/// Write a value parameter - implementation of the actual functionality.
/// </summary>
/// <param name="parameterName">The name of the parameter to write.</param>
/// <param name="parameterValue">The value of the parameter to write.</param>
/// <param name="expectedTypeReference">The expected type reference of the parameter value.</param>
private void WriteValueImplementation(string parameterName, object parameterValue, IEdmTypeReference expectedTypeReference)
{
Debug.Assert(this.State == ParameterWriterState.CanWriteParameter, "this.State == ParameterWriterState.CanWriteParameter");
this.InterceptException(() => this.WriteValueParameter(parameterName, parameterValue, expectedTypeReference));
}
/// <summary>
/// Creates an <see cref="ODataCollectionWriter"/> to write the value of a collection parameter.
/// </summary>
/// <param name="parameterName">The name of the collection parameter to write.</param>
/// <param name="expectedItemType">The type reference of the expected item type or null if no expected item type exists.</param>
/// <returns>The newly created <see cref="ODataCollectionWriter"/>.</returns>
private ODataCollectionWriter CreateCollectionWriterImplementation(string parameterName, IEdmTypeReference expectedItemType)
{
Debug.Assert(this.State == ParameterWriterState.CanWriteParameter, "this.State == ParameterWriterState.CanWriteParameter");
ODataCollectionWriter collectionWriter = this.CreateFormatCollectionWriter(parameterName, expectedItemType);
this.ReplaceScope(ParameterWriterState.ActiveSubWriter);
return collectionWriter;
}
/// <summary>
/// Verifies that calling WriteEnd is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCanWriteEnd(bool synchronousCall)
{
this.VerifyNotDisposed();
this.VerifyCallAllowed(synchronousCall);
this.VerifyNotInErrorOrCompletedState();
if (this.State != ParameterWriterState.CanWriteParameter)
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteEnd);
}
this.VerifyAllParametersWritten();
}
/// <summary>
/// If an <see cref="IEdmFunctionImport"/> is specified, then this method ensures that all parameters present in the
/// function import are written to the payload.
/// </summary>
/// <remarks>The binding parameter is optional in the payload. Hence this method will not check for missing binding parameter.</remarks>
private void VerifyAllParametersWritten()
{
Debug.Assert(this.State == ParameterWriterState.CanWriteParameter, "this.State == ParameterWriterState.CanWriteParameter");
if (this.functionImport != null && this.functionImport.Parameters != null)
{
IEnumerable<IEdmFunctionParameter> parameters = null;
if (this.functionImport.IsBindable)
{
// The binding parameter may or may not be present in the payload. Hence we don't throw error if the binding parameter is missing.
parameters = this.functionImport.Parameters.Skip(1);
}
else
{
parameters = this.functionImport.Parameters;
}
IEnumerable<string> missingParameters = parameters.Where(p => !this.parameterNamesWritten.Contains(p.Name) && !p.Type.IsNullable).Select(p => p.Name);
if (missingParameters.Any())
{
missingParameters = missingParameters.Select(name => String.Format(CultureInfo.InvariantCulture, "'{0}'", name));
// We're calling the ToArray here since not all platforms support the string.Join which takes IEnumerable.
throw new ODataException(Strings.ODataParameterWriterCore_MissingParameterInParameterPayload(string.Join(", ", missingParameters.ToArray()), this.functionImport.Name));
}
}
}
/// <summary>
/// Finish writing a parameter payload - implementation of the actual functionality.
/// </summary>
private void WriteEndImplementation()
{
this.InterceptException(() => this.EndPayload());
this.LeaveScope();
}
/// <summary>
/// Verifies that the current state is not Error or Completed.
/// </summary>
private void VerifyNotInErrorOrCompletedState()
{
if (this.State == ParameterWriterState.Error || this.State == ParameterWriterState.Completed)
{
throw new ODataException(Strings.ODataParameterWriterCore_CannotWriteInErrorOrCompletedState);
}
}
/// <summary>
/// Verifies that calling Flush is valid.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCanFlush(bool synchronousCall)
{
this.VerifyNotDisposed();
this.VerifyCallAllowed(synchronousCall);
}
/// <summary>
/// Verifies that a call is allowed to the writer.
/// </summary>
/// <param name="synchronousCall">true if the call is to be synchronous; false otherwise.</param>
private void VerifyCallAllowed(bool synchronousCall)
{
if (synchronousCall)
{
if (!this.outputContext.Synchronous)
{
throw new ODataException(Strings.ODataParameterWriterCore_SyncCallOnAsyncWriter);
}
}
else
{
#if ODATALIB_ASYNC
if (this.outputContext.Synchronous)
{
throw new ODataException(Strings.ODataParameterWriterCore_AsyncCallOnSyncWriter);
}
#else
Debug.Assert(false, "Async calls are not allowed in this build.");
#endif
}
}
/// <summary>
/// Catch any exception thrown by the action passed in; in the exception case move the writer into
/// state ExceptionThrown and then rethrow the exception.
/// </summary>
/// <param name="action">The action to execute.</param>
private void InterceptException(Action action)
{
try
{
action();
}
catch
{
this.EnterErrorScope();
throw;
}
}
/// <summary>
/// Catch any exception thrown by the function passed in; in the exception case move the writer into
/// state ExceptionThrown and then rethrow the exception.
/// </summary>
/// <typeparam name="T">The return type of <paramref name="function"/>.</typeparam>
/// <param name="function">The function to execute.</param>
/// <returns>Returns the return value from executing <paramref name="function"/>.</returns>
private T InterceptException<T>(Func<T> function)
{
try
{
return function();
}
catch
{
this.EnterErrorScope();
throw;
}
}
/// <summary>
/// Enters the Error scope if we are not already in Error state.
/// </summary>
private void EnterErrorScope()
{
if (this.State != ParameterWriterState.Error)
{
this.EnterScope(ParameterWriterState.Error);
}
}
/// <summary>
/// Verifies that the transition from the current state into new state is valid and enter a new writer scope.
/// </summary>
/// <param name="newState">The writer state to transition into.</param>
private void EnterScope(ParameterWriterState newState)
{
this.ValidateTransition(newState);
this.scopes.Push(newState);
}
/// <summary>
/// Leave the current writer scope and return to the previous scope.
/// When reaching the top-level replace the 'Start' scope with a 'Completed' scope.
/// </summary>
/// <remarks>Note that this method is never called once the writer is in 'Error' state.</remarks>
private void LeaveScope()
{
Debug.Assert(this.State != ParameterWriterState.Error, "this.State != WriterState.Error");
this.ValidateTransition(ParameterWriterState.Completed);
// scopes is either [Start, CanWriteParameter] or [Start]
if (this.State == ParameterWriterState.CanWriteParameter)
{
this.scopes.Pop();
}
Debug.Assert(this.State == ParameterWriterState.Start, "this.State == ParameterWriterState.Start");
this.ReplaceScope(ParameterWriterState.Completed);
}
/// <summary>
/// Replaces the current scope with a new scope; checks that the transition is valid.
/// </summary>
/// <param name="newState">The new state to transition into.</param>
private void ReplaceScope(ParameterWriterState newState)
{
this.ValidateTransition(newState);
this.scopes.Pop();
this.scopes.Push(newState);
}
/// <summary>
/// Verify that the transition from the current state into new state is valid.
/// </summary>
/// <param name="newState">The new writer state to transition into.</param>
private void ValidateTransition(ParameterWriterState newState)
{
if (this.State != ParameterWriterState.Error && newState == ParameterWriterState.Error)
{
// we can always transition into an error state if we are not already in an error state
return;
}
switch (this.State)
{
case ParameterWriterState.Start:
if (newState != ParameterWriterState.CanWriteParameter && newState != ParameterWriterState.Completed)
{
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_InvalidTransitionFromStart));
}
break;
case ParameterWriterState.CanWriteParameter:
if (newState != ParameterWriterState.CanWriteParameter && newState != ParameterWriterState.ActiveSubWriter && newState != ParameterWriterState.Completed)
{
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_InvalidTransitionFromCanWriteParameter));
}
break;
case ParameterWriterState.ActiveSubWriter:
if (newState != ParameterWriterState.CanWriteParameter)
{
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_InvalidTransitionFromActiveSubWriter));
}
break;
case ParameterWriterState.Completed:
// we should never see a state transition when in state 'Completed'
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_InvalidTransitionFromCompleted));
case ParameterWriterState.Error:
if (newState != ParameterWriterState.Error)
{
// No more state transitions once we are in error state
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_InvalidTransitionFromError));
}
break;
default:
throw new ODataException(Strings.General_InternalError(InternalErrorCodes.ODataParameterWriterCore_ValidateTransition_UnreachableCodePath));
}
}
}
}
| |
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 JYaas.API.Areas.HelpPage.ModelDescriptions;
using JYaas.API.Areas.HelpPage.Models;
namespace JYaas.API.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SinchBackend.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using VkApi.Wrapper.Objects;
using VkApi.Wrapper.Responses;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace VkApi.Wrapper.Methods
{
public class Board
{
private readonly Vkontakte _vkontakte;
internal Board(Vkontakte vkontakte) => _vkontakte = vkontakte;
///<summary>
/// Creates a new topic on a community's discussion board.
///</summary>
public Task<int> AddTopic(int? groupId = null, String title = null, String text = null, Boolean? fromGroup = null, String[] attachments = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (title != null)
parameters.Add("title", title.ToApiString());
if (text != null)
parameters.Add("text", text.ToApiString());
if (fromGroup != null)
parameters.Add("from_group", fromGroup.ToApiString());
if (attachments != null)
parameters.Add("attachments", attachments.ToApiString());
return _vkontakte.RequestAsync<int>("board.addTopic", parameters);
}
///<summary>
/// Closes a topic on a community's discussion board so that comments cannot be posted.
///</summary>
public Task<BaseOkResponse> CloseTopic(int? groupId = null, int? topicId = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicId != null)
parameters.Add("topic_id", topicId.ToApiString());
return _vkontakte.RequestAsync<BaseOkResponse>("board.closeTopic", parameters);
}
///<summary>
/// Adds a comment on a topic on a community's discussion board.
///</summary>
public Task<int> CreateComment(int? groupId = null, int? topicId = null, String message = null, String[] attachments = null, Boolean? fromGroup = null, int? stickerId = null, String guid = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicId != null)
parameters.Add("topic_id", topicId.ToApiString());
if (message != null)
parameters.Add("message", message.ToApiString());
if (attachments != null)
parameters.Add("attachments", attachments.ToApiString());
if (fromGroup != null)
parameters.Add("from_group", fromGroup.ToApiString());
if (stickerId != null)
parameters.Add("sticker_id", stickerId.ToApiString());
if (guid != null)
parameters.Add("guid", guid.ToApiString());
return _vkontakte.RequestAsync<int>("board.createComment", parameters);
}
///<summary>
/// Deletes a comment on a topic on a community's discussion board.
///</summary>
public Task<BaseOkResponse> DeleteComment(int? groupId = null, int? topicId = null, int? commentId = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicId != null)
parameters.Add("topic_id", topicId.ToApiString());
if (commentId != null)
parameters.Add("comment_id", commentId.ToApiString());
return _vkontakte.RequestAsync<BaseOkResponse>("board.deleteComment", parameters);
}
///<summary>
/// Deletes a topic from a community's discussion board.
///</summary>
public Task<BaseOkResponse> DeleteTopic(int? groupId = null, int? topicId = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicId != null)
parameters.Add("topic_id", topicId.ToApiString());
return _vkontakte.RequestAsync<BaseOkResponse>("board.deleteTopic", parameters);
}
///<summary>
/// Edits a comment on a topic on a community's discussion board.
///</summary>
public Task<BaseOkResponse> EditComment(int? groupId = null, int? topicId = null, int? commentId = null, String message = null, String[] attachments = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicId != null)
parameters.Add("topic_id", topicId.ToApiString());
if (commentId != null)
parameters.Add("comment_id", commentId.ToApiString());
if (message != null)
parameters.Add("message", message.ToApiString());
if (attachments != null)
parameters.Add("attachments", attachments.ToApiString());
return _vkontakte.RequestAsync<BaseOkResponse>("board.editComment", parameters);
}
///<summary>
/// Edits the title of a topic on a community's discussion board.
///</summary>
public Task<BaseOkResponse> EditTopic(int? groupId = null, int? topicId = null, String title = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicId != null)
parameters.Add("topic_id", topicId.ToApiString());
if (title != null)
parameters.Add("title", title.ToApiString());
return _vkontakte.RequestAsync<BaseOkResponse>("board.editTopic", parameters);
}
///<summary>
/// Pins a topic (fixes its place) to the top of a community's discussion board.
///</summary>
public Task<BaseOkResponse> FixTopic(int? groupId = null, int? topicId = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicId != null)
parameters.Add("topic_id", topicId.ToApiString());
return _vkontakte.RequestAsync<BaseOkResponse>("board.fixTopic", parameters);
}
///<summary>
/// Returns a list of comments on a topic on a community's discussion board.
///</summary>
public Task<BoardGetCommentsResponse> GetComments(int? groupId = null, int? topicId = null, Boolean? needLikes = null, int? startCommentId = null, int? offset = null, int? count = null, Boolean? extended = null, String sort = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicId != null)
parameters.Add("topic_id", topicId.ToApiString());
if (needLikes != null)
parameters.Add("need_likes", needLikes.ToApiString());
if (startCommentId != null)
parameters.Add("start_comment_id", startCommentId.ToApiString());
if (offset != null)
parameters.Add("offset", offset.ToApiString());
if (count != null)
parameters.Add("count", count.ToApiString());
if (extended != null)
parameters.Add("extended", extended.ToApiString());
if (sort != null)
parameters.Add("sort", sort.ToApiString());
return _vkontakte.RequestAsync<BoardGetCommentsResponse>("board.getComments", parameters);
}
///<summary>
/// Returns a list of topics on a community's discussion board.
///</summary>
public Task<BoardGetTopicsResponse> GetTopics(int? groupId = null, int[] topicIds = null, int? order = null, int? offset = null, int? count = null, Boolean? extended = null, int? preview = null, int? previewLength = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicIds != null)
parameters.Add("topic_ids", topicIds.ToApiString());
if (order != null)
parameters.Add("order", order.ToApiString());
if (offset != null)
parameters.Add("offset", offset.ToApiString());
if (count != null)
parameters.Add("count", count.ToApiString());
if (extended != null)
parameters.Add("extended", extended.ToApiString());
if (preview != null)
parameters.Add("preview", preview.ToApiString());
if (previewLength != null)
parameters.Add("preview_length", previewLength.ToApiString());
return _vkontakte.RequestAsync<BoardGetTopicsResponse>("board.getTopics", parameters);
}
///<summary>
/// Re-opens a previously closed topic on a community's discussion board.
///</summary>
public Task<BaseOkResponse> OpenTopic(int? groupId = null, int? topicId = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicId != null)
parameters.Add("topic_id", topicId.ToApiString());
return _vkontakte.RequestAsync<BaseOkResponse>("board.openTopic", parameters);
}
///<summary>
/// Restores a comment deleted from a topic on a community's discussion board.
///</summary>
public Task<BaseOkResponse> RestoreComment(int? groupId = null, int? topicId = null, int? commentId = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicId != null)
parameters.Add("topic_id", topicId.ToApiString());
if (commentId != null)
parameters.Add("comment_id", commentId.ToApiString());
return _vkontakte.RequestAsync<BaseOkResponse>("board.restoreComment", parameters);
}
///<summary>
/// Unpins a pinned topic from the top of a community's discussion board.
///</summary>
public Task<BaseOkResponse> UnfixTopic(int? groupId = null, int? topicId = null)
{
var parameters = new Dictionary<string, string>();
if (groupId != null)
parameters.Add("group_id", groupId.ToApiString());
if (topicId != null)
parameters.Add("topic_id", topicId.ToApiString());
return _vkontakte.RequestAsync<BaseOkResponse>("board.unfixTopic", parameters);
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1995
{
/// <summary>
/// Section 5.3.4. abstract superclass for fire and detonation pdus that have shared information
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
public partial class Warfare : Pdu, IEquatable<Warfare>
{
/// <summary>
/// ID of the entity that shot
/// </summary>
private EntityID _firingEntityID = new EntityID();
/// <summary>
/// ID of the entity that is being shot at
/// </summary>
private EntityID _targetEntityID = new EntityID();
/// <summary>
/// Initializes a new instance of the <see cref="Warfare"/> class.
/// </summary>
public Warfare()
{
ProtocolFamily = (byte)2;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(Warfare left, Warfare right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(Warfare left, Warfare right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._firingEntityID.GetMarshalledSize(); // this._firingEntityID
marshalSize += this._targetEntityID.GetMarshalledSize(); // this._targetEntityID
return marshalSize;
}
/// <summary>
/// Gets or sets the ID of the entity that shot
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "firingEntityID")]
public EntityID FiringEntityID
{
get
{
return this._firingEntityID;
}
set
{
this._firingEntityID = value;
}
}
/// <summary>
/// Gets or sets the ID of the entity that is being shot at
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "targetEntityID")]
public EntityID TargetEntityID
{
get
{
return this._targetEntityID;
}
set
{
this._targetEntityID = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public virtual void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._firingEntityID.Marshal(dos);
this._targetEntityID.Marshal(dos);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._firingEntityID.Unmarshal(dis);
this._targetEntityID.Unmarshal(dis);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<Warfare>");
base.Reflection(sb);
try
{
sb.AppendLine("<firingEntityID>");
this._firingEntityID.Reflection(sb);
sb.AppendLine("</firingEntityID>");
sb.AppendLine("<targetEntityID>");
this._targetEntityID.Reflection(sb);
sb.AppendLine("</targetEntityID>");
sb.AppendLine("</Warfare>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as Warfare;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(Warfare obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._firingEntityID.Equals(obj._firingEntityID))
{
ivarsEqual = false;
}
if (!this._targetEntityID.Equals(obj._targetEntityID))
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._firingEntityID.GetHashCode();
result = GenerateHash(result) ^ this._targetEntityID.GetHashCode();
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using NUnit.Framework;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Net;
using Umbraco.Cms.Core.PublishedCache;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Tests.Common.Builders;
using Umbraco.Cms.Tests.Common.Builders.Extensions;
using Umbraco.Cms.Web.Common.Security;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.Security
{
[TestFixture]
public class MemberManagerTests
{
private MemberUserStore _fakeMemberStore;
private Mock<IOptions<IdentityOptions>> _mockIdentityOptions;
private Mock<IPasswordHasher<MemberIdentityUser>> _mockPasswordHasher;
private Mock<IMemberService> _mockMemberService;
private Mock<IServiceProvider> _mockServiceProviders;
private Mock<IOptions<MemberPasswordConfigurationSettings>> _mockPasswordConfiguration;
public MemberManager CreateSut()
{
IScopeProvider scopeProvider = new Mock<IScopeProvider>().Object;
_mockMemberService = new Mock<IMemberService>();
var mapDefinitions = new List<IMapDefinition>()
{
new IdentityMapDefinition(
Mock.Of<ILocalizedTextService>(),
Mock.Of<IEntityService>(),
Options.Create(new GlobalSettings()),
AppCaches.Disabled),
};
_fakeMemberStore = new MemberUserStore(
_mockMemberService.Object,
new UmbracoMapper(new MapDefinitionCollection(() => mapDefinitions), scopeProvider),
scopeProvider,
new IdentityErrorDescriber(),
Mock.Of<IPublishedSnapshotAccessor>());
_mockIdentityOptions = new Mock<IOptions<IdentityOptions>>();
var idOptions = new IdentityOptions { Lockout = { AllowedForNewUsers = false } };
_mockIdentityOptions.Setup(o => o.Value).Returns(idOptions);
_mockPasswordHasher = new Mock<IPasswordHasher<MemberIdentityUser>>();
var userValidators = new List<IUserValidator<MemberIdentityUser>>();
var validator = new Mock<IUserValidator<MemberIdentityUser>>();
userValidators.Add(validator.Object);
_mockServiceProviders = new Mock<IServiceProvider>();
_mockPasswordConfiguration = new Mock<IOptions<MemberPasswordConfigurationSettings>>();
_mockPasswordConfiguration.Setup(x => x.Value).Returns(() =>
new MemberPasswordConfigurationSettings()
{
});
var pwdValidators = new List<PasswordValidator<MemberIdentityUser>>
{
new PasswordValidator<MemberIdentityUser>()
};
var userManager = new MemberManager(
new Mock<IIpResolver>().Object,
_fakeMemberStore,
_mockIdentityOptions.Object,
_mockPasswordHasher.Object,
userValidators,
pwdValidators,
new MembersErrorDescriber(Mock.Of<ILocalizedTextService>()),
_mockServiceProviders.Object,
new Mock<ILogger<UserManager<MemberIdentityUser>>>().Object,
_mockPasswordConfiguration.Object,
Mock.Of<IPublicAccessService>(),
Mock.Of<IHttpContextAccessor>());
validator.Setup(v => v.ValidateAsync(
userManager,
It.IsAny<MemberIdentityUser>()))
.Returns(Task.FromResult(IdentityResult.Success)).Verifiable();
return userManager;
}
[Test]
public async Task GivenICreateUser_AndTheIdentityResultFailed_ThenIShouldGetAFailedResultAsync()
{
//arrange
MemberManager sut = CreateSut();
var fakeUser = new MemberIdentityUser()
{
PasswordConfig = "testConfig"
};
//act
IdentityResult identityResult = await sut.CreateAsync(fakeUser);
//assert
Assert.IsFalse(identityResult.Succeeded);
Assert.IsFalse(!identityResult.Errors.Any());
}
[Test]
public async Task GivenICreateUser_AndTheUserIsNull_ThenIShouldGetAFailedResultAsync()
{
//arrange
MemberManager sut = CreateSut();
IdentityError[] identityErrors =
{
new IdentityError()
{
Code = "IdentityError1",
Description = "There was an identity error when creating a user"
}
};
//act
Assert.ThrowsAsync<ArgumentNullException>(async () => await sut.CreateAsync(null));
}
[Test]
public async Task GivenICreateANewUser_AndTheUserIsPopulatedCorrectly_ThenIShouldGetASuccessResultAsync()
{
//arrange
MemberManager sut = CreateSut();
MemberIdentityUser fakeUser = CreateValidUser();
IMember fakeMember = CreateMember(fakeUser);
MockMemberServiceForCreateMember(fakeMember);
//act
IdentityResult identityResult = await sut.CreateAsync(fakeUser);
//assert
Assert.IsTrue(identityResult.Succeeded);
Assert.IsTrue(!identityResult.Errors.Any());
}
[Test]
public async Task GivenAUserExists_AndTheCorrectCredentialsAreProvided_ThenACheckOfCredentialsShouldSucceed()
{
//arrange
var password = "password";
MemberManager sut = CreateSut();
MemberIdentityUser fakeUser = CreateValidUser();
IMember fakeMember = CreateMember(fakeUser);
MockMemberServiceForCreateMember(fakeMember);
_mockMemberService.Setup(x => x.GetByUsername(It.Is<string>(y => y == fakeUser.UserName))).Returns(fakeMember);
_mockPasswordHasher.Setup(x => x.VerifyHashedPassword(It.IsAny<MemberIdentityUser>(), It.IsAny<string>(), It.IsAny<string>())).Returns(PasswordVerificationResult.Success);
//act
await sut.CreateAsync(fakeUser);
var result = await sut.ValidateCredentialsAsync(fakeUser.UserName, password);
//assert
Assert.IsTrue(result);
}
[Test]
public async Task GivenAUserExists_AndIncorrectCredentialsAreProvided_ThenACheckOfCredentialsShouldFail()
{
//arrange
var password = "password";
MemberManager sut = CreateSut();
MemberIdentityUser fakeUser = CreateValidUser();
IMember fakeMember = CreateMember(fakeUser);
MockMemberServiceForCreateMember(fakeMember);
_mockMemberService.Setup(x => x.GetByUsername(It.Is<string>(y => y == fakeUser.UserName))).Returns(fakeMember);
_mockPasswordHasher.Setup(x => x.VerifyHashedPassword(It.IsAny<MemberIdentityUser>(), It.IsAny<string>(), It.IsAny<string>())).Returns(PasswordVerificationResult.Failed);
//act
await sut.CreateAsync(fakeUser);
var result = await sut.ValidateCredentialsAsync(fakeUser.UserName, password);
//assert
Assert.IsFalse(result);
}
[Test]
public async Task GivenAUserDoesExists_AndCredentialsAreProvided_ThenACheckOfCredentialsShouldFail()
{
//arrange
var password = "password";
MemberManager sut = CreateSut();
_mockMemberService.Setup(x => x.GetByUsername(It.Is<string>(y => y == "testUser"))).Returns((IMember)null);
//act
var result = await sut.ValidateCredentialsAsync("testUser", password);
//assert
Assert.IsFalse(result);
}
private static MemberIdentityUser CreateValidUser() =>
new MemberIdentityUser(777)
{
UserName = "testUser",
Email = "[email protected]",
Name = "Test",
MemberTypeAlias = "Anything",
PasswordConfig = "testConfig",
PasswordHash = "hashedPassword"
};
private static IMember CreateMember(MemberIdentityUser fakeUser)
{
var builder = new MemberTypeBuilder();
MemberType memberType = builder.BuildSimpleMemberType();
return new Member(memberType)
{
Id = 777,
Username = fakeUser.UserName,
};
}
private void MockMemberServiceForCreateMember(IMember fakeMember)
{
_mockMemberService.Setup(x => x.CreateMember(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(fakeMember);
_mockMemberService.Setup(x => x.Save(fakeMember));
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.Compression;
using Cassandra.Requests;
using Cassandra.Responses;
using Cassandra.Serialization;
using Cassandra.Tasks;
using Microsoft.IO;
namespace Cassandra.Connections
{
/// <inheritdoc />
internal class Connection : IConnection
{
private const int WriteStateInit = 0;
private const int WriteStateRunning = 1;
private const int WriteStateClosed = 2;
private const string StreamReadTag = nameof(Connection) + "/Read";
private const string StreamWriteTag = nameof(Connection) + "/Write";
private static readonly Logger Logger = new Logger(typeof(Connection));
private readonly Serializer _serializer;
private readonly IStartupRequestFactory _startupRequestFactory;
private readonly ITcpSocket _tcpSocket;
private long _disposed;
/// <summary>
/// Determines that the connection canceled pending operations.
/// It could be because its being closed or there was a socket error.
/// </summary>
private volatile bool _isCanceled;
private readonly Timer _idleTimer;
private long _timedOutOperations;
/// <summary>
/// Stores the available stream ids.
/// </summary>
private ConcurrentStack<short> _freeOperations;
/// <summary> Contains the requests that were sent through the wire and that hasn't been received yet.</summary>
private ConcurrentDictionary<short, OperationState> _pendingOperations;
/// <summary> It contains the requests that could not be written due to streamIds not available</summary>
private ConcurrentQueue<OperationState> _writeQueue;
private volatile string _keyspace;
private TaskCompletionSource<bool> _keyspaceSwitchTcs;
/// <summary>
/// Small buffer (less than 8 bytes) that is used when the next received message is smaller than 8 bytes,
/// and it is not possible to read the header.
/// </summary>
private byte[] _minHeaderBuffer;
private byte _frameHeaderSize;
private MemoryStream _readStream;
private FrameHeader _receivingHeader;
private int _writeState = Connection.WriteStateInit;
private int _inFlight;
/// <summary>
/// The event that represents a event RESPONSE from a Cassandra node
/// </summary>
public event CassandraEventHandler CassandraEventResponse;
/// <summary>
/// Event raised when there is an error when executing the request to prevent idle disconnects
/// </summary>
public event Action<Exception> OnIdleRequestException;
/// <summary>
/// Event that gets raised when a write has been completed. Testing purposes only.
/// </summary>
public event Action WriteCompleted;
/// <summary>
/// Event that gets raised the connection is being closed.
/// </summary>
public event Action<IConnection> Closing;
private const string IdleQuery = "SELECT key from system.local";
private const long CoalescingThreshold = 8000;
public IFrameCompressor Compressor { get; set; }
public IConnectionEndPoint EndPoint => _tcpSocket.EndPoint;
public IPEndPoint LocalAddress => _tcpSocket.GetLocalIpEndPoint();
/// <summary>
/// Determines the amount of operations that are not finished.
/// </summary>
public virtual int InFlight => Volatile.Read(ref _inFlight);
/// <summary>
/// Determines if there isn't any operations pending to be written or inflight.
/// </summary>
public virtual bool HasPendingOperations
{
get { return InFlight > 0 || !_writeQueue.IsEmpty; }
}
/// <summary>
/// Gets the amount of operations that timed out and didn't get a response
/// </summary>
public virtual int TimedOutOperations
{
get { return (int)Interlocked.Read(ref _timedOutOperations); }
}
/// <summary>
/// Determine if the Connection has been explicitly disposed
/// </summary>
public bool IsDisposed
{
get { return Interlocked.Read(ref _disposed) > 0L; }
}
/// <summary>
/// Gets the current keyspace.
/// </summary>
public string Keyspace
{
get
{
return _keyspace;
}
}
/// <summary>
/// Gets the amount of concurrent requests depending on the protocol version
/// </summary>
public int MaxConcurrentRequests
{
get
{
if (!_serializer.ProtocolVersion.Uses2BytesStreamIds())
{
return 128;
}
//Protocol 3 supports up to 32K concurrent request without waiting a response
//Allowing larger amounts of concurrent requests will cause large memory consumption
//Limit to 2K per connection sounds reasonable.
return 2048;
}
}
public ProtocolOptions Options => Configuration.ProtocolOptions;
public Configuration Configuration { get; set; }
public Connection(Serializer serializer, IConnectionEndPoint endPoint, Configuration configuration) :
this(serializer, endPoint, configuration, new StartupRequestFactory(configuration.StartupOptionsFactory))
{
}
internal Connection(Serializer serializer, IConnectionEndPoint endPoint, Configuration configuration, IStartupRequestFactory startupRequestFactory)
{
_serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_startupRequestFactory = startupRequestFactory ?? throw new ArgumentNullException(nameof(startupRequestFactory));
_tcpSocket = new TcpSocket(endPoint, configuration.SocketOptions, configuration.ProtocolOptions.SslOptions);
_idleTimer = new Timer(IdleTimeoutHandler, null, Timeout.Infinite, Timeout.Infinite);
}
private void IncrementInFlight()
{
Interlocked.Increment(ref _inFlight);
}
private void DecrementInFlight()
{
Interlocked.Decrement(ref _inFlight);
}
/// <summary>
/// Starts the authentication flow
/// </summary>
/// <param name="name">Authenticator name from server.</param>
/// <exception cref="AuthenticationException" />
private async Task<Response> StartAuthenticationFlow(string name)
{
//Determine which authentication flow to use.
//Check if its using a C* 1.2 with authentication patched version (like DSE 3.1)
var protocolVersion = _serializer.ProtocolVersion;
var isPatchedVersion = protocolVersion == ProtocolVersion.V1 &&
!(Configuration.AuthProvider is NoneAuthProvider) && Configuration.AuthInfoProvider == null;
if (protocolVersion == ProtocolVersion.V1 && !isPatchedVersion)
{
//Use protocol v1 authentication flow
if (Configuration.AuthInfoProvider == null)
{
throw new AuthenticationException(
$"Host {EndPoint.EndpointFriendlyName} requires authentication, but no credentials provided in Cluster configuration",
EndPoint.GetHostIpEndPointWithFallback());
}
var credentialsProvider = Configuration.AuthInfoProvider;
var credentials = credentialsProvider.GetAuthInfos(EndPoint.GetHostIpEndPointWithFallback());
var request = new CredentialsRequest(credentials);
var response = await Send(request).ConfigureAwait(false);
if (!(response is ReadyResponse))
{
//If Cassandra replied with a auth response error
//The task already is faulted and the exception was already thrown.
throw new ProtocolErrorException("Expected SASL response, obtained " + response.GetType().Name);
}
return response;
}
//Use protocol v2+ authentication flow
if (Configuration.AuthProvider is IAuthProviderNamed)
{
//Provide name when required
((IAuthProviderNamed)Configuration.AuthProvider).SetName(name);
}
//NewAuthenticator will throw AuthenticationException when NoneAuthProvider
var authenticator = Configuration.AuthProvider.NewAuthenticator(EndPoint.GetHostIpEndPointWithFallback());
var initialResponse = authenticator.InitialResponse() ?? new byte[0];
return await Authenticate(initialResponse, authenticator).ConfigureAwait(false);
}
/// <exception cref="AuthenticationException" />
private async Task<Response> Authenticate(byte[] token, IAuthenticator authenticator)
{
var request = new AuthResponseRequest(token);
var response = await Send(request).ConfigureAwait(false);
if (response is AuthSuccessResponse)
{
// It is now authenticated, dispose Authenticator if it implements IDisposable()
// ReSharper disable once SuspiciousTypeConversion.Global
var disposableAuthenticator = authenticator as IDisposable;
if (disposableAuthenticator != null)
{
disposableAuthenticator.Dispose();
}
return response;
}
if (response is AuthChallengeResponse)
{
token = authenticator.EvaluateChallenge(((AuthChallengeResponse)response).Token);
if (token == null)
{
// If we get a null response, then authentication has completed
// return without sending a further response back to the server.
return response;
}
return await Authenticate(token, authenticator).ConfigureAwait(false);
}
throw new ProtocolErrorException("Expected SASL response, obtained " + response.GetType().Name);
}
/// <summary>
/// It callbacks all operations already sent / or to be written, that do not have a response.
/// Invoked from an IO Thread or a pool thread
/// </summary>
internal void CancelPending(Exception ex, SocketError? socketError = null)
{
_isCanceled = true;
var wasClosed = Interlocked.Exchange(ref _writeState, Connection.WriteStateClosed) == Connection.WriteStateClosed;
if (!wasClosed)
{
if (Closing != null)
{
Closing(this);
}
Connection.Logger.Info("Cancelling in Connection {0}, {1} pending operations and write queue {2}", EndPoint.EndpointFriendlyName,
InFlight, _writeQueue.Count);
if (socketError != null)
{
Connection.Logger.Verbose("The socket status received was {0}", socketError.Value);
}
}
if (ex == null || ex is ObjectDisposedException)
{
if (socketError != null)
{
ex = new SocketException((int)socketError.Value);
}
else
{
//It is closing
ex = new SocketException((int)SocketError.NotConnected);
}
}
// Dequeue all the items in the write queue
var ops = new LinkedList<OperationState>();
OperationState state;
while (_writeQueue.TryDequeue(out state))
{
ops.AddLast(state);
}
// Remove every pending operation
while (!_pendingOperations.IsEmpty)
{
Interlocked.MemoryBarrier();
// Remove using a snapshot of the keys
var keys = _pendingOperations.Keys.ToArray();
foreach (var key in keys)
{
if (_pendingOperations.TryRemove(key, out state))
{
ops.AddLast(state);
}
}
}
Interlocked.MemoryBarrier();
OperationState.CallbackMultiple(ops, ex);
Interlocked.Exchange(ref _inFlight, 0);
}
public virtual void Dispose()
{
if (Interlocked.Increment(ref _disposed) != 1)
{
//Only dispose once
return;
}
_idleTimer.Dispose();
_tcpSocket.Dispose();
var readStream = Interlocked.Exchange(ref _readStream, null);
if (readStream != null)
{
readStream.Dispose();
}
}
private void EventHandler(Exception ex, Response response)
{
if (!(response is EventResponse))
{
Connection.Logger.Error("Unexpected response type for event: " + response.GetType().Name);
return;
}
if (CassandraEventResponse != null)
{
CassandraEventResponse(this, ((EventResponse)response).CassandraEventArgs);
}
}
/// <summary>
/// Gets executed once the idle timeout has passed
/// </summary>
private void IdleTimeoutHandler(object state)
{
//Ensure there are no more idle timeouts until the query finished sending
if (_isCanceled)
{
if (!IsDisposed)
{
//If it was not manually disposed
Connection.Logger.Warning("Can not issue an heartbeat request as connection is closed");
if (OnIdleRequestException != null)
{
OnIdleRequestException(new SocketException((int)SocketError.NotConnected));
}
}
return;
}
Connection.Logger.Verbose("Connection idling, issuing a Request to prevent idle disconnects");
var request = new OptionsRequest();
Send(request, (ex, response) =>
{
if (ex == null)
{
//The send succeeded
//There is a valid response but we don't care about the response
return;
}
Connection.Logger.Warning("Received heartbeat request exception " + ex.ToString());
if (ex is SocketException && OnIdleRequestException != null)
{
OnIdleRequestException(ex);
}
});
}
/// <summary>
/// Initializes the connection.
/// </summary>
/// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception>
/// <exception cref="AuthenticationException" />
/// <exception cref="UnsupportedProtocolVersionException"></exception>
public async Task<Response> Open()
{
_freeOperations = new ConcurrentStack<short>(Enumerable.Range(0, MaxConcurrentRequests).Select(s => (short)s).Reverse());
_pendingOperations = new ConcurrentDictionary<short, OperationState>();
_writeQueue = new ConcurrentQueue<OperationState>();
if (Options.CustomCompressor != null)
{
Compressor = Options.CustomCompressor;
}
else if (Options.Compression == CompressionType.LZ4)
{
#if NET45
Compressor = new LZ4Compressor();
#else
throw new NotSupportedException("Lz4 compression not supported under .NETCore");
#endif
}
else if (Options.Compression == CompressionType.Snappy)
{
Compressor = new SnappyCompressor();
}
//Init TcpSocket
_tcpSocket.Init();
_tcpSocket.Error += CancelPending;
_tcpSocket.Closing += () => CancelPending(null);
//Read and write event handlers are going to be invoked using IO Threads
_tcpSocket.Read += ReadHandler;
_tcpSocket.WriteCompleted += WriteCompletedHandler;
var protocolVersion = _serializer.ProtocolVersion;
await _tcpSocket.Connect().ConfigureAwait(false);
Response response;
try
{
response = await Startup().ConfigureAwait(false);
}
catch (ProtocolErrorException ex)
{
// As we are starting up, check for protocol version errors.
// There is no other way than checking the error message from Cassandra
if (ex.Message.Contains("Invalid or unsupported protocol version"))
{
throw new UnsupportedProtocolVersionException(protocolVersion, ex);
}
throw;
}
if (response is AuthenticateResponse)
{
return await StartAuthenticationFlow(((AuthenticateResponse)response).Authenticator)
.ConfigureAwait(false);
}
if (response is ReadyResponse)
{
return response;
}
throw new DriverInternalError("Expected READY or AUTHENTICATE, obtained " + response.GetType().Name);
}
/// <summary>
/// Silently kill the connection, for testing purposes only
/// </summary>
internal void Kill()
{
_tcpSocket.Kill();
}
private void ReadHandler(byte[] buffer, int bytesReceived)
{
if (_isCanceled)
{
//All pending operations have been canceled, there is no point in reading from the wire.
return;
}
//We are currently using an IO Thread
//Parse the data received
var streamIdAvailable = ReadParse(buffer, bytesReceived);
if (!streamIdAvailable)
{
return;
}
//Process a next item in the queue if possible.
//Maybe there are there items in the write queue that were waiting on a fresh streamId
RunWriteQueue();
}
/// <summary>
/// Deserializes each frame header and copies the body bytes into a single buffer.
/// </summary>
/// <returns>True if a full operation (streamId) has been processed.</returns>
internal bool ReadParse(byte[] buffer, int length)
{
if (length <= 0)
{
return false;
}
ProtocolVersion protocolVersion;
var headerLength = Volatile.Read(ref _frameHeaderSize);
if (headerLength == 0)
{
// The server replies the first message with the max protocol version supported
protocolVersion = FrameHeader.GetProtocolVersion(buffer);
_serializer.ProtocolVersion = protocolVersion;
headerLength = FrameHeader.GetSize(protocolVersion);
Volatile.Write(ref _frameHeaderSize, headerLength);
}
else
{
protocolVersion = _serializer.ProtocolVersion;
}
// Use _readStream to buffer between messages, when the body is not contained in a single read call
var stream = Interlocked.Exchange(ref _readStream, null);
var previousHeader = Interlocked.Exchange(ref _receivingHeader, null);
if (previousHeader != null && stream == null)
{
// This connection has been disposed
return false;
}
var operationCallbacks = new LinkedList<Action<MemoryStream>>();
var offset = 0;
while (offset < length)
{
var header = previousHeader;
int remainingBodyLength;
if (header == null)
{
header = ReadHeader(buffer, ref offset, length, headerLength, protocolVersion);
if (header == null)
{
// There aren't enough bytes to read the header
break;
}
Connection.Logger.Verbose("Received #{0} from {1}", header.StreamId, EndPoint.EndpointFriendlyName);
remainingBodyLength = header.BodyLength;
}
else
{
previousHeader = null;
remainingBodyLength = header.BodyLength - (int)stream.Length;
}
if (remainingBodyLength > length - offset)
{
// The buffer does not contains the body for the current frame, store it for later
StoreReadState(header, stream, buffer, offset, length, operationCallbacks.Count > 0);
break;
}
stream = stream ?? Configuration.BufferPool.GetStream(Connection.StreamReadTag);
var state = header.Opcode != EventResponse.OpCode
? RemoveFromPending(header.StreamId)
: new OperationState(EventHandler);
stream.Write(buffer, offset, remainingBodyLength);
// State can be null when the Connection is being closed concurrently
// The original callback is being called with an error, use a Noop here
var callback = state != null ? state.SetCompleted() : OperationState.Noop;
operationCallbacks.AddLast(CreateResponseAction(header, callback));
offset += remainingBodyLength;
}
return Connection.InvokeReadCallbacks(stream, operationCallbacks);
}
/// <summary>
/// Reads the header from the buffer, using previous
/// </summary>
private FrameHeader ReadHeader(byte[] buffer, ref int offset, int length, int headerLength,
ProtocolVersion version)
{
if (offset == 0)
{
var previousHeaderBuffer = Interlocked.Exchange(ref _minHeaderBuffer, null);
if (previousHeaderBuffer != null)
{
if (previousHeaderBuffer.Length + length < headerLength)
{
// Unlikely scenario where there were a few bytes for a header buffer and the new bytes are
// not enough to complete the header
Volatile.Write(ref _minHeaderBuffer,
Utils.JoinBuffers(previousHeaderBuffer, 0, previousHeaderBuffer.Length, buffer, 0, length));
return null;
}
offset += headerLength - previousHeaderBuffer.Length;
// Use the previous and the current buffer to build the header
return FrameHeader.ParseResponseHeader(version, previousHeaderBuffer, buffer);
}
}
if (length - offset < headerLength)
{
// There aren't enough bytes in the current buffer to read the header, store it for later
Volatile.Write(ref _minHeaderBuffer, Utils.SliceBuffer(buffer, offset, length - offset));
return null;
}
// The header is contained in the current buffer
var header = FrameHeader.ParseResponseHeader(version, buffer, offset);
offset += headerLength;
return header;
}
/// <summary>
/// Saves the current read state (header and body stream) for the next read event.
/// </summary>
private void StoreReadState(FrameHeader header, MemoryStream stream, byte[] buffer, int offset, int length,
bool hasReadFromStream)
{
MemoryStream nextMessageStream;
if (!hasReadFromStream && stream != null)
{
// There hasn't been any operations completed with this buffer, reuse the current stream
nextMessageStream = stream;
}
else
{
// Allocate a new stream for store in it
nextMessageStream = Configuration.BufferPool.GetStream(Connection.StreamReadTag);
}
nextMessageStream.Write(buffer, offset, length - offset);
Volatile.Write(ref _readStream, nextMessageStream);
Volatile.Write(ref _receivingHeader, header);
if (_isCanceled)
{
// Connection was disposed since we started to store the buffer, try to dispose the stream
Interlocked.Exchange(ref _readStream, null)?.Dispose();
}
}
/// <summary>
/// Returns an action that capture the parameters closure
/// </summary>
private Action<MemoryStream> CreateResponseAction(FrameHeader header, Action<Exception, Response> callback)
{
var compressor = Compressor;
void DeserializeResponseStream(MemoryStream stream)
{
Response response = null;
Exception ex = null;
var nextPosition = stream.Position + header.BodyLength;
try
{
Stream plainTextStream = stream;
if (header.Flags.HasFlag(FrameHeader.HeaderFlag.Compression))
{
plainTextStream = compressor.Decompress(new WrappedStream(stream, header.BodyLength));
plainTextStream.Position = 0;
}
response = FrameParser.Parse(new Frame(header, plainTextStream, _serializer));
}
catch (Exception catchedException)
{
ex = catchedException;
}
if (response is ErrorResponse)
{
//Create an exception from the response error
ex = ((ErrorResponse)response).Output.CreateException();
response = null;
}
//We must advance the position of the stream manually in case it was not correctly parsed
stream.Position = nextPosition;
callback(ex, response);
}
return DeserializeResponseStream;
}
/// <summary>
/// Invokes the callbacks using the default TaskScheduler.
/// </summary>
/// <returns>Returns true if one or more callback has been invoked.</returns>
private static bool InvokeReadCallbacks(MemoryStream stream, ICollection<Action<MemoryStream>> operationCallbacks)
{
if (operationCallbacks.Count == 0)
{
//Not enough data to read a frame
return false;
}
//Invoke all callbacks using the default TaskScheduler
Task.Factory.StartNew(() =>
{
stream.Position = 0;
foreach (var cb in operationCallbacks)
{
cb(stream);
}
stream.Dispose();
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
return true;
}
/// <summary>
/// Sends a protocol STARTUP message
/// </summary>
private Task<Response> Startup()
{
var request = _startupRequestFactory.CreateStartupRequest(Options);
// Use the Connect timeout for the startup request timeout
return Send(request, Configuration.SocketOptions.ConnectTimeoutMillis);
}
/// <inheritdoc />
public Task<Response> Send(IRequest request, int timeoutMillis)
{
var tcs = new TaskCompletionSource<Response>();
Send(request, tcs.TrySet, timeoutMillis);
return tcs.Task;
}
/// <inheritdoc />
public Task<Response> Send(IRequest request)
{
return Send(request, Configuration.DefaultRequestOptions.ReadTimeoutMillis);
}
/// <inheritdoc />
public OperationState Send(IRequest request, Action<Exception, Response> callback, int timeoutMillis)
{
if (_isCanceled)
{
// Avoid calling back before returning
Task.Factory.StartNew(() => callback(new SocketException((int)SocketError.NotConnected), null),
CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
return null;
}
IncrementInFlight();
var state = new OperationState(callback)
{
Request = request,
TimeoutMillis = timeoutMillis
};
_writeQueue.Enqueue(state);
RunWriteQueue();
return state;
}
/// <inheritdoc />
public OperationState Send(IRequest request, Action<Exception, Response> callback)
{
return Send(request, callback, Configuration.DefaultRequestOptions.ReadTimeoutMillis);
}
private void RunWriteQueue()
{
var previousState = Interlocked.CompareExchange(ref _writeState, Connection.WriteStateRunning, Connection.WriteStateInit);
if (previousState == Connection.WriteStateRunning)
{
// There is another thread writing to the wire
return;
}
if (previousState == Connection.WriteStateClosed)
{
// Probably there is an item in the write queue, we should cancel pending
// Avoid canceling in the user thread
Task.Factory.StartNew(() => CancelPending(null), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
return;
}
// Start a new task using the TaskScheduler for writing to avoid using the User thread
Task.Factory.StartNew(RunWriteQueueAction, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
private void RunWriteQueueAction()
{
//Dequeue all items until threshold is passed
long totalLength = 0;
RecyclableMemoryStream stream = null;
while (totalLength < Connection.CoalescingThreshold)
{
OperationState state;
if (!_writeQueue.TryDequeue(out state))
{
//No more items in the write queue
break;
}
short streamId;
if (!_freeOperations.TryPop(out streamId))
{
//Queue it up for later.
_writeQueue.Enqueue(state);
//When receiving the next complete message, we can process it.
Connection.Logger.Info("Enqueued, no streamIds available. If this message is recurrent consider configuring more connections per host or lower the pressure");
break;
}
Connection.Logger.Verbose("Sending #{0} for {1} to {2}", streamId, state.Request.GetType().Name, EndPoint.EndpointFriendlyName);
if (_isCanceled)
{
state.InvokeCallback(new SocketException((int)SocketError.NotConnected));
break;
}
_pendingOperations.AddOrUpdate(streamId, state, (k, oldValue) => state);
int frameLength;
var startLength = stream?.Length ?? 0;
try
{
//lazy initialize the stream
stream = stream ?? (RecyclableMemoryStream)Configuration.BufferPool.GetStream(Connection.StreamWriteTag);
frameLength = state.Request.WriteFrame(streamId, stream, _serializer);
if (state.TimeoutMillis > 0)
{
var requestTimeout = Configuration.Timer.NewTimeout(OnTimeout, streamId, state.TimeoutMillis);
state.SetTimeout(requestTimeout);
}
}
catch (Exception ex)
{
//There was an error while serializing or begin sending
Connection.Logger.Error(ex);
//The request was not written, clear it from pending operations
RemoveFromPending(streamId);
//Callback with the Exception
state.InvokeCallback(ex);
//Reset the stream to before we started writing this frame
stream?.SetLength(startLength);
break;
}
//We will not use the request any more, stop reference it.
state.Request = null;
totalLength += frameLength;
}
if (totalLength == 0L)
{
// Nothing to write, set the queue as not running
Interlocked.CompareExchange(ref _writeState, Connection.WriteStateInit, Connection.WriteStateRunning);
// Until now, we were preventing other threads to running the queue.
// Check if we can now write:
// a read could have finished (freeing streamIds) or new request could have been added to the queue
if (!_freeOperations.IsEmpty && !_writeQueue.IsEmpty)
{
//The write queue is not empty
//An item was added to the queue but we were running: try to launch a new queue
RunWriteQueue();
}
if (stream != null)
{
//The stream instance could be created if there was an exception while generating the frame
stream.Dispose();
}
return;
}
//Write and close the stream when flushed
// ReSharper disable once PossibleNullReferenceException : if totalLength > 0 the stream is initialized
_tcpSocket.Write(stream, () => stream.Dispose());
}
/// <summary>
/// Removes an operation from pending and frees the stream id
/// </summary>
/// <param name="streamId"></param>
protected internal virtual OperationState RemoveFromPending(short streamId)
{
if (_pendingOperations.TryRemove(streamId, out var state))
{
DecrementInFlight();
}
//Set the streamId as available
_freeOperations.Push(streamId);
return state;
}
/// <summary>
/// Sets the keyspace of the connection.
/// If the keyspace is different from the current value, it sends a Query request to change it
/// </summary>
public async Task<bool> SetKeyspace(string value)
{
if (string.IsNullOrEmpty(value))
{
return true;
}
while (_keyspace != value)
{
var switchTcs = Volatile.Read(ref _keyspaceSwitchTcs);
if (switchTcs != null)
{
// Is already switching
await switchTcs.Task.ConfigureAwait(false);
continue;
}
var tcs = new TaskCompletionSource<bool>();
switchTcs = Interlocked.CompareExchange(ref _keyspaceSwitchTcs, tcs, null);
if (switchTcs != null)
{
// Is already switching
await switchTcs.Task.ConfigureAwait(false);
continue;
}
// CAS operation won, this is the only thread changing the keyspace
Connection.Logger.Info("Connection to host {0} switching to keyspace {1}", EndPoint.EndpointFriendlyName, value);
var request = new QueryRequest(_serializer.ProtocolVersion, $"USE \"{value}\"", false, QueryProtocolOptions.Default);
Exception sendException = null;
try
{
await Send(request).ConfigureAwait(false);
_keyspace = value;
}
catch (Exception ex)
{
sendException = ex;
}
// Set the reference to null before setting the result
Interlocked.Exchange(ref _keyspaceSwitchTcs, null);
tcs.TrySet(sendException, true);
return await tcs.Task.ConfigureAwait(false);
}
return true;
}
private void OnTimeout(object stateObj)
{
var streamId = (short)stateObj;
if (!_pendingOperations.TryGetValue(streamId, out var state))
{
return;
}
var ex = new OperationTimedOutException(EndPoint, state.TimeoutMillis);
//Invoke if it hasn't been invoked yet
//Once the response is obtained, we decrement the timed out counter
var timedout = state.MarkAsTimedOut(ex, () => Interlocked.Decrement(ref _timedOutOperations));
if (!timedout)
{
//The response was obtained since the timer elapsed, move on
return;
}
//Increase timed-out counter
Interlocked.Increment(ref _timedOutOperations);
}
/// <summary>
/// Method that gets executed when a write request has been completed.
/// </summary>
protected virtual void WriteCompletedHandler()
{
//This handler is invoked by IO threads
//Make it quick
WriteCompleted?.Invoke();
//There is no need for synchronization here
//Only 1 thread can be here at the same time.
//Set the idle timeout to avoid idle disconnects
var heartBeatInterval = Configuration.GetPoolingOptions(_serializer.ProtocolVersion).GetHeartBeatInterval() ?? 0;
if (heartBeatInterval > 0 && !_isCanceled)
{
try
{
_idleTimer.Change(heartBeatInterval, Timeout.Infinite);
}
catch (ObjectDisposedException)
{
//This connection is being disposed
//Don't mind
}
}
Interlocked.CompareExchange(ref _writeState, Connection.WriteStateInit, Connection.WriteStateRunning);
//Send the next request, if exists
//It will use a new thread
RunWriteQueue();
}
}
}
| |
using System;
using System.Globalization;
namespace Microsoft.TemplateEngine.Utils
{
/// <summary>
/// Wrapper for working with Semantic Versioning v2.0 (http://semver.org/)
/// </summary>
public class SemanticVersion : IEquatable<SemanticVersion>, IComparable
{
private readonly int _hashCode;
/// <summary>
/// Creates a new semantic version object
/// </summary>
/// <param name="originalText">The original text that had been parsed</param>
/// <param name="major">The interpreted major version number</param>
/// <param name="minor">The interpreted minor version number</param>
/// <param name="patch">The interpreted patch number</param>
/// <param name="prereleaseInfo">The prerelease information section, if any (should be null if none was found)</param>
/// <param name="buildMetadata">The build metadata section, if any (should be null if none was found)</param>
private SemanticVersion(string originalText, int major, int minor, int patch, string prereleaseInfo, string buildMetadata)
{
OriginalText = originalText;
Major = major;
Minor = minor;
Patch = patch;
PrereleaseInfo = prereleaseInfo;
BuildMetadata = buildMetadata;
_hashCode = major ^ minor ^ patch ^ (prereleaseInfo ?? string.Empty).GetHashCode() ^ (buildMetadata ?? string.Empty).GetHashCode();
}
/// <summary>
/// Gets the build metadata section (if any), null if no build metadata has been specified
/// </summary>
public string BuildMetadata { get; }
/// <summary>
/// Gets the interpreted major version number
/// </summary>
public int Major { get; }
/// <summary>
/// Gets the interpreted minor version number
/// </summary>
public int Minor { get; }
/// <summary>
/// Gets the original text that this object represents
/// </summary>
public string OriginalText { get; }
/// <summary>
/// Gets the patch number
/// </summary>
public int Patch { get; }
/// <summary>
/// Gets the prerelease section (if any), null if no prerelease information was specified
/// </summary>
public string PrereleaseInfo { get; }
/// <summary>
/// Compares the current instance with another object of the same type and returns an
/// integer that indicates whether the current instance precedes, follows, or occurs
/// in the same position in the sort order as the other object.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>A value that indicates the relative order of the objects being compared.</returns>
public int CompareTo(object obj)
{
SemanticVersion other = obj as SemanticVersion;
return CompareTo(other);
}
/// <summary>
/// Compares the current instance with another object of the same type and returns an
/// integer that indicates whether the current instance precedes, follows, or occurs
/// in the same position in the sort order as the other object.
/// </summary>
/// <param name="other">An object to compare with this instance.</param>
/// <returns>A value that indicates the relative order of the objects being compared.</returns>
public int CompareTo(SemanticVersion other)
{
return CompareTo(other, out bool ignored);
}
/// <summary>
/// Compares the current instance with another object of the same type and returns an
/// integer that indicates whether the current instance precedes, follows, or occurs
/// in the same position in the sort order as the other object.
/// </summary>
/// <param name="other">An object to compare with this instance.</param>
/// <param name="differentInBuildMetadataOnly">[Out] Whether this object and the one to compare with differ only by build metadata.</param>
/// <returns>A value that indicates the relative order of the objects being compared.</returns>
public int CompareTo(SemanticVersion other, out bool differentInBuildMetadataOnly)
{
differentInBuildMetadataOnly = false;
if (other is null)
{
return 1;
}
int versionCompare = CompareVersionInformation(other);
if (versionCompare != 0)
{
return versionCompare;
}
int prereleaseCompare = ComparePrereleaseInfo(other);
if (prereleaseCompare != 0)
{
return prereleaseCompare;
}
int buildMetadataCompare = CompareBuildMetadata(other);
if (buildMetadataCompare != 0)
{
differentInBuildMetadataOnly = true;
return buildMetadataCompare;
}
return 0;
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
public override bool Equals(object obj)
{
return Equals(obj as SemanticVersion);
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <param name="other">The object to compare with the current object.</param>
/// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
public bool Equals(SemanticVersion other)
{
if (other is null)
{
return false;
}
return CompareTo(other, out bool differentInBuildMetadataOnly) == 0 || differentInBuildMetadataOnly;
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
/// <returns>A hash code for the current object.</returns>
public override int GetHashCode()
{
return _hashCode;
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
{
string result = $"{Major}.{Minor}.{Patch}";
if (PrereleaseInfo != null)
{
result += $"-{PrereleaseInfo}";
}
if (BuildMetadata != null)
{
result += $"+{BuildMetadata}";
}
return result + $" ({OriginalText})";
}
/// <summary>
/// Attempts to parse a string as a semantic version
/// </summary>
/// <param name="source">The text to attempt to parse</param>
/// <param name="version">[Out] The resulting version object if the parse was successful.</param>
/// <returns>true if the parse was successful, false otherwise.</returns>
public static bool TryParse(string source, out SemanticVersion version)
{
if (string.IsNullOrWhiteSpace(source))
{
version = null;
return false;
}
source = source.Trim();
int majorEnd = 0,
minorEnd = 0,
patchEnd = 0,
tail = 0;
if (!IsolateVersionRange(source, -1, ref majorEnd))
{
version = null;
return false;
}
if (majorEnd == source.Length || source[majorEnd] != '.')
{
tail = majorEnd;
return TryParsePrereleaseAndBuildMetadata(source, majorEnd, minorEnd, patchEnd, tail, out version);
}
if (!IsolateVersionRange(source, majorEnd, ref minorEnd))
{
version = null;
return false;
}
if (minorEnd == source.Length || source[minorEnd] != '.')
{
tail = minorEnd;
return TryParsePrereleaseAndBuildMetadata(source, majorEnd, minorEnd, patchEnd, tail, out version);
}
if (!IsolateVersionRange(source, minorEnd, ref patchEnd))
{
version = null;
return false;
}
tail = patchEnd;
return TryParsePrereleaseAndBuildMetadata(source, majorEnd, minorEnd, patchEnd, tail, out version);
}
/// <summary>
/// Determines whether two semantic versions are value equal.
/// </summary>
/// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param>
/// <returns>true if the versions are value equal, false otherwise.</returns>
/// <remarks>
/// This respects the portion of the specification that indicates
/// that build metadata should not impact precedence by returning
/// true for versions that differ only in that field.
/// </remarks>
public static bool operator ==(SemanticVersion left, SemanticVersion right)
{
return !(left is null) && left.Equals(right);
}
/// <summary>
/// Determines whether two semantic versions are not value equal.
/// </summary>
/// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param>
/// <returns>true if the versions are value equal, false otherwise.</returns>
/// <remarks>
/// This respects the portion of the specification that indicates
/// that build metadata should not impact precedence by returning
/// false for versions that differ only in that field.
/// </remarks>
public static bool operator !=(SemanticVersion left, SemanticVersion right)
{
return !(left == right);
}
/// <summary>
/// Determines whether the first version has lower precedence than the second version.
/// </summary>
/// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param>
/// <returns>true if the first version has lower precedence than the second, false otherwise.</returns>
/// <remarks>
/// This respects the portion of the specification that indicates
/// that build metadata should not impact precedence by returning
/// false for versions that differ only in that field.
/// </remarks>
public static bool operator <(SemanticVersion left, SemanticVersion right)
{
if (left is null)
{
return !(right is null);
}
return left.CompareTo(right, out bool isDifferentInBuildMetadataOnly) < 0 && !isDifferentInBuildMetadataOnly;
}
/// <summary>
/// Determines whether the first version has lower or equal precedence than the second version.
/// </summary>
/// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param>
/// <returns>true if the first version has lower or equal precedence than the second, false otherwise.</returns>
/// <remarks>
/// This respects the portion of the specification that indicates
/// that build metadata should not impact precedence by returning
/// true for versions that differ only in that field.
/// </remarks>
public static bool operator <=(SemanticVersion left, SemanticVersion right)
{
if (left is null)
{
return !(right is null);
}
return left.CompareTo(right, out bool isDifferentInBuildMetadataOnly) <= 0 || isDifferentInBuildMetadataOnly;
}
/// <summary>
/// Determines whether the first version has higher precedence than the second version.
/// </summary>
/// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param>
/// <returns>true if the first version has higher precedence than the second, false otherwise.</returns>
/// <remarks>
/// This respects the portion of the specification that indicates
/// that build metadata should not impact precedence by returning
/// false for versions that differ only in that field.
/// </remarks>
public static bool operator >(SemanticVersion left, SemanticVersion right)
{
if (left is null)
{
return false;
}
return left.CompareTo(right, out bool isDifferentInBuildMetadataOnly) > 0 && !isDifferentInBuildMetadataOnly;
}
/// <summary>
/// Determines whether the first version has higher or equal precedence than the second version.
/// </summary>
/// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param>
/// <returns>true if the first version has higher or equal precedence than the second, false otherwise.</returns>
/// <remarks>
/// This respects the portion of the specification that indicates
/// that build metadata should not impact precedence by returning
/// true for versions that differ only in that field.
/// </remarks>
public static bool operator >=(SemanticVersion left, SemanticVersion right)
{
if (left is null)
{
return right is null;
}
return left.CompareTo(right, out bool isDifferentInBuildMetadataOnly) >= 0 || isDifferentInBuildMetadataOnly;
}
private int CompareBuildMetadata(SemanticVersion other)
{
//Even though the spec says to ignore this (http://semver.org/#spec-item-10),
// a differentiation on this value is required in order to make a comparison
// sorts stable when using CompareTo(object) or CompareTo(SemanticVersion).
// However, the result of this portion of the comparison is ignored by the
// >, >=, <, <=, == and != operators
//
if (BuildMetadata != null)
{
if (other.BuildMetadata != null)
{
return StringComparer.OrdinalIgnoreCase.Compare(BuildMetadata, other.BuildMetadata);
}
return 1;
}
else if (other.BuildMetadata != null)
{
return -1;
}
return 0;
}
//Must apply the following rules to the prerelease section (per http://semver.org/#spec-item-11)
// * Identifiers consisting only of digits are compared numerically, others lexically
// * There's a slight divergence here from the spec in that digit-only segments
// that have a leading 0 (and more than one digit) are compared lexically
// instead of numerically as they're in violation of what's considered to
// be a valid numeric segment as defined in http://semver.org/#spec-item-9
// * If a numeric segment is compared to a non-numeric segment, the numeric segment
// is considered to be the lesser
// * If the two prerelease values, when divided into sections by periods, have a
// different number of segments (m and n, where m is a smaller number than n)
// and the first m segments of each prerelease value compare as being equal,
// the value with the greater number of segments (the one with n segments) is
// considered greater
private int CompareToPrereleaseInfo(string other)
{
if (string.Equals(PrereleaseInfo, other, StringComparison.OrdinalIgnoreCase))
{
return 0;
}
string[] thisPrerelease = PrereleaseInfo.Split('.');
string[] otherPrerelease = other.Split('.');
for (int i = 0; i < thisPrerelease.Length && i < otherPrerelease.Length; ++i)
{
int segmentCompare = CompareToPrereleaseInfoSegment(thisPrerelease[i], otherPrerelease[i]);
if (segmentCompare != 0)
{
return segmentCompare;
}
}
return thisPrerelease.Length.CompareTo(otherPrerelease.Length);
}
private static int CompareToPrereleaseInfoSegment(string left, string right)
{
if (IsNumericSegment(left, out bool ignored))
{
if (IsNumericSegment(right, out ignored))
{
int us = int.Parse(left, NumberStyles.None, CultureInfo.InvariantCulture);
int them = int.Parse(right, NumberStyles.None, CultureInfo.InvariantCulture);
int numericCompare = us.CompareTo(them);
if (numericCompare != 0)
{
return numericCompare;
}
}
else
{
return -1;
}
}
else if (IsNumericSegment(right, out ignored))
{
return 1;
}
int segmentCompare = StringComparer.OrdinalIgnoreCase.Compare(left, right);
if (segmentCompare != 0)
{
return segmentCompare;
}
return 0;
}
private int CompareVersionInformation(SemanticVersion other)
{
int majorCompare = Major.CompareTo(other.Major);
if (majorCompare != 0)
{
return majorCompare;
}
int minorCompare = Minor.CompareTo(other.Minor);
if (minorCompare != 0)
{
return minorCompare;
}
int patchCompare = Patch.CompareTo(other.Patch);
if (patchCompare != 0)
{
return patchCompare;
}
return 0;
}
private int ComparePrereleaseInfo(SemanticVersion other)
{
if (PrereleaseInfo != null)
{
if (other.PrereleaseInfo != null)
{
//Both exist, return the comparison result
return CompareToPrereleaseInfo(other.PrereleaseInfo);
}
//prerelease < stable
return -1;
}
else if (other.PrereleaseInfo != null)
{
//stable > prerelease
return 1;
}
//both are stable
return 0;
}
//Determines whether a numeric segment is valid per the rules in
// http://semver.org/#spec-item-9 and http://semver.org/#spec-item-2
private static bool IsNumericSegment(string segment, out bool isInvalidBecauseOfLeadingZero)
{
if (segment.Length == 0)
{
isInvalidBecauseOfLeadingZero = false;
return false;
}
bool isNumeric = true;
for (int i = 0; isNumeric && i < segment.Length; ++i)
{
isNumeric &= segment[i] >= '0' && segment[i] <= '9';
}
bool doesNotHaveLeadingZero = segment.Length == 1 || segment[0] != '0';
isInvalidBecauseOfLeadingZero = !doesNotHaveLeadingZero;
return isNumeric && doesNotHaveLeadingZero;
}
private static bool IsolateVersionRange(string source, int start, ref int end)
{
for (end = start + 1; end < source.Length && source[end] >= '0' && source[end] <= '9'; ++end)
{
}
return !(end == start + 1 || (source[start + 1] == '0' && end - start - 1 > 1));
}
private static bool IsCharacterValidForMetadataSection(char c)
{
return c == '-' || c == '.' ||
(c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9');
}
private static bool IsValidMetadataSection(string source, int start, int afterEnd)
{
for (int i = start; i < afterEnd; ++i)
{
if (!IsCharacterValidForMetadataSection(source[i]))
{
return false;
}
}
return true;
}
private static bool TryParsePrereleaseAndBuildMetadata(string source, int majorEnd, int minorEnd, int patchEnd, int tail, out SemanticVersion version)
{
int major = int.Parse(source.Substring(0, majorEnd), NumberStyles.None, CultureInfo.InvariantCulture);
int minor = minorEnd > majorEnd ? int.Parse(source.Substring(majorEnd + 1, minorEnd - majorEnd - 1), NumberStyles.None, CultureInfo.InvariantCulture) : 0;
int patch = patchEnd > minorEnd ? int.Parse(source.Substring(minorEnd + 1, patchEnd - minorEnd - 1), NumberStyles.None, CultureInfo.InvariantCulture) : 0;
string prerelease = null;
string metadata = null;
if (tail < source.Length && !(source[tail] == '-' || source[tail] == '+'))
{
version = null;
return false;
}
if (!ValidateAndExtractPrereleaseSection(source, ref tail, out prerelease))
{
version = null;
return false;
}
if (!ValidateAndExtractBuildMetadataSection(source, tail, out metadata))
{
version = null;
return false;
}
version = new SemanticVersion(source, major, minor, patch, prerelease, metadata);
return true;
}
private static bool TryParseSegment(string source, ref int nextDot, out int value)
{
nextDot = source.IndexOf('.', nextDot);
if (nextDot < 0 || nextDot == source.Length - 1)
{
value = 0;
return false;
}
string segment = source.Substring(0, nextDot);
if (string.IsNullOrWhiteSpace(segment)
|| (segment.Length > 1 && segment[0] == '0')
|| !int.TryParse(segment, NumberStyles.None, CultureInfo.InvariantCulture, out value)
|| value < 0)
{
value = 0;
return false;
}
return true;
}
private static bool ValidateAndExtractBuildMetadataSection(string source, int tail, out string metadata)
{
if (tail < source.Length && source[tail] == '+')
{
if (tail == source.Length - 1 || !IsValidMetadataSection(source, tail + 1, source.Length))
{
metadata = null;
return false;
}
metadata = source.Substring(tail + 1);
return true;
}
metadata = null;
return true;
}
private static bool ValidateAndExtractPrereleaseSection(string source, ref int tail, out string prerelease)
{
if (tail < source.Length && source[tail] == '-')
{
int end = source.IndexOf('+', tail);
if (end < 0)
{
end = source.Length;
}
if (tail == end - 1)
{
prerelease = null;
return false;
}
if (!IsValidMetadataSection(source, tail + 1, end))
{
prerelease = null;
return false;
}
prerelease = source.Substring(tail + 1, end - tail - 1);
if (!ValidateAllDigitOnlySegmentsAreWellFormed(prerelease))
{
prerelease = null;
return false;
}
tail = end;
return true;
}
prerelease = null;
return true;
}
private static bool ValidateAllDigitOnlySegmentsAreWellFormed(string prerelease)
{
string[] parts = prerelease.Split('.');
for (int i = 0; i < parts.Length; ++i)
{
if (!IsNumericSegment(parts[i], out bool isInvalidBecauseOfLeadingZero) && isInvalidBecauseOfLeadingZero)
{
return false;
}
}
return true;
}
}
}
| |
// <copyright file="Precision.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
#if PORTABLE
using System.Runtime.InteropServices;
#endif
namespace MathNet.Numerics
{
/// <summary>
/// Support Interface for Precision Operations (like AlmostEquals).
/// </summary>
/// <typeparam name="T">Type of the implementing class.</typeparam>
public interface IPrecisionSupport<in T>
{
/// <summary>
/// Returns a Norm of a value of this type, which is appropriate for measuring how
/// close this value is to zero.
/// </summary>
/// <returns>A norm of this value.</returns>
double Norm();
/// <summary>
/// Returns a Norm of the difference of two values of this type, which is
/// appropriate for measuring how close together these two values are.
/// </summary>
/// <param name="otherValue">The value to compare with.</param>
/// <returns>A norm of the difference between this and the other value.</returns>
double NormOfDifference(T otherValue);
}
/// <summary>
/// Utilities for working with floating point numbers.
/// </summary>
/// <remarks>
/// <para>
/// Useful links:
/// <list type="bullet">
/// <item>
/// http://docs.sun.com/source/806-3568/ncg_goldberg.html#689 - What every computer scientist should know about floating-point arithmetic
/// </item>
/// <item>
/// http://en.wikipedia.org/wiki/Machine_epsilon - Gives the definition of machine epsilon
/// </item>
/// </list>
/// </para>
/// </remarks>
public static partial class Precision
{
/// <summary>
/// The number of binary digits used to represent the binary number for a double precision floating
/// point value. i.e. there are this many digits used to represent the
/// actual number, where in a number as: 0.134556 * 10^5 the digits are 0.134556 and the exponent is 5.
/// </summary>
const int DoubleWidth = 53;
/// <summary>
/// The number of binary digits used to represent the binary number for a single precision floating
/// point value. i.e. there are this many digits used to represent the
/// actual number, where in a number as: 0.134556 * 10^5 the digits are 0.134556 and the exponent is 5.
/// </summary>
const int SingleWidth = 24;
/// <summary>
/// The maximum relative precision of of double-precision floating numbers (64 bit)
/// </summary>
public static readonly double DoublePrecision = Math.Pow(2, -DoubleWidth);
/// <summary>
/// The maximum relative precision of of single-precision floating numbers (32 bit)
/// </summary>
public static readonly double SinglePrecision = Math.Pow(2, -SingleWidth);
/// <summary>
/// The number of significant double places of double-precision floating numbers (64 bit).
/// </summary>
public static readonly int DoubleDecimalPlaces = (int) Math.Floor(Math.Abs(Math.Log10(DoublePrecision)));
/// <summary>
/// The number of significant double places of single-precision floating numbers (32 bit).
/// </summary>
public static readonly int SingleDecimalPlaces = (int) Math.Floor(Math.Abs(Math.Log10(SinglePrecision)));
/// <summary>
/// Value representing 10 * 2^(-53) = 1.11022302462516E-15
/// </summary>
static readonly double DefaultDoubleAccuracy = DoublePrecision*10;
/// <summary>
/// Value representing 10 * 2^(-24) = 5.96046447753906E-07
/// </summary>
static readonly float DefaultSingleAccuracy = (float) (SinglePrecision*10);
/// <summary>
/// Returns the magnitude of the number.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The magnitude of the number.</returns>
public static int Magnitude(this double value)
{
// Can't do this with zero because the 10-log of zero doesn't exist.
if (value.Equals(0.0))
{
return 0;
}
// Note that we need the absolute value of the input because Log10 doesn't
// work for negative numbers (obviously).
double magnitude = Math.Log10(Math.Abs(value));
#if PORTABLE
var truncated = (int)Truncate(magnitude);
#else
var truncated = (int) Math.Truncate(magnitude);
#endif
// To get the right number we need to know if the value is negative or positive
// truncating a positive number will always give use the correct magnitude
// truncating a negative number will give us a magnitude that is off by 1 (unless integer)
return magnitude < 0d && truncated != magnitude
? truncated - 1
: truncated;
}
/// <summary>
/// Returns the magnitude of the number.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The magnitude of the number.</returns>
public static int Magnitude(this float value)
{
// Can't do this with zero because the 10-log of zero doesn't exist.
if (value.Equals(0.0f))
{
return 0;
}
// Note that we need the absolute value of the input because Log10 doesn't
// work for negative numbers (obviously).
var magnitude = Convert.ToSingle(Math.Log10(Math.Abs(value)));
#if PORTABLE
var truncated = (int)Truncate(magnitude);
#else
var truncated = (int) Math.Truncate(magnitude);
#endif
// To get the right number we need to know if the value is negative or positive
// truncating a positive number will always give use the correct magnitude
// truncating a negative number will give us a magnitude that is off by 1 (unless integer)
return magnitude < 0f && truncated != magnitude
? truncated - 1
: truncated;
}
/// <summary>
/// Returns the number divided by it's magnitude, effectively returning a number between -10 and 10.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The value of the number.</returns>
public static double ScaleUnitMagnitude(this double value)
{
if (value.Equals(0.0))
{
return value;
}
int magnitude = Magnitude(value);
return value*Math.Pow(10, -magnitude);
}
/// <summary>
/// Gets the equivalent <c>long</c> value for the given <c>double</c> value.
/// </summary>
/// <param name="value">The <c>double</c> value which should be turned into a <c>long</c> value.</param>
/// <returns>
/// The resulting <c>long</c> value.
/// </returns>
static long AsInt64(double value)
{
#if PORTABLE
return DoubleToInt64Bits(value);
#else
return BitConverter.DoubleToInt64Bits(value);
#endif
}
/// <summary>
/// Returns a 'directional' long value. This is a long value which acts the same as a double,
/// e.g. a negative double value will return a negative double value starting at 0 and going
/// more negative as the double value gets more negative.
/// </summary>
/// <param name="value">The input double value.</param>
/// <returns>A long value which is roughly the equivalent of the double value.</returns>
static long AsDirectionalInt64(double value)
{
// Convert in the normal way.
long result = AsInt64(value);
// Now find out where we're at in the range
// If the value is larger/equal to zero then we can just return the value
// if the value is negative we subtract long.MinValue from it.
return (result >= 0) ? result : (long.MinValue - result);
}
/// <summary>
/// Returns a 'directional' int value. This is a int value which acts the same as a float,
/// e.g. a negative float value will return a negative int value starting at 0 and going
/// more negative as the float value gets more negative.
/// </summary>
/// <param name="value">The input float value.</param>
/// <returns>An int value which is roughly the equivalent of the double value.</returns>
static int AsDirectionalInt32(float value)
{
// Convert in the normal way.
int result = FloatToInt32Bits(value);
// Now find out where we're at in the range
// If the value is larger/equal to zero then we can just return the value
// if the value is negative we subtract int.MinValue from it.
return (result >= 0) ? result : (int.MinValue - result);
}
/// <summary>
/// Increments a floating point number to the next bigger number representable by the data type.
/// </summary>
/// <param name="value">The value which needs to be incremented.</param>
/// <param name="count">How many times the number should be incremented.</param>
/// <remarks>
/// The incrementation step length depends on the provided value.
/// Increment(double.MaxValue) will return positive infinity.
/// </remarks>
/// <returns>The next larger floating point value.</returns>
public static double Increment(this double value, int count = 1)
{
if (double.IsInfinity(value) || double.IsNaN(value) || count == 0)
{
return value;
}
if (count < 0)
{
return Decrement(value, -count);
}
// Translate the bit pattern of the double to an integer.
// Note that this leads to:
// double > 0 --> long > 0, growing as the double value grows
// double < 0 --> long < 0, increasing in absolute magnitude as the double
// gets closer to zero!
// i.e. 0 - double.epsilon will give the largest long value!
long intValue = AsInt64(value);
if (intValue < 0)
{
intValue -= count;
}
else
{
intValue += count;
}
// Note that long.MinValue has the same bit pattern as -0.0.
if (intValue == long.MinValue)
{
return 0;
}
// Note that not all long values can be translated into double values. There's a whole bunch of them
// which return weird values like infinity and NaN
#if PORTABLE
return Int64BitsToDouble(intValue);
#else
return BitConverter.Int64BitsToDouble(intValue);
#endif
}
/// <summary>
/// Decrements a floating point number to the next smaller number representable by the data type.
/// </summary>
/// <param name="value">The value which should be decremented.</param>
/// <param name="count">How many times the number should be decremented.</param>
/// <remarks>
/// The decrementation step length depends on the provided value.
/// Decrement(double.MinValue) will return negative infinity.
/// </remarks>
/// <returns>The next smaller floating point value.</returns>
public static double Decrement(this double value, int count = 1)
{
if (double.IsInfinity(value) || double.IsNaN(value) || count == 0)
{
return value;
}
if (count < 0)
{
return Decrement(value, -count);
}
// Translate the bit pattern of the double to an integer.
// Note that this leads to:
// double > 0 --> long > 0, growing as the double value grows
// double < 0 --> long < 0, increasing in absolute magnitude as the double
// gets closer to zero!
// i.e. 0 - double.epsilon will give the largest long value!
long intValue = AsInt64(value);
// If the value is zero then we'd really like the value to be -0. So we'll make it -0
// and then everything else should work out.
if (intValue == 0)
{
// Note that long.MinValue has the same bit pattern as -0.0.
intValue = long.MinValue;
}
if (intValue < 0)
{
intValue += count;
}
else
{
intValue -= count;
}
// Note that not all long values can be translated into double values. There's a whole bunch of them
// which return weird values like infinity and NaN
#if PORTABLE
return Int64BitsToDouble(intValue);
#else
return BitConverter.Int64BitsToDouble(intValue);
#endif
}
/// <summary>
/// Forces small numbers near zero to zero, according to the specified absolute accuracy.
/// </summary>
/// <param name="a">The real number to coerce to zero, if it is almost zero.</param>
/// <param name="maxNumbersBetween">The maximum count of numbers between the zero and the number <paramref name="a"/>.</param>
/// <returns>
/// Zero if |<paramref name="a"/>| is fewer than <paramref name="maxNumbersBetween"/> numbers from zero, <paramref name="a"/> otherwise.
/// </returns>
public static double CoerceZero(this double a, int maxNumbersBetween)
{
return CoerceZero(a, (long) maxNumbersBetween);
}
/// <summary>
/// Forces small numbers near zero to zero, according to the specified absolute accuracy.
/// </summary>
/// <param name="a">The real number to coerce to zero, if it is almost zero.</param>
/// <param name="maxNumbersBetween">The maximum count of numbers between the zero and the number <paramref name="a"/>.</param>
/// <returns>
/// Zero if |<paramref name="a"/>| is fewer than <paramref name="maxNumbersBetween"/> numbers from zero, <paramref name="a"/> otherwise.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="maxNumbersBetween"/> is smaller than zero.
/// </exception>
public static double CoerceZero(this double a, long maxNumbersBetween)
{
if (maxNumbersBetween < 0)
{
throw new ArgumentOutOfRangeException("maxNumbersBetween");
}
if (double.IsInfinity(a) || double.IsNaN(a))
{
return a;
}
// We allow maxNumbersBetween between 0 and the number so
// we need to check if there a
if (NumbersBetween(0.0, a) <= (ulong) maxNumbersBetween)
{
return 0.0;
}
return a;
}
/// <summary>
/// Forces small numbers near zero to zero, according to the specified absolute accuracy.
/// </summary>
/// <param name="a">The real number to coerce to zero, if it is almost zero.</param>
/// <param name="maximumAbsoluteError">The absolute threshold for <paramref name="a"/> to consider it as zero.</param>
/// <returns>Zero if |<paramref name="a"/>| is smaller than <paramref name="maximumAbsoluteError"/>, <paramref name="a"/> otherwise.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="maximumAbsoluteError"/> is smaller than zero.
/// </exception>
public static double CoerceZero(this double a, double maximumAbsoluteError)
{
if (maximumAbsoluteError < 0)
{
throw new ArgumentOutOfRangeException("maximumAbsoluteError");
}
if (double.IsInfinity(a) || double.IsNaN(a))
{
return a;
}
if (Math.Abs(a) < maximumAbsoluteError)
{
return 0.0;
}
return a;
}
/// <summary>
/// Forces small numbers near zero to zero.
/// </summary>
/// <param name="a">The real number to coerce to zero, if it is almost zero.</param>
/// <returns>Zero if |<paramref name="a"/>| is smaller than 2^(-53) = 1.11e-16, <paramref name="a"/> otherwise.</returns>
public static double CoerceZero(this double a)
{
return CoerceZero(a, DoublePrecision);
}
/// <summary>
/// Determines the range of floating point numbers that will match the specified value with the given tolerance.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="maxNumbersBetween">The <c>ulps</c> difference.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="maxNumbersBetween"/> is smaller than zero.
/// </exception>
/// <returns>Tuple of the bottom and top range ends.</returns>
public static Tuple<double, double> RangeOfMatchingFloatingPointNumbers(this double value, long maxNumbersBetween)
{
// Make sure ulpDifference is non-negative
if (maxNumbersBetween < 1)
{
throw new ArgumentOutOfRangeException("maxNumbersBetween");
}
// If the value is infinity (positive or negative) just
// return the same infinity for the range.
if (double.IsInfinity(value))
{
return new Tuple<double, double>(value, value);
}
// If the value is a NaN then the range is a NaN too.
if (double.IsNaN(value))
{
return new Tuple<double, double>(double.NaN, double.NaN);
}
// Translate the bit pattern of the double to an integer.
// Note that this leads to:
// double > 0 --> long > 0, growing as the double value grows
// double < 0 --> long < 0, increasing in absolute magnitude as the double
// gets closer to zero!
// i.e. 0 - double.epsilon will give the largest long value!
long intValue = AsInt64(value);
#if PORTABLE
// We need to protect against over- and under-flow of the intValue when
// we start to add the ulpsDifference.
if (intValue < 0)
{
// Note that long.MinValue has the same bit pattern as
// -0.0. Therefore we're working in opposite direction (i.e. add if we want to
// go more negative and subtract if we want to go less negative)
var topRangeEnd = Math.Abs(long.MinValue - intValue) < maxNumbersBetween
// Got underflow, which can be fixed by splitting the calculation into two bits
// first get the remainder of the intValue after subtracting it from the long.MinValue
// and add that to the ulpsDifference. That way we'll turn positive without underflow
? Int64BitsToDouble(maxNumbersBetween + (long.MinValue - intValue))
// No problems here, move along.
: Int64BitsToDouble(intValue - maxNumbersBetween);
var bottomRangeEnd = Math.Abs(intValue) < maxNumbersBetween
// Underflow, which means we'd have to go further than a long would allow us.
// Also we couldn't translate it back to a double, so we'll return -Double.MaxValue
? -double.MaxValue
// intValue is negative. Adding the positive ulpsDifference means that it gets less negative.
// However due to the conversion way this means that the actual double value gets more negative :-S
: Int64BitsToDouble(intValue + maxNumbersBetween);
return new Tuple<double, double>(bottomRangeEnd, topRangeEnd);
}
else
{
// IntValue is positive
var topRangeEnd = long.MaxValue - intValue < maxNumbersBetween
// Overflow, which means we'd have to go further than a long would allow us.
// Also we couldn't translate it back to a double, so we'll return Double.MaxValue
? double.MaxValue
// No troubles here
: Int64BitsToDouble(intValue + maxNumbersBetween);
// Check the bottom range end for underflows
var bottomRangeEnd = intValue > maxNumbersBetween
// No problems here. IntValue is larger than ulpsDifference so we'll end up with a
// positive number.
? Int64BitsToDouble(intValue - maxNumbersBetween)
// Int value is bigger than zero but smaller than the ulpsDifference. So we'll need to deal with
// the reversal at the negative end
: Int64BitsToDouble(long.MinValue + (maxNumbersBetween - intValue));
return new Tuple<double, double>(bottomRangeEnd, topRangeEnd);
}
#else
// We need to protect against over- and under-flow of the intValue when
// we start to add the ulpsDifference.
if (intValue < 0)
{
// Note that long.MinValue has the same bit pattern as
// -0.0. Therefore we're working in opposite direction (i.e. add if we want to
// go more negative and subtract if we want to go less negative)
var topRangeEnd = Math.Abs(long.MinValue - intValue) < maxNumbersBetween
// Got underflow, which can be fixed by splitting the calculation into two bits
// first get the remainder of the intValue after subtracting it from the long.MinValue
// and add that to the ulpsDifference. That way we'll turn positive without underflow
? BitConverter.Int64BitsToDouble(maxNumbersBetween + (long.MinValue - intValue))
// No problems here, move along.
: BitConverter.Int64BitsToDouble(intValue - maxNumbersBetween);
var bottomRangeEnd = Math.Abs(intValue) < maxNumbersBetween
// Underflow, which means we'd have to go further than a long would allow us.
// Also we couldn't translate it back to a double, so we'll return -Double.MaxValue
? -double.MaxValue
// intValue is negative. Adding the positive ulpsDifference means that it gets less negative.
// However due to the conversion way this means that the actual double value gets more negative :-S
: BitConverter.Int64BitsToDouble(intValue + maxNumbersBetween);
return new Tuple<double, double>(bottomRangeEnd, topRangeEnd);
}
else
{
// IntValue is positive
var topRangeEnd = long.MaxValue - intValue < maxNumbersBetween
// Overflow, which means we'd have to go further than a long would allow us.
// Also we couldn't translate it back to a double, so we'll return Double.MaxValue
? double.MaxValue
// No troubles here
: BitConverter.Int64BitsToDouble(intValue + maxNumbersBetween);
// Check the bottom range end for underflows
var bottomRangeEnd = intValue > maxNumbersBetween
// No problems here. IntValue is larger than ulpsDifference so we'll end up with a
// positive number.
? BitConverter.Int64BitsToDouble(intValue - maxNumbersBetween)
// Int value is bigger than zero but smaller than the ulpsDifference. So we'll need to deal with
// the reversal at the negative end
: BitConverter.Int64BitsToDouble(long.MinValue + (maxNumbersBetween - intValue));
return new Tuple<double, double>(bottomRangeEnd, topRangeEnd);
}
#endif
}
/// <summary>
/// Returns the floating point number that will match the value with the tolerance on the maximum size (i.e. the result is
/// always bigger than the value)
/// </summary>
/// <param name="value">The value.</param>
/// <param name="maxNumbersBetween">The <c>ulps</c> difference.</param>
/// <returns>The maximum floating point number which is <paramref name="maxNumbersBetween"/> larger than the given <paramref name="value"/>.</returns>
public static double MaximumMatchingFloatingPointNumber(this double value, long maxNumbersBetween)
{
return RangeOfMatchingFloatingPointNumbers(value, maxNumbersBetween).Item2;
}
/// <summary>
/// Returns the floating point number that will match the value with the tolerance on the minimum size (i.e. the result is
/// always smaller than the value)
/// </summary>
/// <param name="value">The value.</param>
/// <param name="maxNumbersBetween">The <c>ulps</c> difference.</param>
/// <returns>The minimum floating point number which is <paramref name="maxNumbersBetween"/> smaller than the given <paramref name="value"/>.</returns>
public static double MinimumMatchingFloatingPointNumber(this double value, long maxNumbersBetween)
{
return RangeOfMatchingFloatingPointNumbers(value, maxNumbersBetween).Item1;
}
/// <summary>
/// Determines the range of <c>ulps</c> that will match the specified value with the given tolerance.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="relativeDifference">The relative difference.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="relativeDifference"/> is smaller than zero.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="value"/> is <c>double.PositiveInfinity</c> or <c>double.NegativeInfinity</c>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="value"/> is <c>double.NaN</c>.
/// </exception>
/// <returns>
/// Tuple with the number of ULPS between the <c>value</c> and the <c>value - relativeDifference</c> as first,
/// and the number of ULPS between the <c>value</c> and the <c>value + relativeDifference</c> as second value.
/// </returns>
public static Tuple<long, long> RangeOfMatchingNumbers(this double value, double relativeDifference)
{
// Make sure the relative is non-negative
if (relativeDifference < 0)
{
throw new ArgumentOutOfRangeException("relativeDifference");
}
// If the value is infinity (positive or negative) then
// we can't determine the range.
if (double.IsInfinity(value))
{
throw new ArgumentOutOfRangeException("value");
}
// If the value is a NaN then we can't determine the range.
if (double.IsNaN(value))
{
throw new ArgumentOutOfRangeException("value");
}
// If the value is zero (0.0) then we can't calculate the relative difference
// so return the ulps counts for the difference.
if (value.Equals(0))
{
var v = AsInt64(relativeDifference);
return new Tuple<long, long>(v, v);
}
// Calculate the ulps for the maximum and minimum values
// Note that these can overflow
long max = AsDirectionalInt64(value + (relativeDifference*Math.Abs(value)));
long min = AsDirectionalInt64(value - (relativeDifference*Math.Abs(value)));
// Calculate the ulps from the value
long intValue = AsDirectionalInt64(value);
// Determine the ranges
return new Tuple<long, long>(Math.Abs(intValue - min), Math.Abs(max - intValue));
}
/// <summary>
/// Evaluates the count of numbers between two double numbers
/// </summary>
/// <param name="a">The first parameter.</param>
/// <param name="b">The second parameter.</param>
/// <remarks>The second number is included in the number, thus two equal numbers evaluate to zero and two neighbor numbers evaluate to one. Therefore, what is returned is actually the count of numbers between plus 1.</remarks>
/// <returns>The number of floating point values between <paramref name="a"/> and <paramref name="b"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="a"/> is <c>double.PositiveInfinity</c> or <c>double.NegativeInfinity</c>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="a"/> is <c>double.NaN</c>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="b"/> is <c>double.PositiveInfinity</c> or <c>double.NegativeInfinity</c>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if <paramref name="b"/> is <c>double.NaN</c>.
/// </exception>
[CLSCompliant(false)]
public static ulong NumbersBetween(this double a, double b)
{
if (double.IsNaN(a) || double.IsInfinity(a))
{
throw new ArgumentOutOfRangeException("a");
}
if (double.IsNaN(b) || double.IsInfinity(b))
{
throw new ArgumentOutOfRangeException("b");
}
// Calculate the ulps for the maximum and minimum values
// Note that these can overflow
long intA = AsDirectionalInt64(a);
long intB = AsDirectionalInt64(b);
// Now find the number of values between the two doubles. This should not overflow
// given that there are more long values than there are double values
return (a >= b) ? (ulong) (intA - intB) : (ulong) (intB - intA);
}
/// <summary>
/// Evaluates the minimum distance to the next distinguishable number near the argument value.
/// </summary>
/// <param name="value">The value used to determine the minimum distance.</param>
/// <returns>
/// Relative Epsilon (positive double or NaN).
/// </returns>
/// <remarks>Evaluates the <b>negative</b> epsilon. The more common positive epsilon is equal to two times this negative epsilon.</remarks>
/// <seealso cref="PositiveEpsilonOf(double)"/>
public static double EpsilonOf(this double value)
{
if (double.IsInfinity(value) || double.IsNaN(value))
{
return double.NaN;
}
#if PORTABLE
long signed64 = DoubleToInt64Bits(value);
if (signed64 == 0)
{
signed64++;
return Int64BitsToDouble(signed64) - value;
}
if (signed64-- < 0)
{
return Int64BitsToDouble(signed64) - value;
}
return value - Int64BitsToDouble(signed64);
#else
long signed64 = BitConverter.DoubleToInt64Bits(value);
if (signed64 == 0)
{
signed64++;
return BitConverter.Int64BitsToDouble(signed64) - value;
}
if (signed64-- < 0)
{
return BitConverter.Int64BitsToDouble(signed64) - value;
}
return value - BitConverter.Int64BitsToDouble(signed64);
#endif
}
/// <summary>
/// Evaluates the minimum distance to the next distinguishable number near the argument value.
/// </summary>
/// <param name="value">The value used to determine the minimum distance.</param>
/// <returns>Relative Epsilon (positive double or NaN)</returns>
/// <remarks>Evaluates the <b>positive</b> epsilon. See also <see cref="EpsilonOf"/></remarks>
/// <seealso cref="EpsilonOf(double)"/>
public static double PositiveEpsilonOf(this double value)
{
return 2*EpsilonOf(value);
}
/// <summary>
/// Converts a float valut to a bit array stored in an int.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>The bit array.</returns>
static int FloatToInt32Bits(float value)
{
return BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
}
#if PORTABLE
static long DoubleToInt64Bits(double value)
{
var union = new DoubleLongUnion {Double = value};
return union.Int64;
}
static double Int64BitsToDouble(long value)
{
var union = new DoubleLongUnion {Int64 = value};
return union.Double;
}
static double Truncate(double value)
{
return value >= 0.0 ? Math.Floor(value) : Math.Ceiling(value);
}
[StructLayout(LayoutKind.Explicit)]
struct DoubleLongUnion
{
[FieldOffset(0)]
public double Double;
[FieldOffset(0)]
public long Int64;
}
#endif
}
}
| |
using System;
using System.Xml;
using System.Collections;
using System.IO;
using System.Text;
using System.Net;
using System.Diagnostics;
namespace Sgml
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class TestSuite
{
int tests = 0;
int passed = 0;
bool domain = false;
bool crawl = false;
bool debug = false;
bool basify = false;
bool testdoc = false;
bool teststream = false;
string proxy = null;
Encoding encoding = null;
string output = null;
bool formatted = false;
bool noxmldecl = false;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args) {
TestSuite suite = new TestSuite();
suite.ParseCommandLine(args);
suite.Run();
}
void ParseCommandLine(string[] args) {
for (int i = 0; i < args.Length; i++){
string arg = args[i];
if (arg[0] == '-'){
switch (arg.Substring(1)){
case "debug":
debug = true;
break;
case "base":
basify = true;
break;
case "crawl":
crawl = true;
if (args[++i] == "domain")
domain = true;
break;
case "testdoc":
testdoc = true;
break;
case "teststream":
teststream = true;
break;
}
}
}
}
void Run(){
Uri baseUri = new Uri(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
RunTest(baseUri, "..\\..\\html.suite");
RunTest(baseUri, "..\\..\\ofx.suite");
RegressionTest1();
return;
}
void RunTest(Uri baseUri, string inputUri) {
Uri resolved = new Uri(baseUri, inputUri);
string path = resolved.LocalPath;
this.passed = 0;
this.tests = 0;
SgmlReader reader = new SgmlReader();
RunTest(reader, path);
Console.WriteLine("{0} Tests passed", this.passed);
if (this.passed != this.tests) {
Console.WriteLine("{0} Tests failed", this.tests-this.passed);
}
Console.WriteLine();
return;
}
/**************************************************************************
* Run a test suite. Tests suites are organized into expected input/output
* blocks separated by back quotes (`). It runs the input and compares it
* with the expected output and reports any failures.
**************************************************************************/
void RunTest(SgmlReader reader, string file) {
Console.WriteLine(file);
StreamReader sr = new StreamReader(file);
StringBuilder input = new StringBuilder();
StringBuilder expectedOutput = new StringBuilder();
StringBuilder current = null;
StringBuilder args = new StringBuilder();
Uri baseUri = new Uri(new Uri(Directory.GetCurrentDirectory()+"\\"), file);
reader.SetBaseUri(baseUri.AbsoluteUri);
int start = 1;
int line = 1;
int pos = 1;
bool skipToEOL = false;
bool readArgs = false;
int i;
do {
i = sr.Read();
char ch = (char)i;
if (pos == 1 && ch == '`') {
if (current == null) {
current = input;
current.Length = 0;
readArgs = true;
} else if (current == input) {
current = expectedOutput;
}
else {
RunTest(reader, start, args.ToString(), input.ToString(), expectedOutput.ToString());
start = line;
input.Length = 0;
args.Length = 0;
expectedOutput.Length = 0;
current = input;
readArgs = true;
}
skipToEOL = true;
} else {
if (current != null) {
if (readArgs){
args.Append(ch);
} else if (!skipToEOL){
current.Append(ch);
}
}
if (ch == '\r') {
line++; pos = 1;
if (sr.Peek() == '\n') {
i = sr.Read();
if (!skipToEOL) current.Append((char)i);
if (readArgs) args.Append(ch);
}
skipToEOL = false;
readArgs = false;
} else if (ch == '\n'){
skipToEOL = false;
readArgs = false;
line++; pos = 1;
}
}
} while (i != -1);
if (current.Length>0 && expectedOutput.Length>0) {
RunTest(reader, start, args.ToString(), input.ToString(), expectedOutput.ToString());
}
}
void RunTest(SgmlReader reader, int line, string args, string input, string expectedOutput){
bool testdoc = false;
foreach (string arg in args.Split(' ')){
string sarg = arg.Trim();
if (sarg.Length==0) continue;
if (sarg[0] == '-'){
switch (sarg.Substring(1)){
case "html":
reader.DocType = "html";
break;
case "lower":
reader.CaseFolding = CaseFolding.ToLower;
break;
case "upper":
reader.CaseFolding = CaseFolding.ToUpper;
break;
case "testdoc":
testdoc = true;
break;
}
}
}
this.tests++;
reader.InputStream = new StringReader(input);
reader.WhitespaceHandling = WhitespaceHandling.None;
StringWriter output = new StringWriter();
XmlTextWriter w = new XmlTextWriter(output);
w.Formatting = Formatting.Indented;
if (testdoc) {
XmlDocument doc = new XmlDocument();
doc.Load(reader);
doc.WriteTo(w);
} else {
reader.Read();
while (!reader.EOF) {
w.WriteNode(reader, true);
}
}
w.Close();
string actualOutput = output.ToString();
if (actualOutput.Trim() != expectedOutput.Trim()) {
Console.WriteLine("ERROR: Test failed on line {0}", line);
Console.WriteLine("---- Expected output");
Console.WriteLine(expectedOutput);
Console.WriteLine("---- Actual output");
Console.WriteLine(actualOutput);
} else {
this.passed++;
}
}
void Process(SgmlReader reader, string uri, bool loadAsStream) {
if (uri == null) {
reader.InputStream = Console.In;
}
else if (loadAsStream) {
Uri location = new Uri(uri);
if (location.IsFile) {
reader.InputStream = new StreamReader(uri);
} else {
WebRequest wr = WebRequest.Create(location);
reader.InputStream = new StreamReader(wr.GetResponse().GetResponseStream());
}
} else {
reader.Href = uri;
}
if (debug) {
Debug(reader);
reader.Close();
return;
}
if (crawl) {
StartCrawl(reader, uri, basify);
return;
}
if (this.encoding == null) {
this.encoding = reader.GetEncoding();
}
XmlTextWriter w = null;
if (output != null) {
w = new XmlTextWriter(output, this.encoding);
}
else {
w = new XmlTextWriter(Console.Out);
}
if (formatted) w.Formatting = Formatting.Indented;
if (!noxmldecl) {
w.WriteStartDocument();
}
if (testdoc) {
XmlDocument doc = new XmlDocument();
try {
doc.Load(reader);
doc.WriteTo(w);
} catch (XmlException e) {
Console.WriteLine("Error:" + e.Message);
Console.WriteLine("at line " + e.LineNumber + " column " + e.LinePosition);
}
} else {
reader.Read();
while (!reader.EOF) {
w.WriteNode(reader, true);
}
}
w.Flush();
w.Close();
}
/***************************************************************************
* Useful debugging code...
* **************************************************************************/
void StartCrawl(SgmlReader reader, string uri, bool basify) {
Console.WriteLine("Loading '"+reader.BaseURI+"'");
XmlDocument doc = new XmlDocument();
try {
doc.XmlResolver = null; // don't do any downloads!
doc.Load(reader);
}
catch (Exception e) {
Console.WriteLine("Error loading document\n"+e.Message);
}
reader.Close();
if (basify) {
// html and head are option, if they are there use them otherwise not.
XmlElement be = (XmlElement)doc.SelectSingleNode("//base");
if (be == null) {
be = doc.CreateElement("base");
be.SetAttribute("href", doc.BaseURI);
XmlElement head = (XmlElement)doc.SelectSingleNode("//head");
if (head != null) {
head.InsertBefore(be, head.FirstChild);
}
else {
XmlElement html = (XmlElement)doc.SelectSingleNode("//html");
if (html != null) html.InsertBefore(be, html.FirstChild);
else doc.DocumentElement.InsertBefore(be, doc.DocumentElement.FirstChild);
}
}
}
try {
Crawl(reader.Dtd, doc, reader.ErrorLog);
}
catch (Exception e) {
Console.WriteLine("Uncaught exception: " + e.Message);
}
}
enum NodeTypeFlags {
None = 0,
Element = 0x1,
Attribute = 0x2,
Text = 0x4,
CDATA = 0x8,
EntityReference = 0x10,
Entity = 0x20,
ProcessingInstruction = 0x40,
Comment = 0x80,
Document = 0x100,
DocumentType = 0x200,
DocumentFragment = 0x400,
Notation = 0x800,
Whitespace = 0x1000,
SignificantWhitespace = 0x2000,
EndElement = 0x4000,
EndEntity = 0x8000,
filler = 0x10000,
XmlDeclaration = 0x20000,
}
NodeTypeFlags[] NodeTypeMap = new NodeTypeFlags[19] {
NodeTypeFlags.None,
NodeTypeFlags.Element,
NodeTypeFlags.Attribute,
NodeTypeFlags.Text,
NodeTypeFlags.CDATA,
NodeTypeFlags.EntityReference,
NodeTypeFlags.Entity,
NodeTypeFlags.ProcessingInstruction,
NodeTypeFlags.Comment,
NodeTypeFlags.Document,
NodeTypeFlags.DocumentType,
NodeTypeFlags.DocumentFragment,
NodeTypeFlags.Notation,
NodeTypeFlags.Whitespace,
NodeTypeFlags.SignificantWhitespace,
NodeTypeFlags.EndElement,
NodeTypeFlags.EndEntity,
NodeTypeFlags.filler,
NodeTypeFlags.XmlDeclaration,
};
void Debug(SgmlReader sr) {
NodeTypeFlags[] AllowedContentMap = new NodeTypeFlags[19] {
NodeTypeFlags.None, // none
NodeTypeFlags.Element | NodeTypeFlags.Attribute | NodeTypeFlags.Text | NodeTypeFlags.CDATA | NodeTypeFlags.EntityReference | NodeTypeFlags.ProcessingInstruction | NodeTypeFlags.Comment | NodeTypeFlags.Whitespace | NodeTypeFlags.SignificantWhitespace | NodeTypeFlags.EndElement, // element
NodeTypeFlags.Text | NodeTypeFlags.EntityReference, // attribute
NodeTypeFlags.None, // text
NodeTypeFlags.None, // cdata
NodeTypeFlags.None, // entity reference
NodeTypeFlags.None, // entity
NodeTypeFlags.None, // processing instruction
NodeTypeFlags.None, // comment
NodeTypeFlags.Comment | NodeTypeFlags.DocumentType | NodeTypeFlags.Element | NodeTypeFlags.EndElement | NodeTypeFlags.ProcessingInstruction | NodeTypeFlags.Whitespace | NodeTypeFlags.SignificantWhitespace | NodeTypeFlags.XmlDeclaration, // document
NodeTypeFlags.None, // document type
NodeTypeFlags.None, // document fragment (not expecting these)
NodeTypeFlags.None, // notation
NodeTypeFlags.None, // whitespace
NodeTypeFlags.None, // signification whitespace
NodeTypeFlags.None, // end element
NodeTypeFlags.None, // end entity
NodeTypeFlags.None, // filler
NodeTypeFlags.None, // xml declaration.
};
Stack s = new Stack();
while (sr.Read()) {
if (sr.NodeType == XmlNodeType.EndElement) {
s.Pop();
}
if (s.Count > 0) {
XmlNodeType pt = (XmlNodeType)s.Peek();
NodeTypeFlags p = NodeTypeMap[(int)pt];
NodeTypeFlags f = NodeTypeMap[(int)sr.NodeType];
if ((AllowedContentMap[(int)pt]& f) != f) {
Console.WriteLine("Invalid content!!");
}
}
if (s.Count != sr.Depth-1) {
Console.WriteLine("Depth is wrong!");
}
if ( (sr.NodeType == XmlNodeType.Element && !sr.IsEmptyElement) ||
sr.NodeType == XmlNodeType.Document) {
s.Push(sr.NodeType);
}
for (int i = 1; i < sr.Depth; i++)
Console.Write(" ");
Console.Write(sr.NodeType.ToString() + " " + sr.Name);
if (sr.NodeType == XmlNodeType.Element && sr.AttributeCount > 0) {
sr.MoveToAttribute(0);
Console.Write(" (" + sr.Name+"="+sr.Value + ")");
sr.MoveToElement();
}
if (sr.Value != null) {
Console.Write(" " + sr.Value.Replace("\n"," ").Replace("\r",""));
}
Console.WriteLine();
}
}
int depth = 0;
int count = 0;
Hashtable visited = new Hashtable();
bool Crawl(SgmlDtd dtd, XmlDocument doc, TextWriter log) {
depth++;
StringBuilder indent = new StringBuilder();
for (int i = 0; i < depth; i++)
indent.Append(" ");
count++;
Uri baseUri = new Uri(doc.BaseURI);
XmlElement baseElmt = (XmlElement)doc.SelectSingleNode("/html/head/base");
if (baseElmt != null) {
string href = baseElmt.GetAttribute("href");
if (href != "") {
try {
baseUri = new Uri(href);
}
catch (Exception ) {
Console.WriteLine("### Error parsing BASE href '"+href+"'");
}
}
}
foreach (XmlElement a in doc.SelectNodes("//a")) {
string href = a.GetAttribute("href");
if (href != "" && href != null && depth<5) {
Uri local = new Uri(baseUri, href);
if (domain && baseUri.Host != local.Host)
continue;
string ext = Path.GetExtension(local.AbsolutePath).ToLower();
if (ext == ".jpg" || ext == ".gif" || ext==".mpg")
continue;
string url = local.AbsoluteUri;
if (!visited.ContainsKey(url)) {
visited.Add(url, url);
log.WriteLine(indent+"Loading '"+url+"'");
log.Flush();
StreamReader stm = null;
try {
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Timeout = 10000;
if (proxy != null) wr.Proxy = new WebProxy(proxy);
wr.PreAuthenticate = false;
// Pass the credentials of the process.
wr.Credentials = CredentialCache.DefaultCredentials;
WebResponse resp = wr.GetResponse();
Uri actual = resp.ResponseUri;
if (actual.AbsoluteUri != url) {
local = new Uri(actual.AbsoluteUri);
log.WriteLine(indent+"Redirected to '"+actual.AbsoluteUri+"'");
log.Flush();
}
if (resp.ContentType != "text/html") {
log.WriteLine(indent+"Skipping ContentType="+resp.ContentType);
log.Flush();
resp.Close();
}
else {
stm = new StreamReader(resp.GetResponseStream());
}
}
catch (Exception e) {
log.WriteLine(indent+"### Error opening URL: " + e.Message);
log.Flush();
}
if (stm != null) {
SgmlReader reader = new SgmlReader();
reader.Dtd = dtd;
reader.SetBaseUri(local.AbsoluteUri);
reader.InputStream = stm;
reader.WebProxy = proxy;
XmlDocument d2 = new XmlDocument();
d2.XmlResolver = null; // don't do any downloads!
try {
d2.Load(reader);
reader.Close();
stm.Close();
if (!Crawl(dtd, d2, log))
return false;
}
catch (Exception e) {
log.WriteLine(indent+"### Error parsing document '"+local.AbsoluteUri+"', "+e.Message);
log.Flush();
reader.Close();
}
}
}
}
}
depth--;
return true;
}
void RegressionTest1() {
// Make sure we can do MoveToElement after reading multiple attributes.
SgmlReader r = new SgmlReader();
r.InputStream = new StringReader("<test id='10' x='20'><a/><!--comment-->test</test>");
if (r.Read()) {
while (r.MoveToNextAttribute()) {
Trace.WriteLine(r.Name);
}
if (r.MoveToElement()) {
Trace.WriteLine(r.ReadInnerXml());
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Views.Animations;
using Android.Graphics;
namespace Sino.Droid.AppMsg
{
public class AppMsg : Java.Lang.Object
{
public const int LENGTH_SHORT = 3000;
public const int LENGTH_LONG = 5000;
public const int LENGTH_STICKY = -1;
public const int PRIORITY_LOW = int.MinValue;
public const int PRIORITY_NORMAL = 0;
public const int PRIORITY_HIGH = int.MaxValue;
public const int TEXTSIZE = 17;
public static Style STYLE_ALERT = new Style(LENGTH_LONG, Color.White, Color.Red);
public static Style STYLE_CONFIRM = new Style(LENGTH_SHORT, Color.White, Color.Green);
public static Style STYLE_INFO = new Style(LENGTH_SHORT, Color.White, Color.Orange);
private Activity mActivity;
private int mDuration = LENGTH_SHORT;
private View mView;
private ViewGroup mParent;
private ViewGroup.LayoutParams mLayoutParams;
private bool mFloating;
public Animation mInAnimation, mOutAnimation;
private int mPriority = PRIORITY_NORMAL;
public AppMsg(Activity activity)
{
mActivity = activity;
}
public static AppMsg MakeText(Activity context, String text, Style style)
{
return MakeText(context, text, style, Resource.Layout.sino_appmsg_ui);
}
public static AppMsg MakeText(Activity context, String text, Style style, View.IOnClickListener clickListener)
{
return MakeText(context, text, style, Resource.Layout.sino_appmsg_ui);
}
public static AppMsg MakeText(Activity context, String text, Style style, float textSize)
{
return MakeText(context, text, style, Resource.Layout.sino_appmsg_ui, textSize);
}
public static AppMsg MakeText(Activity context, String text, Style style, float textSize, View.IOnClickListener clickListener)
{
return MakeText(context, text, style, Resource.Layout.sino_appmsg_ui, textSize, clickListener);
}
public static AppMsg MakeText(Activity context, String text, Style style, int layoutId)
{
LayoutInflater inflate = context.LayoutInflater;
View v = inflate.Inflate(layoutId, null);
return MakeText(context, text, style, v, true);
}
public static AppMsg MakeText(Activity context, String text, Style style, int layoutId, View.IOnClickListener clickListener)
{
LayoutInflater inflate = context.LayoutInflater;
View v = inflate.Inflate(layoutId, null);
return MakeText(context, text, style, v, true);
}
public static AppMsg MakeText(Activity context, String text, Style style, int layoutId, float textSize, View.IOnClickListener clickListener)
{
LayoutInflater inflate = context.LayoutInflater;
View v = inflate.Inflate(layoutId, null);
return MakeText(context, text, style, v, true, textSize, clickListener);
}
public static AppMsg MakeText(Activity context, String text, Style style, int layoutId, float textSize)
{
LayoutInflater inflate = context.LayoutInflater;
View v = inflate.Inflate(layoutId, null);
return MakeText(context, text, style, v, true, textSize);
}
public static AppMsg MakeText(Activity context, String text, Style style, View customViw)
{
return MakeText(context, text, style, customViw, false);
}
public static AppMsg MakeText(Activity context, String text, Style style, View customeView, View.IOnClickListener clickListener)
{
return MakeText(context, text, style, customeView, false, clickListener);
}
public static AppMsg MakeText(Activity context, String text, Style style, View view, bool floating)
{
return MakeText(context, text, style, view, floating, 0);
}
public static AppMsg MakeText(Activity context, String text, Style style, View view, bool floating, View.IOnClickListener clickListener)
{
return MakeText(context, text, style, view, floating, 0, clickListener);
}
private static AppMsg MakeText(Activity context, String text, Style style, View view, bool floating, float textSize)
{
AppMsg result = new AppMsg(context);
view.SetBackgroundColor(style.BackgroundColor);
TextView tv = view.FindViewById<TextView>(Android.Resource.Id.Message);
if (textSize > 0)
{
tv.SetTextSize(Android.Util.ComplexUnitType.Sp, textSize);
}
else
{
tv.SetTextSize(Android.Util.ComplexUnitType.Dip, TEXTSIZE);
}
tv.Text = text;
tv.SetTextColor(style.TextColor);
result.mView = view;
result.mDuration = style.Duration;
result.mFloating = floating;
return result;
}
private static AppMsg MakeText(Activity context, String text, Style style, View view, bool floating, float textSize, View.IOnClickListener clickListener)
{
AppMsg result = new AppMsg(context);
view.SetBackgroundColor(style.BackgroundColor);
view.Clickable = true;
TextView tv = view.FindViewById<TextView>(Android.Resource.Id.Message);
if (textSize > 0)
{
tv.SetTextSize(Android.Util.ComplexUnitType.Sp, textSize);
}
else
{
tv.SetTextSize(Android.Util.ComplexUnitType.Dip, TEXTSIZE);
}
tv.Text = text;
tv.SetTextColor(style.TextColor);
result.mView = view;
result.mDuration = style.Duration;
result.mFloating = floating;
view.SetOnClickListener(clickListener);
return result;
}
public static AppMsg MakeText(Activity context, int resId, Style style, View customView, bool floating)
{
return MakeText(context, context.Resources.GetText(resId), style, customView, floating);
}
public static AppMsg MakeText(Activity context, int resId, Style style)
{
return MakeText(context, context.Resources.GetText(resId), style);
}
public static AppMsg MakeText(Activity context, int resId, Style style, int layoutId)
{
return MakeText(context, context.Resources.GetText(resId), style, layoutId);
}
public void Show()
{
MsgManager manager = MsgManager.ObTain(mActivity);
manager.Add(this);
}
public bool IsShowing
{
get
{
if (mFloating)
{
return mView != null && mView.Parent != null;
}
else
{
return mView.Visibility == ViewStates.Visible;
}
}
}
public void Dismiss()
{
MsgManager.ObTain(mActivity).RemoveMsg(this);
}
public void Cancel()
{
MsgManager.ObTain(mActivity).ClearMsg(this);
}
public static void CancelAll()
{
MsgManager.ClearAll();
}
public static void CancelAll(Activity activity)
{
MsgManager.Release(activity);
}
public Activity Activity
{
get
{
return mActivity;
}
}
public View View
{
get
{
return mView;
}
set
{
mView = value;
}
}
public int Duration
{
get
{
return mDuration;
}
set
{
mDuration = value;
}
}
public void SetText(int resId)
{
SetText(mActivity.GetText(resId));
}
public void SetText(String s)
{
if (mView == null)
{
throw new ArgumentNullException("mView");
}
TextView tv = mView.FindViewById<TextView>(Android.Resource.Id.Message);
if (tv == null)
{
throw new ArgumentNullException("tv");
}
tv.Text = s;
}
public ViewGroup.LayoutParams LayoutParams
{
get
{
if (mLayoutParams == null)
{
mLayoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
}
return mLayoutParams;
}
set
{
mLayoutParams = value;
}
}
public AppMsg SetLayoutGravity(GravityFlags gravity)
{
mLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent, gravity);
return this;
}
public bool Floating
{
get
{
return mFloating;
}
set
{
mFloating = value;
}
}
public AppMsg SetAnimation(int inAnimation, int outAnimation)
{
return SetAnimation(AnimationUtils.LoadAnimation(mActivity, inAnimation),
AnimationUtils.LoadAnimation(mActivity, outAnimation));
}
public AppMsg SetAnimation(Animation inAnimation, Animation outAnimation)
{
mInAnimation = inAnimation;
mOutAnimation = outAnimation;
return this;
}
public int Priority
{
get
{
return mPriority;
}
set
{
mPriority = value;
}
}
public ViewGroup Parent
{
get
{
return mParent;
}
set
{
mParent = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Reflection;
using UnityEngine;
public class TutorialConfig
{
#region Constant
private const string filePath = "TutorialConfigs";
#endregion
#region Static
public static Dictionary<int, Tutorial> sTutorialDict = new Dictionary<int, Tutorial>();
public static bool LoadXML()
{
string content = ResourceManager.instance.GetAssetDirectly<string>(filePath);
if (content == null)
{
TextAsset ta = Resources.Load<TextAsset>(filePath);
if (ta != null)
{
return Load(ta.text);
}
}
else
{
return Load(content);
}
return false;
}
public static bool Load(string content)
{
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(content);
sTutorialDict.Clear();
foreach (XmlNode childNode in doc.LastChild.ChildNodes)
{
if (childNode.NodeType == XmlNodeType.Comment) continue;
int tutorialId = Convert.ToInt32(childNode.Attributes["ID"].Value);
string triggerExpr = childNode.Attributes["Triggers"].Value;
Tutorial t = new Tutorial(tutorialId, triggerExpr);
foreach (XmlNode stepNode in childNode.ChildNodes)
{
if (stepNode.NodeType == XmlNodeType.Comment) continue;
int stepId = Convert.ToInt32(stepNode.Attributes["ID"].Value);
TutorialStep s = new TutorialStep(stepId);
foreach (XmlNode actionNode in stepNode.ChildNodes)
{
if (actionNode.NodeType == XmlNodeType.Comment) continue;
string actionExpr = actionNode.InnerText;
if (string.IsNullOrEmpty(actionExpr) == false)
{
if (actionNode.Name == "OnResumeAction")
s.AddOnResumeAction(actionExpr);
else if (actionNode.Name == "Action")
s.AddAction(actionExpr);
else if (actionNode.Name == "PostStepAction")
s.AddPostStepAction(actionExpr);
else if (actionNode.Name == "NextStepCondition")
s.AddNextStepCondition(actionExpr);
}
}
t.AddTutorialStep(s);
}
sTutorialDict[tutorialId] = t;
}
return true;
}
catch
{
return false;
}
}
#endregion
}
public class Tutorial
{
public int tutorialId { get; private set; }
private List<TutorialStep> steps = new List<TutorialStep>();
private List<TutorialTrigger> triggers = new List<TutorialTrigger>();
public Tutorial(int id, string triggerExpr)
{
steps.Clear();
tutorialId = id;
ParseTriggerExpression(triggerExpr);
}
private void ParseTriggerExpression(string triggerExpr)
{
string[] triggerList = triggerExpr.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries);
foreach (string triggerStr in triggerList)
{
string trimmed = triggerStr.Trim();
int leftBracketPos = trimmed.IndexOf('(');
string triggerName = trimmed.Substring(0, leftBracketPos);
string triggerParameters = trimmed.Substring(leftBracketPos + 1).TrimEnd(')');
string[] triggerParameterList = triggerParameters.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
Type triggerType = Type.GetType(triggerName);
if (triggerType != null && triggerType.IsSubclassOf(typeof(TutorialTrigger)))
{
TutorialTrigger t = (TutorialTrigger)(Activator.CreateInstance(triggerType));
t.Initialize(triggerParameterList);
triggers.Add(t);
}
else
{
throw new NotImplementedException("Failed to find class " + triggerName + " which is inherited from class TutorialTrigger. Have you implemented it in file TutorialTriggers.cs?");
}
}
}
public void AddTutorialStep(TutorialStep step)
{
steps.Add(step);
}
public bool IsTriggered(Type triggerType, object data)
{
TutorialTrigger trigger = triggers.FirstOrDefault((TutorialTrigger t) => t.GetType() == triggerType);
if(trigger != null)
{
return trigger.IsTriggered(data);
}
else
{
return false;
}
}
public TutorialStep GetStep(int index)
{
if (index >= 0 && index < steps.Count)
return steps[index];
else
return null;
}
public int GetStepIndexById(int stepId)
{
int index = 0;
foreach (TutorialStep step in steps)
{
if (step.stepId == stepId)
{
return index;
}
else
{
index++;
}
}
return -1;
}
public TutorialStep GetStepById(int stepId)
{
return GetStep(GetStepIndexById(stepId));
}
}
public class TutorialStep
{
public int stepId { get; private set; }
List<string> onResumeActions = new List<string>();
List<string> actions = new List<string>();
List<string> postStepActions = new List<string>();
List<string> nextStepConditions = new List<string>();
public TutorialStep(int id)
{
actions.Clear();
stepId = id;
}
public void AddOnResumeAction(string actionExpr)
{
onResumeActions.Add(actionExpr);
}
public void AddAction(string actionExpr)
{
actions.Add(actionExpr);
}
public void AddPostStepAction(string actionExpr)
{
postStepActions.Add(actionExpr);
}
public void AddNextStepCondition(string conditionExpr)
{
nextStepConditions.Add(conditionExpr);
}
public void ExecuteOnResumeActions()
{
foreach (string actionExpr in onResumeActions)
{
ExecuteAction(actionExpr);
}
}
public void ExecuteActions()
{
foreach (string actionExpr in actions)
{
ExecuteAction(actionExpr);
}
}
public void ExecutePostStepActions()
{
foreach (string actionExpr in postStepActions)
{
ExecuteAction(actionExpr);
}
}
private void ExecuteAction(string actionExpr)
{
string trimmed = actionExpr.Trim();
int leftBracketPos = trimmed.IndexOf('(');
string actionName = trimmed.Substring(0, leftBracketPos);
string actionParameters = trimmed.Substring(leftBracketPos + 1).TrimEnd(')');
string[] actionParameterList = actionParameters.Split(new char[] { ',' }, StringSplitOptions.None);
MethodInfo mi = typeof(TutorialActions).GetMethod(actionName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
if (mi != null)
{
if (actionParameters != "")
mi.Invoke(null, new object[] { actionParameterList });
else
mi.Invoke(null, null);
}
else
{
throw new NotImplementedException("Failed to find method: " + actionName + ", have you implemented it in class TutorialActions?");
}
}
public bool CheckNextStepConditions()
{
foreach (string conditionExpr in nextStepConditions)
{
if (CheckNextStepCondition(conditionExpr) == false)
{
return false;
}
}
return true;
}
private bool CheckNextStepCondition(string conditionExpr)
{
string trimmed = conditionExpr.Trim();
int leftBracketPos = trimmed.IndexOf('(');
string conditionName = trimmed.Substring(0, leftBracketPos);
string conditionParameters = trimmed.Substring(leftBracketPos + 1).TrimEnd(')');
string[] conditionParameterList = conditionParameters.Split(new char[] { ',' }, StringSplitOptions.None);
MethodInfo mi = typeof(TutorialConditions).GetMethod(conditionName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
if (mi != null)
{
object result;
if (conditionParameters != "")
result = mi.Invoke(null, new object[] { conditionParameterList });
else
result = mi.Invoke(null, null);
return (bool)result;
}
else
{
throw new NotImplementedException("Failed to find method: " + conditionName + ", have you implemented it in class TutorialConditions?");
}
}
}
| |
//------------------------------------------------------------------------------
// Torque Game Builder
// Copyright (C) GarageGames.com, Inc.
//------------------------------------------------------------------------------
/// @class XML
/// Provides saving and loading support for the XML format.
///
/// @field fileObject The xmlDoc used for reading and writing.
/// @field filename The filename currently being written to or read from.
/// @field index Used when reading to store the element number that should
/// be read next when reading in arbitrary element names.
///
/// @see Persistence
/// @see xmlDoc
//package XMLPersistencePackage
//{
function XML::beginWrite( %this, %filename )
{
// Validate the file.
if( !isWriteableFileName( %filename ) )
{
error( "XML::beginWrite - Failed to write to file" @ %filename @ "." );
return false;
}
// Initialize the xmlDoc
%this.fileObject = new SimXMLDocument();
%this.fileObject.addHeader();
// Save the filename.
%this.filename = %filename;
// Success.
return true;
}
function XML::beginRead( %this, %filename )
{
// Initialize the xmlDoc.
%this.fileObject = new SimXMLDocument();
if( !%this.fileObject.loadFile( %filename ) )
return false;
// Start at element index 0.
%this.index = 0;
// This is a mock stack that holds the parent index.
%this.parentIndex = "";
return true;
}
function XML::endWrite( %this )
{
%this.fileObject.saveFile( %this.filename );
%this.fileObject.delete();
}
function XML::endRead( %this )
{
%this.fileObject.delete();
}
function XML::writeHeader( %this, %documentType, %target, %version, %creator )
{
%this.fileObject.addComment( "Torque Game Builder - http://www.torquepowered.com" );
%this.fileObject.addComment( "Type: " @ %documentType );
%this.fileObject.addComment( "Target: " @ %target );
%this.fileObject.addComment( "Version: " @ %version );
%this.fileObject.addComment( "Creator: Torque Game Builder" );
}
function XML::readHeader( %this )
{
%this.fileObject.readComment( 1 );
%documentType = %this.fileObject.readComment( 2 );
%target = %this.fileObject.readComment( 3 );
%version = %this.fileObject.readComment( 4 );
%creator = %this.fileObject.readComment( 5 );
%documentType = getSubStr( %documentType, 6, strlen( %documentType ) );
%target = getSubStr( %target, 8, strlen( %target ) );
%version = getSubStr( %version, 9, strlen( %version ) );
%creator = getSubStr( %creator, 9, strlen( %creator ) );
return %documentType TAB %target TAB %version TAB %creator;
}
function XML::writeDocument( %this, %document )
{
%document.save( %this );
// Write the file.
return %this.fileObject.saveFile( %this.filename );
}
function XML::readDocument( %this, %document )
{
// Make sure the document can be loaded.
if( !%document.isMethod( "load" ) )
return "";
%document.load( %this );
return %document;
}
function XML::writeClassBegin( %this, %class, %name )
{
%this.fileObject.pushNewElement( %class );
if( %name !$= "" )
%this.fileObject.setAttribute( "name", %name );
}
function XML::writeClassEnd( %this )
{
%this.fileObject.popElement();
}
function XML::readNextClass( %this )
{
%class = "";
%name = "";
if( %this.fileObject.pushChildElement( %this.index ) )
{
// Reset the index to 0 since we are stepping down a level in the
// heirarchy.
%this.parentIndex = %this.index SPC %this.parentIndex;
%this.index = 0;
%class = %this.fileObject.elementValue();
%name = %this.fileObject.attribute( "name" );
}
if( %class $= "" )
return "";
return trim( %class SPC %name );
}
function XML::readClassBegin( %this, %class, %index )
{
if( %this.fileObject.pushFirstChildElement( %class ) )
{
if( %index $= "" ) %index = 0;
for( %i = 0; %i < %index; %i++ )
{
if( !%this.fileObject.nextSiblingElement( %class ) )
{
%this.fileObject.popElement();
return false;
}
}
// Reset the index to 0 since we are stepping down a level in the
// heirarchy.
%this.parentIndex = %this.index SPC %this.parentIndex;
%this.index = 0;
return true;
}
return false;
}
function XML::readClassEnd( %this )
{
%this.fileObject.popElement();
%this.index = firstWord( %this.parentIndex ) + 1;
%this.parentIndex = removeWord( %this.parentIndex, 0 );
}
function XML::writeField( %this, %field, %value )
{
%this.fileObject.pushNewElement( %field );
%this.fileObject.addText( %value );
%this.fileObject.popElement();
}
function XML::readField( %this, %field )
{
%value = "";
if( %this.fileObject.pushFirstChildElement( %field ) )
{
%this.index++;
%value = %this.fileObject.getText();
%this.fileObject.popElement();
}
return %value;
}
function XML::writePoint2F( %this, %field, %value )
{
%this.fileObject.pushNewElement( %field );
%this.writeField( "X", getWord( %value, 0 ) );
%this.writeField( "Y", getWord( %value, 1 ) );
%this.fileObject.popElement();
}
function XML::readPoint2F( %this, %field )
{
%value = "";
if( %this.fileObject.pushFirstChildElement( %field ) )
{
// Store the index since readField will increment it twice.
%index = %this.index;
%value = %this.readField( "X" ) SPC %this.readField( "Y" );
%this.fileObject.popElement();
%this.index = %index + 1;
}
return %value;
}
function XML::writePoint3F( %this, %field, %value )
{
%this.fileObject.pushNewElement( %field );
%this.writeField( "X", getWord( %value, 0 ) );
%this.writeField( "Y", getWord( %value, 1 ) );
%this.writeField( "Z", getWord( %value, 2 ) );
%this.fileObject.popElement();
}
function XML::readPoint3F( %this, %field )
{
%value = "";
if( %this.fileObject.pushFirstChildElement( %field ) )
{
// Store the index since readField will increment it twice.
%index = %this.index;
%value = %this.readField( "X" ) SPC %this.readField( "Y" ) SPC %this.readField( "Z" );
%this.fileObject.popElement();
%this.index = %index + 1;
}
return %value;
}
function XML::writePoint4F( %this, %field, %value )
{
%this.fileObject.pushNewElement( %field );
%this.writeField( "X", getWord( %value, 0 ) );
%this.writeField( "Y", getWord( %value, 1 ) );
%this.writeField( "Z", getWord( %value, 2 ) );
%this.writeField( "W", getWord( %value, 3 ) );
%this.fileObject.popElement();
}
function XML::readPoint4F( %this, %field )
{
%value = "";
if( %this.fileObject.pushFirstChildElement( %field ) )
{
// Store the index since readField will increment it twice.
%index = %this.index;
%value = %this.readField( "X" ) SPC %this.readField( "Y" ) SPC %this.readField( "Z" ) SPC %this.readField( "W" );
%this.fileObject.popElement();
%this.index = %index + 1;
}
return %value;
}
function XML::writeAttribute( %this, %field, %value )
{
%this.fileObject.setAttribute( %field, %value );
}
function XML::readAttribute( %this, %field )
{
return %this.fileObject.attribute( %field );
}
function XML::writeData( %this, %field, %value )
{
%this.fileObject.pushNewElement( %field );
%this.fileObject.addData( %value );
%this.fileObject.popElement();
}
function XML::readData( %this, %field )
{
%value = "";
if( %this.fileObject.pushFirstChildElement( %field ) )
{
%this.index++;
%value = %this.fileObject.getData();
%this.fileObject.popElement();
}
return %value;
}
function XML::writeBool( %this, %field, %value )
{
%write = "false";
if( %value )
%write = "true";
%this.writeField( %field, %write );
}
function XML::readBool( %this, %field )
{
%val = %this.readField( %field );
if( %val $= "" )
return "";
if( %val $= "true" )
return true;
return false;
}
function XML::writeValue( %this, %value )
{
%this.fileObject.addText( %value );
}
function XML::readValue( %this )
{
return %this.fileObject.getText();
}
//};
//Persistence::registerFormat( "XML", XMLPersistencePackage, ".xml" );
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Graph.RBAC.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Graph.RBAC.Fluent.ActiveDirectoryApplication.Definition;
using Microsoft.Azure.Management.Graph.RBAC.Fluent.ActiveDirectoryApplication.Update;
using Microsoft.Azure.Management.Graph.RBAC.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System.Collections.Generic;
using System;
using System.Linq;
using ResourceManager.Fluent.Core.ResourceActions;
using System.Collections.ObjectModel;
/// <summary>
/// Implementation for ServicePrincipal and its parent interfaces.
/// </summary>
public partial class ActiveDirectoryApplicationImpl :
CreatableUpdatable<IActiveDirectoryApplication, ApplicationInner, ActiveDirectoryApplicationImpl, IHasId, IUpdate>,
IActiveDirectoryApplication,
IDefinition,
IUpdate,
IHasCredential<IWithCreate>,
IHasCredential<IUpdate>
{
private GraphRbacManager manager;
private ApplicationCreateParameters createParameters;
private ApplicationUpdateParameters updateParameters;
private Dictionary<string, Microsoft.Azure.Management.Graph.RBAC.Fluent.IPasswordCredential> cachedPasswordCredentials;
private Dictionary<string, Microsoft.Azure.Management.Graph.RBAC.Fluent.ICertificateCredential> cachedCertificateCredentials;
string IHasId.Id => Inner.ObjectId;
GraphRbacManager IHasManager<GraphRbacManager>.Manager => manager;
public ActiveDirectoryApplicationImpl WithAvailableToOtherTenants(bool availableToOtherTenants)
{
if (IsInCreateMode())
{
createParameters.AvailableToOtherTenants = availableToOtherTenants;
}
else
{
updateParameters.AvailableToOtherTenants = availableToOtherTenants;
}
return this;
}
public PasswordCredentialImpl<T> DefinePasswordCredential<T>(string name) where T : class
{
return new PasswordCredentialImpl<T>(name, (IHasCredential<T>)this);
}
public IReadOnlyList<string> ApplicationPermissions()
{
if (Inner.AppPermissions == null)
{
return null;
}
return Inner.AppPermissions.ToList().AsReadOnly();
}
internal async Task<Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication> RefreshCredentialsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
IEnumerable<KeyCredential> keyCredentials = await manager.Inner.Applications.ListKeyCredentialsAsync(Id(), cancellationToken);
this.cachedCertificateCredentials = new Dictionary<string, ICertificateCredential>();
foreach (var cred in keyCredentials)
{
ICertificateCredential cert = new CertificateCredentialImpl<IActiveDirectoryApplication>(cred);
this.cachedCertificateCredentials.Add(cert.Id, cert);
}
IEnumerable<Models.PasswordCredential> passwordCredentials = await manager.Inner.Applications.ListPasswordCredentialsAsync(Id(), cancellationToken);
this.cachedPasswordCredentials = new Dictionary<string, IPasswordCredential>();
foreach (var cred in passwordCredentials)
{
IPasswordCredential cert = new PasswordCredentialImpl<IActiveDirectoryApplication>(cred);
this.cachedPasswordCredentials.Add(cert.Id, cert);
}
return this;
}
public ActiveDirectoryApplicationImpl WithIdentifierUrl(string identifierUrl)
{
if (IsInCreateMode())
{
if (createParameters.IdentifierUris == null)
{
createParameters.IdentifierUris = new List<string>();
}
createParameters.IdentifierUris.Add(identifierUrl);
}
else
{
if (updateParameters.IdentifierUris == null)
{
updateParameters.IdentifierUris = new List<string>(IdentifierUris());
}
updateParameters.IdentifierUris.Add(identifierUrl);
}
return this;
}
internal ActiveDirectoryApplicationImpl(ApplicationInner innerObject, GraphRbacManager manager)
: base(innerObject.DisplayName, innerObject)
{
this.manager = manager;
this.createParameters = new ApplicationCreateParameters
{
DisplayName = innerObject.DisplayName
};
this.updateParameters = new ApplicationUpdateParameters
{
DisplayName = innerObject.DisplayName
};
}
public ActiveDirectoryApplicationImpl WithSignOnUrl(string signOnUrl)
{
if (IsInCreateMode())
{
createParameters.Homepage = signOnUrl;
}
else
{
updateParameters.Homepage = signOnUrl;
}
return WithReplyUrl(signOnUrl);
}
public ISet<string> ReplyUrls()
{
if (Inner.ReplyUrls == null)
{
return null;
}
return new System.Collections.Generic.HashSet<string>(Inner.ReplyUrls);
}
public IUpdate WithoutIdentifierUrl(string identifierUrl)
{
if (updateParameters.IdentifierUris != null)
{
updateParameters.IdentifierUris.Remove(identifierUrl);
}
return this;
}
public IReadOnlyDictionary<string, Microsoft.Azure.Management.Graph.RBAC.Fluent.ICertificateCredential> CertificateCredentials()
{
if (cachedCertificateCredentials == null)
{
return null;
}
return new ReadOnlyDictionary<string, ICertificateCredential>(cachedCertificateCredentials);
}
protected override async Task<Models.ApplicationInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await manager.Inner.Applications.GetAsync(Id(), cancellationToken);
}
public bool AvailableToOtherTenants()
{
return Inner.AvailableToOtherTenants ?? false;
}
public IReadOnlyDictionary<string, Microsoft.Azure.Management.Graph.RBAC.Fluent.IPasswordCredential> PasswordCredentials()
{
if (cachedPasswordCredentials == null)
{
return null;
}
return new ReadOnlyDictionary<string, IPasswordCredential>(cachedPasswordCredentials);
}
public ActiveDirectoryApplicationImpl WithPasswordCredential<T>(PasswordCredentialImpl<T> credential) where T : class
{
if (IsInCreateMode())
{
if (createParameters.PasswordCredentials == null)
{
createParameters.PasswordCredentials = new List<Models.PasswordCredential>();
}
createParameters.PasswordCredentials.Add(credential.Inner);
}
else
{
if (updateParameters.PasswordCredentials == null)
{
updateParameters.PasswordCredentials = cachedPasswordCredentials.Values.Select(pc => pc.Inner).ToList();
}
updateParameters.PasswordCredentials.Add(credential.Inner);
}
return this;
}
public ISet<string> IdentifierUris()
{
if (Inner.IdentifierUris == null)
{
return null;
}
return new HashSet<string>(Inner.IdentifierUris);
}
public string Id()
{
return Inner.ObjectId;
}
public override async Task<Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
if (IsInCreateMode())
{
if (createParameters.IdentifierUris == null)
{
createParameters.IdentifierUris = new List<string>();
createParameters.IdentifierUris.Add(createParameters.Homepage);
}
SetInner(await manager.Inner.Applications.CreateAsync(createParameters, cancellationToken));
return await RefreshCredentialsAsync(cancellationToken);
}
else
{
await manager.Inner.Applications.PatchAsync(Id(), updateParameters, cancellationToken);
return await RefreshAsync(cancellationToken);
}
}
public GraphRbacManager Manager()
{
return manager;
}
public bool IsInCreateMode()
{
return Id() == null;
}
public CertificateCredentialImpl<T> DefineCertificateCredential<T>(string name) where T : class
{
return new CertificateCredentialImpl<T>(name, (IHasCredential<T>)this);
}
public ActiveDirectoryApplicationImpl WithCertificateCredential<T>(CertificateCredentialImpl<T> credential) where T : class
{
if (IsInCreateMode())
{
if (createParameters.KeyCredentials == null)
{
createParameters.KeyCredentials = new List<KeyCredential>();
}
createParameters.KeyCredentials.Add(credential.Inner);
}
else
{
if (updateParameters.KeyCredentials == null)
{
updateParameters.KeyCredentials = new List<KeyCredential>();
}
updateParameters.KeyCredentials.Add(credential.Inner);
}
return this;
}
public Uri SignOnUrl()
{
try
{
return new Uri(Inner.Homepage);
}
catch (UriFormatException)
{
return null;
}
}
public ActiveDirectoryApplicationImpl WithoutReplyUrl(string replyUrl)
{
if (updateParameters.ReplyUrls != null)
{
updateParameters.ReplyUrls.Remove(replyUrl);
}
return this;
}
public ActiveDirectoryApplicationImpl WithoutCredential(string name)
{
foreach (var credential in cachedPasswordCredentials)
{
if (name.Equals(credential.Value.Name))
{
cachedPasswordCredentials.Remove(credential.Value.Id);
updateParameters.PasswordCredentials = cachedPasswordCredentials.Values.Select(pc => pc.Inner).ToList();
return this;
}
}
foreach (var credential in cachedCertificateCredentials)
{
if (name.Equals(credential.Value.Name))
{
cachedCertificateCredentials.Remove(credential.Value.Id);
updateParameters.KeyCredentials = cachedCertificateCredentials.Values.Select(pc => pc.Inner).ToList();
return this;
}
}
return this;
}
public override async Task<Microsoft.Azure.Management.Graph.RBAC.Fluent.IActiveDirectoryApplication> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken))
{
SetInner(await GetInnerAsync(cancellationToken));
return await RefreshCredentialsAsync(cancellationToken);
}
public string ApplicationId()
{
return Inner.AppId;
}
public ActiveDirectoryApplicationImpl WithReplyUrl(string replyUrl)
{
if (IsInCreateMode())
{
if (createParameters.ReplyUrls == null)
{
createParameters.ReplyUrls = new List<string>();
}
createParameters.ReplyUrls.Add(replyUrl);
}
else
{
if (updateParameters.ReplyUrls == null)
{
updateParameters.ReplyUrls = new List<string>(ReplyUrls());
}
updateParameters.ReplyUrls.Add(replyUrl);
}
return this;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SimplesE.API.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
* XmlStreamReader.cs - Implementation of the
* "System.Xml.Private.XmlStreamReader" class.
*
* Copyright (C) 2001, 2002 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Xml.Private
{
using System;
using System.Text;
using System.IO;
internal class XmlStreamReader : TextReader
{
#if !ECMA_COMPAT
// The null stream reader.
public new static readonly XmlStreamReader Null
= new XmlStreamReader(Stream.Null);
#endif
// Default and minimum buffer sizes to use for streams.
private const int STREAM_BUFSIZ = 1024;
private const int FILE_BUFSIZ = 4096;
private const int MIN_BUFSIZ = 128;
// Internal state.
private Stream stream;
private Encoding encoding;
private Decoder decoder;
private int bufferSize;
private byte[] inBuffer;
private int inBufferPosn;
private int inBufferLen;
private char[] outBuffer;
private int outBufferPosn;
private int outBufferLen;
private bool sawEOF;
private bool streamOwner;
private bool encodingDetected;
internal TextReader TxtReader;
internal bool canseek;
// Constructors that are based on a stream.
public XmlStreamReader(Stream stream)
: this(stream, Encoding.UTF8, true, STREAM_BUFSIZ) {}
internal XmlStreamReader(TextReader txtReader)
{
this.TxtReader = txtReader;
StreamReader strReader = txtReader as StreamReader;
if(strReader != null)
{
canseek = strReader.BaseStream.CanSeek;
}
else
{
canseek = txtReader != null && txtReader.Peek() != -1;
}
}
public XmlStreamReader(Stream stream, bool detectEncodingFromByteOrderMarks)
: this(stream, Encoding.UTF8,
detectEncodingFromByteOrderMarks, STREAM_BUFSIZ) {}
public XmlStreamReader(Stream stream, Encoding encoding)
: this(stream, encoding, true, STREAM_BUFSIZ) {}
public XmlStreamReader(Stream stream, Encoding encoding,
bool detectEncodingFromByteOrderMarks)
: this(stream, encoding,
detectEncodingFromByteOrderMarks, STREAM_BUFSIZ) {}
public XmlStreamReader(Stream stream, Encoding encoding,
bool detectEncodingFromByteOrderMarks,
int bufferSize)
{
// Validate the parameters.
if(stream == null)
{
throw new ArgumentNullException("stream");
}
if(encoding == null)
{
throw new ArgumentNullException("encoding");
}
if(!stream.CanRead)
{
throw new ArgumentException(S._("IO_NotSupp_Read"));
}
if(bufferSize <= 0)
{
throw new ArgumentOutOfRangeException
("bufferSize",S._("ArgRange_BufferSize"));
}
if(bufferSize < MIN_BUFSIZ)
{
bufferSize = MIN_BUFSIZ;
}
// Initialize this object.
this.stream = stream;
this.encoding = encoding;
this.bufferSize = bufferSize;
this.inBuffer = new byte [bufferSize];
this.inBufferPosn = 0;
this.inBufferLen = 0;
this.outBuffer = new char [bufferSize];
this.outBufferPosn = 0;
this.outBufferLen = 0;
this.sawEOF = false;
this.streamOwner = false;
this.encodingDetected = !detectEncodingFromByteOrderMarks;
// Get a decoder for the encoding.
decoder = encoding.GetDecoder();
}
// Constructors that are based on a filename.
public XmlStreamReader(String path)
: this(path, Encoding.UTF8, true, STREAM_BUFSIZ) {}
public XmlStreamReader(String path, bool detectEncodingFromByteOrderMarks)
: this(path, Encoding.UTF8,
detectEncodingFromByteOrderMarks, STREAM_BUFSIZ) {}
public XmlStreamReader(String path, Encoding encoding)
: this(path, encoding, true, STREAM_BUFSIZ) {}
public XmlStreamReader(String path, Encoding encoding,
bool detectEncodingFromByteOrderMarks)
: this(path, encoding,
detectEncodingFromByteOrderMarks, STREAM_BUFSIZ) {}
public XmlStreamReader(String path, Encoding encoding,
bool detectEncodingFromByteOrderMarks,
int bufferSize)
{
// Validate the parameters.
if(path == null)
{
throw new ArgumentNullException("path");
}
if(encoding == null)
{
throw new ArgumentNullException("encoding");
}
if(bufferSize <= 0)
{
throw new ArgumentOutOfRangeException
("bufferSize", S._("ArgRange_BufferSize"));
}
if(bufferSize < MIN_BUFSIZ)
{
bufferSize = MIN_BUFSIZ;
}
// Attempt to open the file.
Stream stream = new FileStream(path, FileMode.Open,
FileAccess.Read,
FileShare.Read,
FILE_BUFSIZ);
// Initialize this object.
this.stream = stream;
this.encoding = encoding;
this.bufferSize = bufferSize;
this.inBuffer = new byte [bufferSize];
this.inBufferPosn = 0;
this.inBufferLen = 0;
this.outBuffer = new char [bufferSize];
this.outBufferPosn = 0;
this.outBufferLen = 0;
this.sawEOF = false;
this.streamOwner = true;
this.encodingDetected = !detectEncodingFromByteOrderMarks;
// Get a decoder for the encoding.
decoder = encoding.GetDecoder();
}
// Detect the byte order by inspecting the first few bytes.
private void DetectByteOrder()
{
if(inBufferLen < 1) { return; }
// Cancel the encoding detection if the marker bytes aren't
// recognised.
if(inBuffer[0] != 0xFF &&
inBuffer[0] != 0xFE &&
inBuffer[0] != 0xEF &&
inBuffer[0] != 0x00)
{
/* Cancel encoding detection. Go with default. */
encodingDetected = true;
}
else if(inBufferLen >= 2 &&
inBuffer[1] != 0xFE &&
inBuffer[1] != 0xFF &&
inBuffer[1] != 0xBB &&
inBuffer[1] != 0x00)
{
/* Cancel encoding detection. Go with default. */
encodingDetected = true;
}
else if(inBufferLen >= 3 &&
inBuffer[2] != 0xBF &&
inBuffer[2] != 0xFE &&
inBuffer[2] != 0xFF &&
inBuffer[2] != 0x00)
{
/* Cancel encoding detection. Go with default. */
encodingDetected = true;
}
else if(inBufferLen >= 4 &&
inBuffer[3] != 0xFF &&
inBuffer[3] != 0xFE &&
inBuffer[3] != 0x00)
{
/* Cancel encoding detection. Go with default. */
encodingDetected = true;
}
// Check for recognized byte order marks.
if(inBufferLen < 3) { return; }
if(inBuffer[0] == 0xEF &&
inBuffer[1] == 0xBB &&
inBuffer[2] == 0xBF)
{
// UTF-8.
encoding = Encoding.UTF8;
inBufferPosn = 3;
decoder = encoding.GetDecoder();
encodingDetected = true;
}
else if(inBufferLen >= 4 &&
inBuffer[0] == 0x00 &&
inBuffer[1] == 0x00 &&
inBuffer[2] == 0xFE &&
inBuffer[3] == 0xFF)
{
// UTF-32 (1234).
encoding = new UCS4Encoding
(UCS4Encoding.ByteOrder.Order_1234);
inBufferPosn = 4;
decoder = encoding.GetDecoder();
encodingDetected = true;
}
else if(inBufferLen >= 4 &&
inBuffer[0] == 0xFF &&
inBuffer[1] == 0xFE &&
inBuffer[2] == 0x00 &&
inBuffer[3] == 0x00)
{
// UTF-32 (4321).
encoding = new UCS4Encoding
(UCS4Encoding.ByteOrder.Order_4321);
inBufferPosn = 4;
decoder = encoding.GetDecoder();
encodingDetected = true;
}
else if(inBufferLen >= 4 &&
inBuffer[0] == 0xFE &&
inBuffer[1] == 0xFF &&
inBuffer[2] == 0x00 &&
inBuffer[3] == 0x00)
{
// UTF-32 (3412).
encoding = new UCS4Encoding
(UCS4Encoding.ByteOrder.Order_3412);
inBufferPosn = 4;
decoder = encoding.GetDecoder();
encodingDetected = true;
}
else if(inBufferLen >= 4 &&
inBuffer[0] == 0x00 &&
inBuffer[1] == 0x00 &&
inBuffer[2] == 0xFF &&
inBuffer[3] == 0xFE)
{
// UTF-32 (2143).
encoding = new UCS4Encoding
(UCS4Encoding.ByteOrder.Order_2143);
inBufferPosn = 4;
decoder = encoding.GetDecoder();
encodingDetected = true;
}
else if(inBuffer[0] == 0xFF &&
inBuffer[1] == 0xFE &&
(inBuffer[2] != 0x00 || inBufferLen >= 4))
{
// Little-endian UTF-16.
encoding = Encoding.Unicode;
inBufferPosn = 2;
decoder = encoding.GetDecoder();
encodingDetected = true;
}
else if(inBuffer[0] == 0xFE &&
inBuffer[1] == 0xFF &&
(inBuffer[2] != 0x00 || inBufferLen >= 4))
{
// Big-endian UTF-16.
encoding = Encoding.BigEndianUnicode;
inBufferPosn = 2;
decoder = encoding.GetDecoder();
encodingDetected = true;
}
}
// Close this stream reader.
public override void Close()
{
if(stream != null)
{
stream.Close();
}
Dispose(true);
}
// Discard any data that was buffered by this stream reader.
public void DiscardBufferedData()
{
// Empty the buffers.
inBufferPosn = 0;
inBufferLen = 0;
outBufferPosn = 0;
outBufferLen = 0;
sawEOF = false;
// Create a new decoder. We cannot reuse the
// old one because we have no way to reset the
// state to the default.
decoder = encoding.GetDecoder();
}
// Dispose this stream reader.
protected override void Dispose(bool disposing)
{
if(stream != null)
{
if(this.streamOwner)
{
stream.Close();
}
stream = null;
}
inBuffer = null;
inBufferPosn = 0;
inBufferLen = 0;
outBuffer = null;
outBufferPosn = 0;
outBufferLen = 0;
bufferSize = 0;
sawEOF = true;
base.Dispose(disposing);
}
// Read byte data from the stream and convert it into characters.
private void ReadChars()
{
int len, outLen;
while(outBufferPosn >= outBufferLen && !sawEOF)
{
// This loop exits when there is an EOF or some bytes have been read and
// the encoding has been detected.
while(true)
{
// Move the previous left-over buffer contents down.
if((inBufferLen - inBufferPosn) < bufferSize)
{
if(inBufferPosn < inBufferLen)
{
Array.Copy
(inBuffer, inBufferPosn,
inBuffer, 0, inBufferLen - inBufferPosn);
inBufferLen -= inBufferPosn;
}
else
{
inBufferLen = 0;
}
inBufferPosn = 0;
// Read new bytes into the buffer.
if(stream == null)
{
throw new IOException(S._("IO_StreamClosed"));
}
len = stream.Read
(inBuffer, inBufferLen, bufferSize - inBufferLen);
if(len <= 0)
{
if(!encodingDetected)
{
inBufferLen = 0;
inBufferPosn = 0;
}
sawEOF = true;
break;
}
else
{
inBufferLen += len;
}
}
if(inBufferLen > 0)
{
if(!encodingDetected)
{
// Try to detect the encoding
DetectByteOrder();
}
if(encodingDetected && (inBufferLen - inBufferPosn > 0))
{
// Only exit if the encoding has been detected and some bytes
// have been read.
break;
}
}
}
// Determine the maximum number of bytes that
// we can afford to convert into characters.
len = encoding.GetMaxByteCount(bufferSize);
if(len > (inBufferLen-inBufferPosn))
{
len = inBufferLen-inBufferPosn;
}
// Convert the bytes into characters.
outLen = decoder.GetChars
(inBuffer, inBufferPosn, len, outBuffer, 0);
outBufferPosn = 0;
outBufferLen = outLen;
inBufferPosn += len;
}
}
// Peek at the next character from this stream reader.
public override int Peek()
{
if(outBufferPosn < outBufferLen)
{
// We already have a character available.
return (int)(outBuffer[outBufferPosn]);
}
else
{
// Read another buffer of characters.
ReadChars();
if(outBufferPosn < outBufferLen)
{
return (int)(outBuffer[outBufferPosn]);
}
else
{
return -1;
}
}
}
// Read a single character from this stream reader.
public override int Read()
{
if(outBufferPosn < outBufferLen)
{
// We already have a character available.
return (int)(outBuffer[outBufferPosn++]);
}
else
{
// Read another buffer of characters.
ReadChars();
if(outBufferPosn < outBufferLen)
{
return (int)(outBuffer[outBufferPosn++]);
}
else
{
return -1;
}
}
}
// Read a buffer of characters from this stream reader.
public override int Read(char[] buffer, int index, int count)
{
// Validate the parameters.
if(buffer == null)
{
throw new ArgumentNullException("buffer");
}
if(index < 0)
{
throw new ArgumentOutOfRangeException
("index", S._("ArgRange_Array"));
}
if(count < 0)
{
throw new ArgumentOutOfRangeException
("count", S._("ArgRange_Array"));
}
if((buffer.Length - index) < count)
{
throw new ArgumentException
(S._("Arg_InvalidArrayRange"));
}
// Read data from the input stream into the buffer.
int len = 0;
if(count > 0)
{
// Re-fill the character buffer if necessary.
if(outBufferPosn >= outBufferLen)
{
ReadChars();
if(outBufferPosn >= outBufferLen)
{
return 0;
}
}
// Copy data to the result buffer.
len = outBufferLen - outBufferPosn;
if(len > count)
{
len = count;
}
Array.Copy(outBuffer, outBufferPosn,
buffer, index, len);
outBufferPosn += len;
index += len;
}
return len;
}
// Read a line of characters from this stream reader.
public override String ReadLine()
{
StringBuilder builder = new StringBuilder();
int ch;
for(;;)
{
// Re-fill the character buffer if necessary.
if(outBufferPosn >= outBufferLen)
{
ReadChars();
if(outBufferPosn >= outBufferLen)
{
break;
}
}
// Process characters until we reach a line terminator.
while(outBufferPosn < outBufferLen)
{
ch = outBuffer[outBufferPosn++];
if(ch == 13)
{
// Peek at the next character to determine
// if this is a CRLF or CR line terminator.
if(outBufferPosn >= outBufferLen)
{
ReadChars();
}
if(outBufferPosn < outBufferLen &&
outBuffer[outBufferPosn] == '\u000A')
{
++outBufferPosn;
}
return builder.ToString();
}
else if(ch == 10)
{
// This is an LF line terminator.
return builder.ToString();
}
else
{
builder.Append((char)ch);
}
}
}
if(builder.Length != 0)
{
return builder.ToString();
}
else
{
return null;
}
}
// Read the entire contents of this stream reader until EOF.
public override String ReadToEnd()
{
StringBuilder builder = new StringBuilder();
for(;;)
{
// Re-fill the character buffer if necessary.
if(outBufferPosn >= outBufferLen)
{
ReadChars();
if(outBufferPosn >= outBufferLen)
{
break;
}
}
// Append the character buffer to the builder.
builder.Append(outBuffer, outBufferPosn,
outBufferLen - outBufferPosn);
outBufferPosn = outBufferLen;
}
if(builder.Length != 0)
{
return builder.ToString();
}
else
{
return String.Empty;
}
}
// Get the base stream underlying this stream reader.
public virtual Stream BaseStream
{
get
{
this.streamOwner = false;
return stream;
}
}
// Get the current encoding in use by this stream reader.
public virtual Encoding CurrentEncoding
{
get
{
return encoding;
}
}
}; // class XmlStreamReader
}; // namespace System.Xml.Private
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using OpenCV.Android;
using Android.Util;
using OpenCV.SDKDemo.Utilities;
using OpenCV.Core;
using System.Threading.Tasks;
namespace OpenCV.SDKDemo.CameraCalibration
{
[Activity(Label = ActivityTags.CameraCalibration)]
public class CameraCalibrationActivity : Activity, CameraBridgeViewBase.ICvCameraViewListener2, View.IOnTouchListener
{
public const string TAG = "OCVSample::Activity";
public CameraBridgeViewBase mOpenCvCameraView { get; private set; }
private CameraCalibrator mCalibrator;
private OnCameraFrameRender mOnCameraFrameRender;
private int mWidth;
private int mHeight;
private Callback mLoaderCallback;
public CameraCalibrationActivity()
{
Log.Info(TAG, "Instantiated new " + GetType().ToString());
}
protected override void OnCreate(Bundle savedInstanceState)
{
Log.Info(TAG, "called onCreate");
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.KeepScreenOn);
SetContentView(Resource.Layout.camera_calibration_surface_view);
mOpenCvCameraView = FindViewById<CameraBridgeViewBase>(Resource.Id.camera_calibration_java_surface_view);
mOpenCvCameraView.Visibility = ViewStates.Visible;
mOpenCvCameraView.SetCvCameraViewListener2(this);
mLoaderCallback = new Callback(this, this, this);
}
protected override void OnPause()
{
base.OnPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.DisableView();
}
protected override void OnResume()
{
base.OnResume();
if (!OpenCVLoader.InitDebug())
{
Log.Debug(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.InitAsync(OpenCVLoader.OpencvVersion300, this, mLoaderCallback);
}
else
{
Log.Debug(TAG, "OpenCV library found inside package. Using it!");
mLoaderCallback.OnManagerConnected(LoaderCallbackInterface.Success);
}
}
protected override void OnDestroy()
{
base.OnDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.DisableView();
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
base.OnCreateOptionsMenu(menu);
MenuInflater.Inflate(Resource.Menu.calibration, menu);
return true;
}
public override bool OnPrepareOptionsMenu(IMenu menu)
{
base.OnPrepareOptionsMenu(menu);
menu.FindItem(Resource.Id.preview_mode).SetEnabled(true);
if (!mCalibrator.isCalibrated())
menu.FindItem(Resource.Id.preview_mode).SetEnabled(false);
return true;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.calibration:
mOnCameraFrameRender =
new OnCameraFrameRender(new CalibrationFrameRender(mCalibrator));
item.SetChecked(true);
return true;
case Resource.Id.undistortion:
mOnCameraFrameRender =
new OnCameraFrameRender(new UndistortionFrameRender(mCalibrator));
item.SetChecked(true);
return true;
case Resource.Id.comparison:
mOnCameraFrameRender =
new OnCameraFrameRender(new ComparisonFrameRender(mCalibrator, mWidth, mHeight, Resources));
item.SetChecked(true);
return true;
case Resource.Id.calibrate:
var res = this.Resources;
if (mCalibrator.getCornersBufferSize() < 2)
{
(Toast.MakeText(this, res.GetString(Resource.String.more_samples), ToastLength.Short)).Show();
return true;
}
mOnCameraFrameRender = new OnCameraFrameRender(new PreviewFrameRender());
//OnPreExecute
var calibrationProgress = new ProgressDialog(this);
calibrationProgress.SetTitle(Resources.GetString(Resource.String.calibrating));
calibrationProgress.SetMessage(Resources.GetString(Resource.String.please_wait));
calibrationProgress.SetCancelable(false);
calibrationProgress.Indeterminate = true;
calibrationProgress.Show();
Task.Run(() => mCalibrator.calibrate())
//OnPostExecute
.ContinueWith(t =>
{
calibrationProgress.Dismiss();
mCalibrator.clearCorners();
mOnCameraFrameRender = new OnCameraFrameRender(new CalibrationFrameRender(mCalibrator));
String resultMessage = (mCalibrator.isCalibrated()) ?
Resources.GetString(Resource.String.calibration_successful) + " " + mCalibrator.getAvgReprojectionError() :
Resources.GetString(Resource.String.calibration_unsuccessful);
Toast.MakeText(this, resultMessage, ToastLength.Short).Show();
if (mCalibrator.isCalibrated())
{
CalibrationResult.save(this,
mCalibrator.getCameraMatrix(), mCalibrator.getDistortionCoefficients());
}
}, TaskScheduler.FromCurrentSynchronizationContext());
return true;
default:
return base.OnOptionsItemSelected(item);
}
}
public void OnCameraViewStarted(int width, int height)
{
if (mWidth != width || mHeight != height)
{
mWidth = width;
mHeight = height;
mCalibrator = new CameraCalibrator(mWidth, mHeight);
if (CalibrationResult.tryLoad(this, mCalibrator.getCameraMatrix(), mCalibrator.getDistortionCoefficients()))
{
mCalibrator.setCalibrated();
}
mOnCameraFrameRender = new OnCameraFrameRender(new CalibrationFrameRender(mCalibrator));
}
}
public void OnCameraViewStopped()
{
}
public Mat OnCameraFrame(CameraBridgeViewBase.ICvCameraViewFrame inputFrame)
{
return mOnCameraFrameRender.Render(inputFrame);
}
public bool OnTouch(View v, MotionEvent e)
{
Log.Debug(TAG, "onTouch invoked");
mCalibrator.addCorners();
return false;
}
}
class Callback : BaseLoaderCallback
{
private readonly View.IOnTouchListener _listener;
private readonly CameraCalibrationActivity _activity;
public Callback(Context context, View.IOnTouchListener listener, CameraCalibrationActivity activity)
: base(context)
{
_listener = listener;
_activity = activity;
}
public override void OnManagerConnected(int status)
{
switch (status)
{
case LoaderCallbackInterface.Success:
{
Log.Info(CameraCalibrationActivity.TAG, "OpenCV loaded successfully");
_activity.mOpenCvCameraView.EnableView();
_activity.mOpenCvCameraView.SetOnTouchListener(_listener);
}
break;
default:
{
base.OnManagerConnected(status);
}
break;
}
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2016 Jesse Sweetland
//
// 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 Platibus.Diagnostics;
using Platibus.IO;
using Platibus.Security;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Platibus.Utils;
namespace Platibus.RabbitMQ
{
/// <inheritdoc />
/// <summary>
/// A logical Platibus queue implemented with RabbitMQ queues and exchanges
/// </summary>
public class RabbitMQQueue : IDisposable
{
private readonly QueueName _queueName;
private readonly string _queueExchange;
private readonly string _deadLetterExchange;
private readonly bool _autoAcknowledge;
private readonly QueueName _retryQueueName;
private readonly string _retryExchange;
private readonly IQueueListener _listener;
private readonly ISecurityTokenService _securityTokenService;
private readonly Encoding _encoding;
private readonly TimeSpan _ttl;
private readonly int _maxAttempts;
private readonly TimeSpan _retryDelay;
private readonly bool _isDurable;
private readonly CancellationTokenSource _cancellationTokenSource;
private readonly DurableConsumer _consumer;
private readonly IDiagnosticService _diagnosticService;
private readonly IConnection _connection;
private readonly IMessageEncryptionService _messageEncryptionService;
private bool _disposed;
/// <summary>
/// Initializes a new <see cref="RabbitMQQueue"/>
/// </summary>
/// <param name="connection">The connection to the RabbitMQ server</param>
/// <param name="queueName">The name of the queue</param>
/// <param name="listener">The listener that will receive new messages off of the queue</param>
/// <param name="encoding">(Optional) The encoding to use when converting serialized message
/// content to byte streams</param>
/// <param name="options">(Optional) Queueing options</param>
/// <param name="diagnosticService">(Optional) The service through which diagnostic events
/// are reported and processed</param>
/// <param name="securityTokenService">(Optional) The message security token
/// service to use to issue and validate security tokens for persisted messages.</param>
/// <param name="messageEncryptionService"></param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="queueName"/>,
/// <paramref name="listener"/>, or <paramref name="connection"/> is <c>null</c></exception>
public RabbitMQQueue(IConnection connection,
QueueName queueName, IQueueListener listener,
Encoding encoding, QueueOptions options,
IDiagnosticService diagnosticService,
ISecurityTokenService securityTokenService,
IMessageEncryptionService messageEncryptionService)
{
_queueName = queueName ?? throw new ArgumentNullException(nameof(queueName));
_queueExchange = _queueName.GetExchangeName();
_retryQueueName = queueName.GetRetryQueueName();
_retryExchange = _queueName.GetRetryExchangeName();
_deadLetterExchange = _queueName.GetDeadLetterExchangeName();
_listener = listener ?? throw new ArgumentNullException(nameof(listener));
_connection = connection ?? throw new ArgumentNullException(nameof(connection));
_securityTokenService = securityTokenService ?? throw new ArgumentNullException(nameof(securityTokenService));
_encoding = encoding ?? Encoding.UTF8;
var myOptions = options ?? new QueueOptions();
_ttl = myOptions.TTL;
_autoAcknowledge = myOptions.AutoAcknowledge;
_maxAttempts = myOptions.MaxAttempts;
_retryDelay = myOptions.RetryDelay;
_isDurable = myOptions.IsDurable;
var concurrencyLimit = myOptions.ConcurrencyLimit;
_cancellationTokenSource = new CancellationTokenSource();
_diagnosticService = diagnosticService ?? DiagnosticService.DefaultInstance;
_messageEncryptionService = messageEncryptionService;
var consumerTag = _queueName;
_consumer = new DurableConsumer(_connection, queueName, HandleDelivery, consumerTag,
concurrencyLimit, _autoAcknowledge, _diagnosticService);
}
/// <summary>
/// Initializes RabbitMQ queues and exchanges
/// </summary>
public void Init()
{
using (var channel = _connection.CreateModel())
{
var queueArgs = new Dictionary<string, object>
{
{"x-dead-letter-exchange", _deadLetterExchange},
};
if (_ttl > TimeSpan.Zero)
{
queueArgs["x-expires"] = _ttl;
}
channel.ExchangeDeclare(_queueExchange, "direct", _isDurable, false, null);
_diagnosticService.Emit(new RabbitMQEventBuilder(this, RabbitMQEventType.RabbitMQExchangeDeclared)
{
Detail = "Primary exchange declared for queue",
Exchange = _queueExchange,
Queue = _queueName
}.Build());
channel.ExchangeDeclare(_deadLetterExchange, "direct", _isDurable, false, null);
_diagnosticService.Emit(new RabbitMQEventBuilder(this, RabbitMQEventType.RabbitMQExchangeDeclared)
{
Detail = "Dead letter exchange declared for queue",
Exchange = _deadLetterExchange,
Queue = _queueName
}.Build());
channel.QueueDeclare(_queueName, _isDurable, false, false, queueArgs);
_diagnosticService.Emit(new RabbitMQEventBuilder(this, RabbitMQEventType.RabbitMQQueueDeclared)
{
Detail = "Queue declared",
Queue = _queueName
}.Build());
channel.QueueBind(_queueName, _queueExchange, "", null);
_diagnosticService.Emit(new RabbitMQEventBuilder(this, RabbitMQEventType.RabbitMQQueueBound)
{
Detail = "Queue bound to primary exchange",
Exchange = _queueExchange,
Queue = _queueName
}.Build());
var retryTtlMs = (int) _retryDelay.TotalMilliseconds;
var retryQueueArgs = new Dictionary<string, object>
{
{"x-dead-letter-exchange", _queueExchange},
{"x-message-ttl", retryTtlMs}
};
channel.ExchangeDeclare(_retryExchange, "direct", _isDurable, false, null);
_diagnosticService.Emit(new RabbitMQEventBuilder(this, RabbitMQEventType.RabbitMQExchangeDeclared)
{
Detail = "Retry exchange declared for queue",
Exchange = _retryExchange,
Queue = _queueName
}.Build());
channel.QueueDeclare(_retryQueueName, _isDurable, false, false, retryQueueArgs);
_diagnosticService.Emit(new RabbitMQEventBuilder(this, RabbitMQEventType.RabbitMQQueueDeclared)
{
Detail = "Retry queue declared",
Queue = _retryQueueName
}.Build());
channel.QueueBind(_retryQueueName, _retryExchange, "", null);
_diagnosticService.Emit(new RabbitMQEventBuilder(this, RabbitMQEventType.RabbitMQQueueDeclared)
{
Detail = "Retry queue bound to retry exchange",
Exchange = _retryExchange,
Queue = _retryQueueName
}.Build());
}
_consumer.Init();
_diagnosticService.Emit(new RabbitMQEventBuilder(this, DiagnosticEventType.ComponentInitialization)
{
Detail = "RabbitMQ queue initialized",
Queue = _queueName
}.Build());
}
/// <summary>
/// Enqueues a message
/// </summary>
/// <param name="message">The message to enqueue</param>
/// <param name="principal">The sender principal</param>
/// <returns>Returns a task that completes when the message has been enqueued</returns>
public async Task Enqueue(Message message, IPrincipal principal)
{
CheckDisposed();
var expires = message.Headers.Expires;
var securityToken = await _securityTokenService.NullSafeIssue(principal, expires);
var persistedMessage = message.WithSecurityToken(securityToken);
if (_messageEncryptionService != null)
{
persistedMessage = await _messageEncryptionService.Encrypt(persistedMessage);
}
using (var channel = _connection.CreateModel())
{
await RabbitMQHelper.PublishMessage(persistedMessage, principal, channel, null, _queueExchange, _encoding);
await _diagnosticService.EmitAsync(
new RabbitMQEventBuilder(this, DiagnosticEventType.MessageEnqueued)
{
Queue = _queueName,
Message = message,
ChannelNumber = channel.ChannelNumber
}.Build());
}
}
/// <summary>
/// Deletes the RabbitMQ queues and exchanges
/// </summary>
public void Delete()
{
CheckDisposed();
Dispose(true);
using (var channel = _connection.CreateModel())
{
channel.QueueDeleteNoWait(_queueName, false, false);
channel.QueueDeleteNoWait(_retryQueueName, false, false);
channel.ExchangeDeleteNoWait(_deadLetterExchange, false);
channel.ExchangeDeleteNoWait(_queueExchange, false);
channel.ExchangeDeleteNoWait(_retryExchange, false);
}
}
private void HandleDelivery(IModel channel, BasicDeliverEventArgs delivery, CancellationToken cancellationToken)
{
try
{
// Put on the thread pool to avoid deadlock
var result = DispatchToListener(delivery, cancellationToken).GetResultFromCompletionSource();
if (result.Acknowledged)
{
_diagnosticService.Emit(
new RabbitMQEventBuilder(this, DiagnosticEventType.MessageAcknowledged)
{
Queue = _queueName,
Message = result.Message,
ConsumerTag = delivery.ConsumerTag,
DeliveryTag = delivery.DeliveryTag
}.Build());
if (!_autoAcknowledge)
{
channel.BasicAck(delivery.DeliveryTag, false);
}
}
else
{
_diagnosticService.Emit(
new RabbitMQEventBuilder(this, DiagnosticEventType.MessageNotAcknowledged)
{
Queue = _queueName,
Message = result.Message,
ConsumerTag = delivery.ConsumerTag,
DeliveryTag = delivery.DeliveryTag
}.Build());
// Add 1 to the header value because the number of attempts will be zero
// on the first try
var currentAttempt = delivery.BasicProperties.GetDeliveryAttempts() + 1;
if (currentAttempt < _maxAttempts)
{
_diagnosticService.Emit(
new RabbitMQEventBuilder(this, DiagnosticEventType.QueuedMessageRetry)
{
Detail = "Message not acknowledged; retrying in " + _retryDelay,
Message = result.Message,
Queue = _queueName,
ConsumerTag = delivery.ConsumerTag,
DeliveryTag = delivery.DeliveryTag
}.Build());
var retryProperties = delivery.BasicProperties;
retryProperties.IncrementDeliveryAttempts();
channel.BasicPublish(_retryExchange, "", retryProperties, delivery.Body);
}
else
{
_diagnosticService.Emit(
new RabbitMQEventBuilder(this, DiagnosticEventType.MaxAttemptsExceeded)
{
Message = result.Message,
Queue = _queueName,
ConsumerTag = delivery.ConsumerTag,
DeliveryTag = delivery.DeliveryTag
}.Build());
if (!_autoAcknowledge)
{
channel.BasicNack(delivery.DeliveryTag, false, false);
}
_diagnosticService.Emit(
new RabbitMQEventBuilder(this, DiagnosticEventType.DeadLetter)
{
Message = result.Message,
Queue = _queueName,
Exchange = _deadLetterExchange,
ConsumerTag = delivery.ConsumerTag,
DeliveryTag = delivery.DeliveryTag
}.Build());
}
}
}
catch (OperationCanceledException)
{
_diagnosticService.Emit(
new RabbitMQEventBuilder(this, DiagnosticEventType.MessageNotAcknowledged)
{
Detail = "Message not acknowledged due to requested cancelation",
Queue = _queueName,
ConsumerTag = delivery.ConsumerTag,
DeliveryTag = delivery.DeliveryTag
}.Build());
channel.BasicNack(delivery.DeliveryTag, false, false);
}
catch (Exception ex)
{
_diagnosticService.Emit(
new RabbitMQEventBuilder(this, RabbitMQEventType.RabbitMQDeliveryError)
{
Detail = "Unhandled exception processing delivery",
Exception = ex,
Queue = _queueName,
ConsumerTag = delivery.ConsumerTag,
DeliveryTag = delivery.DeliveryTag
}.Build());
if (!_autoAcknowledge)
{
// Due to the complexity of managing retry counts and delays in
// RabbitMQ, listener exceptions are caught and handled in the
// DispatchToListener method and publication to the retry
// exchange is performed within the try block above. If that
// fails then there is no other option but to nack the
// message.
channel.BasicNack(delivery.DeliveryTag, false, false);
}
}
}
private async Task<DispatchResult> DispatchToListener(BasicDeliverEventArgs delivery, CancellationToken cancellationToken)
{
Message message = null;
var acknowledged = false;
try
{
var messageBody = _encoding.GetString(delivery.Body);
using (var reader = new StringReader(messageBody))
using (var messageReader = new MessageReader(reader))
{
message = await messageReader.ReadMessage();
if (_messageEncryptionService != null && message.IsEncrypted())
{
message = await _messageEncryptionService.Decrypt(message);
}
var securityToken = message.Headers.SecurityToken;
var principal = await _securityTokenService.NullSafeValidate(securityToken);
// Remove sensitive information from the header, including security token
var headers = new MessageHeaders(message.Headers.Sanitize());
if (headers.Received == default(DateTime))
{
headers.Received = DateTime.UtcNow;
}
var context = new RabbitMQQueuedMessageContext(headers, principal);
Thread.CurrentPrincipal = context.Principal;
await _listener.MessageReceived(message, context, cancellationToken);
acknowledged = context.Acknowledged || _autoAcknowledge;
}
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
_diagnosticService.Emit(
new RabbitMQEventBuilder(this, RabbitMQEventType.RabbitMQDeliveryError)
{
Message = message,
Exception = ex,
Queue = _queueName,
ConsumerTag = delivery.ConsumerTag,
DeliveryTag = delivery.DeliveryTag
}.Build());
}
return new DispatchResult(message, acknowledged);
}
/// <summary>
/// Throws an exception if this object has already been disposed
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown if the object has been disposed</exception>
protected void CheckDisposed()
{
if (_disposed) throw new ObjectDisposedException(GetType().FullName);
}
/// <summary>
/// Finalizer that ensures all resources are released
/// </summary>
~RabbitMQQueue()
{
Dispose(false);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
if (_disposed) return;
Dispose(true);
_disposed = true;
GC.SuppressFinalize(this);
}
/// <summary>
/// Called by the <see cref="Dispose()"/> method or finalizer to ensure that
/// resources are released
/// </summary>
/// <param name="disposing">Indicates whether this method is called from the
/// <see cref="Dispose()"/> method (<c>true</c>) or the finalizer (<c>false</c>)</param>
/// <remarks>
/// This method will not be called more than once
/// </remarks>
protected virtual void Dispose(bool disposing)
{
_cancellationTokenSource.Cancel();
if (disposing)
{
_cancellationTokenSource.Dispose();
_consumer.Dispose();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Elasticsearch.Net.Connection.RequestState;
using Elasticsearch.Net.ConnectionPool;
using Elasticsearch.Net.Exceptions;
using Elasticsearch.Net.Providers;
using Elasticsearch.Net.Serialization;
using System.Threading.Tasks;
using Elasticsearch.Net.Connection.Configuration;
namespace Elasticsearch.Net.Connection.RequestHandlers
{
internal class RequestHandlerBase
{
protected const int BufferSize = 4096;
protected static readonly string MaxRetryExceptionMessage = "Failed after retrying {2} times: '{0} {1}'. {3}";
protected static readonly string TookTooLongExceptionMessage = "Retry timeout {4} was hit after retrying {2} times: '{0} {1}'. {3}";
protected static readonly string MaxRetryInnerMessage = "InnerException: {0}, InnerMessage: {1}, InnerStackTrace: {2}";
protected readonly IConnectionConfigurationValues _settings;
protected readonly IConnection _connection;
protected readonly IConnectionPool _connectionPool;
protected readonly IElasticsearchSerializer _serializer;
protected readonly IMemoryStreamProvider _memoryStreamProvider;
protected readonly ITransportDelegator _delegator;
protected readonly bool _throwMaxRetry;
protected RequestHandlerBase(
IConnectionConfigurationValues settings,
IConnection connection,
IConnectionPool connectionPool,
IElasticsearchSerializer serializer,
IMemoryStreamProvider memoryStreamProvider,
ITransportDelegator delegator)
{
_settings = settings;
_connection = connection;
_connectionPool = connectionPool;
_serializer = serializer;
_memoryStreamProvider = memoryStreamProvider;
_delegator = delegator;
this._throwMaxRetry = !(this._connectionPool is SingleNodeConnectionPool);
}
protected byte[] PostData(object data)
{
if (data == null) return null;
var bytes = data as byte[];
if (bytes != null) return bytes;
var s = data as string;
if (s != null) return s.Utf8Bytes();
var ss = data as IEnumerable<string>;
if (ss != null) return (string.Join("\n", ss) + "\n").Utf8Bytes();
var so = data as IEnumerable<object>;
var indent = this._settings.UsesPrettyRequests
? SerializationFormatting.Indented
: SerializationFormatting.None;
if (so == null) return this._serializer.Serialize(data, indent);
var joined = string.Join("\n", so
.Select(soo => this._serializer.Serialize(soo, SerializationFormatting.None).Utf8String())) + "\n";
return joined.Utf8Bytes();
}
protected static bool IsValidResponse(ITransportRequestState requestState, IElasticsearchResponse streamResponse)
{
return streamResponse.Success
|| StatusCodeAllowed(requestState.RequestConfiguration, streamResponse.HttpStatusCode);
}
protected static bool StatusCodeAllowed(IRequestConfiguration requestConfiguration, int? statusCode)
{
if (requestConfiguration == null)
return false;
return requestConfiguration.AllowedStatusCodes.HasAny(i => i == statusCode);
}
protected bool TypeOfResponseCopiesDirectly<T>()
{
var type = typeof(T);
return type == typeof(string) || type == typeof(byte[]) || typeof(Stream).IsAssignableFrom(typeof(T));
}
protected bool SetStringOrByteResult<T>(ElasticsearchResponse<T> original, byte[] bytes)
{
var type = typeof(T);
if (type == typeof(string))
{
this.SetStringResult(original as ElasticsearchResponse<string>, bytes);
return true;
}
if (type == typeof(byte[]))
{
this.SetByteResult(original as ElasticsearchResponse<byte[]>, bytes);
return true;
}
return false;
}
/// <summary>
/// Determines whether the stream response is our final stream response:
/// IF response is success or known error
/// OR maxRetries is 0 and retried is 0 (maxRetries could change in between retries to 0)
/// AND sniff on connection fault does not find more nodes (causing maxRetry to grow)
/// AND maxretries is no retried
/// </summary>
protected bool DoneProcessing<T>(
ElasticsearchResponse<Stream> streamResponse,
TransportRequestState<T> requestState,
int maxRetries,
int retried)
{
return (streamResponse != null && streamResponse.SuccessOrKnownError)
|| (maxRetries == 0
&& retried == 0
&& !this._delegator.SniffOnFaultDiscoveredMoreNodes(requestState, retried, streamResponse)
);
}
protected void ThrowMaxRetryExceptionWhenNeeded<T>(TransportRequestState<T> requestState, int maxRetries)
{
var tookToLong = this._delegator.TookTooLongToRetry(requestState);
//not out of date and we havent depleted our retries, get the hell out of here
if (!tookToLong && requestState.Retried < maxRetries) return;
var innerExceptions = requestState.SeenExceptions.Where(e => e != null).ToList();
var innerException = !innerExceptions.HasAny()
? null
: (innerExceptions.Count() == 1)
? innerExceptions.First()
: new AggregateException(requestState.SeenExceptions);
//When we are not using pooling we forcefully rethrow the exception
if (!requestState.UsingPooling && innerException != null && maxRetries == 0)
{
innerException.RethrowKeepingStackTrace();
return;
}
var exceptionMessage = tookToLong
? CreateTookTooLongExceptionMessage(requestState, innerException)
: CreateMaxRetryExceptionMessage(requestState, innerException);
throw new MaxRetryException(exceptionMessage, innerException);
}
protected string CreateInnerExceptionMessage<T>(TransportRequestState<T> requestState, Exception e)
{
if (e == null) return null;
var aggregate = e as AggregateException;
if (aggregate == null)
return "\r\n" + MaxRetryInnerMessage.F(e.GetType().Name, e.Message, e.StackTrace);
aggregate = aggregate.Flatten();
var innerExceptions = aggregate.InnerExceptions
.Select(ae => MaxRetryInnerMessage.F(ae.GetType().Name, ae.Message, ae.StackTrace))
.ToList();
return "\r\n" + string.Join("\r\n", innerExceptions);
}
protected string CreateMaxRetryExceptionMessage<T>(TransportRequestState<T> requestState, Exception e)
{
string innerException = CreateInnerExceptionMessage(requestState, e);
var exceptionMessage = MaxRetryExceptionMessage
.F(requestState.Method, requestState.Path, requestState.Retried, innerException);
return exceptionMessage;
}
protected string CreateTookTooLongExceptionMessage<T>(TransportRequestState<T> requestState, Exception e)
{
string innerException = CreateInnerExceptionMessage(requestState, e);
var timeout = this._settings.MaxRetryTimeout.GetValueOrDefault(TimeSpan.FromMilliseconds(this._settings.Timeout));
var exceptionMessage = TookTooLongExceptionMessage
.F(requestState.Method, requestState.Path, requestState.Retried, innerException, timeout);
return exceptionMessage;
}
protected void OptionallyCloseResponseStreamAndSetSuccess<T>(
ITransportRequestState requestState,
ElasticsearchServerError error,
ElasticsearchResponse<T> typedResponse,
ElasticsearchResponse<Stream> streamResponse)
{
if (streamResponse.Response != null && !typeof(Stream).IsAssignableFrom(typeof(T)))
streamResponse.Response.Close();
if (error != null)
{
typedResponse.Success = false;
if (typedResponse.OriginalException == null)
typedResponse.OriginalException = new ElasticsearchServerException(error);
}
//TODO UNIT TEST OR BEGONE
if (!typedResponse.Success
&& requestState.RequestConfiguration != null
&& requestState.RequestConfiguration.AllowedStatusCodes.HasAny(i => i == streamResponse.HttpStatusCode))
{
typedResponse.Success = true;
}
}
protected void SetStringResult(ElasticsearchResponse<string> response, byte[] rawResponse)
{
response.Response = rawResponse.Utf8String();
}
protected void SetByteResult(ElasticsearchResponse<byte[]> response, byte[] rawResponse)
{
response.Response = rawResponse;
}
protected ElasticsearchServerError GetErrorFromStream<T>(Stream stream)
{
try
{
var e = this._serializer.Deserialize<OneToOneServerException>(stream);
return ElasticsearchServerError.Create(e);
}
// ReSharper disable once EmptyGeneralCatchClause
// parsing failure of exception should not be fatal, its a best case helper.
catch { }
return null;
}
/// <summary>
/// Sniffs when the cluster state is stale, when sniffing returns a 401 return a response for T to return directly
/// </summary>
protected ElasticsearchResponse<T> TrySniffOnStaleClusterState<T>(TransportRequestState<T> requestState)
{
try
{
//If connectionSettings is configured to sniff periodically, sniff when stale.
this._delegator.SniffOnStaleClusterState(requestState);
return null;
}
catch(ElasticsearchAuthException e)
{
return this.HandleAuthenticationException(requestState, e);
}
}
protected ElasticsearchResponse<T> HandleAuthenticationException<T>(TransportRequestState<T> requestState, ElasticsearchAuthException exception)
{
if (requestState.ClientSettings.ThrowOnElasticsearchServerExceptions)
throw exception.ToElasticsearchServerException();
var response = ElasticsearchResponse.CloneFrom<T>(exception.Response, default(T));
response.Request = requestState.PostData;
response.RequestUrl = requestState.Path;
response.RequestMethod = requestState.Method;
return response;
}
}
}
| |
using DotVVM.Framework.Controls;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using DotVVM.Framework.Compilation.ControlTree;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Extensions.DependencyModel;
using System.Security.Cryptography;
using System.Text;
namespace DotVVM.Framework.Utils
{
public static class ReflectionUtils
{
public static IEnumerable<Assembly> GetAllAssemblies()
{
#if DotNetCore
return DependencyContext.Default.GetDefaultAssemblyNames().Select(Assembly.Load);
#else
return AppDomain.CurrentDomain.GetAssemblies();
#endif
}
public static bool IsFullName(string typeName)
=> typeName.Contains(".");
public static bool IsAssemblyNamespace(string fullName)
=> GetAllNamespaces().Contains(fullName, StringComparer.Ordinal);
public static ISet<string> GetAllNamespaces()
=> new HashSet<string>(GetAllAssemblies()
.SelectMany(a => a.GetLoadableTypes()
.Select(t => t.Namespace))
.Distinct()
.ToList());
/// <summary>
/// Gets the property name from lambda expression, e.g. 'a => a.FirstName'
/// </summary>
public static MemberInfo GetMemberFromExpression(Expression expression)
{
var body = expression as MemberExpression;
if (body == null)
{
var unaryExpressionBody = (UnaryExpression)expression;
body = unaryExpressionBody.Operand as MemberExpression;
}
return body.Member;
}
// http://haacked.com/archive/2012/07/23/get-all-types-in-an-assembly.aspx/
public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException("assembly");
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return e.Types.Where(t => t != null);
}
}
/// <summary>
/// Gets filesystem path of assembly CodeBase
/// http://stackoverflow.com/questions/52797/how-do-i-get-the-path-of-the-assembly-the-code-is-in
/// </summary>
public static string GetCodeBasePath(this Assembly assembly)
{
string codeBase = assembly.CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
return Uri.UnescapeDataString(uri.Path);
}
/// <summary>
/// Gets the specified property of a given object.
/// </summary>
public static object GetObjectPropertyValue(object item, string propertyName, out PropertyInfo prop)
{
prop = null;
if (item == null) return null;
var type = item.GetType();
prop = type.GetProperty(propertyName);
if (prop == null)
{
throw new Exception(String.Format("The object of type {0} does not have a property named {1}!", type, propertyName)); // TODO: exception handling
}
return prop.GetValue(item);
}
/// <summary>
/// Extracts the value of a specified property and converts it to string. If the property name is empty, returns a string representation of a given object.
/// Null values are converted to empty string.
/// </summary>
public static string ExtractMemberStringValue(object item, string propertyName)
{
if (!string.IsNullOrEmpty(propertyName))
{
PropertyInfo prop;
item = GetObjectPropertyValue(item, propertyName, out prop);
}
return item?.ToString() ?? "";
}
/// <summary>
/// Converts a value to a specified type
/// </summary>
public static object ConvertValue(object value, Type type)
{
var typeinfo = type.GetTypeInfo();
// handle null values
if ((value == null) && (typeinfo.IsValueType))
return Activator.CreateInstance(type);
// handle nullable types
if (typeinfo.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if ((value is string) && ((string)value == string.Empty))
{
// value is an empty string, return null
return null;
}
else
{
// value is not null
type = Nullable.GetUnderlyingType(type); typeinfo = type.GetTypeInfo();
}
}
// handle exceptions
if ((value is string) && (type == typeof(Guid)))
return new Guid((string)value);
if (type == typeof(object)) return value;
// handle enums
if (typeinfo.IsEnum && value is string)
{
var split = ((string)value).Split(',', '|');
var isFlags = type.GetTypeInfo().IsDefined(typeof(FlagsAttribute));
if (!isFlags && split.Length > 1) throw new Exception($"Enum {type} does allow multiple values. Use [FlagsAttribute] to allow it.");
dynamic result = null;
foreach (var val in split)
{
try
{
if (result == null) result = Enum.Parse(type, val.Trim(), ignoreCase: true); // Enum.TryParse requires type parameter
else
{
result |= (dynamic)Enum.Parse(type, val.Trim(), ignoreCase: true);
}
}
catch (Exception ex)
{
throw new Exception($"The enum {type} does not allow a value '{val}'!", ex); // TODO: exception handling
}
}
return result;
}
// generic to string
if (type == typeof(string))
{
return value.ToString();
}
if (value is string && type.IsArray)
{
var str = value as string;
var objectArray = str.Split(',').Select(s => ConvertValue(s.Trim(), typeinfo.GetElementType()))
.ToArray();
var array = Array.CreateInstance(type.GetElementType(), objectArray.Length);
objectArray.CopyTo(array, 0);
return array;
}
// convert
return Convert.ChangeType(value, type);
}
public static Type FindType(string name, bool ignoreCase = false)
{
var stringComparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
// Type.GetType might sometimes work well
var type = Type.GetType(name, false, ignoreCase);
if (type != null) return type;
var split = name.Split(',');
name = split[0];
var assemblies = ReflectionUtils.GetAllAssemblies();
if (split.Length > 1)
{
var assembly = split[1];
return assemblies.Where(a => a.GetName().Name == assembly).Select(a => a.GetType(name)).FirstOrDefault(t => t != null);
}
type = assemblies.Where(a => name.StartsWith(a.GetName().Name, stringComparison)).Select(a => a.GetType(name, false, ignoreCase)).FirstOrDefault(t => t != null);
if (type != null) return type;
return assemblies.Select(a => a.GetType(name, false, ignoreCase)).FirstOrDefault(t => t != null);
}
public static Type GetEnumerableType(Type collectionType)
{
var result = TypeDescriptorUtils.GetCollectionItemType(new ResolvedTypeDescriptor(collectionType));
if (result == null) return null;
return ResolvedTypeDescriptor.ToSystemType(result);
}
private static readonly HashSet<Type> NumericTypes = new HashSet<Type>()
{
typeof (sbyte),
typeof (byte),
typeof (short),
typeof (ushort),
typeof (int),
typeof (uint),
typeof (long),
typeof (ulong),
typeof (char),
typeof (float),
typeof (double),
typeof (decimal)
};
public static bool IsNumericType(this Type type)
{
return NumericTypes.Contains(type);
}
public static bool IsDynamicOrObject(this Type type)
{
return type.GetInterfaces().Contains(typeof(IDynamicMetaObjectProvider)) ||
type == typeof(object);
}
public static bool IsDelegate(this Type type)
{
return typeof(Delegate).IsAssignableFrom(type);
}
public static bool IsReferenceType(this Type type)
{
return type.IsArray || type.GetTypeInfo().IsClass || type.GetTypeInfo().IsInterface || type.IsDelegate();
}
public static bool IsDerivedFrom(this Type T, Type superClass)
{
return superClass.IsAssignableFrom(T);
}
public static bool Implements(this Type T, Type interfaceType)
{
return T.GetInterfaces().Any(x =>
{
return x.Name == interfaceType.Name;
});
}
public static bool IsDynamic(this Type type)
{
return type.GetInterfaces().Contains(typeof(IDynamicMetaObjectProvider));
}
public static bool IsObject(this Type type)
{
return type == typeof(Object);
}
public static bool IsNullable(this Type type)
{
return Nullable.GetUnderlyingType(type) != null;
}
public static T GetCustomAttribute<T>(this ICustomAttributeProvider attributeProvider, bool inherit = true) =>
(T)attributeProvider.GetCustomAttributes(typeof(T), inherit).FirstOrDefault();
public static IEnumerable<T> GetCustomAttributes<T>(this ICustomAttributeProvider attributeProvider, bool inherit = true) =>
attributeProvider.GetCustomAttributes(typeof(T), inherit).Cast<T>();
public static string GetTypeHash(this Type type)
{
using (var sha1 = SHA1.Create())
{
var hashBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(type.AssemblyQualifiedName));
return Convert.ToBase64String(hashBytes);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using System.Linq;
using Xunit;
using BindingFlags = System.Reflection.BindingFlags;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class ResultsViewTests : CSharpResultProviderTestBase
{
// IEnumerable pattern not supported.
[Fact]
public void IEnumerablePattern()
{
var source =
@"using System.Collections;
class C
{
private readonly IEnumerable e;
internal C(IEnumerable e)
{
this.e = e;
}
public IEnumerator GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly));
}
}
// IEnumerable<T> pattern not supported.
[Fact]
public void IEnumerableOfTPattern()
{
var source =
@"using System.Collections.Generic;
class C<T>
{
private readonly IEnumerable<T> e;
internal C(IEnumerable<T> e)
{
this.e = e;
}
public IEnumerator<T> GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("e", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly));
}
}
[Fact]
public void IEnumerableImplicitImplementation()
{
var source =
@"using System.Collections;
class C : IEnumerable
{
private readonly IEnumerable e;
internal C(IEnumerable e)
{
this.e = e;
}
public IEnumerator GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"e",
"{int[2]}",
"System.Collections.IEnumerable {int[]}",
"o.e",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[1]);
Verify(children,
EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[0]"),
EvalResult("[1]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[1]"));
}
}
[Fact]
public void IEnumerableOfTImplicitImplementation()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
struct S<T> : IEnumerable<T>
{
private readonly IEnumerable<T> e;
internal S(IEnumerable<T> e)
{
this.e = e;
}
public IEnumerator<T> GetEnumerator()
{
return this.e.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("S`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{S<int>}", "S<int>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"e",
"{int[2]}",
"System.Collections.Generic.IEnumerable<int> {int[]}",
"o.e",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[1]);
Verify(children,
EvalResult("[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]"),
EvalResult("[1]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[1]"));
}
}
[Fact]
public void IEnumerableExplicitImplementation()
{
var source =
@"using System.Collections;
class C : IEnumerable
{
private readonly IEnumerable e;
internal C(IEnumerable e)
{
this.e = e;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"e",
"{int[2]}",
"System.Collections.IEnumerable {int[]}",
"o.e",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[1]);
Verify(children,
EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[0]"),
EvalResult("[1]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o).Items[1]"));
}
}
[Fact]
public void IEnumerableOfTExplicitImplementation()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
class C<T> : IEnumerable<T>
{
private readonly IEnumerable<T> e;
internal C(IEnumerable<T> e)
{
this.e = e;
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.e.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"e",
"{int[2]}",
"System.Collections.Generic.IEnumerable<int> {int[]}",
"o.e",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[1]);
Verify(children,
EvalResult("[0]", "1", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]"),
EvalResult("[1]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[1]"));
}
}
// Results View not supported for
// IEnumerator implementation.
[Fact]
public void IEnumerator()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
class C : IEnumerator<int>
{
private int[] c = new[] { 1, 2, 3 };
private int i = 0;
object IEnumerator.Current
{
get { return this.c[this.i]; }
}
int IEnumerator<int>.Current
{
get { return this.c[this.i]; }
}
bool IEnumerator.MoveNext()
{
this.i++;
return this.i < this.c.Length;
}
void IEnumerator.Reset()
{
this.i = 0;
}
void IDisposable.Dispose()
{
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"System.Collections.Generic.IEnumerator<int>.Current",
"1",
"int",
"((System.Collections.Generic.IEnumerator<int>)o).Current",
DkmEvaluationResultFlags.ReadOnly),
EvalResult(
"System.Collections.IEnumerator.Current",
"1",
"object {int}",
"((System.Collections.IEnumerator)o).Current",
DkmEvaluationResultFlags.ReadOnly),
EvalResult("c", "{int[3]}", "int[]", "o.c", DkmEvaluationResultFlags.Expandable),
EvalResult("i", "0", "int", "o.i"));
}
}
[Fact]
public void Overrides()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
class A : IEnumerable<object>
{
public virtual IEnumerator<object> GetEnumerator()
{
yield return 0;
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
class B1 : A
{
public override IEnumerator<object> GetEnumerator()
{
yield return 1;
}
}
class B2 : A, IEnumerable<int>
{
public new IEnumerator<int> GetEnumerator()
{
yield return 2;
}
}
class B3 : A
{
public new IEnumerable<int> GetEnumerator()
{
yield return 3;
}
}
class B4 : A
{
}
class C
{
A _1 = new B1();
A _2 = new B2();
A _3 = new B3();
A _4 = new B4();
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("_1", "{B1}", "A {B1}", "o._1", DkmEvaluationResultFlags.Expandable),
EvalResult("_2", "{B2}", "A {B2}", "o._2", DkmEvaluationResultFlags.Expandable),
EvalResult("_3", "{B3}", "A {B3}", "o._3", DkmEvaluationResultFlags.Expandable),
EvalResult("_4", "{B4}", "A {B4}", "o._4", DkmEvaluationResultFlags.Expandable));
// A _1 = new B1();
var moreChildren = GetChildren(children[0]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._1, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._1).Items[0]"));
// A _2 = new B2();
moreChildren = GetChildren(children[1]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._2, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult("[0]", "2", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(o._2).Items[0]"));
// A _3 = new B3();
moreChildren = GetChildren(children[2]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._3, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._3).Items[0]"));
// A _4 = new B4();
moreChildren = GetChildren(children[3]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._4, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._4).Items[0]"));
}
}
/// <summary>
/// Include Results View on base types
/// (matches legacy EE behavior).
/// </summary>
[Fact]
public void BaseTypes()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
class A1
{
}
class B1 : A1, IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return 0;
}
}
class A2
{
public IEnumerator GetEnumerator()
{
yield return 1;
}
}
class B2 : A2, IEnumerable<object>
{
IEnumerator<object> IEnumerable<object>.GetEnumerator()
{
yield return 2;
}
}
struct S : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return 3;
}
}
class C
{
A1 _1 = new B1();
B2 _2 = new B2();
System.ValueType _3 = new S();
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("_1", "{B1}", "A1 {B1}", "o._1", DkmEvaluationResultFlags.Expandable),
EvalResult("_2", "{B2}", "B2", "o._2", DkmEvaluationResultFlags.Expandable),
EvalResult("_3", "{S}", "System.ValueType {S}", "o._3", DkmEvaluationResultFlags.Expandable));
// A1 _1 = new B1();
var moreChildren = GetChildren(children[0]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._1, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
Verify(GetChildren(moreChildren[0]),
EvalResult("[0]", "0", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o._1).Items[0]"));
// B2 _2 = new B2();
moreChildren = GetChildren(children[1]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._2, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
Verify(GetChildren(moreChildren[0]),
EvalResult("[0]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView<object>(o._2).Items[0]"));
// System.ValueType _3 = new S();
moreChildren = GetChildren(children[2]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._3, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
Verify(GetChildren(moreChildren[0]),
EvalResult("[0]", "3", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(o._3).Items[0]"));
}
}
[Fact]
public void Nullable()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
struct S : IEnumerable<object>
{
internal readonly object[] c;
internal S(object[] c)
{
this.c = c;
}
public IEnumerator<object> GetEnumerator()
{
foreach (var o in this.c)
{
yield return o;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
class C
{
S? F = new S(new object[] { null });
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "{S}", "S?", "o.F", DkmEvaluationResultFlags.Expandable));
children = GetChildren(children[0]);
Verify(children,
EvalResult("c", "{object[1]}", "object[]", "o.F.c", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o.F, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[1]);
Verify(children,
EvalResult(
"[0]",
"null",
"object",
"new System.Linq.SystemCore_EnumerableDebugView<object>(o.F).Items[0]"));
}
}
[Fact]
public void ConstructedType()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
class A<T> : IEnumerable<T>
{
private readonly T[] items;
internal A(T[] items)
{
this.items = items;
}
public IEnumerator<T> GetEnumerator()
{
foreach (var item in items)
{
yield return item;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
class B
{
internal object F;
}
class C : A<B>
{
internal C() : base(new[] { new B() })
{
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"items",
"{B[1]}",
"B[]",
"o.items",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
var moreChildren = GetChildren(children[1]);
Verify(moreChildren,
// The legacy EE treats the Items elements as readonly, but since
// Items is a T[], we treat the elements as read/write. However, Items
// is not updated when modifying elements so this is harmless.
EvalResult(
"[0]",
"{B}",
"B",
"new System.Linq.SystemCore_EnumerableDebugView<B>(o).Items[0]",
DkmEvaluationResultFlags.Expandable));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult("F", "null", "object", "new System.Linq.SystemCore_EnumerableDebugView<B>(o).Items[0].F"));
}
}
/// <summary>
/// System.Array should not have Results View.
/// </summary>
[Fact]
public void Array()
{
var source =
@"using System;
using System.Collections;
class C
{
char[] _1 = new char[] { '1' };
Array _2 = new char[] { '2' };
IEnumerable _3 = new char[] { '3' };
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("_1", "{char[1]}", "char[]", "o._1", DkmEvaluationResultFlags.Expandable),
EvalResult("_2", "{char[1]}", "System.Array {char[]}", "o._2", DkmEvaluationResultFlags.Expandable),
EvalResult("_3", "{char[1]}", "System.Collections.IEnumerable {char[]}", "o._3", DkmEvaluationResultFlags.Expandable));
Verify(GetChildren(children[0]),
EvalResult("[0]", "49 '1'", "char", "o._1[0]", editableValue: "'1'"));
Verify(GetChildren(children[1]),
EvalResult("[0]", "50 '2'", "char", "((char[])o._2)[0]", editableValue: "'2'"));
children = GetChildren(children[2]);
Verify(children,
EvalResult("[0]", "51 '3'", "char", "((char[])o._3)[0]", editableValue: "'3'"));
}
}
/// <summary>
/// String should not have Results View.
/// </summary>
[Fact]
public void String()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
class C
{
string _1 = ""1"";
object _2 = ""2"";
IEnumerable _3 = ""3"";
IEnumerable<char> _4 = ""4"";
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("_1", "\"1\"", "string", "o._1", DkmEvaluationResultFlags.RawString, editableValue: "\"1\""),
EvalResult("_2", "\"2\"", "object {string}", "o._2", DkmEvaluationResultFlags.RawString, editableValue: "\"2\""),
EvalResult("_3", "\"3\"", "System.Collections.IEnumerable {string}", "o._3", DkmEvaluationResultFlags.RawString, editableValue: "\"3\""),
EvalResult("_4", "\"4\"", "System.Collections.Generic.IEnumerable<char> {string}", "o._4", DkmEvaluationResultFlags.RawString, editableValue: "\"4\""));
}
}
[WorkItem(1006160)]
[Fact]
public void MultipleImplementations_DifferentImplementors()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
class A<T> : IEnumerable<T>
{
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
yield return default(T);
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
class B1 : A<object>, IEnumerable<int>
{
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
yield return 1;
}
}
class B2 : A<int>, IEnumerable<object>
{
IEnumerator<object> IEnumerable<object>.GetEnumerator()
{
yield return null;
}
}
class B3 : A<object>, IEnumerable
{
IEnumerator IEnumerable.GetEnumerator()
{
yield return 3;
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
// class B1 : A<object>, IEnumerable<int>
var type = assembly.GetType("B1");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B1}", "B1", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[0]);
Verify(children,
EvalResult(
"[0]",
"1",
"int",
"new System.Linq.SystemCore_EnumerableDebugView<int>(o).Items[0]"));
// class B2 : A<int>, IEnumerable<object>
type = assembly.GetType("B2");
value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B2}", "B2", "o", DkmEvaluationResultFlags.Expandable));
children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[0]);
Verify(children,
EvalResult(
"[0]",
"null",
"object",
"new System.Linq.SystemCore_EnumerableDebugView<object>(o).Items[0]"));
// class B3 : A<object>, IEnumerable
type = assembly.GetType("B3");
value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B3}", "B3", "o", DkmEvaluationResultFlags.Expandable));
children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[0]);
Verify(children,
EvalResult(
"[0]",
"null",
"object",
"new System.Linq.SystemCore_EnumerableDebugView<object>(o).Items[0]"));
}
}
[Fact]
public void MultipleImplementations_SameImplementor()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
class A : IEnumerable<int>, IEnumerable<string>
{
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
yield return 1;
}
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
yield return null;
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
class B : IEnumerable<string>, IEnumerable<int>
{
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
yield return null;
}
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
yield return 1;
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
// class A : IEnumerable<int>, IEnumerable<string>
var type = assembly.GetType("A");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("a", value);
Verify(evalResult,
EvalResult("a", "{A}", "A", "a", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"a, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[0]);
Verify(children,
EvalResult(
"[0]",
"1",
"int",
"new System.Linq.SystemCore_EnumerableDebugView<int>(a).Items[0]"));
// class B : IEnumerable<string>, IEnumerable<int>
type = assembly.GetType("B");
value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
evalResult = FormatResult("b", value);
Verify(evalResult,
EvalResult("b", "{B}", "B", "b", DkmEvaluationResultFlags.Expandable));
children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"b, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[0]);
Verify(children,
EvalResult(
"[0]",
"null",
"string",
"new System.Linq.SystemCore_EnumerableDebugView<string>(b).Items[0]"));
}
}
/// <summary>
/// Types with [DebuggerTypeProxy] should not have Results View.
/// </summary>
[Fact]
public void DebuggerTypeProxy()
{
var source =
@"using System.Collections;
using System.Diagnostics;
public class P : IEnumerable
{
private readonly C c;
public P(C c)
{
this.c = c;
}
public IEnumerator GetEnumerator()
{
return this.c.GetEnumerator();
}
public int Length
{
get { return this.c.o.Length; }
}
}
[DebuggerTypeProxy(typeof(P))]
public class C : IEnumerable
{
internal readonly object[] o;
public C(object[] o)
{
this.o = o;
}
public IEnumerator GetEnumerator()
{
return this.o.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new object[] { new object[] { string.Empty } }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Length", "1", "int", "new P(o).Length", DkmEvaluationResultFlags.ReadOnly),
EvalResult("Raw View", null, "", "o, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
children = GetChildren(children[1]);
Verify(children,
EvalResult("o", "{object[1]}", "object[]", "o.o", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly));
}
}
/// <summary>
/// Do not expose Results View if the proxy type is missing.
/// </summary>
[Fact]
public void MissingProxyType()
{
var source =
@"using System.Collections;
class C : IEnumerable
{
private readonly IEnumerable e;
internal C(IEnumerable e)
{
this.e = e;
}
public IEnumerator GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = new[] { assembly };
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly));
}
}
/// <summary>
/// Proxy type not in System.Core.dll.
/// </summary>
[Fact]
public void MissingProxyType_SystemCore()
{
// "System.Core.dll"
var source0 = "";
var compilation0 = CSharpTestBase.CreateCompilationWithMscorlib(source0, assemblyName: "system.core");
var assembly0 = ReflectionUtilities.Load(compilation0.EmitToArray());
var source =
@"using System.Collections;
class C : IEnumerable
{
private readonly IEnumerable e;
internal C(IEnumerable e)
{
this.e = e;
}
public IEnumerator GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = new[] { assembly0, assembly };
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly));
// Verify the module was found but ResolveTypeName failed.
var module = runtime.Modules.Single(m => m.Assembly == assembly0);
Assert.Equal(module.ResolveTypeNameFailures, 1);
}
}
/// <summary>
/// Report "Enumeration yielded no results" when
/// GetEnumerator returns an empty collection or null.
/// </summary>
[Fact]
public void GetEnumeratorEmptyOrNull()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
// IEnumerable returns empty collection.
class C0 : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield break;
}
}
// IEnumerable<T> returns empty collection.
class C1<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
yield break;
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
// IEnumerable returns null.
class C2 : IEnumerable
{
public IEnumerator GetEnumerator()
{
return null;
}
}
// IEnumerable<T> returns null.
class C3<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
return null;
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
class C
{
C0 _0 = new C0();
C1<object> _1 = new C1<object>();
C2 _2 = new C2();
C3<object> _3 = new C3<object>();
}";
using (new EnsureEnglishUICulture())
{
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("_0", "{C0}", "C0", "o._0", DkmEvaluationResultFlags.Expandable),
EvalResult("_1", "{C1<object>}", "C1<object>", "o._1", DkmEvaluationResultFlags.Expandable),
EvalResult("_2", "{C2}", "C2", "o._2", DkmEvaluationResultFlags.Expandable),
EvalResult("_3", "{C3<object>}", "C3<object>", "o._3", DkmEvaluationResultFlags.Expandable));
// C0 _0 = new C0();
var moreChildren = GetChildren(children[0]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._0, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult(
"Empty",
"\"Enumeration yielded no results\"",
"string",
null,
DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString));
// C1<object> _1 = new C1<object>();
moreChildren = GetChildren(children[1]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._1, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult(
"Empty",
"\"Enumeration yielded no results\"",
"string",
null,
DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString));
// C2 _2 = new C2();
moreChildren = GetChildren(children[2]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._2, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult(
"Empty",
"\"Enumeration yielded no results\"",
"string",
null,
DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString));
// C3<object> _3 = new C3<object>();
moreChildren = GetChildren(children[3]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._3, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult(
"Empty",
"\"Enumeration yielded no results\"",
"string",
null,
DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.RawString));
}
}
}
/// <summary>
/// Do not instantiate proxy type for null IEnumerable.
/// </summary>
[WorkItem(1009646)]
[Fact]
public void IEnumerableNull()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
interface I : IEnumerable
{
}
class C
{
IEnumerable<char> E = null;
I F = null;
string S = null;
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("E", "null", "System.Collections.Generic.IEnumerable<char>", "o.E"),
EvalResult("F", "null", "I", "o.F"),
EvalResult("S", "null", "string", "o.S"));
}
}
[Fact]
public void GetEnumeratorException()
{
var source =
@"using System;
using System.Collections;
class C : IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}";
using (new EnsureEnglishUICulture())
{
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.GetMscorlibAndSystemCore(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new DkmClrRuntimeInstance(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[0]);
Verify(children[6],
EvalResult("Message", "\"The method or operation is not implemented.\"", "string", null, DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly));
}
}
}
[Fact, WorkItem(1145125, "DevDiv")]
public void GetEnumerableException()
{
var source =
@"using System;
using System.Collections;
class E : Exception, IEnumerable
{
IEnumerator IEnumerable.GetEnumerator()
{
yield return 1;
}
}
class C
{
internal IEnumerable P
{
get { throw new NotImplementedException(); }
}
internal IEnumerable Q
{
get { throw new E(); }
}
}";
var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)));
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = CreateDkmClrValue(type.Instantiate(), type: type);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"P",
"'o.P' threw an exception of type 'System.NotImplementedException'",
"System.Collections.IEnumerable {System.NotImplementedException}",
"o.P",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.ExceptionThrown),
EvalResult(
"Q",
"'o.Q' threw an exception of type 'E'",
"System.Collections.IEnumerable {E}",
"o.Q",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.ExceptionThrown));
children = GetChildren(children[1]);
Verify(children[6],
EvalResult(
"Message",
"\"Exception of type 'E' was thrown.\"",
"string",
null,
DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly));
}
}
[Fact]
public void GetEnumerableError()
{
var source =
@"using System.Collections;
class C
{
bool f;
internal ArrayList P
{
get { while (!this.f) { } return new ArrayList(); }
}
}";
DkmClrRuntimeInstance runtime = null;
GetMemberValueDelegate getMemberValue = (v, m) => (m == "P") ? CreateErrorValue(runtime.GetType(typeof(System.Collections.ArrayList)), "Function evaluation timed out") : null;
runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue);
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = CreateDkmClrValue(type.Instantiate(), type: type);
var memberValue = value.GetMemberValue("P", (int)System.Reflection.MemberTypes.Property, "C", DefaultInspectionContext);
var evalResult = FormatResult("o.P", memberValue);
Verify(evalResult,
EvalFailedResult("o.P", "Function evaluation timed out", "System.Collections.ArrayList", "o.P"));
}
}
/// <summary>
/// If evaluation of the proxy Items property returns an error
/// (say, evaluation of the enumerable requires func-eval and
/// either func-eval is disabled or we're debugging a .dmp),
/// we should include a row that reports the error rather than
/// having an empty expansion (since the container Items property
/// is [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]).
/// Note, the native EE has an empty expansion when .dmp debugging.
/// </summary>
[WorkItem(1043746)]
[Fact]
public void GetProxyPropertyValueError()
{
var source =
@"using System.Collections;
class C : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return 1;
}
}";
DkmClrRuntimeInstance runtime = null;
GetMemberValueDelegate getMemberValue = (v, m) => (m == "Items") ? CreateErrorValue(runtime.GetType(typeof(object)).MakeArrayType(), string.Format("Unable to evaluate '{0}'", m)) : null;
runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue);
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = CreateDkmClrValue(type.Instantiate(), type: type);
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(children[0]);
Verify(children,
EvalFailedResult("Error", "Unable to evaluate 'Items'", flags: DkmEvaluationResultFlags.None));
}
}
/// <summary>
/// Root-level synthetic values declared as IEnumerable or
/// IEnumerable<T> should be expanded directly
/// without intermediate "Results View" row.
/// </summary>
[WorkItem(1114276)]
[Fact]
public void SyntheticIEnumerable()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
class C
{
IEnumerable P { get { yield return 1; yield return 2; } }
IEnumerable<int> Q { get { yield return 3; } }
IEnumerable R { get { return null; } }
IEnumerable S { get { return string.Empty; } }
IEnumerable<int> T { get { return new int[] { 4, 5 }; } }
IList<int> U { get { return new List<int>(new int[] { 6 }); } }
}";
var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)));
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = type.Instantiate();
// IEnumerable
var evalResult = FormatPropertyValue(runtime, value, "P");
Verify(evalResult,
EvalResult(
"P",
"{C.<get_P>d__1}",
"System.Collections.IEnumerable {C.<get_P>d__1}",
"P",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(P).Items[0]"),
EvalResult("[1]", "2", "object {int}", "new System.Linq.SystemCore_EnumerableDebugView(P).Items[1]"));
// IEnumerable<int>
evalResult = FormatPropertyValue(runtime, value, "Q");
Verify(evalResult,
EvalResult(
"Q",
"{C.<get_Q>d__3}",
"System.Collections.Generic.IEnumerable<int> {C.<get_Q>d__3}",
"Q",
DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly,
DkmEvaluationResultCategory.Method));
children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "3", "int", "new System.Linq.SystemCore_EnumerableDebugView<int>(Q).Items[0]"));
// null (unchanged)
evalResult = FormatPropertyValue(runtime, value, "R");
Verify(evalResult,
EvalResult(
"R",
"null",
"System.Collections.IEnumerable",
"R",
DkmEvaluationResultFlags.None));
// string (unchanged)
evalResult = FormatPropertyValue(runtime, value, "S");
Verify(evalResult,
EvalResult(
"S",
"\"\"",
"System.Collections.IEnumerable {string}",
"S",
DkmEvaluationResultFlags.RawString,
DkmEvaluationResultCategory.Other,
editableValue: "\"\""));
// array (unchanged)
evalResult = FormatPropertyValue(runtime, value, "T");
Verify(evalResult,
EvalResult(
"T",
"{int[2]}",
"System.Collections.Generic.IEnumerable<int> {int[]}",
"T",
DkmEvaluationResultFlags.Expandable));
children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "4", "int", "((int[])T)[0]"),
EvalResult("[1]", "5", "int", "((int[])T)[1]"));
// IList<int> declared type (unchanged)
evalResult = FormatPropertyValue(runtime, value, "U");
Verify(evalResult,
EvalResult(
"U",
"Count = 1",
"System.Collections.Generic.IList<int> {System.Collections.Generic.List<int>}",
"U",
DkmEvaluationResultFlags.Expandable));
children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "6", "int", "new System.Collections.Generic.Mscorlib_CollectionDebugView<int>(U).Items[0]"),
EvalResult("Raw View", null, "", "U, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));
}
}
private DkmEvaluationResult FormatPropertyValue(DkmClrRuntimeInstance runtime, object value, string propertyName)
{
var propertyInfo = value.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var propertyValue = propertyInfo.GetValue(value);
var propertyType = runtime.GetType(propertyInfo.PropertyType);
var valueType = (propertyValue == null) ? propertyType : runtime.GetType(propertyValue.GetType());
return FormatResult(
propertyName,
CreateDkmClrValue(propertyValue, type: valueType, valueFlags: DkmClrValueFlags.Synthetic),
declaredType: propertyType);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using System.Globalization;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies the state of the <see cref="JsonWriter"/>.
/// </summary>
public enum WriteState
{
/// <summary>
/// An exception has been thrown, which has left the <see cref="JsonWriter"/> in an invalid state.
/// You may call the <see cref="JsonWriter.Close"/> method to put the <see cref="JsonWriter"/> in the <c>Closed</c> state.
/// Any other <see cref="JsonWriter"/> method calls results in an <see cref="InvalidOperationException"/> being thrown.
/// </summary>
Error,
/// <summary>
/// The <see cref="JsonWriter.Close"/> method has been called.
/// </summary>
Closed,
/// <summary>
/// An object is being written.
/// </summary>
Object,
/// <summary>
/// A array is being written.
/// </summary>
Array,
/// <summary>
/// A constructor is being written.
/// </summary>
Constructor,
/// <summary>
/// A property is being written.
/// </summary>
Property,
/// <summary>
/// A write method has not been called.
/// </summary>
Start
}
/// <summary>
/// Specifies formatting options for the <see cref="JsonTextWriter"/>.
/// </summary>
public enum Formatting
{
/// <summary>
/// No special formatting is applied. This is the default.
/// </summary>
None,
/// <summary>
/// Causes child objects to be indented according to the <see cref="JsonTextWriter.Indentation"/> and <see cref="JsonTextWriter.IndentChar"/> settings.
/// </summary>
Indented
}
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating Json data.
/// </summary>
public abstract class JsonWriter : IDisposable
{
private enum State
{
Start,
Property,
ObjectStart,
Object,
ArrayStart,
Array,
ConstructorStart,
Constructor,
Bytes,
Closed,
Error
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] stateArray = new[] {
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[]{ State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[]{ State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[]{ State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[]{ State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* StartProperty */new[]{ State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[]{ State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value */new[]{ State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
};
private int _top;
private readonly List<JTokenType> _stack;
private State _currentState;
private Formatting _formatting;
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the writer is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the writer is closed; otherwise false. The default is true.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get { return _top; }
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw new JsonWriterException("Invalid state: " + _currentState);
}
}
}
/// <summary>
/// Indicates how the output is formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting; }
set { _formatting = value; }
}
/// <summary>
/// Creates an instance of the <c>JsonWriter</c> class.
/// </summary>
protected JsonWriter()
{
_stack = new List<JTokenType>(8);
_stack.Add(JTokenType.None);
_currentState = State.Start;
_formatting = Formatting.None;
CloseOutput = true;
}
private void Push(JTokenType value)
{
_top++;
if (_stack.Count <= _top)
_stack.Add(value);
else
_stack[_top] = value;
}
private JTokenType Pop()
{
JTokenType value = Peek();
_top--;
return value;
}
private JTokenType Peek()
{
return _stack[_top];
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public virtual void Close()
{
AutoCompleteAll();
}
/// <summary>
/// Writes the beginning of a Json object.
/// </summary>
public virtual void WriteStartObject()
{
AutoComplete(JsonToken.StartObject);
Push(JTokenType.Object);
}
/// <summary>
/// Writes the end of a Json object.
/// </summary>
public void WriteEndObject()
{
AutoCompleteClose(JsonToken.EndObject);
}
/// <summary>
/// Writes the beginning of a Json array.
/// </summary>
public virtual void WriteStartArray()
{
AutoComplete(JsonToken.StartArray);
Push(JTokenType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public void WriteEndArray()
{
AutoCompleteClose(JsonToken.EndArray);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
AutoComplete(JsonToken.StartConstructor);
Push(JTokenType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public void WriteEndConstructor()
{
AutoCompleteClose(JsonToken.EndConstructor);
}
/// <summary>
/// Writes the property name of a name/value pair on a Json object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
AutoComplete(JsonToken.PropertyName);
}
/// <summary>
/// Writes the end of the current Json object or array.
/// </summary>
public void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
ValidationUtils.ArgumentNotNull(reader, "reader");
int initialDepth;
if (reader.TokenType == JsonToken.None)
initialDepth = -1;
else if (!IsStartToken(reader.TokenType))
initialDepth = reader.Depth + 1;
else
initialDepth = reader.Depth;
WriteToken(reader, initialDepth);
}
internal void WriteToken(JsonReader reader, int initialDepth)
{
do
{
switch (reader.TokenType)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
// write a JValue date when the constructor is for a date
if (string.Compare(constructorName, "Date", StringComparison.Ordinal) == 0)
WriteConstructorDate(reader);
else
WriteStartConstructor(reader.Value.ToString());
break;
case JsonToken.PropertyName:
WritePropertyName(reader.Value.ToString());
break;
case JsonToken.Comment:
WriteComment(reader.Value.ToString());
break;
case JsonToken.Integer:
WriteValue((long)reader.Value);
break;
case JsonToken.Float:
WriteValue((double)reader.Value);
break;
case JsonToken.String:
WriteValue(reader.Value.ToString());
break;
case JsonToken.Boolean:
WriteValue((bool)reader.Value);
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
WriteValue((DateTime)reader.Value);
break;
case JsonToken.Raw:
WriteRawValue((string)reader.Value);
break;
case JsonToken.Bytes:
WriteValue((byte[])reader.Value);
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", reader.TokenType, "Unexpected token type.");
}
}
while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (IsEndToken(reader.TokenType) ? 1 : 0)
&& reader.Read());
}
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
throw new Exception("Unexpected end while reading date constructor.");
if (reader.TokenType != JsonToken.Integer)
throw new Exception("Unexpected token while reading date constructor. Expected Integer, got " + reader.TokenType);
long ticks = (long)reader.Value;
DateTime date = JsonConvert.ConvertJavaScriptTicksToDateTime(ticks);
if (!reader.Read())
throw new Exception("Unexpected end while reading date constructor.");
if (reader.TokenType != JsonToken.EndConstructor)
throw new Exception("Unexpected token while reading date constructor. Expected EndConstructor, got " + reader.TokenType);
WriteValue(date);
}
private bool IsEndToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
case JsonToken.EndArray:
case JsonToken.EndConstructor:
return true;
default:
return false;
}
}
private bool IsStartToken(JsonToken token)
{
switch (token)
{
case JsonToken.StartObject:
case JsonToken.StartArray:
case JsonToken.StartConstructor:
return true;
default:
return false;
}
}
private void WriteEnd(JTokenType type)
{
switch (type)
{
case JTokenType.Object:
WriteEndObject();
break;
case JTokenType.Array:
WriteEndArray();
break;
case JTokenType.Constructor:
WriteEndConstructor();
break;
default:
throw new JsonWriterException("Unexpected type when writing end: " + type);
}
}
private void AutoCompleteAll()
{
while (_top > 0)
{
WriteEnd();
}
}
private JTokenType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JTokenType.Object;
case JsonToken.EndArray:
return JTokenType.Array;
case JsonToken.EndConstructor:
return JTokenType.Constructor;
default:
throw new JsonWriterException("No type for token: " + token);
}
}
private JsonToken GetCloseTokenForType(JTokenType type)
{
switch (type)
{
case JTokenType.Object:
return JsonToken.EndObject;
case JTokenType.Array:
return JsonToken.EndArray;
case JTokenType.Constructor:
return JsonToken.EndConstructor;
default:
throw new JsonWriterException("No close token for type: " + type);
}
}
private void AutoCompleteClose(JsonToken tokenBeingClosed)
{
// write closing symbol and calculate new state
int levelsToComplete = 0;
for (int i = 0; i < _top; i++)
{
int currentLevel = _top - i;
if (_stack[currentLevel] == GetTypeForCloseToken(tokenBeingClosed))
{
levelsToComplete = i + 1;
break;
}
}
if (levelsToComplete == 0)
throw new JsonWriterException("No token to close.");
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
WriteIndent();
WriteEnd(token);
}
JTokenType currentLevelType = Peek();
switch (currentLevelType)
{
case JTokenType.Object:
_currentState = State.Object;
break;
case JTokenType.Array:
_currentState = State.Array;
break;
case JTokenType.Constructor:
_currentState = State.Array;
break;
case JTokenType.None:
_currentState = State.Start;
break;
default:
throw new JsonWriterException("Unknown JsonType: " + currentLevelType);
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
int token;
switch (tokenBeingWritten)
{
default:
token = (int)tokenBeingWritten;
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
// a value is being written
token = 7;
break;
}
// gets new state based on the current state and what is being written
State newState = stateArray[token][(int)_currentState];
if (newState == State.Error)
throw new JsonWriterException("Token {0} in state {1} would result in an invalid JavaScript object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()));
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
else if (_currentState == State.Property)
{
if (_formatting == Formatting.Indented)
WriteIndentSpace();
}
WriteState writeState = WriteState;
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((tokenBeingWritten == JsonToken.PropertyName && writeState != WriteState.Start) ||
writeState == WriteState.Array || writeState == WriteState.Constructor)
{
WriteIndent();
}
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
AutoComplete(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
AutoComplete(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
{
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
{
// hack. want writer to change state as if a value had been written
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
AutoComplete(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
AutoComplete(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte value)
{
AutoComplete(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
AutoComplete(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
AutoComplete(JsonToken.Date);
}
#if !PocketPC && !NET20
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
AutoComplete(JsonToken.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Nullable{Int32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Single}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Double}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Boolean}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Int16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{UInt16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Char}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Byte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{SByte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{Decimal}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
/// <summary>
/// Writes a <see cref="Nullable{DateTime}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
#if !PocketPC && !NET20
/// <summary>
/// Writes a <see cref="Nullable{DateTimeOffset}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
WriteNull();
else
WriteValue(value.Value);
}
#endif
/// <summary>
/// Writes a <see cref="T:Byte[]"/> value.
/// </summary>
/// <param name="value">The <see cref="T:Byte[]"/> value to write.</param>
public virtual void WriteValue(byte[] value)
{
if (value == null)
WriteNull();
else
AutoComplete(JsonToken.Bytes);
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object value)
{
if (value == null)
{
WriteNull();
return;
}
else if (value is IConvertible)
{
IConvertible convertible = value as IConvertible;
switch (convertible.GetTypeCode())
{
case TypeCode.String:
WriteValue(convertible.ToString(CultureInfo.InvariantCulture));
return;
case TypeCode.Char:
WriteValue(convertible.ToChar(CultureInfo.InvariantCulture));
return;
case TypeCode.Boolean:
WriteValue(convertible.ToBoolean(CultureInfo.InvariantCulture));
return;
case TypeCode.SByte:
WriteValue(convertible.ToSByte(CultureInfo.InvariantCulture));
return;
case TypeCode.Int16:
WriteValue(convertible.ToInt16(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt16:
WriteValue(convertible.ToUInt16(CultureInfo.InvariantCulture));
return;
case TypeCode.Int32:
WriteValue(convertible.ToInt32(CultureInfo.InvariantCulture));
return;
case TypeCode.Byte:
WriteValue(convertible.ToByte(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt32:
WriteValue(convertible.ToUInt32(CultureInfo.InvariantCulture));
return;
case TypeCode.Int64:
WriteValue(convertible.ToInt64(CultureInfo.InvariantCulture));
return;
case TypeCode.UInt64:
WriteValue(convertible.ToUInt64(CultureInfo.InvariantCulture));
return;
case TypeCode.Single:
WriteValue(convertible.ToSingle(CultureInfo.InvariantCulture));
return;
case TypeCode.Double:
WriteValue(convertible.ToDouble(CultureInfo.InvariantCulture));
return;
case TypeCode.DateTime:
WriteValue(convertible.ToDateTime(CultureInfo.InvariantCulture));
return;
case TypeCode.Decimal:
WriteValue(convertible.ToDecimal(CultureInfo.InvariantCulture));
return;
case TypeCode.DBNull:
WriteNull();
return;
}
}
#if !PocketPC && !NET20
else if (value is DateTimeOffset)
{
WriteValue((DateTimeOffset)value);
return;
}
#endif
else if (value is byte[])
{
WriteValue((byte[])value);
return;
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#endregion
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string text)
{
AutoComplete(JsonToken.Comment);
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
throw new JsonWriterException("Only white space characters should be used.");
}
}
void IDisposable.Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (WriteState != WriteState.Closed)
Close();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using log4net;
using NetGore;
using NetGore.World;
namespace DemoGame
{
/// <summary>
/// Base class for keeping track of a collection of equipped items.
/// </summary>
public abstract class EquippedBase<T> : IDisposable, IEnumerable<KeyValuePair<EquipmentSlot, T>> where T : ItemEntityBase
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Greatest index of all the EquipmentSlots.
/// </summary>
static readonly int _highestSlotIndex = EnumHelper<EquipmentSlot>.MaxValue;
/// <summary>
/// Array indexed by the numeric value of the EquipmentSlot, containing the item
/// corresponding to that slot.
/// </summary>
readonly T[] _equipped = new T[_highestSlotIndex + 1];
bool _disposed = false;
/// <summary>
/// Notifies listeners when an item has been equipped.
/// </summary>
public event TypedEventHandler<EquippedBase<T>, EquippedEventArgs<T>> Equipped;
/// <summary>
/// Notifies listeners when an item has been unequipped.
/// </summary>
public event TypedEventHandler<EquippedBase<T>, EquippedEventArgs<T>> Unequipped;
/// <summary>
/// Gets the item at the given <paramref name="slot"/>.
/// </summary>
/// <param name="slot">Slot to get the item of.</param>
/// <returns>Item at the specified <paramref name="slot"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1043:UseIntegralOrStringArgumentForIndexers")]
public T this[EquipmentSlot slot]
{
get { return this[slot.GetValue()]; }
}
/// <summary>
/// Gets the item at the given <paramref name="slot"/>.
/// </summary>
/// <param name="slot">Index of the slot. This must be a valid value, since no bounds-checking
/// is performed (which is why this is only private).</param>
/// <returns>Item at the specified <paramref name="slot"/>.</returns>
T this[int slot]
{
get { return _equipped[slot]; }
}
/// <summary>
/// Gets if this object has been disposed.
/// </summary>
public bool IsDisposed
{
get { return _disposed; }
}
/// <summary>
/// Gets all of the equipped items in this collection.
/// </summary>
public IEnumerable<T> Items
{
get
{
for (var i = 0; i < _equipped.Length; i++)
{
if (_equipped[i] != null)
yield return _equipped[i];
}
}
}
/// <summary>
/// When overridden in the derived class, checks if the given <paramref name="item"/> can be
/// equipped at all by the owner of this EquippedBase. This does not guarentee that the item
/// will be equipped successfully when calling Equip().
/// </summary>
/// <param name="item">Item to check if able to be equipped.</param>
/// <returns>True if the <paramref name="item"/> can be equipped, else false.</returns>
public abstract bool CanEquip(T item);
/// <summary>
/// When overridden in the derived class, checks if the item in the given <paramref name="slot"/>
/// can be removed properly.
/// </summary>
/// <param name="slot">Slot of the item to be removed.</param>
/// <returns>True if the item can be properly removed, else false.</returns>
protected abstract bool CanRemove(EquipmentSlot slot);
/// <summary>
/// When overridden in the derived class, handles when this object is disposed.
/// </summary>
/// <param name="disposeManaged">True if dispose was called directly; false if this object was garbage collected.</param>
protected virtual void Dispose(bool disposeManaged)
{
}
/// <summary>
/// Gets the EquipmentSlot of the specified <paramref name="item"/> in this EquippedBase.
/// </summary>
/// <param name="item">Item to find the EquipmentSlot for.</param>
/// <returns>EquipmentSlot that the <paramref name="item"/> is in this EquippedBase.</returns>
/// <exception cref="ArgumentException">Specified item could not be found in this EquippedBase.</exception>
public EquipmentSlot GetSlot(T item)
{
for (var i = 0; i < _equipped.Length; i++)
{
if (item == this[i])
return (EquipmentSlot)i;
}
throw new ArgumentException("Specified item could not be found in this EquippedBase.");
}
void InternalDispose(bool disposeManaged)
{
foreach (var item in _equipped.Where(x => x != null))
{
item.Disposed -= ItemDisposeHandler;
}
Dispose(disposeManaged);
}
/// <summary>
/// Handles when an ItemEntity being handled by this <see cref="EquippedBase{T}"/> is disposed while still equipped.
/// </summary>
/// <param name="sender">Item that was disposed.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void ItemDisposeHandler(Entity sender, EventArgs e)
{
var item = (T)sender;
// Try to get the slot of the item
EquipmentSlot slot;
try
{
slot = GetSlot(item);
}
catch (ArgumentException)
{
const string errmsg = "Equipment item `{0}` was disposed, but was not be found in the EquippedBase.";
Debug.Fail(string.Format(errmsg, item));
if (log.IsWarnEnabled)
log.WarnFormat(errmsg, item);
return;
}
// Remove the item from the EquippedBase
RemoveAt(slot);
}
/// <summary>
/// When overridden in the derived class, handles when an item has been equipped.
/// </summary>
/// <param name="item">The item the event is related to.</param>
/// <param name="slot">The slot of the item the event is related to.</param>
protected virtual void OnEquipped(T item, EquipmentSlot slot)
{
}
/// <summary>
/// When overridden in the derived class, handles when an item has been removed.
/// </summary>
/// <param name="item">The item the event is related to.</param>
/// <param name="slot">The slot of the item the event is related to.</param>
protected virtual void OnUnequipped(T item, EquipmentSlot slot)
{
}
/// <summary>
/// Removes all items from the EquippedBase.
/// </summary>
/// <param name="dispose">If true, then all of the items in the EquippedBase will be disposed of. If false,
/// they will only be removed from the EquippedBase, but could still referenced by other objects.</param>
public void RemoveAll(bool dispose)
{
for (var i = 0; i < _equipped.Length; i++)
{
var item = this[i];
if (item == null)
continue;
RemoveAt((EquipmentSlot)i);
if (dispose)
item.Dispose();
}
}
/// <summary>
/// Removes an item from the specified <paramref name="slot"/>.
/// </summary>
/// <param name="slot">Slot to remove the item from.</param>
/// <returns>True if the item was successfully removed from the given <paramref name="slot"/> or if
/// there was no item in the slot, else false if the item was unable to be removed.</returns>
public bool RemoveAt(EquipmentSlot slot)
{
return TrySetSlot(slot, null, false);
}
/// <summary>
/// Tries to set a given <paramref name="slot"/> to a new <paramref name="item"/>.
/// </summary>
/// <param name="slot">Slot to set the item in.</param>
/// <param name="item">Item to set the slot to.</param>
/// <param name="checkIfCanEquip">If true, the specified <paramref name="item"/> will
/// be checked if it can be euqipped with <see cref="CanEquip"/>. If false, this additional
/// check will be completely bypassed.</param>
/// <returns>True if the <paramref name="item"/> was successfully added to the specified
/// <paramref name="slot"/>, else false. When false, it is guarenteed the equipment will
/// not have been modified.</returns>
protected bool TrySetSlot(EquipmentSlot slot, T item, bool checkIfCanEquip = true)
{
// Check for a valid EquipmentSlot
if (!EnumHelper<EquipmentSlot>.IsDefined(slot))
{
const string errmsg = "Invalid EquipmentSlot `{0}` specified.";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, slot);
Debug.Fail(string.Format(errmsg, slot));
return false;
}
// Get the array index for the slot
var index = slot.GetValue();
// If the slot is equal to the value we are trying to set it, we never want
// to do anything extra, so just abort
var currentItem = this[index];
if (currentItem == item)
return false;
if (item != null)
{
// Add item
// Ensure the item can be equipped
if (checkIfCanEquip)
{
if (!CanEquip(item))
return false;
}
// If the slot is already in use, remove the item, aborting if removal failed
if (currentItem != null)
{
if (!RemoveAt(slot))
return false;
}
// Attach the listener for the OnDispose event
item.Disposed -= ItemDisposeHandler;
item.Disposed += ItemDisposeHandler;
// Set the item into the slot
_equipped[index] = item;
OnEquipped(item, slot);
if (Equipped != null)
Equipped.Raise(this, new EquippedEventArgs<T>(item, slot));
}
else
{
// Remove item (set to null)
// Check if the item can be removed
if (!CanRemove(slot))
return false;
var oldItem = _equipped[index];
// Remove the listener for the OnDispose event
oldItem.Disposed -= ItemDisposeHandler;
// Remove the item
_equipped[index] = null;
OnUnequipped(oldItem, slot);
if (Unequipped != null)
Unequipped.Raise(this, new EquippedEventArgs<T>(oldItem, slot));
}
// Slot setting was successful (since we always aborted early with false if it wasn't)
return true;
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (IsDisposed)
return;
_disposed = true;
GC.SuppressFinalize(this);
InternalDispose(true);
}
#endregion
#region IEnumerable<KeyValuePair<EquipmentSlot,T>> Members
///<summary>
///Returns an enumerator that iterates through the collection.
///</summary>
///
///<returns>
///A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection.
///</returns>
///
public IEnumerator<KeyValuePair<EquipmentSlot, T>> GetEnumerator()
{
for (var i = 0; i < _equipped.Length; i++)
{
var item = this[i];
if (item != null)
yield return new KeyValuePair<EquipmentSlot, T>((EquipmentSlot)i, item);
}
}
///<summary>
/// Returns an enumerator that iterates through a collection.
///</summary>
///
///<returns>
/// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.
///</returns>
///
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| |
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 CloudNinja.AuthorizationApi.Web.Areas.HelpPage.ModelDescriptions;
using CloudNinja.AuthorizationApi.Web.Areas.HelpPage.Models;
namespace CloudNinja.AuthorizationApi.Web.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);
}
}
}
}
| |
//----------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Security
{
using System.IdentityModel.Tokens;
using System.IO;
using System.Runtime;
using System.Security.Cryptography;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.Xml;
using ExclusiveCanonicalizationTransform = System.IdentityModel.ExclusiveCanonicalizationTransform;
using HashStream = System.IdentityModel.HashStream;
using IPrefixGenerator = System.IdentityModel.IPrefixGenerator;
using ISecurityElement = System.IdentityModel.ISecurityElement;
using ISignatureValueSecurityElement = System.IdentityModel.ISignatureValueSecurityElement;
using PreDigestedSignedInfo = System.IdentityModel.PreDigestedSignedInfo;
using Reference = System.IdentityModel.Reference;
using SignedInfo = System.IdentityModel.SignedInfo;
using SignedXml = System.IdentityModel.SignedXml;
using StandardSignedInfo = System.IdentityModel.StandardSignedInfo;
using System.ServiceModel.Security.Tokens;
class WSSecurityOneDotZeroSendSecurityHeader : SendSecurityHeader
{
HashStream hashStream;
PreDigestedSignedInfo signedInfo;
SignedXml signedXml;
SecurityKey signatureKey;
MessagePartSpecification effectiveSignatureParts;
SymmetricAlgorithm encryptingSymmetricAlgorithm;
ReferenceList referenceList;
SecurityKeyIdentifier encryptionKeyIdentifier;
bool hasSignedEncryptedMessagePart;
// For Transport Secrity we have to sign the 'To' header with the
// supporting tokens.
byte[] toHeaderHash = null;
string toHeaderId = null;
public WSSecurityOneDotZeroSendSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay,
SecurityStandardsManager standardsManager,
SecurityAlgorithmSuite algorithmSuite,
MessageDirection direction)
: base(message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, direction)
{
}
protected string EncryptionAlgorithm
{
get { return this.AlgorithmSuite.DefaultEncryptionAlgorithm; }
}
protected XmlDictionaryString EncryptionAlgorithmDictionaryString
{
get { return this.AlgorithmSuite.DefaultEncryptionAlgorithmDictionaryString; }
}
protected override bool HasSignedEncryptedMessagePart
{
get
{
return this.hasSignedEncryptedMessagePart;
}
}
void AddEncryptionReference(MessageHeader header, string headerId, IPrefixGenerator prefixGenerator, bool sign,
out MemoryStream plainTextStream, out string encryptedDataId)
{
plainTextStream = new MemoryStream();
XmlDictionaryWriter encryptingWriter = XmlDictionaryWriter.CreateTextWriter(plainTextStream);
if (sign)
{
AddSignatureReference(header, headerId, prefixGenerator, encryptingWriter);
}
else
{
header.WriteHeader(encryptingWriter, this.Version);
encryptingWriter.Flush();
}
encryptedDataId = this.GenerateId();
referenceList.AddReferredId(encryptedDataId);
}
void AddSignatureReference(SecurityToken token, int position, SecurityTokenAttachmentMode mode)
{
SecurityKeyIdentifierClause keyIdentifierClause = null;
bool strTransformEnabled = this.ShouldUseStrTransformForToken(token, position, mode, out keyIdentifierClause);
AddTokenSignatureReference(token, keyIdentifierClause, strTransformEnabled);
}
void AddPrimaryTokenSignatureReference(SecurityToken token, SecurityTokenParameters securityTokenParameters)
{
// Currently we only support signing the primary token if the primary token is an issued token and protectTokens knob is set to true.
// We will get rid of the below check when we support all token types.
IssuedSecurityTokenParameters istp = securityTokenParameters as IssuedSecurityTokenParameters;
if (istp == null)
{
return;
}
bool strTransformEnabled = istp != null && istp.UseStrTransform;
SecurityKeyIdentifierClause keyIdentifierClause = null;
// Only if the primary token is included in the message that we sign it because WCF at present does not resolve externally referenced tokens.
// This means in the server's response
if (ShouldSerializeToken(securityTokenParameters, this.MessageDirection))
{
if (strTransformEnabled)
{
keyIdentifierClause = securityTokenParameters.CreateKeyIdentifierClause(token, GetTokenReferenceStyle(securityTokenParameters));
}
AddTokenSignatureReference(token, keyIdentifierClause, strTransformEnabled);
}
}
// Given a token and useStarTransform value this method adds apporopriate reference accordingly.
// 1. If strTransform is disabled, it adds a reference to the token's id.
// 2. Else if strtransform is enabled it adds a reference the security token's keyIdentifier's id.
void AddTokenSignatureReference(SecurityToken token, SecurityKeyIdentifierClause keyIdentifierClause, bool strTransformEnabled)
{
if (!strTransformEnabled && token.Id == null)
{
throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.ElementToSignMustHaveId)), this.Message);
}
HashStream hashStream = TakeHashStream();
XmlDictionaryWriter utf8Writer = TakeUtf8Writer();
utf8Writer.StartCanonicalization(hashStream, false, null);
this.StandardsManager.SecurityTokenSerializer.WriteToken(utf8Writer, token);
utf8Writer.EndCanonicalization();
if (strTransformEnabled)
{
if (keyIdentifierClause != null)
{
if (String.IsNullOrEmpty(keyIdentifierClause.Id))
keyIdentifierClause.Id = SecurityUniqueId.Create().Value;
this.ElementContainer.MapSecurityTokenToStrClause(token, keyIdentifierClause);
this.signedInfo.AddReference(keyIdentifierClause.Id, hashStream.FlushHashAndGetValue(), true);
}
else
throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TokenManagerCannotCreateTokenReference)), this.Message);
}
else
this.signedInfo.AddReference(token.Id, hashStream.FlushHashAndGetValue());
}
void AddSignatureReference(SendSecurityHeaderElement[] elements)
{
if (elements != null)
{
for (int i = 0; i < elements.Length; ++i)
{
SecurityKeyIdentifierClause keyIdentifierClause = null;
TokenElement signedEncryptedTokenElement = elements[i].Item as TokenElement;
// signedEncryptedTokenElement can either be a TokenElement ( in SignThenEncrypt case) or EncryptedData ( in !SignThenEncryptCase)
// STR-Transform does not make sense in !SignThenEncrypt case .
// note: signedEncryptedTokenElement can also be SignatureConfirmation but we do not care about it here.
bool useStrTransform = signedEncryptedTokenElement != null
&& SignThenEncrypt
&& this.ShouldUseStrTransformForToken(signedEncryptedTokenElement.Token,
i,
SecurityTokenAttachmentMode.SignedEncrypted,
out keyIdentifierClause);
if (!useStrTransform && elements[i].Id == null)
{
throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.ElementToSignMustHaveId)), this.Message);
}
HashStream hashStream = TakeHashStream();
XmlDictionaryWriter utf8Writer = TakeUtf8Writer();
utf8Writer.StartCanonicalization(hashStream, false, null);
elements[i].Item.WriteTo(utf8Writer, ServiceModelDictionaryManager.Instance);
utf8Writer.EndCanonicalization();
if (useStrTransform)
{
if (keyIdentifierClause != null)
{
if (String.IsNullOrEmpty(keyIdentifierClause.Id))
keyIdentifierClause.Id = SecurityUniqueId.Create().Value;
this.ElementContainer.MapSecurityTokenToStrClause(signedEncryptedTokenElement.Token, keyIdentifierClause);
this.signedInfo.AddReference(keyIdentifierClause.Id, hashStream.FlushHashAndGetValue(), true);
}
else
throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TokenManagerCannotCreateTokenReference)), this.Message);
}
else
this.signedInfo.AddReference(elements[i].Id, hashStream.FlushHashAndGetValue());
}
}
}
void AddSignatureReference(SecurityToken[] tokens, SecurityTokenAttachmentMode mode)
{
if (tokens != null)
{
for (int i = 0; i < tokens.Length; ++i)
{
AddSignatureReference(tokens[i], i, mode);
}
}
}
string GetSignatureHash(MessageHeader header, string headerId, IPrefixGenerator prefixGenerator, XmlDictionaryWriter writer, out byte[] hash)
{
HashStream hashStream = TakeHashStream();
XmlDictionaryWriter effectiveWriter;
XmlBuffer canonicalBuffer = null;
if (writer.CanCanonicalize)
{
effectiveWriter = writer;
}
else
{
canonicalBuffer = new XmlBuffer(int.MaxValue);
effectiveWriter = canonicalBuffer.OpenSection(XmlDictionaryReaderQuotas.Max);
}
effectiveWriter.StartCanonicalization(hashStream, false, null);
header.WriteStartHeader(effectiveWriter, this.Version);
if (headerId == null)
{
headerId = GenerateId();
this.StandardsManager.IdManager.WriteIdAttribute(effectiveWriter, headerId);
}
header.WriteHeaderContents(effectiveWriter, this.Version);
effectiveWriter.WriteEndElement();
effectiveWriter.EndCanonicalization();
effectiveWriter.Flush();
if (!ReferenceEquals(effectiveWriter, writer))
{
Fx.Assert(canonicalBuffer != null, "Canonical buffer cannot be null.");
canonicalBuffer.CloseSection();
canonicalBuffer.Close();
XmlDictionaryReader dicReader = canonicalBuffer.GetReader(0);
writer.WriteNode(dicReader, false);
dicReader.Close();
}
hash = hashStream.FlushHashAndGetValue();
return headerId;
}
void AddSignatureReference(MessageHeader header, string headerId, IPrefixGenerator prefixGenerator, XmlDictionaryWriter writer)
{
byte[] hashValue;
headerId = GetSignatureHash(header, headerId, prefixGenerator, writer, out hashValue);
this.signedInfo.AddReference(headerId, hashValue);
}
void ApplySecurityAndWriteHeader(MessageHeader header, string headerId, XmlDictionaryWriter writer, IPrefixGenerator prefixGenerator)
{
if (!this.RequireMessageProtection && this.ShouldSignToHeader)
{
if ((header.Name == XD.AddressingDictionary.To.Value) &&
(header.Namespace == this.Message.Version.Addressing.Namespace))
{
if (this.toHeaderHash == null)
{
byte[] headerHash;
headerId = GetSignatureHash(header, headerId, prefixGenerator, writer, out headerHash);
this.toHeaderHash = headerHash;
this.toHeaderId = headerId;
}
else
// More than one 'To' header is specified in the message.
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TransportSecuredMessageHasMoreThanOneToHeader)));
return;
}
}
MessagePartProtectionMode protectionMode = GetProtectionMode(header);
MemoryStream plainTextStream;
string encryptedDataId;
switch (protectionMode)
{
case MessagePartProtectionMode.None:
header.WriteHeader(writer, this.Version);
return;
case MessagePartProtectionMode.Sign:
AddSignatureReference(header, headerId, prefixGenerator, writer);
return;
case MessagePartProtectionMode.SignThenEncrypt:
AddEncryptionReference(header, headerId, prefixGenerator, true, out plainTextStream, out encryptedDataId);
EncryptAndWriteHeader(header, encryptedDataId, plainTextStream, writer);
this.hasSignedEncryptedMessagePart = true;
return;
case MessagePartProtectionMode.Encrypt:
AddEncryptionReference(header, headerId, prefixGenerator, false, out plainTextStream, out encryptedDataId);
EncryptAndWriteHeader(header, encryptedDataId, plainTextStream, writer);
return;
case MessagePartProtectionMode.EncryptThenSign:
AddEncryptionReference(header, headerId, prefixGenerator, false, out plainTextStream, out encryptedDataId);
EncryptedHeader encryptedHeader = EncryptHeader(
header, this.encryptingSymmetricAlgorithm, this.encryptionKeyIdentifier, this.Version, encryptedDataId, plainTextStream);
AddSignatureReference(encryptedHeader, encryptedDataId, prefixGenerator, writer);
return;
default:
Fx.Assert("Invalid MessagePartProtectionMode");
return;
}
}
public override void ApplySecurityAndWriteHeaders(MessageHeaders headers, XmlDictionaryWriter writer, IPrefixGenerator prefixGenerator)
{
string[] headerIds;
if (this.RequireMessageProtection || this.ShouldSignToHeader)
{
headerIds = headers.GetHeaderAttributes(UtilityStrings.IdAttribute,
this.StandardsManager.IdManager.DefaultIdNamespaceUri);
}
else
{
headerIds = null;
}
for (int i = 0; i < headers.Count; i++)
{
MessageHeader header = headers.GetMessageHeader(i);
if (this.Version.Addressing == AddressingVersion.None && header.Namespace == AddressingVersion.None.Namespace)
{
continue;
}
if (header != this)
{
ApplySecurityAndWriteHeader(header, headerIds == null ? null : headerIds[i], writer, prefixGenerator);
}
}
}
static bool CanCanonicalizeAndFragment(XmlDictionaryWriter writer)
{
if (!writer.CanCanonicalize)
{
return false;
}
IFragmentCapableXmlDictionaryWriter fragmentingWriter = writer as IFragmentCapableXmlDictionaryWriter;
return fragmentingWriter != null && fragmentingWriter.CanFragment;
}
public override void ApplyBodySecurity(XmlDictionaryWriter writer, IPrefixGenerator prefixGenerator)
{
SecurityAppliedMessage message = this.SecurityAppliedMessage;
EncryptedData encryptedData;
HashStream hashStream;
switch (message.BodyProtectionMode)
{
case MessagePartProtectionMode.None:
return;
case MessagePartProtectionMode.Sign:
hashStream = TakeHashStream();
if (CanCanonicalizeAndFragment(writer))
{
message.WriteBodyToSignWithFragments(hashStream, false, null, writer);
}
else
{
message.WriteBodyToSign(hashStream);
}
this.signedInfo.AddReference(message.BodyId, hashStream.FlushHashAndGetValue());
return;
case MessagePartProtectionMode.SignThenEncrypt:
hashStream = TakeHashStream();
encryptedData = CreateEncryptedDataForBody();
if (CanCanonicalizeAndFragment(writer))
{
message.WriteBodyToSignThenEncryptWithFragments(hashStream, false, null, encryptedData, this.encryptingSymmetricAlgorithm, writer);
}
else
{
message.WriteBodyToSignThenEncrypt(hashStream, encryptedData, this.encryptingSymmetricAlgorithm);
}
this.signedInfo.AddReference(message.BodyId, hashStream.FlushHashAndGetValue());
this.referenceList.AddReferredId(encryptedData.Id);
this.hasSignedEncryptedMessagePart = true;
return;
case MessagePartProtectionMode.Encrypt:
encryptedData = CreateEncryptedDataForBody();
message.WriteBodyToEncrypt(encryptedData, this.encryptingSymmetricAlgorithm);
this.referenceList.AddReferredId(encryptedData.Id);
return;
case MessagePartProtectionMode.EncryptThenSign:
hashStream = TakeHashStream();
encryptedData = CreateEncryptedDataForBody();
message.WriteBodyToEncryptThenSign(hashStream, encryptedData, this.encryptingSymmetricAlgorithm);
this.signedInfo.AddReference(message.BodyId, hashStream.FlushHashAndGetValue());
this.referenceList.AddReferredId(encryptedData.Id);
return;
default:
Fx.Assert("Invalid MessagePartProtectionMode");
return;
}
}
protected static MemoryStream CaptureToken(SecurityToken token, SecurityStandardsManager serializer)
{
MemoryStream stream = new MemoryStream();
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);
serializer.SecurityTokenSerializer.WriteToken(writer, token);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
return stream;
}
protected static MemoryStream CaptureSecurityElement(ISecurityElement element)
{
MemoryStream stream = new MemoryStream();
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream);
element.WriteTo(writer, ServiceModelDictionaryManager.Instance);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
return stream;
}
protected override ISecurityElement CompleteEncryptionCore(
SendSecurityHeaderElement primarySignature,
SendSecurityHeaderElement[] basicTokens,
SendSecurityHeaderElement[] signatureConfirmations,
SendSecurityHeaderElement[] endorsingSignatures)
{
if (this.referenceList == null)
{
return null;
}
if (primarySignature != null && primarySignature.Item != null && primarySignature.MarkedForEncryption)
{
EncryptElement(primarySignature);
}
if (basicTokens != null)
{
for (int i = 0; i < basicTokens.Length; ++i)
{
if (basicTokens[i].MarkedForEncryption)
EncryptElement(basicTokens[i]);
}
}
if (signatureConfirmations != null)
{
for (int i = 0; i < signatureConfirmations.Length; ++i)
{
if (signatureConfirmations[i].MarkedForEncryption)
EncryptElement(signatureConfirmations[i]);
}
}
if (endorsingSignatures != null)
{
for (int i = 0; i < endorsingSignatures.Length; ++i)
{
if (endorsingSignatures[i].MarkedForEncryption)
EncryptElement(endorsingSignatures[i]);
}
}
try
{
return this.referenceList.DataReferenceCount > 0 ? this.referenceList : null;
}
finally
{
this.referenceList = null;
this.encryptingSymmetricAlgorithm = null;
this.encryptionKeyIdentifier = null;
}
}
protected override ISignatureValueSecurityElement CompletePrimarySignatureCore(
SendSecurityHeaderElement[] signatureConfirmations,
SecurityToken[] signedEndorsingTokens,
SecurityToken[] signedTokens,
SendSecurityHeaderElement[] basicTokens, bool isPrimarySignature)
{
if (this.signedXml == null)
{
return null;
}
SecurityTimestamp timestamp = this.Timestamp;
if (timestamp != null)
{
if (timestamp.Id == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TimestampToSignHasNoId)));
}
HashStream hashStream = TakeHashStream();
this.StandardsManager.WSUtilitySpecificationVersion.WriteTimestampCanonicalForm(
hashStream, timestamp, this.signedInfo.ResourcePool.TakeEncodingBuffer());
signedInfo.AddReference(timestamp.Id, hashStream.FlushHashAndGetValue());
}
if ((this.ShouldSignToHeader) && (this.signatureKey is AsymmetricSecurityKey) && (this.Version.Addressing != AddressingVersion.None))
{
if (this.toHeaderHash != null)
signedInfo.AddReference(this.toHeaderId, this.toHeaderHash);
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.TransportSecurityRequireToHeader)));
}
AddSignatureReference(signatureConfirmations);
if (isPrimarySignature && this.ShouldProtectTokens)
{
AddPrimaryTokenSignatureReference(this.ElementContainer.SourceSigningToken, this.SigningTokenParameters);
}
if (this.RequireMessageProtection)
{
AddSignatureReference(signedEndorsingTokens, SecurityTokenAttachmentMode.SignedEndorsing);
AddSignatureReference(signedTokens, SecurityTokenAttachmentMode.Signed);
AddSignatureReference(basicTokens);
}
if (this.signedInfo.ReferenceCount == 0)
{
throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.NoPartsOfMessageMatchedPartsToSign)), this.Message);
}
try
{
this.signedXml.ComputeSignature(this.signatureKey);
return this.signedXml;
}
finally
{
this.hashStream = null;
this.signedInfo = null;
this.signedXml = null;
this.signatureKey = null;
this.effectiveSignatureParts = null;
}
}
EncryptedData CreateEncryptedData()
{
EncryptedData encryptedData = new EncryptedData();
encryptedData.SecurityTokenSerializer = this.StandardsManager.SecurityTokenSerializer;
encryptedData.KeyIdentifier = this.encryptionKeyIdentifier;
encryptedData.EncryptionMethod = this.EncryptionAlgorithm;
encryptedData.EncryptionMethodDictionaryString = this.EncryptionAlgorithmDictionaryString;
return encryptedData;
}
EncryptedData CreateEncryptedData(MemoryStream stream, string id, bool typeElement)
{
EncryptedData encryptedData = CreateEncryptedData();
encryptedData.Id = id;
encryptedData.SetUpEncryption(this.encryptingSymmetricAlgorithm, new ArraySegment<byte>(stream.GetBuffer(), 0, (int) stream.Length));
if (typeElement)
{
encryptedData.Type = EncryptedData.ElementType;
}
return encryptedData;
}
EncryptedData CreateEncryptedDataForBody()
{
EncryptedData encryptedData = CreateEncryptedData();
encryptedData.Type = EncryptedData.ContentType;
return encryptedData;
}
void EncryptAndWriteHeader(MessageHeader plainTextHeader, string id, MemoryStream stream, XmlDictionaryWriter writer)
{
EncryptedHeader encryptedHeader = EncryptHeader(
plainTextHeader,
this.encryptingSymmetricAlgorithm, this.encryptionKeyIdentifier, this.Version,
id, stream);
encryptedHeader.WriteHeader(writer, this.Version);
}
void EncryptElement(SendSecurityHeaderElement element)
{
string id = GenerateId();
ISecurityElement encryptedElement = CreateEncryptedData(CaptureSecurityElement(element.Item), id, true);
this.referenceList.AddReferredId(id);
element.Replace(id, encryptedElement);
}
protected virtual EncryptedHeader EncryptHeader(MessageHeader plainTextHeader, SymmetricAlgorithm algorithm,
SecurityKeyIdentifier keyIdentifier, MessageVersion version, string id, MemoryStream stream)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.GetString(SR.HeaderEncryptionNotSupportedInWsSecurityJan2004, plainTextHeader.Name, plainTextHeader.Namespace)));
}
HashStream TakeHashStream()
{
HashStream hashStream = null;
if (this.hashStream == null)
{
this.hashStream = hashStream = new HashStream(CryptoHelper.CreateHashAlgorithm(this.AlgorithmSuite.DefaultDigestAlgorithm));
}
else
{
hashStream = this.hashStream;;
hashStream.Reset();
}
return hashStream;
}
XmlDictionaryWriter TakeUtf8Writer()
{
return this.signedInfo.ResourcePool.TakeUtf8Writer();
}
MessagePartProtectionMode GetProtectionMode(MessageHeader header)
{
if (!this.RequireMessageProtection)
{
return MessagePartProtectionMode.None;
}
bool sign = this.signedInfo != null && this.effectiveSignatureParts.IsHeaderIncluded(header);
bool encrypt = this.referenceList != null && this.EncryptionParts.IsHeaderIncluded(header);
return MessagePartProtectionModeHelper.GetProtectionMode(sign, encrypt, this.SignThenEncrypt);
}
protected override void StartEncryptionCore(SecurityToken token, SecurityKeyIdentifier keyIdentifier)
{
this.encryptingSymmetricAlgorithm = SecurityUtils.GetSymmetricAlgorithm(this.EncryptionAlgorithm, token);
if (this.encryptingSymmetricAlgorithm == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(
SR.GetString(SR.UnableToCreateSymmetricAlgorithmFromToken, this.EncryptionAlgorithm)));
}
this.encryptionKeyIdentifier = keyIdentifier;
this.referenceList = new ReferenceList();
}
protected override void StartPrimarySignatureCore(SecurityToken token,
SecurityKeyIdentifier keyIdentifier,
MessagePartSpecification signatureParts,
bool generateTargettableSignature)
{
SecurityAlgorithmSuite suite = this.AlgorithmSuite;
string canonicalizationAlgorithm = suite.DefaultCanonicalizationAlgorithm;
XmlDictionaryString canonicalizationAlgorithmDictionaryString = suite.DefaultCanonicalizationAlgorithmDictionaryString;
if (canonicalizationAlgorithm != SecurityAlgorithms.ExclusiveC14n)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new MessageSecurityException(SR.GetString(SR.UnsupportedCanonicalizationAlgorithm, suite.DefaultCanonicalizationAlgorithm)));
}
string signatureAlgorithm;
XmlDictionaryString signatureAlgorithmDictionaryString;
suite.GetSignatureAlgorithmAndKey(token, out signatureAlgorithm, out this.signatureKey, out signatureAlgorithmDictionaryString);
string digestAlgorithm = suite.DefaultDigestAlgorithm;
XmlDictionaryString digestAlgorithmDictionaryString = suite.DefaultDigestAlgorithmDictionaryString;
this.signedInfo = new PreDigestedSignedInfo(ServiceModelDictionaryManager.Instance, canonicalizationAlgorithm, canonicalizationAlgorithmDictionaryString, digestAlgorithm, digestAlgorithmDictionaryString, signatureAlgorithm, signatureAlgorithmDictionaryString);
this.signedXml = new SignedXml(this.signedInfo, ServiceModelDictionaryManager.Instance, this.StandardsManager.SecurityTokenSerializer);
if (keyIdentifier != null)
{
this.signedXml.Signature.KeyIdentifier = keyIdentifier;
}
if (generateTargettableSignature)
{
this.signedXml.Id = GenerateId();
}
this.effectiveSignatureParts = signatureParts;
this.hashStream = this.signedInfo.ResourcePool.TakeHashStream(digestAlgorithm);
}
protected override ISignatureValueSecurityElement CreateSupportingSignature(SecurityToken token, SecurityKeyIdentifier identifier)
{
StartPrimarySignatureCore(token, identifier, MessagePartSpecification.NoParts, false);
return CompletePrimarySignatureCore(null, null, null, null, false);
}
protected override ISignatureValueSecurityElement CreateSupportingSignature(SecurityToken token, SecurityKeyIdentifier identifier, ISecurityElement elementToSign)
{
SecurityAlgorithmSuite algorithmSuite = this.AlgorithmSuite;
string signatureAlgorithm;
XmlDictionaryString signatureAlgorithmDictionaryString;
SecurityKey signatureKey;
algorithmSuite.GetSignatureAlgorithmAndKey(token, out signatureAlgorithm, out signatureKey, out signatureAlgorithmDictionaryString);
SignedXml signedXml = new SignedXml(ServiceModelDictionaryManager.Instance, this.StandardsManager.SecurityTokenSerializer);
SignedInfo signedInfo = signedXml.Signature.SignedInfo;
signedInfo.CanonicalizationMethod = algorithmSuite.DefaultCanonicalizationAlgorithm;
signedInfo.CanonicalizationMethodDictionaryString = algorithmSuite.DefaultCanonicalizationAlgorithmDictionaryString;
signedInfo.SignatureMethod = signatureAlgorithm;
signedInfo.SignatureMethodDictionaryString = signatureAlgorithmDictionaryString;
if (elementToSign.Id == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ElementToSignMustHaveId)));
}
Reference reference = new Reference(ServiceModelDictionaryManager.Instance, "#" + elementToSign.Id, elementToSign);
reference.DigestMethod = algorithmSuite.DefaultDigestAlgorithm;
reference.DigestMethodDictionaryString = algorithmSuite.DefaultDigestAlgorithmDictionaryString;
reference.AddTransform(new ExclusiveCanonicalizationTransform());
((StandardSignedInfo)signedInfo).AddReference(reference);
signedXml.ComputeSignature(signatureKey);
if (identifier != null)
{
signedXml.Signature.KeyIdentifier = identifier;
}
return signedXml;
}
protected override void WriteSecurityTokenReferencyEntry(XmlDictionaryWriter writer, SecurityToken securityToken, SecurityTokenParameters securityTokenParameters)
{
SecurityKeyIdentifierClause keyIdentifierClause = null;
// Given a token this method writes its corresponding security token reference entry in the security header
// 1. If the token parameters is an issuedSecurityTokenParamter
// 2. If UseStrTransform is enabled on it.
IssuedSecurityTokenParameters issuedSecurityTokenParameters = securityTokenParameters as IssuedSecurityTokenParameters;
if (issuedSecurityTokenParameters == null || !issuedSecurityTokenParameters.UseStrTransform)
return;
if (this.ElementContainer.TryGetIdentifierClauseFromSecurityToken(securityToken, out keyIdentifierClause))
{
if (keyIdentifierClause != null && !String.IsNullOrEmpty(keyIdentifierClause.Id))
{
WrappedXmlDictionaryWriter wrappedLocalWriter = new WrappedXmlDictionaryWriter(writer, keyIdentifierClause.Id);
this.StandardsManager.SecurityTokenSerializer.WriteKeyIdentifierClause(wrappedLocalWriter, keyIdentifierClause);
}
else
throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TokenManagerCannotCreateTokenReference)), this.Message);
}
}
}
class WrappedXmlDictionaryWriter : XmlDictionaryWriter
{
XmlDictionaryWriter innerWriter;
int index;
bool insertId;
bool isStrReferenceElement;
string id;
public WrappedXmlDictionaryWriter(XmlDictionaryWriter writer, string id)
{
this.innerWriter = writer;
this.index = 0;
this.insertId = false;
this.isStrReferenceElement = false;
this.id = id;
}
public override void WriteStartAttribute(string prefix, string localName, string namespaceUri)
{
if (isStrReferenceElement && this.insertId && localName == XD.UtilityDictionary.IdAttribute.Value)
{
// This means the serializer is already writing the Id out, so we don't write it again.
this.insertId = false;
}
this.innerWriter.WriteStartAttribute(prefix, localName, namespaceUri);
}
public override void WriteStartElement(string prefix, string localName, string namespaceUri)
{
if (isStrReferenceElement && this.insertId)
{
if (id != null)
{
this.innerWriter.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, id);
}
isStrReferenceElement = false;
this.insertId = false;
}
index++;
if (index == 1 && localName == XD.SecurityJan2004Dictionary.SecurityTokenReference.Value)
{
this.insertId = true;
isStrReferenceElement = true;
}
this.innerWriter.WriteStartElement(prefix, localName, namespaceUri);
}
// Below methods simply call into innerWritter
public override void Close()
{
this.innerWriter.Close();
}
public override void Flush()
{
this.innerWriter.Flush();
}
public override string LookupPrefix(string ns)
{
return this.innerWriter.LookupPrefix(ns);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
this.innerWriter.WriteBase64(buffer, index, count);
}
public override void WriteCData(string text)
{
this.innerWriter.WriteCData(text);
}
public override void WriteCharEntity(char ch)
{
this.innerWriter.WriteCharEntity(ch);
}
public override void WriteChars(char[] buffer, int index, int count)
{
this.innerWriter.WriteChars(buffer, index, count);
}
public override void WriteComment(string text)
{
this.innerWriter.WriteComment(text);
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
this.innerWriter.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteEndAttribute()
{
this.innerWriter.WriteEndAttribute();
}
public override void WriteEndDocument()
{
this.innerWriter.WriteEndDocument();
}
public override void WriteEndElement()
{
this.innerWriter.WriteEndElement();
}
public override void WriteEntityRef(string name)
{
this.innerWriter.WriteEntityRef(name);
}
public override void WriteFullEndElement()
{
this.innerWriter.WriteFullEndElement();
}
public override void WriteProcessingInstruction(string name, string text)
{
this.innerWriter.WriteProcessingInstruction(name, text);
}
public override void WriteRaw(string data)
{
this.innerWriter.WriteRaw(data);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
this.innerWriter.WriteRaw(buffer, index, count);
}
public override void WriteStartDocument(bool standalone)
{
this.innerWriter.WriteStartDocument(standalone);
}
public override void WriteStartDocument()
{
this.innerWriter.WriteStartDocument();
}
public override WriteState WriteState
{
get { return this.innerWriter.WriteState; }
}
public override void WriteString(string text)
{
this.innerWriter.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
this.innerWriter.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteWhitespace(string ws)
{
this.innerWriter.WriteWhitespace(ws);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
namespace System.Text
{
// Shared implementations for commonly overriden Encoding methods
internal static class EncodingForwarder
{
// We normally have to duplicate a lot of code between UTF8Encoding,
// UTF7Encoding, EncodingNLS, etc. because we want to override many
// of the methods in all of those classes to just forward to the unsafe
// version. (e.g. GetBytes(char[]))
// Ideally, everything would just derive from EncodingNLS, but that's
// not exposed in the public API, and C# prohibits a public class from
// inheriting from an internal one. So, we have to override each of the
// methods in question and repeat the argument validation/logic.
// These set of methods exist so instead of duplicating code, we can
// simply have those overriden methods call here to do the actual work.
// NOTE: This class should ONLY be called from Encodings that override
// the internal methods which accept an Encoder/DecoderNLS. The reason
// for this is that by default, those methods just call the same overload
// except without the encoder/decoder parameter. If an overriden method
// without that parameter calls this class, which calls the overload with
// the parameter, it will call the same method again, which will eventually
// lead to a StackOverflowException.
public unsafe static int GetByteCount(Encoding encoding, char[] chars, int index, int count)
{
// Validate parameters
Contract.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here
if (chars == null)
{
throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException(index < 0 ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (chars.Length - index < count)
{
throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
}
Contract.EndContractBlock();
// If no input, return 0, avoid fixed empty array problem
if (count == 0)
return 0;
// Just call the (internal) pointer version
fixed (char* pChars = chars)
return encoding.GetByteCount(pChars + index, count, encoder: null);
}
public unsafe static int GetByteCount(Encoding encoding, string s)
{
Contract.Assert(encoding != null);
if (s == null)
{
string paramName = encoding is ASCIIEncoding ? "chars" : "s"; // ASCIIEncoding calls the string chars
// UTF8Encoding does this as well, but it originally threw an ArgumentNull for "s" so don't check for that
throw new ArgumentNullException(paramName);
}
Contract.EndContractBlock();
// NOTE: The behavior of fixed *is* defined by
// the spec for empty strings, although not for
// null strings/empty char arrays. See
// http://stackoverflow.com/q/37757751/4077294
// Regardless, we may still want to check
// for if (s.Length == 0) in the future
// and short-circuit as an optimization (TODO).
fixed (char* pChars = s)
return encoding.GetByteCount(pChars, s.Length, encoder: null);
}
public unsafe static int GetByteCount(Encoding encoding, char* chars, int count)
{
Contract.Assert(encoding != null);
if (chars == null)
{
throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
// Call the internal version, with an empty encoder
return encoding.GetByteCount(chars, count, encoder: null);
}
public unsafe static int GetBytes(Encoding encoding, string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
Contract.Assert(encoding != null);
if (s == null || bytes == null)
{
string stringName = encoding is ASCIIEncoding ? "chars" : "s"; // ASCIIEncoding calls the first parameter chars
throw new ArgumentNullException(s == null ? stringName : "bytes", SR.ArgumentNull_Array);
}
if (charIndex < 0 || charCount < 0)
{
throw new ArgumentOutOfRangeException(charIndex < 0 ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (s.Length - charIndex < charCount)
{
string stringName = encoding is ASCIIEncoding ? "chars" : "s"; // ASCIIEncoding calls the first parameter chars
// Duplicate the above check since we don't want the overhead of a type check on the general path
throw new ArgumentOutOfRangeException(stringName, SR.ArgumentOutOfRange_IndexCount);
}
if (byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
int byteCount = bytes.Length - byteIndex;
// Fixed doesn't like empty arrays
if (bytes.Length == 0)
bytes = new byte[1];
fixed (char* pChars = s) fixed (byte* pBytes = bytes)
{
return encoding.GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, encoder: null);
}
}
public unsafe static int GetBytes(Encoding encoding, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
Contract.Assert(encoding != null);
if (chars == null || bytes == null)
{
throw new ArgumentNullException(chars == null ? "chars" : "bytes", SR.ArgumentNull_Array);
}
if (charIndex < 0 || charCount < 0)
{
throw new ArgumentOutOfRangeException(charIndex < 0 ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (chars.Length - charIndex < charCount)
{
throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
}
if (byteIndex < 0 || byteIndex > bytes.Length)
{
throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
// If nothing to encode return 0, avoid fixed problem
if (charCount == 0)
return 0;
// Note that this is the # of bytes to decode,
// not the size of the array
int byteCount = bytes.Length - byteIndex;
// Fixed doesn't like 0 length arrays.
if (bytes.Length == 0)
bytes = new byte[1];
// Just call the (internal) pointer version
fixed (char* pChars = chars) fixed (byte* pBytes = bytes)
{
return encoding.GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, encoder: null);
}
}
public unsafe static int GetBytes(Encoding encoding, char* chars, int charCount, byte* bytes, int byteCount)
{
Contract.Assert(encoding != null);
if (bytes == null || chars == null)
{
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
}
if (charCount < 0 || byteCount < 0)
{
throw new ArgumentOutOfRangeException(charCount < 0 ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
return encoding.GetBytes(chars, charCount, bytes, byteCount, encoder: null);
}
public unsafe static int GetCharCount(Encoding encoding, byte[] bytes, int index, int count)
{
Contract.Assert(encoding != null);
if (bytes == null)
{
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException(index < 0 ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (bytes.Length - index < count)
{
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
}
Contract.EndContractBlock();
// If no input just return 0, fixed doesn't like 0 length arrays.
if (count == 0)
return 0;
// Just call pointer version
fixed (byte* pBytes = bytes)
return encoding.GetCharCount(pBytes + index, count, decoder: null);
}
public unsafe static int GetCharCount(Encoding encoding, byte* bytes, int count)
{
Contract.Assert(encoding != null);
if (bytes == null)
{
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
return encoding.GetCharCount(bytes, count, decoder: null);
}
public unsafe static int GetChars(Encoding encoding, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
Contract.Assert(encoding != null);
if (bytes == null || chars == null)
{
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
}
if (byteIndex < 0 || byteCount < 0)
{
throw new ArgumentOutOfRangeException(byteIndex < 0 ? "byteIndex" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (bytes.Length - byteIndex < byteCount)
{
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
}
if (charIndex < 0 || charIndex > chars.Length)
{
throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
if (byteCount == 0)
return 0;
// NOTE: This is the # of chars we can decode,
// not the size of the array
int charCount = chars.Length - charIndex;
// Fixed doesn't like 0 length arrays.
if (chars.Length == 0)
chars = new char[1];
fixed (byte* pBytes = bytes) fixed (char* pChars = chars)
{
return encoding.GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, decoder: null);
}
}
public unsafe static int GetChars(Encoding encoding, byte* bytes, int byteCount, char* chars, int charCount)
{
Contract.Assert(encoding != null);
if (bytes == null || chars == null)
{
throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
}
if (charCount < 0 || byteCount < 0)
{
throw new ArgumentOutOfRangeException(charCount < 0 ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
return encoding.GetChars(bytes, byteCount, chars, charCount, decoder: null);
}
public unsafe static string GetString(Encoding encoding, byte[] bytes, int index, int count)
{
Contract.Assert(encoding != null);
if (bytes == null)
{
throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
}
if (index < 0 || count < 0)
{
// ASCIIEncoding has different names for its parameters here (byteIndex, byteCount)
bool ascii = encoding is ASCIIEncoding;
string indexName = ascii ? "byteIndex" : "index";
string countName = ascii ? "byteCount" : "count";
throw new ArgumentOutOfRangeException(index < 0 ? indexName : countName, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (bytes.Length - index < count)
{
throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
}
Contract.EndContractBlock();
// Avoid problems with empty input buffer
if (count == 0)
return string.Empty;
// Call string.CreateStringFromEncoding here, which
// allocates a string and lets the Encoding modify
// it in place. This way, we don't have to allocate
// an intermediary char[] to decode into and then
// call the string constructor; instead we decode
// directly into the string.
fixed (byte* pBytes = bytes)
{
return string.CreateStringFromEncoding(pBytes + index, count, encoding);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Speech.Recognition;
using System.Diagnostics;
using System.Speech.Recognition.SrgsGrammar;
using System.IO;
using System.Xml;
using eDocumentReader.Hubs.activities.system.lightweight;
using eDocumentReader.Hubs.structure;
namespace eDocumentReader.Hubs
{
/*
* Generate text for the given page.
* Produce highlighting for the recognized text.
* Generate appropriate grammars from further recognition.
*/
public class TextProcessor
{
private System.Object lockThis = new System.Object();
private readonly string GRAMMAR_TMP_DIR = "tmp"; //a directory store the temporary grammar files
private readonly float PLAY_ANIMATION_CONFIDENT_THRESHOLD = 0.2f; //play the animation only when the intermidiate confidence is greater than this
private readonly float HYP_THRESHOLD = 0.2f; //display the intermidiate result only when the conficence is greater than this
private readonly double maxLag = 750; //milliseconds maximum possible lag time in a speech
private readonly bool enableCache = true; //cache page's text and annotation in memory, fast loading time for the same page
private readonly int INITIAL_LOOK_AHEAD = 4; //the minimal syllables to look ahead
//indicate how many words a speech can skip, and the prototype considers it is a continuation
//for example, consider this sentence "I am working on the protoype, and I am writting some comments."
//if a reader say "I am working on the", and pause for a second, and say "and I am writing some comments"
//The prototype will treat it as the reader say "I am working on the prototype, and I am writting some comments."
//value in the SPEECH_JUMP_GAP_THRESHOLD is 2 in above example
private readonly int SPEECH_JUMP_GAP_THRESHOLD = 2;
private Dictionary<int,string[]> pageTextCached = new Dictionary<int,string[]>();
private Dictionary<int, string[]> pageTextHTMLCached = new Dictionary<int, string[]>();
private Dictionary<int, string[]> annotationArrayCached = new Dictionary<int, string[]>();
private Dictionary<int, int[]> syllableArrayCached = new Dictionary<int, int[]>();
private List<int> defaultStartIndexes = new List<int>();
private Page currentPage;
private string[] allSpeechText;
private string[] allSpeechTextHTML;
private string[] annotationArray;
private int[] syllableArray;
private int confirmedStartIndex;
private int confirmedEndIndex;
private int confirmedLastSegPosition;
private int hypothesisEndIndex;
private int startIndex;
private int endIndex;
private int lastSegPosition;
//for test only
//private string intermediateSpeechText;
//private string allConfirmedSpeechText;
private bool guessAhead = true;
private int numOfHypothsis;
private string storyDirectory;
private int lastConfirmIndexRM = -1;//to keep track the position where the last confirmed speech in record mode
private int maxSyllableAhead;
private Mode mode;
private List<string> playedAnimationList = new List<string>();//keep track which animation already played in the current speech
private int speechState; //value=1 means in speech, value=0 means silent
private double timePerSyllable = 150; //continuously estimate the time to spoke one syllable, in ms. default value = 250ms
public TextProcessor()
{
}
/// <summary>
/// set current story's directory
/// </summary>
/// <param name="storyDirectory">The full path to where all stories are reside</param>
public void SetStoryDirectory(string storyDirectory){
this.storyDirectory = storyDirectory;
Debug.WriteLine("set story directory to " + storyDirectory);
}
/// <summary>
/// Withdraw the last uncomfirmed hightlighting for the speech.
/// This method is called when reader click on reject button to remove
/// the previous recorded speed in record my voice mode.
/// </summary>
public void rollBackHighlight()
{
confirmedLastSegPosition = lastConfirmIndexRM+1;
lastSegPosition = confirmedLastSegPosition;
if (lastConfirmIndexRM >= 0)
{
endIndex = lastConfirmIndexRM;
}
else
{
endIndex = 0;
}
confirmedEndIndex = endIndex;
if (lastConfirmIndexRM < 0)
{
string pageTextStr = constructPageText();
ActivityExecutor.add(new InternalUpdatePageTextActivity(pageTextStr, currentPage.GetPageNumber()));
}
else
{
constructTextAndDisplay();
}
string cfgPath = storyDirectory + "\\" + GRAMMAR_TMP_DIR + "\\" + currentPage.GetPageNumber() + "_" +
(endIndex + 1) + ".cfg";
if (!defaultStartIndexes.Contains(endIndex + 1))
{
Grammar g = new Grammar(cfgPath);
g.Weight = EBookConstant.NEXT_WORD_WEIGHT;
g.Priority = EBookConstant.NEXT_WORD_PRIORITY;
ActivityExecutor.add(new InternalReloadOnGoingGrammarActivity(g));
Debug.WriteLine("Load onGoing grammar " + cfgPath);
}
else
{
ActivityExecutor.add(new InternalChangeGrammarPriorityActivity(endIndex+1));
}
}
/// <summary>
/// Take a note of the end index of the confirm text in recording mode.
/// This method is called when user click on the accept button in record my voice mode.
/// </summary>
public void confirmHighlight()
{
lastConfirmIndexRM = confirmedEndIndex;
if (confirmedEndIndex == allSpeechText.Length - 1)
{
ActivityExecutor.add(new InternalFinishPageActivity());
}
}
/// <summary>
/// Clean cached indexes
/// </summary>
private void resetParameters()
{
defaultStartIndexes.Clear();
confirmedStartIndex = -1;
confirmedEndIndex = -1;
confirmedLastSegPosition = 0;
startIndex = -1;
endIndex = -1;
lastSegPosition = -1;
numOfHypothsis = 0;
lastConfirmIndexRM = -1;
playedAnimationList.Clear();
}
/// <summary>
/// Extract data out from page object. If enableCache is true, this method
/// will save the data in cache for later fast access.
/// </summary>
/// <param name="page">The page object</param>
private void retrivePageContent(Page page)
{
//retrieve page data from cache
if (enableCache && pageTextCached.ContainsKey(page.GetPageNumber()))
{
pageTextCached.TryGetValue(page.GetPageNumber(), out allSpeechText);
pageTextHTMLCached.TryGetValue(page.GetPageNumber(), out allSpeechTextHTML);
annotationArrayCached.TryGetValue(page.GetPageNumber(), out annotationArray);
syllableArrayCached.TryGetValue(page.GetPageNumber(), out syllableArray);
}
else
{
List<string[]> pageText = page.GetListOfTextArray();
List<string> annotation = page.GetListOfAnnotations();
List<string> annArray = new List<string>();
//cover list to array
string whole = "";
string wholeHTML = "";
//obtain the text and the text in HTML format for the current page
for (int i = 0; i < pageText.Count; i++)
{
if (pageText.ElementAt(i) == null)
{
wholeHTML = wholeHTML.TrimEnd() + "<br> ";
}
else
{
foreach (string str in pageText.ElementAt(i))
{
whole += str + " ";
if (str.Trim().Length == 0)
{
wholeHTML = wholeHTML.TrimEnd() + " ";
}
else
{
wholeHTML += str + " ";
}
annArray.Add(annotation.ElementAt(i));
}
//wholeHTML = wholeHTML.TrimEnd() + "<br> ";
}
}
whole = whole.Replace("\"", "");
allSpeechText = whole.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
allSpeechTextHTML = wholeHTML.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
annotationArray = annArray.ToArray();
syllableArray = EBookUtil.CountSyllables(allSpeechText);
//save the data to hash map, we can simply retrieve the page data when
//the page get revisit again
if (enableCache)
{
pageTextCached.Add(page.GetPageNumber(), allSpeechText);
pageTextHTMLCached.Add(page.GetPageNumber(), allSpeechTextHTML);
annotationArrayCached.Add(page.GetPageNumber(), annotationArray);
syllableArrayCached.Add(page.GetPageNumber(), syllableArray);
}
}
}
/// <summary>
/// The method is to process a new page (or refresh a page).
/// Generate necessary grammars for the current page.
/// Generate text and display in browser.
/// If Mode == REAL TIME, enable user to start from /jump to any sentence. otherwise,
/// disable this feature.
/// </summary>
/// <param name="page">The page to be display in browser</param>
/// <param name="mode">The story mode {read it now, record my voice}</param>
public void process(Page page, Mode mode)
{
this.mode = mode;
currentPage = page;
//reset parameters when process a new page
resetParameters();
retrivePageContent(page);
if (mode != Mode.REPLAY)
{
List<SrgsDocument> srgsDocs = EBookUtil.GenerateGrammars(allSpeechText, annotationArray);
Debug.WriteLine("generated " + srgsDocs.Count + " grammar files");
//load grammars
List<Grammar> gs = new List<Grammar>();
//loop from srgsDocs.Count to 0 will give the earlier sentence the higher priority (if
//two sentence contain the same word, Microsft choose the latest grammar that load into its engine).
for (int i = srgsDocs.Count; --i >= 0; )
{
string cfgPath = storyDirectory + "\\" + GRAMMAR_TMP_DIR + "\\" + page.GetPageNumber() + "_" + i + ".cfg";
Directory.CreateDirectory(storyDirectory + "\\" + GRAMMAR_TMP_DIR);
EBookUtil.CompileGrammarToFile(srgsDocs.ElementAt(i), cfgPath);
//allow user to start from new sentence in read time mode
if (mode == Mode.REALTIME)
{
if (i == 0 || (i > 0 && (EBookUtil.containEndOfSentencePunctuation(allSpeechText[i-1]))))
{
defaultStartIndexes.Add(i);
Debug.WriteLine("loading grammar:" + cfgPath);
Grammar storyG = new Grammar(cfgPath);
storyG.Weight = EBookConstant.DEFAULT_WEIGHT;
storyG.Priority = EBookConstant.DEFAULT_PRIORITY;
gs.Add(storyG);
}
}
else //in recording mode, only allow the reader to start from where she/he left off
{
if (i == 0)
{
defaultStartIndexes.Add(i);
Debug.WriteLine("loading grammar:" + cfgPath);
Grammar storyG = new Grammar(cfgPath);
storyG.Weight = EBookConstant.DEFAULT_WEIGHT;
storyG.Priority = EBookConstant.DEFAULT_PRIORITY;
ActivityExecutor.add(new InternalReloadOnGoingGrammarActivity(storyG));
}
}
}
if (gs.Count > 0)
{
ActivityExecutor.add(new InternalReloadStoryGrammarActivity(gs));
}
}
string pageTextStr = constructPageText();
ActivityExecutor.add(new InternalUpdatePageTextActivity(pageTextStr, page.pageNumber));
}
/// <summary>
/// There is some delay in SR processing. the method is to guesstimate how many word the reader
/// had been reading ahead when the SR return the result.
/// </summary>
/// <param name="currentSpeedStartIndex"></param>
/// <param name="textArray"></param>
/// <returns></returns>
private int getGuessAheadCount(int currentSpeedStartIndex, string[] textArray)
{
int increment = 0;
if (guessAhead && EBookInteractiveSystem.lookAheadDivider > 0 && syllableArray.Length >= textArray.Length + currentSpeedStartIndex)
{
int syCount = 0;
for (int i = currentSpeedStartIndex; i < textArray.Length + currentSpeedStartIndex; i++)
{
syCount += syllableArray[i];
}
int syIn = syCount / EBookInteractiveSystem.lookAheadDivider; //one syllable forward for every lookAheadDivide
if (syIn < INITIAL_LOOK_AHEAD)
{
//The highlighting seems slow in the first second of a speech, let's highlight 2 syllables
//ahead in the beginning of a speech
syIn = INITIAL_LOOK_AHEAD;
}
int enInc = currentSpeedStartIndex + textArray.Length;
if (maxSyllableAhead > 0)
{
//Debug.WriteLine("Time pier syllable=" + timePerSyllable);
if (syIn > maxSyllableAhead)
{
syIn = (int)maxSyllableAhead;
}
}
string currentEndWord = "";
if (enInc > 0 && enInc <= allSpeechText.Length)
{
currentEndWord = allSpeechText[enInc - 1];
}
Boolean cont = true;
while (syIn > 0 && cont)
{
if (enInc < syllableArray.Length)
{
string guessWord = allSpeechText[enInc];
//if the current end word has pause punctuation, stop look ahead
if (EBookUtil.containPausePunctuation(currentEndWord))
{
Debug.WriteLine("currentEndWord \"" + currentEndWord + "\" contains pause, stop look ahead");
break;
}
else if (EBookUtil.containPausePunctuation(guessWord))
{
//reduce 4 syllables from enInc
syIn -= 3;
//no guess ahead if there is any possible pause in guess ahead word.
//Debug.WriteLine("guessWord \"" + guessWord + "\" contains pause, stop look ahead");
//cont = false;
}
if (syIn >= syllableArray[enInc])
{
increment++;
}
syIn -= syllableArray[enInc];
enInc++;
}
else
{
break;
}
}
Debug.WriteLine("guess " + increment + " word(s) ahead");
}
return increment;
}
/// <summary>
/// Process the result from speech recognizer. This method will figure out the
/// highlighting, and generate the grammar that start from the last word it left off.
/// </summary>
/// <param name="result">The recognized text</param>
/// <param name="currentSpeedStartIndex"></param>
/// <param name="isH">indicate whether the result is a hypothesis</param>
/// <param name="confidence">The confidence score between [0,1]</param>
/// <param name="duration">the duration of the detected speech in millisecond</param>
/// <returns>return 1 if the result is a complete speech and it is in the end of the page.</returns>
private int processSpeechResult(string result, int currentSpeedStartIndex, bool isH, float confidence, double duration)
{
//lock this method, in case the this method will take more time than the next result from SR
lock (lockThis)
{
int ret = 0;
string[] arr = result.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
if (isH)
{
int increment = getGuessAheadCount(currentSpeedStartIndex, arr);
//ONLY DISPLAY INTERMIDIATE RESULT WITH CONFIDENCE SCORE GREATER THAN HYP_THRESHOLD
if (confidence > HYP_THRESHOLD)
{
if (currentSpeedStartIndex == lastSegPosition+1) //continue with last segment
{
if (confirmedStartIndex != -1)
{
startIndex = confirmedStartIndex;
}
else
{
startIndex = currentSpeedStartIndex;
}
hypothesisEndIndex = arr.Length + lastSegPosition;
endIndex = hypothesisEndIndex + increment;
}
else if (arr.Length > 1) //jumping to onther sentence when at least two word in the speech
{
int gap = 0;
if (confirmedEndIndex != -1)
{
if (currentSpeedStartIndex < confirmedEndIndex)
{
//the reader jump to the text prior to the last confirmed text
gap = SPEECH_JUMP_GAP_THRESHOLD + 1;
}
else
{
gap = currentSpeedStartIndex - confirmedEndIndex;
}
}
else
{
gap = currentSpeedStartIndex;
}
if (gap > 0 && gap <= SPEECH_JUMP_GAP_THRESHOLD)
{
//if reader skip maximum of SPEECH_JUMP_GAP_THRESHOLD, consider
//the continue highlight the sentence
}
else
{
startIndex = currentSpeedStartIndex;
}
hypothesisEndIndex = arr.Length + currentSpeedStartIndex - 1;
endIndex = hypothesisEndIndex + increment;
}
}
}
else
{
//duration != -1 only when !isH, so we need to estimate the time
//per syllable for the next scentence using the previous speech
int syCount = 0;
for (int i = currentSpeedStartIndex; i < arr.Length + currentSpeedStartIndex; i++)
{
syCount += syllableArray[i];
}
timePerSyllable = duration / syCount;
Trace.WriteLine("timePerSyllable: " + timePerSyllable);
maxSyllableAhead = (int)(maxLag / timePerSyllable); //
numOfHypothsis = 0;
if (currentSpeedStartIndex == lastSegPosition+1)
{
//if number of confirmed word in the complete speech is one word less than hypothesis speech,
//we can treat the last imcomplete speech as complete
int completeEndIndex = arr.Length + lastSegPosition;
if (endIndex - completeEndIndex == 1)
{
//the completed speed is one word less than the previous hypothesis speech
}
else
{
endIndex = completeEndIndex;
}
lastSegPosition = endIndex;
}
//the reader 'skip' the sentence
else
{
int gap = currentSpeedStartIndex - lastSegPosition+1;
if (currentSpeedStartIndex < lastSegPosition)
{
gap = SPEECH_JUMP_GAP_THRESHOLD + 1;
}
if (gap > 0 && gap <= SPEECH_JUMP_GAP_THRESHOLD)
{
//if reader skip maximum of SPEECH_JUMP_GAP_THRESHOLD, consider
//the continue highlight the sentence
}
else
{
startIndex = currentSpeedStartIndex;
}
endIndex = arr.Length + currentSpeedStartIndex - 1;
lastSegPosition = endIndex;
}
confirmedStartIndex = startIndex;
confirmedEndIndex = endIndex;
confirmedLastSegPosition = lastSegPosition;
if (mode != Mode.REPLAY)
{
//reach the end of the page
if (confirmedEndIndex == allSpeechText.Length - 1)
{
//do nothing. We don't need to handle the end of the page for
//replay mode in this class
}
else
{
string cfgPath = storyDirectory + "\\" + GRAMMAR_TMP_DIR + "\\" +
currentPage.GetPageNumber() + "_" + (endIndex + 1) + ".cfg";
if (!defaultStartIndexes.Contains(endIndex + 1))
{
Grammar g = new Grammar(cfgPath);
g.Weight = EBookConstant.NEXT_WORD_WEIGHT;
g.Priority = EBookConstant.NEXT_WORD_PRIORITY;
ActivityExecutor.add(new InternalReloadOnGoingGrammarActivity(g));
Debug.WriteLine("Load onGoing grammar " + cfgPath);
}
else
{
//the next sentence has higher priority
ActivityExecutor.add(new InternalChangeGrammarPriorityActivity(endIndex + 1));
}
}
}
if (mode != Mode.RECORD && confirmedEndIndex == allSpeechText.Length - 1)
{
//the complete recognized result reaches the end of the page
ret = 1;
}
}
Debug.WriteLine("startIndex=" + startIndex);
Debug.WriteLine("endIndex=" + endIndex);
Debug.WriteLine("lastSegPosition=" + lastSegPosition);
Debug.WriteLine("confirmedStartIndex=" + confirmedStartIndex);
Debug.WriteLine("confirmedEndIndex=" + confirmedEndIndex);
Debug.WriteLine("confirmedLastSegPosition=" + confirmedLastSegPosition);
return ret;
}
}
/// <summary>
/// construct the highlight text and fire up a internal activity
/// </summary>
private void constructTextAndDisplay()
{
//if startIndex not equals to confirmedStartIndex, the hypothesis result
//starts from different position.
string displayText = "<span class='storytext'>";
for (int i = 0; i < allSpeechTextHTML.Length; i++)
{
//the on going speech is not yet confirmed
if (startIndex == confirmedStartIndex && endIndex > confirmedEndIndex && startIndex != -1){
//if it is the beginning (no confirmed speech)
if (confirmedEndIndex == 0)
{
if (startIndex == i && endIndex == i)
{
if (endIndex > hypothesisEndIndex)
{
displayText += "<span class='hypothesis'>" + allSpeechTextHTML[i] + " </span> <span class='lookAhead'>" ;
}
else
{
displayText += "<span class='hypothesis'>" + allSpeechTextHTML[i] + " </span> ";
}
}
else if (startIndex == i)
{
displayText += " <span class='hypothesis'>" + allSpeechTextHTML[i] + " ";
}
else if (hypothesisEndIndex == i && hypothesisEndIndex < endIndex)
{
displayText += allSpeechTextHTML[i] + " </span> <span class='lookAhead'>";
}
else if (endIndex == i)
{
displayText += allSpeechTextHTML[i] + " </span> ";
}
else
{
displayText += allSpeechTextHTML[i] + " ";
}
}
else
{
if (startIndex == i && endIndex == i)
{
if (endIndex > hypothesisEndIndex)
{
displayText += "<span class='hypothesis'>" + allSpeechTextHTML[i] + " </span> <span class='lookAhead'>" ;
}
else
{
displayText += "<span class='hypothesis'>" + allSpeechTextHTML[i] + " </span> ";
}
}
else if (startIndex == i)
{
displayText += "<span class='highlight'>" + allSpeechTextHTML[i] + " ";
}
else if (confirmedEndIndex == i)
{
displayText += allSpeechTextHTML[i] + " </span> <span class='hypothesis'>";
}
else if (hypothesisEndIndex == i && hypothesisEndIndex < endIndex)
{
displayText += allSpeechTextHTML[i] + " </span> <span class='lookAhead'>";
}
else if (endIndex == i)
{
displayText += allSpeechTextHTML[i] + " </span> ";
}
else
{
displayText += allSpeechTextHTML[i] + " ";
}
}
}
//the on going speech is not yet confirmed and the hypothesis result starts from different position
else if (startIndex != confirmedStartIndex && startIndex != -1)
{
//display the confimred words
if (confirmedStartIndex == i && confirmedEndIndex == i)
{
displayText += "<span class='highlight'>" + allSpeechTextHTML[i] + " </span> ";
}
else if (confirmedStartIndex == i)
{
displayText += "<span class='highlight'>" + allSpeechTextHTML[i] + " ";
}
else if (confirmedEndIndex == i)
{
displayText += allSpeechTextHTML[i] + " </span> ";
}
else if (startIndex == i)
{
displayText += "<span class='hypothesis'>" + allSpeechTextHTML[i] + " ";
}
else if (endIndex == i)
{
displayText += allSpeechTextHTML[i] + " </span> ";
}
else
{
displayText += allSpeechTextHTML[i] + " ";
}
}
//all spoken speech are confirmed
else
{
if (startIndex == i && endIndex == i)
{
displayText += "<span class='highlight'>" + allSpeechTextHTML[i] + "</span> ";
}
else if (startIndex == i)
{
displayText += "<span class='highlight'>" + allSpeechTextHTML[i] + " ";
}
else if (endIndex == i)
{
displayText += allSpeechTextHTML[i] + "</span> ";
}
else
{
displayText += allSpeechTextHTML[i] + " ";
}
}
}
displayText += "</span>";
Debug.WriteLine(displayText);
ActivityExecutor.add(new InternalUpdateTextHighLightActivity(displayText));
}
/// <summary>
/// Construct the html text for the current page with no highlight
/// </summary>
/// <returns>The html formatted text</returns>
private string constructPageText()
{
string displayText = "<span class='storytext'>";
for (int i = 0; i < allSpeechTextHTML.Length; i++)
{
displayText += allSpeechTextHTML[i] + " ";
}
displayText += "</span>";
return displayText;
}
/// <summary>
/// play the animation for a completed recognition, do nothing if the
/// animation already been played in the hypothesis result.
/// </summary>
/// <param name="reverseIndex">The index of the last word in the recognized speech</param>
private void processAnimation(int reverseIndex)
{
//preserve the last animation in the list
string lastAnim = "";
if (playedAnimationList.Count > 0)
{
lastAnim = playedAnimationList.ElementAt(playedAnimationList.Count-1);
playedAnimationList.Clear();
}
int maxLen = annotationArray.Length;
for (int i = reverseIndex; i >= 0 && i < maxLen; i--)
{
if (annotationArray[i].Length > 0)
{
string[] annX = annotationArray[i].Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string each in annX)
{
if (each.StartsWith("action="))
{
string action = each.Substring(7);
if (currentPage != null)
{
if (!lastAnim.Equals(action))
{
Trace.WriteLine("Processing animation:" + action);
currentPage.processAction(action);
//playedAnimationList.Add(action);
return;
}
else
{
//the latest animation was just played in hypothesis result
//don't need to do anything
return;
}
}
}
}
}
}
}
/// <summary>
/// Play the animation in the hypothesized result.
/// </summary>
/// <param name="textLength">the word count of the hypothesized result</param>
/// <param name="start">the start index of the hypothesized result</param>
private void processHypothesisAnimation(int textLength, int start)
{
//just play the last animation within the result
int endIndex = textLength + start;
endIndex = Math.Min(endIndex, annotationArray.Length - 1);
for (int i = endIndex; i >= start; i--)
{
if (annotationArray[i].Length > 0)
{
string[] annX = annotationArray[i].Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string each in annX)
{
if (each.StartsWith("action="))
{
string action = each.Substring(7);
if (currentPage != null && !playedAnimationList.Contains(action))
{
Trace.WriteLine("Processing animation:" + action);
currentPage.processAction(action);
playedAnimationList.Add(action);
return;
}
}
}
}
}
}
/// <summary>
/// take out the hypothesis highlighting if SR return recognition result or
/// if the audio contains no speech.
/// </summary>
private void withdrawAudioEnergyHypothesizedHighlight()
{
Trace.WriteLine("withdraw highlight from " + endIndex + " to " + confirmedEndIndex);
startIndex = confirmedStartIndex;
endIndex = confirmedEndIndex;
if (startIndex == endIndex && endIndex == 0)
{
//display no highlight
string pageTextStr = constructPageText();
ActivityExecutor.add(new InternalUpdatePageTextActivity(pageTextStr, currentPage.GetPageNumber()));
}
else
{
//display the previous highlight
constructTextAndDisplay();
}
}
/// <summary>
/// The SR detects the audio energy jumps to a significant level, but hasn't yet declear
/// it is a speech. The audio can be the beginning of a speech, or any other noise. In
/// all cases, we want to start highlighting the next word to reduce the delay.
/// </summary>
/// <param name="audioStartTime">The start time of audio</param>
private void processAudioEnergyHypothesizedHighlight(double audioStartTime)
{
if (EBookInteractiveSystem.initialLookAhead > 0 )
{
double elapsedTime = EBookUtil.GetUnixTimeMillis() - audioStartTime;
int syIn = (int)(elapsedTime / timePerSyllable);
int MAX_INITIAL_HIGHLIGHT = EBookInteractiveSystem.initialLookAhead;
int forLoopMax = confirmedEndIndex + 1 + MAX_INITIAL_HIGHLIGHT;
int syCount = 0;
for (int i = confirmedEndIndex+1; i < forLoopMax && i < syllableArray.Length; i++)
{
syCount += syllableArray[i];
}
//int syIn = syCount / EBookDialogueSystem.lookAheadDivider; //one syllable forward for every lookAheadDivide
//make sure we can highlight at least one word
if (confirmedEndIndex +1 < syllableArray.Length && syIn < syllableArray[confirmedEndIndex + 1])
{
syIn = syllableArray[confirmedEndIndex + 1];
}
//the upperbound
if (syIn > syCount)
{
syIn = syCount;
}
int enInc = confirmedEndIndex+1;
Boolean cont = true;
int increment = 0;
while (syIn > 0 && cont)
{
if (enInc < syllableArray.Length)
{
if (syIn >= syllableArray[enInc])
{
increment++;
}
syIn -= syllableArray[enInc];
enInc++;
}
else
{
break;
}
}
Trace.WriteLine("(audio level)guess " + increment + " word(s) ahead");
startIndex = confirmedStartIndex;
endIndex = confirmedEndIndex + increment;
}
constructTextAndDisplay();
}
/// <summary>
/// Interpret the meaning for a command speech.
/// Caution: the string comparison in this function for the commands are
/// rely on the script in command.grxml. If you can something in the command.grxml file
/// you may need to edit command string in this function, vice versa.
/// </summary>
/// <param name="semantics"></param>
private void processCommandSemantics(KeyValuePair<string, SemanticValue>[] semantics)
{
foreach (KeyValuePair<string, SemanticValue> each in semantics)
{
if (each.Key.CompareTo("NavigatePage") == 0)
{
if (each.Value.Value.ToString().CompareTo("[next]") == 0)
{
ActivityExecutor.add(new InternalSpeechNavigatePageActivity(PageAction.NEXT));
}
else if (each.Value.Value.ToString().CompareTo("[previous]") == 0)
{
ActivityExecutor.add(new InternalSpeechNavigatePageActivity(PageAction.PREVIOUS));
}
else
{
int pageN = Convert.ToInt32(each.Value.Value);
ActivityExecutor.add(new InternalSpeechNavigatePageActivity(PageAction.GO_PAGE_X, pageN));
}
}
}
}
/// <summary>
/// The method is currently used in replay mode. The recognitionResult is
/// simulated from log file.
/// </summary>
/// <param name="result">The RecognitionResult ecapsulate the text, confidence, grammars, etc.</param>
private void processRecognitionResult(RecognitionResult result)
{
processRecognitionResult(result.confidence, result.textResult, result.isHypothesis,
result.semanticResult, result.grammarName,
result.ruleName, result.audioDuration, result.wavPath);
}
/// <summary>
/// process the recognition result, the recognition result can be the
/// hypothesis result or the complete result.
/// </summary>
/// <param name="confidence"></param>
/// <param name="textResult"></param>
/// <param name="isHypothesis"></param>
/// <param name="semantics"></param>
/// <param name="grammarName"></param>
/// <param name="ruleName"></param>
/// <param name="audioDuration"></param>
/// <param name="wavPath"></param>
public void processRecognitionResult(float confidence, string textResult,
bool isHypothesis, KeyValuePair<string, SemanticValue>[] semantics, string grammarName,
string ruleName, double audioDuration, string wavPath)
{
//handle result if the recognized speech is a command
if (grammarName.CompareTo("command") == 0)
{
if (!isHypothesis && confidence*100 > EBookInteractiveSystem.commandConfidenceThreshold)
{
processCommandSemantics(semantics);
}
}
//handle result if this is story text
else
{
int start = -1; //the index of the first word of the recognized text in the current page
//process the story annotations
if (semantics != null && semantics.Length > 0)
{
foreach (KeyValuePair<string, SemanticValue> each in semantics)
{
if (each.Key.CompareTo("startIndex") == 0)
{
start = Convert.ToInt32(each.Value.Value);
}
}
}
if (start == -1)
{
string rule = ruleName;
if (rule.StartsWith("index_"))
{
string startIndex = rule.Substring(6);
if (startIndex.Length > 0)
{
start = Convert.ToInt32(startIndex);
}
}
}
//process the highlighting before animation (try to underline the text as fast as possible)
Debug.WriteLine(textResult);
Trace.WriteLine("start process Text time: " + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
int isEndOfPage = processSpeechResult(textResult, start, isHypothesis,
confidence, audioDuration);
constructTextAndDisplay();
Trace.WriteLine("end process Text time: " + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
//for some reasons, the hypothesis results do not contain any semantic results, so
//we have to find it manually
if (isHypothesis)
{
string[] tmp = textResult.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
//it is offen misrecognize the first word in a speech.
//generate animation when hypothsis text is greater than 1
if (tmp.Length > 1)
{
processHypothesisAnimation(tmp.Length, start);
}
}
else
{
string[] tmp = textResult.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
processAnimation(tmp.Length+start);
//keep the last action in the list, remove rest of the them
if (isEndOfPage == 1)
{
//Debug.WriteLine("generating a finishpageactivity "+isHypothesis);
ActivityExecutor.add(new InternalFinishPageActivity());
}
}
}
}
/// <summary>
/// Update the speech state that detected in SR.
/// </summary>
/// <param name="state"></param>
public void setSpeechState(SpeechState state)
{
if (state == SpeechState.SPEECH_START)
{
speechState = 1;
}
else if (state == SpeechState.SPEECH_END)
{
speechState = 0;
}
}
/// <summary>
/// highlight words if the system detect sound but SR has yet detected any speech.
/// </summary>
/// <param name="audioState">the state of sound {begin, end}</param>
/// <param name="startTime">the time where it first detected</param>
public void processAcousticHypothesisHighlight(int audioState, double startTime)
{
//process highlight if any sound is detected
if (speechState == 0 && audioState >= 0)
{
processAudioEnergyHypothesizedHighlight(startTime);
}
// remove the acoustic hypothesis highlight if it is the end of the sound
else if (speechState == 0 && audioState < 0)
{
withdrawAudioEnergyHypothesizedHighlight();
}
}
/// <summary>
/// SR rejects the recent hypothesis result, roll the highlighting back to previous
/// comfirmed text
/// </summary>
public void rollBackText()
{
numOfHypothsis = 0;
lastSegPosition = confirmedLastSegPosition;
startIndex = confirmedStartIndex;
endIndex = confirmedEndIndex;
processAnimation(endIndex);
//construct the text without highlight if the rejected recognition is the first sentence/word of the page
if (confirmedLastSegPosition == confirmedStartIndex && confirmedStartIndex == confirmedEndIndex &&
confirmedEndIndex == 0)
{
string pageTextStr = constructPageText();
ActivityExecutor.add(new InternalUpdatePageTextActivity(pageTextStr, currentPage.GetPageNumber()));
}
else
{
//construct html text with highlight
constructTextAndDisplay();
}
}
}
}
| |
/*
* 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 Apache.NMS.Util;
using NUnit.Framework;
namespace Apache.NMS.Test
{
[TestFixture]
public class TransactionTest : NMSTestSupport
{
protected static string DESTINATION_NAME = "queue://TEST.TransactionTestDestination";
[Test]
public void TestSendRollback(
[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
MsgDeliveryMode deliveryMode)
{
using(IConnection connection = CreateConnection(GetTestClientId()))
{
connection.Start();
using(ISession session = connection.CreateSession(AcknowledgementMode.Transactional))
{
IDestination destination = CreateDestination(session, DESTINATION_NAME);
using(IMessageConsumer consumer = session.CreateConsumer(destination))
using(IMessageProducer producer = session.CreateProducer(destination))
{
producer.DeliveryMode = deliveryMode;
ITextMessage firstMsgSend = session.CreateTextMessage("First Message");
producer.Send(firstMsgSend);
session.Commit();
ITextMessage rollbackMsg = session.CreateTextMessage("I'm going to get rolled back.");
producer.Send(rollbackMsg);
session.Rollback();
ITextMessage secondMsgSend = session.CreateTextMessage("Second Message");
producer.Send(secondMsgSend);
session.Commit();
// Receive the messages
IMessage message = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(firstMsgSend, message, "First message does not match.");
message = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(secondMsgSend, message, "Second message does not match.");
// validates that the rollback was not consumed
session.Commit();
}
}
}
}
[Test]
public void TestSendSessionClose(
[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
MsgDeliveryMode deliveryMode)
{
ITextMessage firstMsgSend;
ITextMessage secondMsgSend;
using(IConnection connection1 = CreateConnection(GetTestClientId()))
{
connection1.Start();
using(ISession session1 = connection1.CreateSession(AcknowledgementMode.Transactional))
{
IDestination destination1 = CreateDestination(session1, DESTINATION_NAME);
using(IMessageConsumer consumer = session1.CreateConsumer(destination1))
{
// First connection session that sends one message, and the
// second message is implicitly rolled back as the session is
// disposed before Commit() can be called.
using(IConnection connection2 = CreateConnection(GetTestClientId()))
{
connection2.Start();
using(ISession session2 = connection2.CreateSession(AcknowledgementMode.Transactional))
{
IDestination destination2 = CreateDestination(session2, DESTINATION_NAME);
using(IMessageProducer producer = session2.CreateProducer(destination2))
{
producer.DeliveryMode = deliveryMode;
firstMsgSend = session2.CreateTextMessage("First Message");
producer.Send(firstMsgSend);
session2.Commit();
ITextMessage rollbackMsg = session2.CreateTextMessage("I'm going to get rolled back.");
producer.Send(rollbackMsg);
}
}
}
// Second connection session that will send one message.
using(IConnection connection2 = CreateConnection(GetTestClientId()))
{
connection2.Start();
using(ISession session2 = connection2.CreateSession(AcknowledgementMode.Transactional))
{
IDestination destination2 = CreateDestination(session2, DESTINATION_NAME);
using(IMessageProducer producer = session2.CreateProducer(destination2))
{
producer.DeliveryMode = deliveryMode;
secondMsgSend = session2.CreateTextMessage("Second Message");
producer.Send(secondMsgSend);
session2.Commit();
}
}
}
// Check the consumer to verify which messages were actually received.
IMessage message = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(firstMsgSend, message, "First message does not match.");
message = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(secondMsgSend, message, "Second message does not match.");
// validates that the rollback was not consumed
session1.Commit();
}
}
}
}
[Test]
public void TestReceiveRollback(
[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
MsgDeliveryMode deliveryMode)
{
using(IConnection connection = CreateConnection(GetTestClientId()))
{
connection.Start();
using(ISession session = connection.CreateSession(AcknowledgementMode.Transactional))
{
IDestination destination = CreateDestination(session, DESTINATION_NAME);
using(IMessageConsumer consumer = session.CreateConsumer(destination))
using(IMessageProducer producer = session.CreateProducer(destination))
{
producer.DeliveryMode = deliveryMode;
// Send both messages
ITextMessage firstMsgSend = session.CreateTextMessage("First Message");
producer.Send(firstMsgSend);
ITextMessage secondMsgSend = session.CreateTextMessage("Second Message");
producer.Send(secondMsgSend);
session.Commit();
// Receive the messages
IMessage message = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(firstMsgSend, message, "First message does not match.");
session.Commit();
message = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(secondMsgSend, message, "Second message does not match.");
// Rollback so we can get that last message again.
session.Rollback();
IMessage rollbackMsg = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(secondMsgSend, rollbackMsg, "Rollback message does not match.");
session.Commit();
}
}
}
}
[Test]
public void TestReceiveTwoThenRollback(
[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
MsgDeliveryMode deliveryMode)
{
using(IConnection connection = CreateConnection(GetTestClientId()))
{
connection.Start();
using(ISession session = connection.CreateSession(AcknowledgementMode.Transactional))
{
IDestination destination = CreateDestination(session, DESTINATION_NAME);
using(IMessageConsumer consumer = session.CreateConsumer(destination))
using(IMessageProducer producer = session.CreateProducer(destination))
{
producer.DeliveryMode = deliveryMode;
// Send both messages
ITextMessage firstMsgSend = session.CreateTextMessage("First Message");
producer.Send(firstMsgSend);
ITextMessage secondMsgSend = session.CreateTextMessage("Second Message");
producer.Send(secondMsgSend);
session.Commit();
// Receive the messages
IMessage message = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(firstMsgSend, message, "First message does not match.");
message = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(secondMsgSend, message, "Second message does not match.");
// Rollback so we can get that last two messages again.
session.Rollback();
IMessage rollbackMsg = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(firstMsgSend, rollbackMsg, "First rollback message does not match.");
rollbackMsg = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(secondMsgSend, rollbackMsg, "Second rollback message does not match.");
Assert.IsNull(consumer.ReceiveNoWait());
session.Commit();
}
}
}
}
[Test]
public void TestSendCommitNonTransaction(
[Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge)]
AcknowledgementMode ackMode,
[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
MsgDeliveryMode deliveryMode)
{
using(IConnection connection = CreateConnection(GetTestClientId()))
{
connection.Start();
using(ISession session = connection.CreateSession(ackMode))
{
IDestination destination = CreateDestination(session, DESTINATION_NAME);
using(IMessageConsumer consumer = session.CreateConsumer(destination))
using(IMessageProducer producer = session.CreateProducer(destination))
{
producer.DeliveryMode = deliveryMode;
ITextMessage firstMsgSend = session.CreateTextMessage("SendCommitNonTransaction Message");
producer.Send(firstMsgSend);
try
{
session.Commit();
Assert.Fail("Should have thrown an InvalidOperationException.");
}
catch(InvalidOperationException)
{
}
}
}
}
}
[Test]
public void TestReceiveCommitNonTransaction(
[Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge)]
AcknowledgementMode ackMode,
[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
MsgDeliveryMode deliveryMode)
{
using(IConnection connection = CreateConnection(GetTestClientId()))
{
connection.Start();
using(ISession session = connection.CreateSession(ackMode))
{
IDestination destination = CreateDestination(session, DESTINATION_NAME);
using(IMessageConsumer consumer = session.CreateConsumer(destination))
using(IMessageProducer producer = session.CreateProducer(destination))
{
producer.DeliveryMode = deliveryMode;
ITextMessage firstMsgSend = session.CreateTextMessage("ReceiveCommitNonTransaction Message");
producer.Send(firstMsgSend);
// Receive the messages
IMessage message = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(firstMsgSend, message, "First message does not match.");
if(AcknowledgementMode.ClientAcknowledge == ackMode)
{
message.Acknowledge();
}
try
{
session.Commit();
Assert.Fail("Should have thrown an InvalidOperationException.");
}
catch(InvalidOperationException)
{
}
}
}
}
}
[Test]
public void TestReceiveRollbackNonTransaction(
[Values(AcknowledgementMode.AutoAcknowledge, AcknowledgementMode.ClientAcknowledge)]
AcknowledgementMode ackMode,
[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
MsgDeliveryMode deliveryMode)
{
using(IConnection connection = CreateConnection(GetTestClientId()))
{
connection.Start();
using(ISession session = connection.CreateSession(ackMode))
{
IDestination destination = CreateDestination(session, DESTINATION_NAME);
using(IMessageConsumer consumer = session.CreateConsumer(destination))
using(IMessageProducer producer = session.CreateProducer(destination))
{
producer.DeliveryMode = deliveryMode;
ITextMessage firstMsgSend = session.CreateTextMessage("ReceiveCommitNonTransaction Message");
producer.Send(firstMsgSend);
// Receive the messages
IMessage message = consumer.Receive(receiveTimeout);
AssertTextMessageEqual(firstMsgSend, message, "First message does not match.");
if(AcknowledgementMode.ClientAcknowledge == ackMode)
{
message.Acknowledge();
}
try
{
session.Rollback();
Assert.Fail("Should have thrown an InvalidOperationException.");
}
catch(InvalidOperationException)
{
}
}
}
}
}
/// <summary>
/// Assert that two messages are ITextMessages and their text bodies are equal.
/// </summary>
/// <param name="expected"></param>
/// <param name="actual"></param>
/// <param name="message"></param>
protected void AssertTextMessageEqual(IMessage expected, IMessage actual, String message)
{
ITextMessage expectedTextMsg = expected as ITextMessage;
Assert.IsNotNull(expectedTextMsg, "'expected' message not a text message");
ITextMessage actualTextMsg = actual as ITextMessage;
Assert.IsNotNull(actualTextMsg, "'actual' message not a text message");
Assert.AreEqual(expectedTextMsg.Text, actualTextMsg.Text, message);
}
[Test]
public void TestRedispatchOfRolledbackTx(
[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
MsgDeliveryMode deliveryMode)
{
using(IConnection connection = CreateConnection(GetTestClientId()))
{
connection.Start();
ISession session = connection.CreateSession(AcknowledgementMode.Transactional);
IDestination destination = CreateDestination(session, DestinationType.Queue);
SendMessages(connection, destination, deliveryMode, 2);
IMessageConsumer consumer = session.CreateConsumer(destination);
Assert.IsNotNull(consumer.Receive(TimeSpan.FromMilliseconds(1500)));
Assert.IsNotNull(consumer.Receive(TimeSpan.FromMilliseconds(1500)));
// install another consumer while message dispatch is unacked/uncommitted
ISession redispatchSession = connection.CreateSession(AcknowledgementMode.Transactional);
IMessageConsumer redispatchConsumer = redispatchSession.CreateConsumer(destination);
session.Rollback();
session.Close();
IMessage msg = redispatchConsumer.Receive(TimeSpan.FromMilliseconds(1500));
Assert.IsNotNull(msg);
Assert.IsTrue(msg.NMSRedelivered);
Assert.AreEqual(2, msg.Properties.GetLong("NMSXDeliveryCount"));
msg = redispatchConsumer.Receive(TimeSpan.FromMilliseconds(1500));
Assert.IsNotNull(msg);
Assert.IsTrue(msg.NMSRedelivered);
Assert.AreEqual(2, msg.Properties.GetLong("NMSXDeliveryCount"));
redispatchSession.Commit();
Assert.IsNull(redispatchConsumer.Receive(TimeSpan.FromMilliseconds(500)));
redispatchSession.Close();
}
}
[Test]
public void TestRedispatchOfUncommittedTx(
[Values(MsgDeliveryMode.Persistent, MsgDeliveryMode.NonPersistent)]
MsgDeliveryMode deliveryMode)
{
using(IConnection connection = CreateConnection(GetTestClientId()))
{
connection.Start();
ISession session = connection.CreateSession(AcknowledgementMode.Transactional);
IDestination destination = CreateDestination(session, DestinationType.Queue);
SendMessages(connection, destination, deliveryMode, 2);
IMessageConsumer consumer = session.CreateConsumer(destination);
Assert.IsNotNull(consumer.Receive(TimeSpan.FromMilliseconds(2000)));
Assert.IsNotNull(consumer.Receive(TimeSpan.FromMilliseconds(2000)));
// install another consumer while message dispatch is unacked/uncommitted
ISession redispatchSession = connection.CreateSession(AcknowledgementMode.Transactional);
IMessageConsumer redispatchConsumer = redispatchSession.CreateConsumer(destination);
// no commit so will auto rollback and get re-dispatched to redisptachConsumer
session.Close();
IMessage msg = redispatchConsumer.Receive(TimeSpan.FromMilliseconds(2000));
Assert.IsNotNull(msg);
Assert.IsTrue(msg.NMSRedelivered);
Assert.AreEqual(2, msg.Properties.GetLong("NMSXDeliveryCount"));
msg = redispatchConsumer.Receive(TimeSpan.FromMilliseconds(2000));
Assert.IsNotNull(msg);
Assert.IsTrue(msg.NMSRedelivered);
Assert.AreEqual(2, msg.Properties.GetLong("NMSXDeliveryCount"));
redispatchSession.Commit();
Assert.IsNull(redispatchConsumer.Receive(TimeSpan.FromMilliseconds(500)));
redispatchSession.Close();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Nether.Web.Features.Analytics;
using Nether.Web.Features.Identity;
using Nether.Web.Features.Leaderboard;
using Nether.Web.Features.PlayerManagement;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using Microsoft.Extensions.PlatformAbstractions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Nether.Web.Utilities;
using Swashbuckle.AspNetCore.Swagger;
using IdentityServer4;
using System.Linq;
using IdentityServer4.Models;
using Microsoft.Extensions.FileProviders;
namespace Nether.Web
{
public class Startup
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly ILogger _logger;
public Startup(IHostingEnvironment env, ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<Startup>();
_hostingEnvironment = env;
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
loggerFactory.AddTrace(LogLevel.Information);
loggerFactory.AddAzureWebAppDiagnostics(); // docs: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging#appservice
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
// Add framework services.
services
.AddMvc(options =>
{
options.Conventions.Add(new FeatureConvention());
options.Filters.AddService(typeof(ExceptionLoggingFilterAttribute));
})
.AddRazorOptions(options =>
{
// {0} - Action Name
// {1} - Controller Name
// {2} - Area Name
// {3} - Feature Name
options.AreaViewLocationFormats.Clear();
options.AreaViewLocationFormats.Add("/Areas/{2}/Features/{3}/Views/{1}/{0}.cshtml");
options.AreaViewLocationFormats.Add("/Areas/{2}/Features/{3}/Views/{0}.cshtml");
options.AreaViewLocationFormats.Add("/Areas/{2}/Features/Views/Shared/{0}.cshtml");
options.AreaViewLocationFormats.Add("/Areas/Shared/{0}.cshtml");
// replace normal view location entirely
options.ViewLocationFormats.Clear();
options.ViewLocationFormats.Add("/Features/{3}/Views/{1}/{0}.cshtml");
options.ViewLocationFormats.Add("/Features/{3}/Views/Shared/{0}.cshtml");
options.ViewLocationFormats.Add("/Features/{3}/Views/{0}.cshtml");
options.ViewLocationFormats.Add("/Features/Views/Shared/{0}.cshtml");
options.ViewLocationExpanders.Add(new FeatureViewLocationExpander());
})
.AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter
{
CamelCaseText = true
});
});
services.AddCors();
services.ConfigureSwaggerGen(options =>
{
string commentsPath = Path.Combine(
PlatformServices.Default.Application.ApplicationBasePath,
"Nether.Web.xml");
options.IncludeXmlComments(commentsPath);
});
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v0.1", new Info
{
Version = "v0.1",
Title = "Project Nether",
License = new License
{
Name = "MIT",
Url = "https://github.com/MicrosoftDX/nether/blob/master/LICENSE"
}
});
//options.OperationFilter<ApiPrefixFilter>();
options.CustomSchemaIds(type => type.FullName);
options.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Type = "oauth2",
Flow = "implicit",
AuthorizationUrl = "/identity/connect/authorize",
Scopes = new Dictionary<string, string>
{
{ "nether-all", "nether API access" },
}
});
options.OperationFilter<SecurityRequirementsOperationFilter>();
});
services.AddSingleton<ExceptionLoggingFilterAttribute>();
// TODO make this conditional with feature switches
services.AddIdentityServices(Configuration, _logger, _hostingEnvironment);
services.AddLeaderboardServices(Configuration, _logger);
services.AddPlayerManagementServices(Configuration, _logger);
services.AddAnalyticsServices(Configuration, _logger);
services.AddAuthorization(options =>
{
options.AddPolicy(
PolicyName.NetherIdentityClientId,
policy => policy.RequireClaim(
"client_id",
"nether-identity"
));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger<Startup>();
app.EnsureInitialAdminUser(Configuration, logger);
// Set up separate web pipelines for identity, MVC UI, and API
// as they each have different auth requirements!
app.Map("/identity", idapp =>
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
idapp.UseIdentityServer();
idapp.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
AutomaticAuthenticate = false,
AutomaticChallenge = false
});
var facebookEnabled = bool.Parse(Configuration["Identity:SignInMethods:Facebook:Enabled"] ?? "false");
if (facebookEnabled)
{
var appId = Configuration["Identity:SignInMethods:Facebook:AppId"];
var appSecret = Configuration["Identity:SignInMethods:Facebook:AppSecret"];
idapp.UseFacebookAuthentication(new FacebookOptions()
{
DisplayName = "Facebook",
SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
CallbackPath = "/signin-facebook",
AppId = appId,
AppSecret = appSecret
});
}
idapp.UseStaticFiles();
idapp.UseMvc(routes =>
{
routes.MapRoute(
name: "account",
template: "account/{action}",
defaults: new { controller = "Account" });
});
});
app.Map("/api", apiapp =>
{
apiapp.UseCors(options =>
{
logger.LogInformation("CORS options:");
var config = Configuration.GetSection("Common:Cors");
var allowedOrigins = config.ParseStringArray("AllowedOrigins").ToArray();
logger.LogInformation("AllowedOrigins: {0}", string.Join(",", allowedOrigins));
options.WithOrigins(allowedOrigins);
// TODO - allow configuration of headers/methods
options
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var idsvrConfig = Configuration.GetSection("Identity:IdentityServer");
string authority = idsvrConfig["Authority"];
bool requireHttps = idsvrConfig.GetValue("RequireHttps", true);
apiapp.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = authority,
RequireHttpsMetadata = requireHttps,
ApiName = "nether-all",
AllowedScopes = { "nether-all" },
});
// TODO filter which routes this matches (i.e. only API routes)
apiapp.UseMvc();
apiapp.UseSwagger(options =>
{
options.RouteTemplate = "swagger/{documentName}/swagger.json";
});
apiapp.UseSwaggerUi(options =>
{
options.RoutePrefix = "swagger/ui";
options.SwaggerEndpoint("/api/swagger/v0.1/swagger.json", "v0.1 Docs");
options.ConfigureOAuth2("swaggerui", "swaggeruisecret".Sha256(), "swagger-ui-realm", "Swagger UI");
});
});
app.Map("/ui", uiapp =>
{
uiapp.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies"
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var authority = Configuration["Identity:IdentityServer:Authority"];
var uiBaseUrl = Configuration["Identity:IdentityServer:UiBaseUrl"];
// hybrid
uiapp.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
SignInScheme = "Cookies",
Authority = authority,
RequireHttpsMetadata = false,
PostLogoutRedirectUri = uiBaseUrl,
ClientId = "mvc2",
ClientSecret = "secret",
ResponseType = "code id_token",
Scope = { "api1", "offline_access" },
GetClaimsFromUserInfoEndpoint = true,
SaveTokens = true
});
// serve admin ui static files under /ui/admin
uiapp.UseStaticFiles(new StaticFileOptions
{
RequestPath = "/admin",
FileProvider = new PhysicalFileProvider(Path.Combine(_hostingEnvironment.WebRootPath, "Features", "AdminWebUi"))
});
uiapp.UseMvc(); // TODO filter which routes this matches (i.e. only non-API routes)
});
// serve Landing page static files at root
app.UseStaticFiles(new StaticFileOptions
{
RequestPath = "",
FileProvider = new PhysicalFileProvider(Path.Combine(_hostingEnvironment.WebRootPath, "Features", "LandingPage"))
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "landing-page",
template: "",
defaults: new { controller = "LandingPage", action = "Index" }
);
});
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Host
{
/// <summary>
/// Utility class for initializing an Orleans client running inside Azure.
/// </summary>
public static class AzureClient
{
private static readonly IServiceRuntimeWrapper serviceRuntimeWrapper = new ServiceRuntimeWrapper(AzureSilo.CreateDefaultLoggerFactory("AzureClient.log"));
/// <summary>Number of retry attempts to make when searching for gateway silos to connect to.</summary>
public static readonly int MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes
/// <summary>Amount of time to pause before each retry attempt.</summary>
public static readonly TimeSpan StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
/// <summary> delegate to configure logging, default to none logger configured </summary>
public static Action<ILoggingBuilder> ConfigureLoggingDelegate { get; set; } = builder => { };
/// <summary>
/// Whether the Orleans Azure client runtime has already been initialized
/// </summary>
/// <returns><c>true</c> if client runtime is already initialized</returns>
public static bool IsInitialized { get { return GrainClient.IsInitialized; } }
/// <summary>
/// Initialise the Orleans client runtime in this Azure process
/// </summary>
public static void Initialize()
{
InitializeImpl_FromFile(null);
}
/// <summary>
/// Initialise the Orleans client runtime in this Azure process
/// </summary>
/// <param name="orleansClientConfigFile">Location of the Orleans client config file to use for base config settings</param>
/// <remarks>Any silo gateway address specified in the config file is ignored, and gateway endpoint info is read from the silo instance table in Azure storage instead.</remarks>
public static void Initialize(FileInfo orleansClientConfigFile)
{
InitializeImpl_FromFile(orleansClientConfigFile);
}
/// <summary>
/// Initialise the Orleans client runtime in this Azure process
/// </summary>
/// <param name="clientConfigFilePath">Location of the Orleans client config file to use for base config settings</param>
/// <remarks>Any silo gateway address specified in the config file is ignored, and gateway endpoint info is read from the silo instance table in Azure storage instead.</remarks>
public static void Initialize(string clientConfigFilePath)
{
InitializeImpl_FromFile(new FileInfo(clientConfigFilePath));
}
/// <summary>
/// Initializes the Orleans client runtime in this Azure process from the provided client configuration object.
/// If the configuration object is null, the initialization fails.
/// </summary>
/// <param name="config">A ClientConfiguration object.</param>
public static void Initialize(ClientConfiguration config)
{
InitializeImpl_FromConfig(config);
}
/// <summary>
/// Uninitializes the Orleans client runtime in this Azure process.
/// </summary>
public static void Uninitialize()
{
if (!GrainClient.IsInitialized) return;
Trace.TraceInformation("Uninitializing connection to Orleans gateway silo.");
GrainClient.Uninitialize();
}
/// <summary>
/// Returns default client configuration object for passing to AzureClient.
/// </summary>
/// <returns></returns>
public static ClientConfiguration DefaultConfiguration()
{
var config = new ClientConfiguration
{
GatewayProvider = ClientConfiguration.GatewayProviderType.AzureTable,
DeploymentId = GetDeploymentId(),
DataConnectionString = GetDataConnectionString(),
};
return config;
}
#region Internal implementation of client initialization processing
private static void InitializeImpl_FromFile(FileInfo configFile)
{
if (GrainClient.IsInitialized)
{
Trace.TraceInformation("Connection to Orleans gateway silo already initialized.");
return;
}
ClientConfiguration config;
try
{
if (configFile == null)
{
Trace.TraceInformation("Looking for standard Orleans client config file");
config = ClientConfiguration.StandardLoad();
}
else
{
var configFileLocation = configFile.FullName;
Trace.TraceInformation("Loading Orleans client config file {0}", configFileLocation);
config = ClientConfiguration.LoadFromFile(configFileLocation);
}
}
catch (Exception ex)
{
var msg = String.Format("Error loading Orleans client configuration file {0} {1} -- unable to continue. {2}", configFile, ex.Message, LogFormatter.PrintException(ex));
Trace.TraceError(msg);
throw new AggregateException(msg, ex);
}
Trace.TraceInformation("Overriding Orleans client config from Azure runtime environment.");
try
{
config.DeploymentId = GetDeploymentId();
config.DataConnectionString = GetDataConnectionString();
config.GatewayProvider = ClientConfiguration.GatewayProviderType.AzureTable;
}
catch (Exception ex)
{
var msg = string.Format("ERROR: No AzureClient role setting value '{0}' specified for this role -- unable to continue", AzureConstants.DataConnectionConfigurationSettingName);
Trace.TraceError(msg);
throw new AggregateException(msg, ex);
}
InitializeImpl_FromConfig(config);
}
internal static string GetDeploymentId()
{
return GrainClient.TestOnlyNoConnect ? "FakeDeploymentId" : serviceRuntimeWrapper.DeploymentId;
}
internal static string GetDataConnectionString()
{
return GrainClient.TestOnlyNoConnect
? "FakeConnectionString"
: serviceRuntimeWrapper.GetConfigurationSettingValue(AzureConstants.DataConnectionConfigurationSettingName);
}
private static void InitializeImpl_FromConfig(ClientConfiguration config)
{
if (GrainClient.IsInitialized)
{
Trace.TraceInformation("Connection to Orleans gateway silo already initialized.");
return;
}
//// Find endpoint info for the gateway to this Orleans silo cluster
//Trace.WriteLine("Searching for Orleans gateway silo via Orleans instance table...");
var deploymentId = config.DeploymentId;
var connectionString = config.DataConnectionString;
if (String.IsNullOrEmpty(deploymentId))
throw new ArgumentException("Cannot connect to Azure silos with null deploymentId", "config.DeploymentId");
if (String.IsNullOrEmpty(connectionString))
throw new ArgumentException("Cannot connect to Azure silos with null connectionString", "config.DataConnectionString");
bool initSucceeded = false;
Exception lastException = null;
for (int i = 0; i < MaxRetries; i++)
{
try
{
//parse through ConfigureLoggingDelegate to GrainClient
GrainClient.ConfigureLoggingDelegate = ConfigureLoggingDelegate;
// Initialize will throw if cannot find Gateways
GrainClient.Initialize(config);
initSucceeded = true;
break;
}
catch (Exception exc)
{
lastException = exc;
Trace.TraceError("Client.Initialize failed with exc -- {0}. Will try again", exc.Message);
}
// Pause to let Primary silo start up and register
Trace.TraceInformation("Pausing {0} awaiting silo and gateways registration for Deployment={1}", StartupRetryPause, deploymentId);
Thread.Sleep(StartupRetryPause);
}
if (initSucceeded) return;
OrleansException err;
err = lastException != null ? new OrleansException(String.Format("Could not Initialize Client for DeploymentId={0}. Last exception={1}",
deploymentId, lastException.Message), lastException) : new OrleansException(String.Format("Could not Initialize Client for DeploymentId={0}.", deploymentId));
Trace.TraceError("Error starting Orleans Azure client application -- {0} -- bailing. {1}", err.Message, LogFormatter.PrintException(err));
throw err;
}
#endregion
}
}
| |
#region Header
/**
* JsonData.cs
* Generic type to hold JSON data (objects, arrays, and so on). This is
* the default type returned by JsonMapper.ToObject().
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using MarkerMetro.Unity.WinLegacy.Plugin.Collections.Specialized;
namespace LitJson
{
public class JsonData : IJsonWrapper, IEquatable<JsonData>
{
#region Fields
private IList<JsonData> inst_array;
private bool inst_boolean;
private double inst_double;
private int inst_int;
private long inst_long;
private IDictionary<string, JsonData> inst_object;
private string inst_string;
private string json;
private JsonType type;
// Used to implement the IOrderedDictionary interface
private IList<KeyValuePair<string, JsonData>> object_list;
#endregion
#region Properties
public int Count {
get { return EnsureCollection ().Count; }
}
public bool IsArray {
get { return type == JsonType.Array; }
}
public bool IsBoolean {
get { return type == JsonType.Boolean; }
}
public bool IsDouble {
get { return type == JsonType.Double; }
}
public bool IsInt {
get { return type == JsonType.Int; }
}
public bool IsLong {
get { return type == JsonType.Long; }
}
public bool IsObject {
get { return type == JsonType.Object; }
}
public bool IsString {
get { return type == JsonType.String; }
}
public ICollection<string> Keys {
get { EnsureDictionary (); return inst_object.Keys; }
}
#endregion
#region ICollection Properties
int ICollection.Count {
get {
return Count;
}
}
bool ICollection.IsSynchronized {
get {
return EnsureCollection ().IsSynchronized;
}
}
object ICollection.SyncRoot {
get {
return EnsureCollection ().SyncRoot;
}
}
#endregion
#region IDictionary Properties
bool IDictionary.IsFixedSize {
get {
return EnsureDictionary ().IsFixedSize;
}
}
bool IDictionary.IsReadOnly {
get {
return EnsureDictionary ().IsReadOnly;
}
}
ICollection IDictionary.Keys {
get {
EnsureDictionary ();
IList<string> keys = new List<string> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
keys.Add (entry.Key);
}
return (ICollection) keys;
}
}
ICollection IDictionary.Values {
get {
EnsureDictionary ();
IList<JsonData> values = new List<JsonData> ();
foreach (KeyValuePair<string, JsonData> entry in
object_list) {
values.Add (entry.Value);
}
return (ICollection) values;
}
}
#endregion
#region IJsonWrapper Properties
bool IJsonWrapper.IsArray {
get { return IsArray; }
}
bool IJsonWrapper.IsBoolean {
get { return IsBoolean; }
}
bool IJsonWrapper.IsDouble {
get { return IsDouble; }
}
bool IJsonWrapper.IsInt {
get { return IsInt; }
}
bool IJsonWrapper.IsLong {
get { return IsLong; }
}
bool IJsonWrapper.IsObject {
get { return IsObject; }
}
bool IJsonWrapper.IsString {
get { return IsString; }
}
#endregion
#region IList Properties
bool IList.IsFixedSize {
get {
return EnsureList ().IsFixedSize;
}
}
bool IList.IsReadOnly {
get {
return EnsureList ().IsReadOnly;
}
}
#endregion
#region IDictionary Indexer
object IDictionary.this[object key] {
get {
return EnsureDictionary ()[key];
}
set {
if (! (key is String))
throw new ArgumentException (
"The key has to be a string");
JsonData data = ToJsonData (value);
this[(string) key] = data;
}
}
#endregion
#region IOrderedDictionary Indexer
object IOrderedDictionary.this[int idx] {
get {
EnsureDictionary ();
return object_list[idx].Value;
}
set {
EnsureDictionary ();
JsonData data = ToJsonData (value);
KeyValuePair<string, JsonData> old_entry = object_list[idx];
inst_object[old_entry.Key] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (old_entry.Key, data);
object_list[idx] = entry;
}
}
#endregion
#region IList Indexer
object IList.this[int index] {
get {
return EnsureList ()[index];
}
set {
EnsureList ();
JsonData data = ToJsonData (value);
this[index] = data;
}
}
#endregion
#region Public Indexers
public JsonData this[string prop_name] {
get {
EnsureDictionary ();
return inst_object[prop_name];
}
set {
EnsureDictionary ();
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (prop_name, value);
if (inst_object.ContainsKey (prop_name)) {
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == prop_name) {
object_list[i] = entry;
break;
}
}
} else
object_list.Add (entry);
inst_object[prop_name] = value;
json = null;
}
}
public JsonData this[int index] {
get {
EnsureCollection ();
if (type == JsonType.Array)
return inst_array[index];
return object_list[index].Value;
}
set {
EnsureCollection ();
if (type == JsonType.Array)
inst_array[index] = value;
else {
KeyValuePair<string, JsonData> entry = object_list[index];
KeyValuePair<string, JsonData> new_entry =
new KeyValuePair<string, JsonData> (entry.Key, value);
object_list[index] = new_entry;
inst_object[entry.Key] = value;
}
json = null;
}
}
#endregion
#region Constructors
public JsonData ()
{
}
public JsonData (bool boolean)
{
type = JsonType.Boolean;
inst_boolean = boolean;
}
public JsonData (double number)
{
type = JsonType.Double;
inst_double = number;
}
public JsonData (int number)
{
type = JsonType.Int;
inst_int = number;
}
public JsonData (long number)
{
type = JsonType.Long;
inst_long = number;
}
public JsonData (object obj)
{
if (obj is Boolean) {
type = JsonType.Boolean;
inst_boolean = (bool) obj;
return;
}
if (obj is Double) {
type = JsonType.Double;
inst_double = (double) obj;
return;
}
if (obj is Int32) {
type = JsonType.Int;
inst_int = (int) obj;
return;
}
if (obj is Int64) {
type = JsonType.Long;
inst_long = (long) obj;
return;
}
if (obj is String) {
type = JsonType.String;
inst_string = (string) obj;
return;
}
throw new ArgumentException (
"Unable to wrap the given object with JsonData");
}
public JsonData (string str)
{
type = JsonType.String;
inst_string = str;
}
#endregion
#region Implicit Conversions
public static implicit operator JsonData (Boolean data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Double data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int32 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (Int64 data)
{
return new JsonData (data);
}
public static implicit operator JsonData (String data)
{
return new JsonData (data);
}
#endregion
#region Explicit Conversions
public static explicit operator Boolean (JsonData data)
{
if (data.type != JsonType.Boolean)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_boolean;
}
public static explicit operator Double (JsonData data)
{
if (data.type != JsonType.Double)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a double");
return data.inst_double;
}
public static explicit operator Int32 (JsonData data)
{
if (data.type != JsonType.Int)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_int;
}
public static explicit operator Int64 (JsonData data)
{
if (data.type != JsonType.Long)
throw new InvalidCastException (
"Instance of JsonData doesn't hold an int");
return data.inst_long;
}
public static explicit operator String (JsonData data)
{
if (data.type != JsonType.String)
throw new InvalidCastException (
"Instance of JsonData doesn't hold a string");
return data.inst_string;
}
#endregion
#region ICollection Methods
void ICollection.CopyTo (Array array, int index)
{
EnsureCollection ().CopyTo (array, index);
}
#endregion
#region IDictionary Methods
void IDictionary.Add (object key, object value)
{
JsonData data = ToJsonData (value);
EnsureDictionary ().Add (key, data);
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> ((string) key, data);
object_list.Add (entry);
json = null;
}
void IDictionary.Clear ()
{
EnsureDictionary ().Clear ();
object_list.Clear ();
json = null;
}
bool IDictionary.Contains (object key)
{
return EnsureDictionary ().Contains (key);
}
IDictionaryEnumerator IDictionary.GetEnumerator ()
{
return ((IOrderedDictionary) this).GetEnumerator ();
}
void IDictionary.Remove (object key)
{
EnsureDictionary ().Remove (key);
for (int i = 0; i < object_list.Count; i++) {
if (object_list[i].Key == (string) key) {
object_list.RemoveAt (i);
break;
}
}
json = null;
}
#endregion
#region IEnumerable Methods
IEnumerator IEnumerable.GetEnumerator ()
{
return EnsureCollection ().GetEnumerator ();
}
#endregion
#region IJsonWrapper Methods
bool IJsonWrapper.GetBoolean ()
{
if (type != JsonType.Boolean)
throw new InvalidOperationException (
"JsonData instance doesn't hold a boolean");
return inst_boolean;
}
double IJsonWrapper.GetDouble ()
{
if (type != JsonType.Double)
throw new InvalidOperationException (
"JsonData instance doesn't hold a double");
return inst_double;
}
int IJsonWrapper.GetInt ()
{
if (type != JsonType.Int)
throw new InvalidOperationException (
"JsonData instance doesn't hold an int");
return inst_int;
}
long IJsonWrapper.GetLong ()
{
if (type != JsonType.Long)
throw new InvalidOperationException (
"JsonData instance doesn't hold a long");
return inst_long;
}
string IJsonWrapper.GetString ()
{
if (type != JsonType.String)
throw new InvalidOperationException (
"JsonData instance doesn't hold a string");
return inst_string;
}
void IJsonWrapper.SetBoolean (bool val)
{
type = JsonType.Boolean;
inst_boolean = val;
json = null;
}
void IJsonWrapper.SetDouble (double val)
{
type = JsonType.Double;
inst_double = val;
json = null;
}
void IJsonWrapper.SetInt (int val)
{
type = JsonType.Int;
inst_int = val;
json = null;
}
void IJsonWrapper.SetLong (long val)
{
type = JsonType.Long;
inst_long = val;
json = null;
}
void IJsonWrapper.SetString (string val)
{
type = JsonType.String;
inst_string = val;
json = null;
}
string IJsonWrapper.ToJson ()
{
return ToJson ();
}
void IJsonWrapper.ToJson (JsonWriter writer)
{
ToJson (writer);
}
#endregion
#region IList Methods
int IList.Add (object value)
{
return Add (value);
}
void IList.Clear ()
{
EnsureList ().Clear ();
json = null;
}
bool IList.Contains (object value)
{
return EnsureList ().Contains (value);
}
int IList.IndexOf (object value)
{
return EnsureList ().IndexOf (value);
}
void IList.Insert (int index, object value)
{
EnsureList ().Insert (index, value);
json = null;
}
void IList.Remove (object value)
{
EnsureList ().Remove (value);
json = null;
}
void IList.RemoveAt (int index)
{
EnsureList ().RemoveAt (index);
json = null;
}
#endregion
#region IOrderedDictionary Methods
IDictionaryEnumerator IOrderedDictionary.GetEnumerator ()
{
EnsureDictionary ();
return new OrderedDictionaryEnumerator (
object_list.GetEnumerator ());
}
void IOrderedDictionary.Insert (int idx, object key, object value)
{
string property = (string) key;
JsonData data = ToJsonData (value);
this[property] = data;
KeyValuePair<string, JsonData> entry =
new KeyValuePair<string, JsonData> (property, data);
object_list.Insert (idx, entry);
}
void IOrderedDictionary.RemoveAt (int idx)
{
EnsureDictionary ();
inst_object.Remove (object_list[idx].Key);
object_list.RemoveAt (idx);
}
#endregion
#region Private Methods
private ICollection EnsureCollection ()
{
if (type == JsonType.Array)
return (ICollection) inst_array;
if (type == JsonType.Object)
return (ICollection) inst_object;
throw new InvalidOperationException (
"The JsonData instance has to be initialized first");
}
private IDictionary EnsureDictionary ()
{
if (type == JsonType.Object)
return (IDictionary) inst_object;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a dictionary");
type = JsonType.Object;
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
return (IDictionary) inst_object;
}
private IList EnsureList ()
{
if (type == JsonType.Array)
return (IList) inst_array;
if (type != JsonType.None)
throw new InvalidOperationException (
"Instance of JsonData is not a list");
type = JsonType.Array;
inst_array = new List<JsonData> ();
return (IList) inst_array;
}
private JsonData ToJsonData (object obj)
{
if (obj == null)
return null;
if (obj is JsonData)
return (JsonData) obj;
return new JsonData (obj);
}
private static void WriteJson (IJsonWrapper obj, JsonWriter writer)
{
if (obj == null) {
writer.Write (null);
return;
}
if (obj.IsString) {
writer.Write (obj.GetString ());
return;
}
if (obj.IsBoolean) {
writer.Write (obj.GetBoolean ());
return;
}
if (obj.IsDouble) {
writer.Write (obj.GetDouble ());
return;
}
if (obj.IsInt) {
writer.Write (obj.GetInt ());
return;
}
if (obj.IsLong) {
writer.Write (obj.GetLong ());
return;
}
if (obj.IsArray) {
writer.WriteArrayStart ();
foreach (object elem in (IList) obj)
WriteJson ((JsonData) elem, writer);
writer.WriteArrayEnd ();
return;
}
if (obj.IsObject) {
writer.WriteObjectStart ();
foreach (DictionaryEntry entry in ((IDictionary) obj)) {
writer.WritePropertyName ((string) entry.Key);
WriteJson ((JsonData) entry.Value, writer);
}
writer.WriteObjectEnd ();
return;
}
}
#endregion
public int Add (object value)
{
JsonData data = ToJsonData (value);
json = null;
return EnsureList ().Add (data);
}
public void Clear ()
{
if (IsObject) {
((IDictionary) this).Clear ();
return;
}
if (IsArray) {
((IList) this).Clear ();
return;
}
}
public bool Equals (JsonData x)
{
if (x == null)
return false;
if (x.type != this.type)
return false;
switch (this.type) {
case JsonType.None:
return true;
case JsonType.Object:
return this.inst_object.Equals (x.inst_object);
case JsonType.Array:
return this.inst_array.Equals (x.inst_array);
case JsonType.String:
return this.inst_string.Equals (x.inst_string);
case JsonType.Int:
return this.inst_int.Equals (x.inst_int);
case JsonType.Long:
return this.inst_long.Equals (x.inst_long);
case JsonType.Double:
return this.inst_double.Equals (x.inst_double);
case JsonType.Boolean:
return this.inst_boolean.Equals (x.inst_boolean);
}
return false;
}
public JsonType GetJsonType ()
{
return type;
}
public void SetJsonType (JsonType type)
{
if (this.type == type)
return;
switch (type) {
case JsonType.None:
break;
case JsonType.Object:
inst_object = new Dictionary<string, JsonData> ();
object_list = new List<KeyValuePair<string, JsonData>> ();
break;
case JsonType.Array:
inst_array = new List<JsonData> ();
break;
case JsonType.String:
inst_string = default (String);
break;
case JsonType.Int:
inst_int = default (Int32);
break;
case JsonType.Long:
inst_long = default (Int64);
break;
case JsonType.Double:
inst_double = default (Double);
break;
case JsonType.Boolean:
inst_boolean = default (Boolean);
break;
}
this.type = type;
}
public string ToJson ()
{
if (json != null)
return json;
StringWriter sw = new StringWriter ();
JsonWriter writer = new JsonWriter (sw);
writer.Validate = false;
WriteJson (this, writer);
json = sw.ToString ();
return json;
}
public void ToJson (JsonWriter writer)
{
bool old_validate = writer.Validate;
writer.Validate = false;
WriteJson (this, writer);
writer.Validate = old_validate;
}
public override string ToString ()
{
switch (type) {
case JsonType.Array:
return "JsonData array";
case JsonType.Boolean:
return inst_boolean.ToString ();
case JsonType.Double:
return inst_double.ToString ();
case JsonType.Int:
return inst_int.ToString ();
case JsonType.Long:
return inst_long.ToString ();
case JsonType.Object:
return "JsonData object";
case JsonType.String:
return inst_string;
}
return "Uninitialized JsonData";
}
}
internal class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
IEnumerator<KeyValuePair<string, JsonData>> list_enumerator;
public object Current {
get { return Entry; }
}
public DictionaryEntry Entry {
get {
KeyValuePair<string, JsonData> curr = list_enumerator.Current;
return new DictionaryEntry (curr.Key, curr.Value);
}
}
public object Key {
get { return list_enumerator.Current.Key; }
}
public object Value {
get { return list_enumerator.Current.Value; }
}
public OrderedDictionaryEnumerator (
IEnumerator<KeyValuePair<string, JsonData>> enumerator)
{
list_enumerator = enumerator;
}
public bool MoveNext ()
{
return list_enumerator.MoveNext ();
}
public void Reset ()
{
list_enumerator.Reset ();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
using Http2;
using Http2.Hpack;
using static Http2Tests.TestHeaders;
namespace Http2Tests
{
public class ClientStreamTests
{
private ILoggerProvider loggerProvider;
public ClientStreamTests(ITestOutputHelper outHelper)
{
loggerProvider = new XUnitOutputLoggerProvider(outHelper);
}
public static class StreamCreator
{
public struct Result
{
public Encoder hEncoder;
public Connection conn;
public IStream stream;
}
public static async Task<Result> CreateConnectionAndStream(
StreamState state,
ILoggerProvider loggerProvider,
IBufferedPipe iPipe, IBufferedPipe oPipe,
Settings? localSettings = null,
Settings? remoteSettings = null,
HuffmanStrategy huffmanStrategy = HuffmanStrategy.Never)
{
if (state == StreamState.Idle)
{
throw new Exception("Not supported");
}
var hEncoder = new Encoder();
var conn = await ConnectionUtils.BuildEstablishedConnection(
false, iPipe, oPipe, loggerProvider, null,
localSettings: localSettings,
remoteSettings: remoteSettings,
huffmanStrategy: huffmanStrategy);
var endOfStream = false;
if (state == StreamState.HalfClosedLocal ||
state == StreamState.Closed)
endOfStream = true;
var stream = await conn.CreateStreamAsync(
DefaultGetHeaders, endOfStream: endOfStream);
await oPipe.ReadAndDiscardHeaders(1u, endOfStream);
if (state == StreamState.HalfClosedRemote ||
state == StreamState.Closed)
{
var outBuf = new byte[Settings.Default.MaxFrameSize];
var result = hEncoder.EncodeInto(
new ArraySegment<byte>(outBuf),
DefaultStatusHeaders);
await iPipe.WriteFrameHeaderWithTimeout(
new FrameHeader
{
Type = FrameType.Headers,
Flags = (byte)(HeadersFrameFlags.EndOfHeaders |
HeadersFrameFlags.EndOfStream),
StreamId = 1u,
Length = result.UsedBytes,
});
await iPipe.WriteAsync(new ArraySegment<byte>(outBuf, 0, result.UsedBytes));
var readHeadersTask = stream.ReadHeadersAsync();
var combined = await Task.WhenAny(readHeadersTask, Task.Delay(
ReadableStreamTestExtensions.ReadTimeout));
Assert.True(readHeadersTask == combined, "Expected to receive headers");
var headers = await readHeadersTask;
Assert.True(headers.SequenceEqual(DefaultStatusHeaders));
// Consume the data - which should be empty
var data = await stream.ReadAllToArrayWithTimeout();
Assert.Equal(0, data.Length);
}
else if (state == StreamState.Reset)
{
await iPipe.WriteResetStream(1u, ErrorCode.Cancel);
await Assert.ThrowsAsync<StreamResetException>(
() => stream.ReadHeadersAsync());
}
return new Result
{
hEncoder = hEncoder,
conn = conn,
stream = stream,
};
}
}
[Theory]
[InlineData(StreamState.Open)]
[InlineData(StreamState.HalfClosedLocal)]
[InlineData(StreamState.HalfClosedRemote)]
[InlineData(StreamState.Closed)]
[InlineData(StreamState.Reset)]
public async Task StreamCreatorShouldCreateStreamInCorrectState(
StreamState state)
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var res = await StreamCreator.CreateConnectionAndStream(
state, loggerProvider, inPipe, outPipe);
Assert.NotNull(res.stream);
Assert.Equal(state, res.stream.State);
}
[Fact]
public async Task CreatingStreamShouldEmitHeaders()
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var conn = await ConnectionUtils.BuildEstablishedConnection(
false, inPipe, outPipe, loggerProvider);
var stream1Task = conn.CreateStreamAsync(DefaultGetHeaders, false);
var stream1 = await stream1Task;
Assert.Equal(StreamState.Open, stream1.State);
Assert.Equal(1u, stream1.Id);
var fh = await outPipe.ReadFrameHeaderWithTimeout();
Assert.Equal(1u, fh.StreamId);
Assert.Equal(FrameType.Headers, fh.Type);
Assert.Equal((byte)HeadersFrameFlags.EndOfHeaders, fh.Flags);
Assert.Equal(EncodedDefaultGetHeaders.Length, fh.Length);
var hdrData = new byte[fh.Length];
await outPipe.ReadWithTimeout(new ArraySegment<byte>(hdrData));
Assert.Equal(EncodedDefaultGetHeaders, hdrData);
var stream3Task = conn.CreateStreamAsync(DefaultGetHeaders, true);
var stream3 = await stream3Task;
Assert.Equal(StreamState.HalfClosedLocal, stream3.State);
Assert.Equal(3u, stream3.Id);
fh = await outPipe.ReadFrameHeaderWithTimeout();
Assert.Equal(3u, fh.StreamId);
Assert.Equal(FrameType.Headers, fh.Type);
Assert.Equal(
(byte)(HeadersFrameFlags.EndOfHeaders | HeadersFrameFlags.EndOfStream),
fh.Flags);
Assert.Equal(EncodedIndexedDefaultGetHeaders.Length, fh.Length);
var hdrData3 = new byte[fh.Length];
await outPipe.ReadWithTimeout(new ArraySegment<byte>(hdrData3));
Assert.Equal(EncodedIndexedDefaultGetHeaders, hdrData3);
}
[Theory]
[InlineData(100)]
public async Task CreatedStreamsShouldAlwaysUseIncreasedStreamIds(
int nrStreams)
{
// This test checks if there are race conditions in the stream
// establish code
var inPipe = new BufferedPipe(10*1024);
var outPipe = new BufferedPipe(10*1024);
var conn = await ConnectionUtils.BuildEstablishedConnection(
false, inPipe, outPipe, loggerProvider);
var createStreamTasks = new Task<IStream>[nrStreams];
for (var i = 0; i < nrStreams; i++)
{
// Create the task in the threadpool
var t = Task.Run(
() => conn.CreateStreamAsync(DefaultGetHeaders, false));
createStreamTasks[i] = t;
}
// Wait until all streams are open
await Task.WhenAll(createStreamTasks);
var streams = createStreamTasks.Select(t => t.Result).ToList();
// Check output data
// Sequence IDs must be always increasing
var buffer = new byte[Settings.Default.MaxFrameSize];
for (var i = 0; i < nrStreams; i++)
{
var expectedId = 1u + 2*i;
var fh = await outPipe.ReadFrameHeaderWithTimeout();
Assert.Equal(expectedId, fh.StreamId);
Assert.Equal(FrameType.Headers, fh.Type);
Assert.Equal((byte)HeadersFrameFlags.EndOfHeaders, fh.Flags);
// Discard header data
await outPipe.ReadWithTimeout(
new ArraySegment<byte>(buffer, 0, fh.Length));
}
}
[Fact]
public async Task ReceivingDataBeforeHeadersShouldYieldAResetException()
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var res = await StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider,
inPipe, outPipe);
await inPipe.WriteData(1u, 1);
await outPipe.AssertResetStreamReception(1u, ErrorCode.ProtocolError);
var ex = await Assert.ThrowsAsync<AggregateException>(
() => res.stream.ReadWithTimeout(new ArraySegment<byte>(
new byte[1])));
Assert.IsType<StreamResetException>(ex.InnerException);
Assert.Equal(StreamState.Reset, res.stream.State);
}
[Fact]
public async Task ReceivingResetShouldYieldAResetException()
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var conn = await ConnectionUtils.BuildEstablishedConnection(
false, inPipe, outPipe, loggerProvider);
IStream stream = await conn.CreateStreamAsync(DefaultGetHeaders);
await outPipe.ReadAndDiscardHeaders(1u, false);
var readTask = stream.ReadWithTimeout(new ArraySegment<byte>(new byte[1]));
await inPipe.WriteResetStream(1u, ErrorCode.Cancel);
var ex = await Assert.ThrowsAsync<AggregateException>(
() => readTask);
Assert.IsType<StreamResetException>(ex.InnerException);
Assert.Equal(StreamState.Reset, stream.State);
}
[Fact]
public async Task CreatingStreamsOnServerConnectionShouldYieldException()
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var conn = await ConnectionUtils.BuildEstablishedConnection(
true, inPipe, outPipe, loggerProvider);
var ex = await Assert.ThrowsAsync<NotSupportedException>(
() => conn.CreateStreamAsync(DefaultGetHeaders));
Assert.Equal("Streams can only be created for clients", ex.Message);
}
[Fact]
public async Task ClientsShouldBeAbleToReceiveInformationalHeaders()
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var res = await StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider, inPipe, outPipe);
// Send and receive first set of informational headers
var readInfoHeaders1Task = res.stream.ReadHeadersAsync();
Assert.False(readInfoHeaders1Task.IsCompleted);
var infoHeaders1 = new HeaderField[]
{
new HeaderField { Name = ":status", Value = "100" },
new HeaderField { Name = "extension-field", Value = "bar" },
};
await inPipe.WriteHeaders(res.hEncoder, 1u, false, infoHeaders1);
var recvdInfoHeaders1 = await readInfoHeaders1Task;
Assert.True(infoHeaders1.SequenceEqual(recvdInfoHeaders1));
// Send and receive second set of informational headers
var readInfoHeaders2Task = res.stream.ReadHeadersAsync();
Assert.False(readInfoHeaders2Task.IsCompleted);
var infoHeaders2 = new HeaderField[]
{
new HeaderField { Name = ":status", Value = "108" },
new HeaderField { Name = "extension-field-b", Value = "bar2" },
};
await inPipe.WriteHeaders(res.hEncoder, 1u, false, infoHeaders2);
var recvdInfoHeaders2 = await readInfoHeaders2Task;
Assert.True(infoHeaders2.SequenceEqual(recvdInfoHeaders2));
// Send and receive final headers
var recvHeadersTask = res.stream.ReadHeadersAsync();
Assert.False(recvHeadersTask.IsCompleted);
await inPipe.WriteHeaders(res.hEncoder, 1u, true, DefaultStatusHeaders);
var recvdHeaders = await recvHeadersTask;
Assert.True(DefaultStatusHeaders.SequenceEqual(recvdHeaders));
}
[Fact]
public async Task ReceivingAnInformationalHeaderAfterANormalHeaderShouldBeAnError()
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var res = await StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider, inPipe, outPipe);
await inPipe.WriteHeaders(res.hEncoder, 1u, false, DefaultStatusHeaders);
// Expect to receive the status headers
var recvdHeaders = await res.stream.ReadHeadersAsync();
Assert.True(DefaultStatusHeaders.SequenceEqual(recvdHeaders));
// Send informational headers to the client
var infoHeaders = new HeaderField[]
{
new HeaderField { Name = ":status", Value = "100" },
new HeaderField { Name = "extension-field", Value = "bar" },
};
await inPipe.WriteHeaders(res.hEncoder, 1u, false, infoHeaders);
// Expect to receive an error
await outPipe.AssertResetStreamReception(1u, ErrorCode.ProtocolError);
Assert.Equal(StreamState.Reset, res.stream.State);
await Assert.ThrowsAsync<StreamResetException>(
() => res.stream.ReadHeadersAsync());
}
[Fact]
public async Task ReceivingDataDirectlyAfterInformationalHeadersShouldBeAnError()
{
var inPipe = new BufferedPipe(1024);
var outPipe = new BufferedPipe(1024);
var res = await StreamCreator.CreateConnectionAndStream(
StreamState.Open, loggerProvider, inPipe, outPipe);
// Send informational headers to the client
var infoHeaders = new HeaderField[]
{
new HeaderField { Name = ":status", Value = "100" },
new HeaderField { Name = "extension-field", Value = "bar" },
};
await inPipe.WriteHeaders(res.hEncoder, 1u, false, infoHeaders);
var recvdHeaders = await res.stream.ReadHeadersAsync();
Assert.True(infoHeaders.SequenceEqual(recvdHeaders));
// Try to send data
await inPipe.WriteData(1u, 100, null, true);
// Expect to receive an error
await outPipe.AssertResetStreamReception(1u, ErrorCode.ProtocolError);
Assert.Equal(StreamState.Reset, res.stream.State);
await Assert.ThrowsAsync<StreamResetException>(
() => res.stream.ReadHeadersAsync());
}
}
}
| |
// 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.Drawing
{
internal static class KnownColorTable
{
private static int[] s_colorTable;
private static string[] s_colorNameTable;
private static void EnsureColorTable()
{
// no need to lock... worse case is a double create of the table...
//
if (s_colorTable == null)
{
InitColorTable();
}
}
private static void InitColorTable()
{
int[] values = new int[KnownColor.LastColor - KnownColor.FirstColor + 1];
// just consts...
//
values[(int)KnownColor.Transparent] = 0x00FFFFFF;
values[(int)KnownColor.AliceBlue] = unchecked((int)0xFFF0F8FF);
values[(int)KnownColor.AntiqueWhite] = unchecked((int)0xFFFAEBD7);
values[(int)KnownColor.Aqua] = unchecked((int)0xFF00FFFF);
values[(int)KnownColor.Aquamarine] = unchecked((int)0xFF7FFFD4);
values[(int)KnownColor.Azure] = unchecked((int)0xFFF0FFFF);
values[(int)KnownColor.Beige] = unchecked((int)0xFFF5F5DC);
values[(int)KnownColor.Bisque] = unchecked((int)0xFFFFE4C4);
values[(int)KnownColor.Black] = unchecked((int)0xFF000000);
values[(int)KnownColor.BlanchedAlmond] = unchecked((int)0xFFFFEBCD);
values[(int)KnownColor.Blue] = unchecked((int)0xFF0000FF);
values[(int)KnownColor.BlueViolet] = unchecked((int)0xFF8A2BE2);
values[(int)KnownColor.Brown] = unchecked((int)0xFFA52A2A);
values[(int)KnownColor.BurlyWood] = unchecked((int)0xFFDEB887);
values[(int)KnownColor.CadetBlue] = unchecked((int)0xFF5F9EA0);
values[(int)KnownColor.Chartreuse] = unchecked((int)0xFF7FFF00);
values[(int)KnownColor.Chocolate] = unchecked((int)0xFFD2691E);
values[(int)KnownColor.Coral] = unchecked((int)0xFFFF7F50);
values[(int)KnownColor.CornflowerBlue] = unchecked((int)0xFF6495ED);
values[(int)KnownColor.Cornsilk] = unchecked((int)0xFFFFF8DC);
values[(int)KnownColor.Crimson] = unchecked((int)0xFFDC143C);
values[(int)KnownColor.Cyan] = unchecked((int)0xFF00FFFF);
values[(int)KnownColor.DarkBlue] = unchecked((int)0xFF00008B);
values[(int)KnownColor.DarkCyan] = unchecked((int)0xFF008B8B);
values[(int)KnownColor.DarkGoldenrod] = unchecked((int)0xFFB8860B);
values[(int)KnownColor.DarkGray] = unchecked((int)0xFFA9A9A9);
values[(int)KnownColor.DarkGreen] = unchecked((int)0xFF006400);
values[(int)KnownColor.DarkKhaki] = unchecked((int)0xFFBDB76B);
values[(int)KnownColor.DarkMagenta] = unchecked((int)0xFF8B008B);
values[(int)KnownColor.DarkOliveGreen] = unchecked((int)0xFF556B2F);
values[(int)KnownColor.DarkOrange] = unchecked((int)0xFFFF8C00);
values[(int)KnownColor.DarkOrchid] = unchecked((int)0xFF9932CC);
values[(int)KnownColor.DarkRed] = unchecked((int)0xFF8B0000);
values[(int)KnownColor.DarkSalmon] = unchecked((int)0xFFE9967A);
values[(int)KnownColor.DarkSeaGreen] = unchecked((int)0xFF8FBC8B);
values[(int)KnownColor.DarkSlateBlue] = unchecked((int)0xFF483D8B);
values[(int)KnownColor.DarkSlateGray] = unchecked((int)0xFF2F4F4F);
values[(int)KnownColor.DarkTurquoise] = unchecked((int)0xFF00CED1);
values[(int)KnownColor.DarkViolet] = unchecked((int)0xFF9400D3);
values[(int)KnownColor.DeepPink] = unchecked((int)0xFFFF1493);
values[(int)KnownColor.DeepSkyBlue] = unchecked((int)0xFF00BFFF);
values[(int)KnownColor.DimGray] = unchecked((int)0xFF696969);
values[(int)KnownColor.DodgerBlue] = unchecked((int)0xFF1E90FF);
values[(int)KnownColor.Firebrick] = unchecked((int)0xFFB22222);
values[(int)KnownColor.FloralWhite] = unchecked((int)0xFFFFFAF0);
values[(int)KnownColor.ForestGreen] = unchecked((int)0xFF228B22);
values[(int)KnownColor.Fuchsia] = unchecked((int)0xFFFF00FF);
values[(int)KnownColor.Gainsboro] = unchecked((int)0xFFDCDCDC);
values[(int)KnownColor.GhostWhite] = unchecked((int)0xFFF8F8FF);
values[(int)KnownColor.Gold] = unchecked((int)0xFFFFD700);
values[(int)KnownColor.Goldenrod] = unchecked((int)0xFFDAA520);
values[(int)KnownColor.Gray] = unchecked((int)0xFF808080);
values[(int)KnownColor.Green] = unchecked((int)0xFF008000);
values[(int)KnownColor.GreenYellow] = unchecked((int)0xFFADFF2F);
values[(int)KnownColor.Honeydew] = unchecked((int)0xFFF0FFF0);
values[(int)KnownColor.HotPink] = unchecked((int)0xFFFF69B4);
values[(int)KnownColor.IndianRed] = unchecked((int)0xFFCD5C5C);
values[(int)KnownColor.Indigo] = unchecked((int)0xFF4B0082);
values[(int)KnownColor.Ivory] = unchecked((int)0xFFFFFFF0);
values[(int)KnownColor.Khaki] = unchecked((int)0xFFF0E68C);
values[(int)KnownColor.Lavender] = unchecked((int)0xFFE6E6FA);
values[(int)KnownColor.LavenderBlush] = unchecked((int)0xFFFFF0F5);
values[(int)KnownColor.LawnGreen] = unchecked((int)0xFF7CFC00);
values[(int)KnownColor.LemonChiffon] = unchecked((int)0xFFFFFACD);
values[(int)KnownColor.LightBlue] = unchecked((int)0xFFADD8E6);
values[(int)KnownColor.LightCoral] = unchecked((int)0xFFF08080);
values[(int)KnownColor.LightCyan] = unchecked((int)0xFFE0FFFF);
values[(int)KnownColor.LightGoldenrodYellow] = unchecked((int)0xFFFAFAD2);
values[(int)KnownColor.LightGray] = unchecked((int)0xFFD3D3D3);
values[(int)KnownColor.LightGreen] = unchecked((int)0xFF90EE90);
values[(int)KnownColor.LightPink] = unchecked((int)0xFFFFB6C1);
values[(int)KnownColor.LightSalmon] = unchecked((int)0xFFFFA07A);
values[(int)KnownColor.LightSeaGreen] = unchecked((int)0xFF20B2AA);
values[(int)KnownColor.LightSkyBlue] = unchecked((int)0xFF87CEFA);
values[(int)KnownColor.LightSlateGray] = unchecked((int)0xFF778899);
values[(int)KnownColor.LightSteelBlue] = unchecked((int)0xFFB0C4DE);
values[(int)KnownColor.LightYellow] = unchecked((int)0xFFFFFFE0);
values[(int)KnownColor.Lime] = unchecked((int)0xFF00FF00);
values[(int)KnownColor.LimeGreen] = unchecked((int)0xFF32CD32);
values[(int)KnownColor.Linen] = unchecked((int)0xFFFAF0E6);
values[(int)KnownColor.Magenta] = unchecked((int)0xFFFF00FF);
values[(int)KnownColor.Maroon] = unchecked((int)0xFF800000);
values[(int)KnownColor.MediumAquamarine] = unchecked((int)0xFF66CDAA);
values[(int)KnownColor.MediumBlue] = unchecked((int)0xFF0000CD);
values[(int)KnownColor.MediumOrchid] = unchecked((int)0xFFBA55D3);
values[(int)KnownColor.MediumPurple] = unchecked((int)0xFF9370DB);
values[(int)KnownColor.MediumSeaGreen] = unchecked((int)0xFF3CB371);
values[(int)KnownColor.MediumSlateBlue] = unchecked((int)0xFF7B68EE);
values[(int)KnownColor.MediumSpringGreen] = unchecked((int)0xFF00FA9A);
values[(int)KnownColor.MediumTurquoise] = unchecked((int)0xFF48D1CC);
values[(int)KnownColor.MediumVioletRed] = unchecked((int)0xFFC71585);
values[(int)KnownColor.MidnightBlue] = unchecked((int)0xFF191970);
values[(int)KnownColor.MintCream] = unchecked((int)0xFFF5FFFA);
values[(int)KnownColor.MistyRose] = unchecked((int)0xFFFFE4E1);
values[(int)KnownColor.Moccasin] = unchecked((int)0xFFFFE4B5);
values[(int)KnownColor.NavajoWhite] = unchecked((int)0xFFFFDEAD);
values[(int)KnownColor.Navy] = unchecked((int)0xFF000080);
values[(int)KnownColor.OldLace] = unchecked((int)0xFFFDF5E6);
values[(int)KnownColor.Olive] = unchecked((int)0xFF808000);
values[(int)KnownColor.OliveDrab] = unchecked((int)0xFF6B8E23);
values[(int)KnownColor.Orange] = unchecked((int)0xFFFFA500);
values[(int)KnownColor.OrangeRed] = unchecked((int)0xFFFF4500);
values[(int)KnownColor.Orchid] = unchecked((int)0xFFDA70D6);
values[(int)KnownColor.PaleGoldenrod] = unchecked((int)0xFFEEE8AA);
values[(int)KnownColor.PaleGreen] = unchecked((int)0xFF98FB98);
values[(int)KnownColor.PaleTurquoise] = unchecked((int)0xFFAFEEEE);
values[(int)KnownColor.PaleVioletRed] = unchecked((int)0xFFDB7093);
values[(int)KnownColor.PapayaWhip] = unchecked((int)0xFFFFEFD5);
values[(int)KnownColor.PeachPuff] = unchecked((int)0xFFFFDAB9);
values[(int)KnownColor.Peru] = unchecked((int)0xFFCD853F);
values[(int)KnownColor.Pink] = unchecked((int)0xFFFFC0CB);
values[(int)KnownColor.Plum] = unchecked((int)0xFFDDA0DD);
values[(int)KnownColor.PowderBlue] = unchecked((int)0xFFB0E0E6);
values[(int)KnownColor.Purple] = unchecked((int)0xFF800080);
values[(int)KnownColor.Red] = unchecked((int)0xFFFF0000);
values[(int)KnownColor.RosyBrown] = unchecked((int)0xFFBC8F8F);
values[(int)KnownColor.RoyalBlue] = unchecked((int)0xFF4169E1);
values[(int)KnownColor.SaddleBrown] = unchecked((int)0xFF8B4513);
values[(int)KnownColor.Salmon] = unchecked((int)0xFFFA8072);
values[(int)KnownColor.SandyBrown] = unchecked((int)0xFFF4A460);
values[(int)KnownColor.SeaGreen] = unchecked((int)0xFF2E8B57);
values[(int)KnownColor.SeaShell] = unchecked((int)0xFFFFF5EE);
values[(int)KnownColor.Sienna] = unchecked((int)0xFFA0522D);
values[(int)KnownColor.Silver] = unchecked((int)0xFFC0C0C0);
values[(int)KnownColor.SkyBlue] = unchecked((int)0xFF87CEEB);
values[(int)KnownColor.SlateBlue] = unchecked((int)0xFF6A5ACD);
values[(int)KnownColor.SlateGray] = unchecked((int)0xFF708090);
values[(int)KnownColor.Snow] = unchecked((int)0xFFFFFAFA);
values[(int)KnownColor.SpringGreen] = unchecked((int)0xFF00FF7F);
values[(int)KnownColor.SteelBlue] = unchecked((int)0xFF4682B4);
values[(int)KnownColor.Tan] = unchecked((int)0xFFD2B48C);
values[(int)KnownColor.Teal] = unchecked((int)0xFF008080);
values[(int)KnownColor.Thistle] = unchecked((int)0xFFD8BFD8);
values[(int)KnownColor.Tomato] = unchecked((int)0xFFFF6347);
values[(int)KnownColor.Turquoise] = unchecked((int)0xFF40E0D0);
values[(int)KnownColor.Violet] = unchecked((int)0xFFEE82EE);
values[(int)KnownColor.Wheat] = unchecked((int)0xFFF5DEB3);
values[(int)KnownColor.White] = unchecked((int)0xFFFFFFFF);
values[(int)KnownColor.WhiteSmoke] = unchecked((int)0xFFF5F5F5);
values[(int)KnownColor.Yellow] = unchecked((int)0xFFFFFF00);
values[(int)KnownColor.YellowGreen] = unchecked((int)0xFF9ACD32);
s_colorTable = values;
}
private static void EnsureColorNameTable()
{
// no need to lock... worse case is a double create of the table...
//
if (s_colorNameTable == null)
{
InitColorNameTable();
}
}
private static void InitColorNameTable()
{
string[] values = new string[KnownColor.LastColor - KnownColor.FirstColor + 1];
// just consts...
//
values[(int)KnownColor.Transparent] = "Transparent";
values[(int)KnownColor.AliceBlue] = "AliceBlue";
values[(int)KnownColor.AntiqueWhite] = "AntiqueWhite";
values[(int)KnownColor.Aqua] = "Aqua";
values[(int)KnownColor.Aquamarine] = "Aquamarine";
values[(int)KnownColor.Azure] = "Azure";
values[(int)KnownColor.Beige] = "Beige";
values[(int)KnownColor.Bisque] = "Bisque";
values[(int)KnownColor.Black] = "Black";
values[(int)KnownColor.BlanchedAlmond] = "BlanchedAlmond";
values[(int)KnownColor.Blue] = "Blue";
values[(int)KnownColor.BlueViolet] = "BlueViolet";
values[(int)KnownColor.Brown] = "Brown";
values[(int)KnownColor.BurlyWood] = "BurlyWood";
values[(int)KnownColor.CadetBlue] = "CadetBlue";
values[(int)KnownColor.Chartreuse] = "Chartreuse";
values[(int)KnownColor.Chocolate] = "Chocolate";
values[(int)KnownColor.Coral] = "Coral";
values[(int)KnownColor.CornflowerBlue] = "CornflowerBlue";
values[(int)KnownColor.Cornsilk] = "Cornsilk";
values[(int)KnownColor.Crimson] = "Crimson";
values[(int)KnownColor.Cyan] = "Cyan";
values[(int)KnownColor.DarkBlue] = "DarkBlue";
values[(int)KnownColor.DarkCyan] = "DarkCyan";
values[(int)KnownColor.DarkGoldenrod] = "DarkGoldenrod";
values[(int)KnownColor.DarkGray] = "DarkGray";
values[(int)KnownColor.DarkGreen] = "DarkGreen";
values[(int)KnownColor.DarkKhaki] = "DarkKhaki";
values[(int)KnownColor.DarkMagenta] = "DarkMagenta";
values[(int)KnownColor.DarkOliveGreen] = "DarkOliveGreen";
values[(int)KnownColor.DarkOrange] = "DarkOrange";
values[(int)KnownColor.DarkOrchid] = "DarkOrchid";
values[(int)KnownColor.DarkRed] = "DarkRed";
values[(int)KnownColor.DarkSalmon] = "DarkSalmon";
values[(int)KnownColor.DarkSeaGreen] = "DarkSeaGreen";
values[(int)KnownColor.DarkSlateBlue] = "DarkSlateBlue";
values[(int)KnownColor.DarkSlateGray] = "DarkSlateGray";
values[(int)KnownColor.DarkTurquoise] = "DarkTurquoise";
values[(int)KnownColor.DarkViolet] = "DarkViolet";
values[(int)KnownColor.DeepPink] = "DeepPink";
values[(int)KnownColor.DeepSkyBlue] = "DeepSkyBlue";
values[(int)KnownColor.DimGray] = "DimGray";
values[(int)KnownColor.DodgerBlue] = "DodgerBlue";
values[(int)KnownColor.Firebrick] = "Firebrick";
values[(int)KnownColor.FloralWhite] = "FloralWhite";
values[(int)KnownColor.ForestGreen] = "ForestGreen";
values[(int)KnownColor.Fuchsia] = "Fuchsia";
values[(int)KnownColor.Gainsboro] = "Gainsboro";
values[(int)KnownColor.GhostWhite] = "GhostWhite";
values[(int)KnownColor.Gold] = "Gold";
values[(int)KnownColor.Goldenrod] = "Goldenrod";
values[(int)KnownColor.Gray] = "Gray";
values[(int)KnownColor.Green] = "Green";
values[(int)KnownColor.GreenYellow] = "GreenYellow";
values[(int)KnownColor.Honeydew] = "Honeydew";
values[(int)KnownColor.HotPink] = "HotPink";
values[(int)KnownColor.IndianRed] = "IndianRed";
values[(int)KnownColor.Indigo] = "Indigo";
values[(int)KnownColor.Ivory] = "Ivory";
values[(int)KnownColor.Khaki] = "Khaki";
values[(int)KnownColor.Lavender] = "Lavender";
values[(int)KnownColor.LavenderBlush] = "LavenderBlush";
values[(int)KnownColor.LawnGreen] = "LawnGreen";
values[(int)KnownColor.LemonChiffon] = "LemonChiffon";
values[(int)KnownColor.LightBlue] = "LightBlue";
values[(int)KnownColor.LightCoral] = "LightCoral";
values[(int)KnownColor.LightCyan] = "LightCyan";
values[(int)KnownColor.LightGoldenrodYellow] = "LightGoldenrodYellow";
values[(int)KnownColor.LightGray] = "LightGray";
values[(int)KnownColor.LightGreen] = "LightGreen";
values[(int)KnownColor.LightPink] = "LightPink";
values[(int)KnownColor.LightSalmon] = "LightSalmon";
values[(int)KnownColor.LightSeaGreen] = "LightSeaGreen";
values[(int)KnownColor.LightSkyBlue] = "LightSkyBlue";
values[(int)KnownColor.LightSlateGray] = "LightSlateGray";
values[(int)KnownColor.LightSteelBlue] = "LightSteelBlue";
values[(int)KnownColor.LightYellow] = "LightYellow";
values[(int)KnownColor.Lime] = "Lime";
values[(int)KnownColor.LimeGreen] = "LimeGreen";
values[(int)KnownColor.Linen] = "Linen";
values[(int)KnownColor.Magenta] = "Magenta";
values[(int)KnownColor.Maroon] = "Maroon";
values[(int)KnownColor.MediumAquamarine] = "MediumAquamarine";
values[(int)KnownColor.MediumBlue] = "MediumBlue";
values[(int)KnownColor.MediumOrchid] = "MediumOrchid";
values[(int)KnownColor.MediumPurple] = "MediumPurple";
values[(int)KnownColor.MediumSeaGreen] = "MediumSeaGreen";
values[(int)KnownColor.MediumSlateBlue] = "MediumSlateBlue";
values[(int)KnownColor.MediumSpringGreen] = "MediumSpringGreen";
values[(int)KnownColor.MediumTurquoise] = "MediumTurquoise";
values[(int)KnownColor.MediumVioletRed] = "MediumVioletRed";
values[(int)KnownColor.MidnightBlue] = "MidnightBlue";
values[(int)KnownColor.MintCream] = "MintCream";
values[(int)KnownColor.MistyRose] = "MistyRose";
values[(int)KnownColor.Moccasin] = "Moccasin";
values[(int)KnownColor.NavajoWhite] = "NavajoWhite";
values[(int)KnownColor.Navy] = "Navy";
values[(int)KnownColor.OldLace] = "OldLace";
values[(int)KnownColor.Olive] = "Olive";
values[(int)KnownColor.OliveDrab] = "OliveDrab";
values[(int)KnownColor.Orange] = "Orange";
values[(int)KnownColor.OrangeRed] = "OrangeRed";
values[(int)KnownColor.Orchid] = "Orchid";
values[(int)KnownColor.PaleGoldenrod] = "PaleGoldenrod";
values[(int)KnownColor.PaleGreen] = "PaleGreen";
values[(int)KnownColor.PaleTurquoise] = "PaleTurquoise";
values[(int)KnownColor.PaleVioletRed] = "PaleVioletRed";
values[(int)KnownColor.PapayaWhip] = "PapayaWhip";
values[(int)KnownColor.PeachPuff] = "PeachPuff";
values[(int)KnownColor.Peru] = "Peru";
values[(int)KnownColor.Pink] = "Pink";
values[(int)KnownColor.Plum] = "Plum";
values[(int)KnownColor.PowderBlue] = "PowderBlue";
values[(int)KnownColor.Purple] = "Purple";
values[(int)KnownColor.Red] = "Red";
values[(int)KnownColor.RosyBrown] = "RosyBrown";
values[(int)KnownColor.RoyalBlue] = "RoyalBlue";
values[(int)KnownColor.SaddleBrown] = "SaddleBrown";
values[(int)KnownColor.Salmon] = "Salmon";
values[(int)KnownColor.SandyBrown] = "SandyBrown";
values[(int)KnownColor.SeaGreen] = "SeaGreen";
values[(int)KnownColor.SeaShell] = "SeaShell";
values[(int)KnownColor.Sienna] = "Sienna";
values[(int)KnownColor.Silver] = "Silver";
values[(int)KnownColor.SkyBlue] = "SkyBlue";
values[(int)KnownColor.SlateBlue] = "SlateBlue";
values[(int)KnownColor.SlateGray] = "SlateGray";
values[(int)KnownColor.Snow] = "Snow";
values[(int)KnownColor.SpringGreen] = "SpringGreen";
values[(int)KnownColor.SteelBlue] = "SteelBlue";
values[(int)KnownColor.Tan] = "Tan";
values[(int)KnownColor.Teal] = "Teal";
values[(int)KnownColor.Thistle] = "Thistle";
values[(int)KnownColor.Tomato] = "Tomato";
values[(int)KnownColor.Turquoise] = "Turquoise";
values[(int)KnownColor.Violet] = "Violet";
values[(int)KnownColor.Wheat] = "Wheat";
values[(int)KnownColor.White] = "White";
values[(int)KnownColor.WhiteSmoke] = "WhiteSmoke";
values[(int)KnownColor.Yellow] = "Yellow";
values[(int)KnownColor.YellowGreen] = "YellowGreen";
s_colorNameTable = values;
}
public static int KnownColorToArgb(KnownColor color)
{
EnsureColorTable();
if (color >= KnownColor.FirstColor && color <= KnownColor.LastColor)
{
return s_colorTable[(int)color];
}
else
{
return 0;
}
}
public static string KnownColorToName(KnownColor color)
{
EnsureColorNameTable();
if (color >= KnownColor.FirstColor && color <= KnownColor.LastColor)
{
return s_colorNameTable[(int)color];
}
else
{
return null;
}
}
}
}
| |
// Generated from https://github.com/nuke-build/nuke/blob/master/source/Nuke.Common/Tools/MauiCheck/MauiCheck.json
using JetBrains.Annotations;
using Newtonsoft.Json;
using Nuke.Common;
using Nuke.Common.Execution;
using Nuke.Common.Tooling;
using Nuke.Common.Tools;
using Nuke.Common.Utilities.Collections;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
namespace Nuke.Common.Tools.MauiCheck
{
/// <summary>
/// <p>A dotnet tool for helping set up your .NET MAUI environment.</p>
/// <p>For more details, visit the <a href="https://github.com/Redth/dotnet-maui-check">official website</a>.</p>
/// </summary>
[PublicAPI]
[ExcludeFromCodeCoverage]
public static partial class MauiCheckTasks
{
/// <summary>
/// Path to the MauiCheck executable.
/// </summary>
public static string MauiCheckPath =>
ToolPathResolver.TryGetEnvironmentExecutable("MAUICHECK_EXE") ??
ToolPathResolver.GetPackageExecutable("Redth.Net.Maui.Check", "MauiCheck.dll");
public static Action<OutputType, string> MauiCheckLogger { get; set; } = ProcessTasks.DefaultLogger;
/// <summary>
/// <p>A dotnet tool for helping set up your .NET MAUI environment.</p>
/// <p>For more details, visit the <a href="https://github.com/Redth/dotnet-maui-check">official website</a>.</p>
/// </summary>
public static IReadOnlyCollection<Output> MauiCheck(string arguments, string workingDirectory = null, IReadOnlyDictionary<string, string> environmentVariables = null, int? timeout = null, bool? logOutput = null, bool? logInvocation = null, Func<string, string> outputFilter = null)
{
using var process = ProcessTasks.StartProcess(MauiCheckPath, arguments, workingDirectory, environmentVariables, timeout, logOutput, logInvocation, MauiCheckLogger, outputFilter);
process.AssertZeroExitCode();
return process.Output;
}
/// <summary>
/// <p>A dotnet tool for helping set up your .NET MAUI environment.</p>
/// <p>For more details, visit the <a href="https://github.com/Redth/dotnet-maui-check">official website</a>.</p>
/// </summary>
/// <remarks>
/// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p>
/// <ul>
/// <li><c>--ci</c> via <see cref="MauiCheckSettings.Ci"/></li>
/// <li><c>--fix</c> via <see cref="MauiCheckSettings.Fix"/></li>
/// <li><c>--manifest</c> via <see cref="MauiCheckSettings.Manifest"/></li>
/// <li><c>--non-interactive</c> via <see cref="MauiCheckSettings.NonInteractive"/></li>
/// <li><c>--preview</c> via <see cref="MauiCheckSettings.Preview"/></li>
/// <li><c>--skip</c> via <see cref="MauiCheckSettings.Skip"/></li>
/// </ul>
/// </remarks>
public static IReadOnlyCollection<Output> MauiCheck(MauiCheckSettings toolSettings = null)
{
toolSettings = toolSettings ?? new MauiCheckSettings();
using var process = ProcessTasks.StartProcess(toolSettings);
process.AssertZeroExitCode();
return process.Output;
}
/// <summary>
/// <p>A dotnet tool for helping set up your .NET MAUI environment.</p>
/// <p>For more details, visit the <a href="https://github.com/Redth/dotnet-maui-check">official website</a>.</p>
/// </summary>
/// <remarks>
/// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p>
/// <ul>
/// <li><c>--ci</c> via <see cref="MauiCheckSettings.Ci"/></li>
/// <li><c>--fix</c> via <see cref="MauiCheckSettings.Fix"/></li>
/// <li><c>--manifest</c> via <see cref="MauiCheckSettings.Manifest"/></li>
/// <li><c>--non-interactive</c> via <see cref="MauiCheckSettings.NonInteractive"/></li>
/// <li><c>--preview</c> via <see cref="MauiCheckSettings.Preview"/></li>
/// <li><c>--skip</c> via <see cref="MauiCheckSettings.Skip"/></li>
/// </ul>
/// </remarks>
public static IReadOnlyCollection<Output> MauiCheck(Configure<MauiCheckSettings> configurator)
{
return MauiCheck(configurator(new MauiCheckSettings()));
}
/// <summary>
/// <p>A dotnet tool for helping set up your .NET MAUI environment.</p>
/// <p>For more details, visit the <a href="https://github.com/Redth/dotnet-maui-check">official website</a>.</p>
/// </summary>
/// <remarks>
/// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p>
/// <ul>
/// <li><c>--ci</c> via <see cref="MauiCheckSettings.Ci"/></li>
/// <li><c>--fix</c> via <see cref="MauiCheckSettings.Fix"/></li>
/// <li><c>--manifest</c> via <see cref="MauiCheckSettings.Manifest"/></li>
/// <li><c>--non-interactive</c> via <see cref="MauiCheckSettings.NonInteractive"/></li>
/// <li><c>--preview</c> via <see cref="MauiCheckSettings.Preview"/></li>
/// <li><c>--skip</c> via <see cref="MauiCheckSettings.Skip"/></li>
/// </ul>
/// </remarks>
public static IEnumerable<(MauiCheckSettings Settings, IReadOnlyCollection<Output> Output)> MauiCheck(CombinatorialConfigure<MauiCheckSettings> configurator, int degreeOfParallelism = 1, bool completeOnFailure = false)
{
return configurator.Invoke(MauiCheck, MauiCheckLogger, degreeOfParallelism, completeOnFailure);
}
/// <summary>
/// <p>A dotnet tool for helping set up your .NET MAUI environment.</p>
/// <p>For more details, visit the <a href="https://github.com/Redth/dotnet-maui-check">official website</a>.</p>
/// </summary>
/// <remarks>
/// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p>
/// <ul>
/// <li><c>--dotnet-pre</c> via <see cref="MauiCheckConfigSettings.DotNetPrerelease"/></li>
/// <li><c>--dotnet-rollForward</c> via <see cref="MauiCheckConfigSettings.DotNetRollForward"/></li>
/// <li><c>--dotnet-version</c> via <see cref="MauiCheckConfigSettings.DotNetVersion"/></li>
/// <li><c>--nuget-sources</c> via <see cref="MauiCheckConfigSettings.NuGetSources"/></li>
/// </ul>
/// </remarks>
public static IReadOnlyCollection<Output> MauiCheckConfig(MauiCheckConfigSettings toolSettings = null)
{
toolSettings = toolSettings ?? new MauiCheckConfigSettings();
using var process = ProcessTasks.StartProcess(toolSettings);
process.AssertZeroExitCode();
return process.Output;
}
/// <summary>
/// <p>A dotnet tool for helping set up your .NET MAUI environment.</p>
/// <p>For more details, visit the <a href="https://github.com/Redth/dotnet-maui-check">official website</a>.</p>
/// </summary>
/// <remarks>
/// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p>
/// <ul>
/// <li><c>--dotnet-pre</c> via <see cref="MauiCheckConfigSettings.DotNetPrerelease"/></li>
/// <li><c>--dotnet-rollForward</c> via <see cref="MauiCheckConfigSettings.DotNetRollForward"/></li>
/// <li><c>--dotnet-version</c> via <see cref="MauiCheckConfigSettings.DotNetVersion"/></li>
/// <li><c>--nuget-sources</c> via <see cref="MauiCheckConfigSettings.NuGetSources"/></li>
/// </ul>
/// </remarks>
public static IReadOnlyCollection<Output> MauiCheckConfig(Configure<MauiCheckConfigSettings> configurator)
{
return MauiCheckConfig(configurator(new MauiCheckConfigSettings()));
}
/// <summary>
/// <p>A dotnet tool for helping set up your .NET MAUI environment.</p>
/// <p>For more details, visit the <a href="https://github.com/Redth/dotnet-maui-check">official website</a>.</p>
/// </summary>
/// <remarks>
/// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p>
/// <ul>
/// <li><c>--dotnet-pre</c> via <see cref="MauiCheckConfigSettings.DotNetPrerelease"/></li>
/// <li><c>--dotnet-rollForward</c> via <see cref="MauiCheckConfigSettings.DotNetRollForward"/></li>
/// <li><c>--dotnet-version</c> via <see cref="MauiCheckConfigSettings.DotNetVersion"/></li>
/// <li><c>--nuget-sources</c> via <see cref="MauiCheckConfigSettings.NuGetSources"/></li>
/// </ul>
/// </remarks>
public static IEnumerable<(MauiCheckConfigSettings Settings, IReadOnlyCollection<Output> Output)> MauiCheckConfig(CombinatorialConfigure<MauiCheckConfigSettings> configurator, int degreeOfParallelism = 1, bool completeOnFailure = false)
{
return configurator.Invoke(MauiCheckConfig, MauiCheckLogger, degreeOfParallelism, completeOnFailure);
}
}
#region MauiCheckSettings
/// <summary>
/// Used within <see cref="MauiCheckTasks"/>.
/// </summary>
[PublicAPI]
[ExcludeFromCodeCoverage]
[Serializable]
public partial class MauiCheckSettings : ToolSettings
{
/// <summary>
/// Path to the MauiCheck executable.
/// </summary>
public override string ProcessToolPath => base.ProcessToolPath ?? MauiCheckTasks.MauiCheckPath;
public override Action<OutputType, string> ProcessCustomLogger => MauiCheckTasks.MauiCheckLogger;
/// <summary>
/// Manifest files are currently used by the doctor to fetch the latest versions and requirements. The manifest is hosted by default at: <a href="https://aka.ms/dotnet-maui-check-manifest">https://aka.ms/dotnet-maui-check-manifest</a>. Use this option to specify an alternative file path or URL to use.
/// </summary>
public virtual string Manifest { get; internal set; }
/// <summary>
/// You can try using the <c>--fix</c> argument to automatically enable solutions to run without being prompted.
/// </summary>
public virtual bool? Fix { get; internal set; }
/// <summary>
/// If you're running on CI you may want to run without any required input with the <c>--non-interactive</c> argument. You can combine this with <c>--fix</c> to automatically fix without prompting.
/// </summary>
public virtual bool? NonInteractive { get; internal set; }
/// <summary>
/// This uses a more frequently updated manifest with newer versions of things more often. The manifest is hosted by default at: <a href="https://aka.ms/dotnet-maui-check-manifest-dev">https://aka.ms/dotnet-maui-check-manifest-dev</a>
/// </summary>
public virtual bool? Preview { get; internal set; }
/// <summary>
/// Uses the <c>dotnet-install</c> powershell / bash scripts for installing the dotnet SDK version from the manifest instead of the global installer.
/// </summary>
public virtual bool? Ci { get; internal set; }
/// <summary>
/// Skips a checkup by name or id as listed in maui-check list. NOTE: If there are any other checkups which depend on a skipped checkup, they will be skipped too.
/// </summary>
public virtual IReadOnlyList<MauiCheckCheckup> Skip => SkipInternal.AsReadOnly();
internal List<MauiCheckCheckup> SkipInternal { get; set; } = new List<MauiCheckCheckup>();
protected override Arguments ConfigureProcessArguments(Arguments arguments)
{
arguments
.Add("--manifest {value}", Manifest)
.Add("--fix", Fix)
.Add("--non-interactive", NonInteractive)
.Add("--preview", Preview)
.Add("--ci", Ci)
.Add("--skip {value}", Skip);
return base.ConfigureProcessArguments(arguments);
}
}
#endregion
#region MauiCheckConfigSettings
/// <summary>
/// Used within <see cref="MauiCheckTasks"/>.
/// </summary>
[PublicAPI]
[ExcludeFromCodeCoverage]
[Serializable]
public partial class MauiCheckConfigSettings : ToolSettings
{
/// <summary>
/// Path to the MauiCheck executable.
/// </summary>
public override string ProcessToolPath => base.ProcessToolPath ?? MauiCheckTasks.MauiCheckPath;
public override Action<OutputType, string> ProcessCustomLogger => MauiCheckTasks.MauiCheckLogger;
/// <summary>
/// Use the SDK version in the manifest in <em>global.json</em>.
/// </summary>
public virtual bool? DotNetVersion { get; internal set; }
/// <summary>
/// Change the <c>allowPrerelease</c> value in the <em>global.json</em>.
/// </summary>
public virtual bool? DotNetPrerelease { get; internal set; }
/// <summary>
/// Change the <c>rollForward</c> value in <em>global.json</em> to one of the allowed values specified.
/// </summary>
public virtual MauiCheckDotNetRollForward DotNetRollForward { get; internal set; }
/// <summary>
/// Adds the nuget sources specified in the manifest to the <em>NuGet.config</em> and creates the file if needed.
/// </summary>
public virtual bool? NuGetSources { get; internal set; }
protected override Arguments ConfigureProcessArguments(Arguments arguments)
{
arguments
.Add("config")
.Add("--dotnet-version", DotNetVersion)
.Add("--dotnet-pre {value}", DotNetPrerelease)
.Add("--dotnet-rollForward {value}", DotNetRollForward)
.Add("--nuget-sources", NuGetSources);
return base.ConfigureProcessArguments(arguments);
}
}
#endregion
#region MauiCheckSettingsExtensions
/// <summary>
/// Used within <see cref="MauiCheckTasks"/>.
/// </summary>
[PublicAPI]
[ExcludeFromCodeCoverage]
public static partial class MauiCheckSettingsExtensions
{
#region Manifest
/// <summary>
/// <p><em>Sets <see cref="MauiCheckSettings.Manifest"/></em></p>
/// <p>Manifest files are currently used by the doctor to fetch the latest versions and requirements. The manifest is hosted by default at: <a href="https://aka.ms/dotnet-maui-check-manifest">https://aka.ms/dotnet-maui-check-manifest</a>. Use this option to specify an alternative file path or URL to use.</p>
/// </summary>
[Pure]
public static T SetManifest<T>(this T toolSettings, string manifest) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Manifest = manifest;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MauiCheckSettings.Manifest"/></em></p>
/// <p>Manifest files are currently used by the doctor to fetch the latest versions and requirements. The manifest is hosted by default at: <a href="https://aka.ms/dotnet-maui-check-manifest">https://aka.ms/dotnet-maui-check-manifest</a>. Use this option to specify an alternative file path or URL to use.</p>
/// </summary>
[Pure]
public static T ResetManifest<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Manifest = null;
return toolSettings;
}
#endregion
#region Fix
/// <summary>
/// <p><em>Sets <see cref="MauiCheckSettings.Fix"/></em></p>
/// <p>You can try using the <c>--fix</c> argument to automatically enable solutions to run without being prompted.</p>
/// </summary>
[Pure]
public static T SetFix<T>(this T toolSettings, bool? fix) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Fix = fix;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MauiCheckSettings.Fix"/></em></p>
/// <p>You can try using the <c>--fix</c> argument to automatically enable solutions to run without being prompted.</p>
/// </summary>
[Pure]
public static T ResetFix<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Fix = null;
return toolSettings;
}
/// <summary>
/// <p><em>Enables <see cref="MauiCheckSettings.Fix"/></em></p>
/// <p>You can try using the <c>--fix</c> argument to automatically enable solutions to run without being prompted.</p>
/// </summary>
[Pure]
public static T EnableFix<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Fix = true;
return toolSettings;
}
/// <summary>
/// <p><em>Disables <see cref="MauiCheckSettings.Fix"/></em></p>
/// <p>You can try using the <c>--fix</c> argument to automatically enable solutions to run without being prompted.</p>
/// </summary>
[Pure]
public static T DisableFix<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Fix = false;
return toolSettings;
}
/// <summary>
/// <p><em>Toggles <see cref="MauiCheckSettings.Fix"/></em></p>
/// <p>You can try using the <c>--fix</c> argument to automatically enable solutions to run without being prompted.</p>
/// </summary>
[Pure]
public static T ToggleFix<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Fix = !toolSettings.Fix;
return toolSettings;
}
#endregion
#region NonInteractive
/// <summary>
/// <p><em>Sets <see cref="MauiCheckSettings.NonInteractive"/></em></p>
/// <p>If you're running on CI you may want to run without any required input with the <c>--non-interactive</c> argument. You can combine this with <c>--fix</c> to automatically fix without prompting.</p>
/// </summary>
[Pure]
public static T SetNonInteractive<T>(this T toolSettings, bool? nonInteractive) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.NonInteractive = nonInteractive;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MauiCheckSettings.NonInteractive"/></em></p>
/// <p>If you're running on CI you may want to run without any required input with the <c>--non-interactive</c> argument. You can combine this with <c>--fix</c> to automatically fix without prompting.</p>
/// </summary>
[Pure]
public static T ResetNonInteractive<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.NonInteractive = null;
return toolSettings;
}
/// <summary>
/// <p><em>Enables <see cref="MauiCheckSettings.NonInteractive"/></em></p>
/// <p>If you're running on CI you may want to run without any required input with the <c>--non-interactive</c> argument. You can combine this with <c>--fix</c> to automatically fix without prompting.</p>
/// </summary>
[Pure]
public static T EnableNonInteractive<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.NonInteractive = true;
return toolSettings;
}
/// <summary>
/// <p><em>Disables <see cref="MauiCheckSettings.NonInteractive"/></em></p>
/// <p>If you're running on CI you may want to run without any required input with the <c>--non-interactive</c> argument. You can combine this with <c>--fix</c> to automatically fix without prompting.</p>
/// </summary>
[Pure]
public static T DisableNonInteractive<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.NonInteractive = false;
return toolSettings;
}
/// <summary>
/// <p><em>Toggles <see cref="MauiCheckSettings.NonInteractive"/></em></p>
/// <p>If you're running on CI you may want to run without any required input with the <c>--non-interactive</c> argument. You can combine this with <c>--fix</c> to automatically fix without prompting.</p>
/// </summary>
[Pure]
public static T ToggleNonInteractive<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.NonInteractive = !toolSettings.NonInteractive;
return toolSettings;
}
#endregion
#region Preview
/// <summary>
/// <p><em>Sets <see cref="MauiCheckSettings.Preview"/></em></p>
/// <p>This uses a more frequently updated manifest with newer versions of things more often. The manifest is hosted by default at: <a href="https://aka.ms/dotnet-maui-check-manifest-dev">https://aka.ms/dotnet-maui-check-manifest-dev</a></p>
/// </summary>
[Pure]
public static T SetPreview<T>(this T toolSettings, bool? preview) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Preview = preview;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MauiCheckSettings.Preview"/></em></p>
/// <p>This uses a more frequently updated manifest with newer versions of things more often. The manifest is hosted by default at: <a href="https://aka.ms/dotnet-maui-check-manifest-dev">https://aka.ms/dotnet-maui-check-manifest-dev</a></p>
/// </summary>
[Pure]
public static T ResetPreview<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Preview = null;
return toolSettings;
}
/// <summary>
/// <p><em>Enables <see cref="MauiCheckSettings.Preview"/></em></p>
/// <p>This uses a more frequently updated manifest with newer versions of things more often. The manifest is hosted by default at: <a href="https://aka.ms/dotnet-maui-check-manifest-dev">https://aka.ms/dotnet-maui-check-manifest-dev</a></p>
/// </summary>
[Pure]
public static T EnablePreview<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Preview = true;
return toolSettings;
}
/// <summary>
/// <p><em>Disables <see cref="MauiCheckSettings.Preview"/></em></p>
/// <p>This uses a more frequently updated manifest with newer versions of things more often. The manifest is hosted by default at: <a href="https://aka.ms/dotnet-maui-check-manifest-dev">https://aka.ms/dotnet-maui-check-manifest-dev</a></p>
/// </summary>
[Pure]
public static T DisablePreview<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Preview = false;
return toolSettings;
}
/// <summary>
/// <p><em>Toggles <see cref="MauiCheckSettings.Preview"/></em></p>
/// <p>This uses a more frequently updated manifest with newer versions of things more often. The manifest is hosted by default at: <a href="https://aka.ms/dotnet-maui-check-manifest-dev">https://aka.ms/dotnet-maui-check-manifest-dev</a></p>
/// </summary>
[Pure]
public static T TogglePreview<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Preview = !toolSettings.Preview;
return toolSettings;
}
#endregion
#region Ci
/// <summary>
/// <p><em>Sets <see cref="MauiCheckSettings.Ci"/></em></p>
/// <p>Uses the <c>dotnet-install</c> powershell / bash scripts for installing the dotnet SDK version from the manifest instead of the global installer.</p>
/// </summary>
[Pure]
public static T SetCi<T>(this T toolSettings, bool? ci) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Ci = ci;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MauiCheckSettings.Ci"/></em></p>
/// <p>Uses the <c>dotnet-install</c> powershell / bash scripts for installing the dotnet SDK version from the manifest instead of the global installer.</p>
/// </summary>
[Pure]
public static T ResetCi<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Ci = null;
return toolSettings;
}
/// <summary>
/// <p><em>Enables <see cref="MauiCheckSettings.Ci"/></em></p>
/// <p>Uses the <c>dotnet-install</c> powershell / bash scripts for installing the dotnet SDK version from the manifest instead of the global installer.</p>
/// </summary>
[Pure]
public static T EnableCi<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Ci = true;
return toolSettings;
}
/// <summary>
/// <p><em>Disables <see cref="MauiCheckSettings.Ci"/></em></p>
/// <p>Uses the <c>dotnet-install</c> powershell / bash scripts for installing the dotnet SDK version from the manifest instead of the global installer.</p>
/// </summary>
[Pure]
public static T DisableCi<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Ci = false;
return toolSettings;
}
/// <summary>
/// <p><em>Toggles <see cref="MauiCheckSettings.Ci"/></em></p>
/// <p>Uses the <c>dotnet-install</c> powershell / bash scripts for installing the dotnet SDK version from the manifest instead of the global installer.</p>
/// </summary>
[Pure]
public static T ToggleCi<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Ci = !toolSettings.Ci;
return toolSettings;
}
#endregion
#region Skip
/// <summary>
/// <p><em>Sets <see cref="MauiCheckSettings.Skip"/> to a new list</em></p>
/// <p>Skips a checkup by name or id as listed in maui-check list. NOTE: If there are any other checkups which depend on a skipped checkup, they will be skipped too.</p>
/// </summary>
[Pure]
public static T SetSkip<T>(this T toolSettings, params MauiCheckCheckup[] skip) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.SkipInternal = skip.ToList();
return toolSettings;
}
/// <summary>
/// <p><em>Sets <see cref="MauiCheckSettings.Skip"/> to a new list</em></p>
/// <p>Skips a checkup by name or id as listed in maui-check list. NOTE: If there are any other checkups which depend on a skipped checkup, they will be skipped too.</p>
/// </summary>
[Pure]
public static T SetSkip<T>(this T toolSettings, IEnumerable<MauiCheckCheckup> skip) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.SkipInternal = skip.ToList();
return toolSettings;
}
/// <summary>
/// <p><em>Adds values to <see cref="MauiCheckSettings.Skip"/></em></p>
/// <p>Skips a checkup by name or id as listed in maui-check list. NOTE: If there are any other checkups which depend on a skipped checkup, they will be skipped too.</p>
/// </summary>
[Pure]
public static T AddSkip<T>(this T toolSettings, params MauiCheckCheckup[] skip) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.SkipInternal.AddRange(skip);
return toolSettings;
}
/// <summary>
/// <p><em>Adds values to <see cref="MauiCheckSettings.Skip"/></em></p>
/// <p>Skips a checkup by name or id as listed in maui-check list. NOTE: If there are any other checkups which depend on a skipped checkup, they will be skipped too.</p>
/// </summary>
[Pure]
public static T AddSkip<T>(this T toolSettings, IEnumerable<MauiCheckCheckup> skip) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.SkipInternal.AddRange(skip);
return toolSettings;
}
/// <summary>
/// <p><em>Clears <see cref="MauiCheckSettings.Skip"/></em></p>
/// <p>Skips a checkup by name or id as listed in maui-check list. NOTE: If there are any other checkups which depend on a skipped checkup, they will be skipped too.</p>
/// </summary>
[Pure]
public static T ClearSkip<T>(this T toolSettings) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.SkipInternal.Clear();
return toolSettings;
}
/// <summary>
/// <p><em>Removes values from <see cref="MauiCheckSettings.Skip"/></em></p>
/// <p>Skips a checkup by name or id as listed in maui-check list. NOTE: If there are any other checkups which depend on a skipped checkup, they will be skipped too.</p>
/// </summary>
[Pure]
public static T RemoveSkip<T>(this T toolSettings, params MauiCheckCheckup[] skip) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
var hashSet = new HashSet<MauiCheckCheckup>(skip);
toolSettings.SkipInternal.RemoveAll(x => hashSet.Contains(x));
return toolSettings;
}
/// <summary>
/// <p><em>Removes values from <see cref="MauiCheckSettings.Skip"/></em></p>
/// <p>Skips a checkup by name or id as listed in maui-check list. NOTE: If there are any other checkups which depend on a skipped checkup, they will be skipped too.</p>
/// </summary>
[Pure]
public static T RemoveSkip<T>(this T toolSettings, IEnumerable<MauiCheckCheckup> skip) where T : MauiCheckSettings
{
toolSettings = toolSettings.NewInstance();
var hashSet = new HashSet<MauiCheckCheckup>(skip);
toolSettings.SkipInternal.RemoveAll(x => hashSet.Contains(x));
return toolSettings;
}
#endregion
}
#endregion
#region MauiCheckConfigSettingsExtensions
/// <summary>
/// Used within <see cref="MauiCheckTasks"/>.
/// </summary>
[PublicAPI]
[ExcludeFromCodeCoverage]
public static partial class MauiCheckConfigSettingsExtensions
{
#region DotNetVersion
/// <summary>
/// <p><em>Sets <see cref="MauiCheckConfigSettings.DotNetVersion"/></em></p>
/// <p>Use the SDK version in the manifest in <em>global.json</em>.</p>
/// </summary>
[Pure]
public static T SetDotNetVersion<T>(this T toolSettings, bool? dotNetVersion) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetVersion = dotNetVersion;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MauiCheckConfigSettings.DotNetVersion"/></em></p>
/// <p>Use the SDK version in the manifest in <em>global.json</em>.</p>
/// </summary>
[Pure]
public static T ResetDotNetVersion<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetVersion = null;
return toolSettings;
}
/// <summary>
/// <p><em>Enables <see cref="MauiCheckConfigSettings.DotNetVersion"/></em></p>
/// <p>Use the SDK version in the manifest in <em>global.json</em>.</p>
/// </summary>
[Pure]
public static T EnableDotNetVersion<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetVersion = true;
return toolSettings;
}
/// <summary>
/// <p><em>Disables <see cref="MauiCheckConfigSettings.DotNetVersion"/></em></p>
/// <p>Use the SDK version in the manifest in <em>global.json</em>.</p>
/// </summary>
[Pure]
public static T DisableDotNetVersion<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetVersion = false;
return toolSettings;
}
/// <summary>
/// <p><em>Toggles <see cref="MauiCheckConfigSettings.DotNetVersion"/></em></p>
/// <p>Use the SDK version in the manifest in <em>global.json</em>.</p>
/// </summary>
[Pure]
public static T ToggleDotNetVersion<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetVersion = !toolSettings.DotNetVersion;
return toolSettings;
}
#endregion
#region DotNetPrerelease
/// <summary>
/// <p><em>Sets <see cref="MauiCheckConfigSettings.DotNetPrerelease"/></em></p>
/// <p>Change the <c>allowPrerelease</c> value in the <em>global.json</em>.</p>
/// </summary>
[Pure]
public static T SetDotNetPrerelease<T>(this T toolSettings, bool? dotNetPrerelease) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetPrerelease = dotNetPrerelease;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MauiCheckConfigSettings.DotNetPrerelease"/></em></p>
/// <p>Change the <c>allowPrerelease</c> value in the <em>global.json</em>.</p>
/// </summary>
[Pure]
public static T ResetDotNetPrerelease<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetPrerelease = null;
return toolSettings;
}
/// <summary>
/// <p><em>Enables <see cref="MauiCheckConfigSettings.DotNetPrerelease"/></em></p>
/// <p>Change the <c>allowPrerelease</c> value in the <em>global.json</em>.</p>
/// </summary>
[Pure]
public static T EnableDotNetPrerelease<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetPrerelease = true;
return toolSettings;
}
/// <summary>
/// <p><em>Disables <see cref="MauiCheckConfigSettings.DotNetPrerelease"/></em></p>
/// <p>Change the <c>allowPrerelease</c> value in the <em>global.json</em>.</p>
/// </summary>
[Pure]
public static T DisableDotNetPrerelease<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetPrerelease = false;
return toolSettings;
}
/// <summary>
/// <p><em>Toggles <see cref="MauiCheckConfigSettings.DotNetPrerelease"/></em></p>
/// <p>Change the <c>allowPrerelease</c> value in the <em>global.json</em>.</p>
/// </summary>
[Pure]
public static T ToggleDotNetPrerelease<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetPrerelease = !toolSettings.DotNetPrerelease;
return toolSettings;
}
#endregion
#region DotNetRollForward
/// <summary>
/// <p><em>Sets <see cref="MauiCheckConfigSettings.DotNetRollForward"/></em></p>
/// <p>Change the <c>rollForward</c> value in <em>global.json</em> to one of the allowed values specified.</p>
/// </summary>
[Pure]
public static T SetDotNetRollForward<T>(this T toolSettings, MauiCheckDotNetRollForward dotNetRollForward) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetRollForward = dotNetRollForward;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MauiCheckConfigSettings.DotNetRollForward"/></em></p>
/// <p>Change the <c>rollForward</c> value in <em>global.json</em> to one of the allowed values specified.</p>
/// </summary>
[Pure]
public static T ResetDotNetRollForward<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DotNetRollForward = null;
return toolSettings;
}
#endregion
#region NuGetSources
/// <summary>
/// <p><em>Sets <see cref="MauiCheckConfigSettings.NuGetSources"/></em></p>
/// <p>Adds the nuget sources specified in the manifest to the <em>NuGet.config</em> and creates the file if needed.</p>
/// </summary>
[Pure]
public static T SetNuGetSources<T>(this T toolSettings, bool? nuGetSources) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.NuGetSources = nuGetSources;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MauiCheckConfigSettings.NuGetSources"/></em></p>
/// <p>Adds the nuget sources specified in the manifest to the <em>NuGet.config</em> and creates the file if needed.</p>
/// </summary>
[Pure]
public static T ResetNuGetSources<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.NuGetSources = null;
return toolSettings;
}
/// <summary>
/// <p><em>Enables <see cref="MauiCheckConfigSettings.NuGetSources"/></em></p>
/// <p>Adds the nuget sources specified in the manifest to the <em>NuGet.config</em> and creates the file if needed.</p>
/// </summary>
[Pure]
public static T EnableNuGetSources<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.NuGetSources = true;
return toolSettings;
}
/// <summary>
/// <p><em>Disables <see cref="MauiCheckConfigSettings.NuGetSources"/></em></p>
/// <p>Adds the nuget sources specified in the manifest to the <em>NuGet.config</em> and creates the file if needed.</p>
/// </summary>
[Pure]
public static T DisableNuGetSources<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.NuGetSources = false;
return toolSettings;
}
/// <summary>
/// <p><em>Toggles <see cref="MauiCheckConfigSettings.NuGetSources"/></em></p>
/// <p>Adds the nuget sources specified in the manifest to the <em>NuGet.config</em> and creates the file if needed.</p>
/// </summary>
[Pure]
public static T ToggleNuGetSources<T>(this T toolSettings) where T : MauiCheckConfigSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.NuGetSources = !toolSettings.NuGetSources;
return toolSettings;
}
#endregion
}
#endregion
#region MauiCheckDotNetRollForward
/// <summary>
/// Used within <see cref="MauiCheckTasks"/>.
/// </summary>
[PublicAPI]
[Serializable]
[ExcludeFromCodeCoverage]
[TypeConverter(typeof(TypeConverter<MauiCheckDotNetRollForward>))]
public partial class MauiCheckDotNetRollForward : Enumeration
{
public static MauiCheckDotNetRollForward disable = (MauiCheckDotNetRollForward) "disable";
public static MauiCheckDotNetRollForward major = (MauiCheckDotNetRollForward) "major";
public static MauiCheckDotNetRollForward minor = (MauiCheckDotNetRollForward) "minor";
public static MauiCheckDotNetRollForward feature = (MauiCheckDotNetRollForward) "feature";
public static MauiCheckDotNetRollForward patch = (MauiCheckDotNetRollForward) "patch";
public static MauiCheckDotNetRollForward latestMajor = (MauiCheckDotNetRollForward) "latestMajor";
public static MauiCheckDotNetRollForward latestMinor = (MauiCheckDotNetRollForward) "latestMinor";
public static MauiCheckDotNetRollForward latestFeature = (MauiCheckDotNetRollForward) "latestFeature";
public static MauiCheckDotNetRollForward latestPatch = (MauiCheckDotNetRollForward) "latestPatch";
public static implicit operator MauiCheckDotNetRollForward(string value)
{
return new MauiCheckDotNetRollForward { Value = value };
}
}
#endregion
#region MauiCheckCheckup
/// <summary>
/// Used within <see cref="MauiCheckTasks"/>.
/// </summary>
[PublicAPI]
[Serializable]
[ExcludeFromCodeCoverage]
[TypeConverter(typeof(TypeConverter<MauiCheckCheckup>))]
public partial class MauiCheckCheckup : Enumeration
{
public static MauiCheckCheckup OpenJdkCheckup = (MauiCheckCheckup) "OpenJdkCheckup";
public static MauiCheckCheckup VisualStudioMacCheckup = (MauiCheckCheckup) "VisualStudioMacCheckup";
public static MauiCheckCheckup AndroidSdkPackagesCheckup = (MauiCheckCheckup) "AndroidSdkPackagesCheckup";
public static MauiCheckCheckup AndroidEmulatorCheckup = (MauiCheckCheckup) "AndroidEmulatorCheckup";
public static MauiCheckCheckup XCodeCheckup = (MauiCheckCheckup) "XCodeCheckup";
public static MauiCheckCheckup DotNetCheckup = (MauiCheckCheckup) "DotNetCheckup";
public static MauiCheckCheckup DotNetWorkloadDuplicatesCheckup = (MauiCheckCheckup) "DotNetWorkloadDuplicatesCheckup";
public static MauiCheckCheckup DotNetSentinelCheckup = (MauiCheckCheckup) "DotNetSentinelCheckup";
public static MauiCheckCheckup DotNetWorkloadsCheckup = (MauiCheckCheckup) "DotNetWorkloadsCheckup";
public static implicit operator MauiCheckCheckup(string value)
{
return new MauiCheckCheckup { Value = value };
}
}
#endregion
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, 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.
//
#if !NETSTANDARD1_3
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
/// <summary>
/// Color formatting for <see cref="ColoredConsoleTarget"/> using ANSI Color Codes
/// </summary>
internal class ColoredConsoleAnsiPrinter : IColoredConsolePrinter
{
public TextWriter AcquireTextWriter(TextWriter consoleStream, StringBuilder reusableBuilder)
{
// Writes into an in-memory console writer for sake of optimizations (Possible when not using system-colors)
return new StringWriter(reusableBuilder ?? new StringBuilder(50), consoleStream.FormatProvider);
}
public void ReleaseTextWriter(TextWriter consoleWriter, TextWriter consoleStream, ConsoleColor? oldForegroundColor, ConsoleColor? oldBackgroundColor, bool flush)
{
// Flushes the in-memory console-writer to the actual console-stream
var builder = (consoleWriter as StringWriter)?.GetStringBuilder();
if (builder != null)
{
builder.Append(TerminalDefaultColorEscapeCode);
ConsoleTargetHelper.WriteLineThreadSafe(consoleStream, builder.ToString(), flush);
}
}
public ConsoleColor? ChangeForegroundColor(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? oldForegroundColor = null)
{
if (foregroundColor.HasValue)
{
consoleWriter.Write(GetForegroundColorEscapeCode(foregroundColor.Value));
}
return null; // There is no "old" console color
}
public ConsoleColor? ChangeBackgroundColor(TextWriter consoleWriter, ConsoleColor? backgroundColor, ConsoleColor? oldBackgroundColor = null)
{
if (backgroundColor.HasValue)
{
consoleWriter.Write(GetBackgroundColorEscapeCode(backgroundColor.Value));
}
return null; // There is no "old" console color
}
public void ResetDefaultColors(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? backgroundColor)
{
consoleWriter.Write(TerminalDefaultColorEscapeCode);
}
public void WriteSubString(TextWriter consoleWriter, string text, int index, int endIndex)
{
// No need to allocate SubString, because we are already writing in-memory
for (int i = index; i < endIndex; ++i)
consoleWriter.Write(text[i]);
}
public void WriteChar(TextWriter consoleWriter, char text)
{
consoleWriter.Write(text);
}
public void WriteLine(TextWriter consoleWriter, string text)
{
consoleWriter.Write(text); // Newline is added when flushing to actual console-stream
}
/// <summary>
/// Not using bold to get light colors, as it has to be cleared
/// </summary>
private static string GetForegroundColorEscapeCode(ConsoleColor color)
{
switch (color)
{
case ConsoleColor.Black:
return "\x1B[30m";
case ConsoleColor.Blue:
return "\x1B[94m";
case ConsoleColor.Cyan:
return "\x1B[96m";
case ConsoleColor.DarkBlue:
return "\x1B[34m";
case ConsoleColor.DarkCyan:
return "\x1B[36m";
case ConsoleColor.DarkGray:
return "\x1B[90m";
case ConsoleColor.DarkGreen:
return "\x1B[32m";
case ConsoleColor.DarkMagenta:
return "\x1B[35m";
case ConsoleColor.DarkRed:
return "\x1B[31m";
case ConsoleColor.DarkYellow:
return "\x1B[33m";
case ConsoleColor.Gray:
return "\x1B[37m";
case ConsoleColor.Green:
return "\x1B[92m";
case ConsoleColor.Magenta:
return "\x1B[95m";
case ConsoleColor.Red:
return "\x1B[91m";
case ConsoleColor.White:
return "\x1b[97m";
case ConsoleColor.Yellow:
return "\x1B[93m";
default:
return TerminalDefaultForegroundColorEscapeCode; // default foreground color
}
}
private static string TerminalDefaultForegroundColorEscapeCode
{
get { return "\x1B[39m\x1B[22m"; }
}
/// <summary>
/// Not using bold to get light colors, as it has to be cleared (And because it only works for text, and not background)
/// </summary>
private static string GetBackgroundColorEscapeCode(ConsoleColor color)
{
switch (color)
{
case ConsoleColor.Black:
return "\x1B[40m";
case ConsoleColor.Blue:
return "\x1B[104m";
case ConsoleColor.Cyan:
return "\x1B[106m";
case ConsoleColor.DarkBlue:
return "\x1B[44m";
case ConsoleColor.DarkCyan:
return "\x1B[46m";
case ConsoleColor.DarkGray:
return "\x1B[100m";
case ConsoleColor.DarkGreen:
return "\x1B[42m";
case ConsoleColor.DarkMagenta:
return "\x1B[45m";
case ConsoleColor.DarkRed:
return "\x1B[41m";
case ConsoleColor.DarkYellow:
return "\x1B[43m";
case ConsoleColor.Gray:
return "\x1B[47m";
case ConsoleColor.Green:
return "\x1B[102m";
case ConsoleColor.Magenta:
return "\x1B[105m";
case ConsoleColor.Red:
return "\x1B[101m";
case ConsoleColor.White:
return "\x1B[107m";
case ConsoleColor.Yellow:
return "\x1B[103m";
default:
return TerminalDefaultBackgroundColorEscapeCode;
}
}
private static string TerminalDefaultBackgroundColorEscapeCode
{
get { return "\x1B[49m"; }
}
/// <summary>
/// Resets both foreground and background color.
/// </summary>
private static string TerminalDefaultColorEscapeCode
{
get { return "\x1B[0m"; }
}
/// <summary>
/// ANSI have 8 color-codes (30-37) by default. The "bright" (or "intense") color-codes (90-97) are extended values not supported by all terminals
/// </summary>
public IList<ConsoleRowHighlightingRule> DefaultConsoleRowHighlightingRules { get; } = new List<ConsoleRowHighlightingRule>()
{
new ConsoleRowHighlightingRule("level == LogLevel.Fatal", ConsoleOutputColor.DarkRed, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Error", ConsoleOutputColor.DarkYellow, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Warn", ConsoleOutputColor.DarkMagenta, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Info", ConsoleOutputColor.NoChange, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Debug", ConsoleOutputColor.NoChange, ConsoleOutputColor.NoChange),
new ConsoleRowHighlightingRule("level == LogLevel.Trace", ConsoleOutputColor.NoChange, ConsoleOutputColor.NoChange),
};
}
}
#endif
| |
using System;
using System.IO;
using NUnit.Framework;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Tests
{
/// <remarks>Basic test class for the GOST28147 cipher</remarks>
[TestFixture]
public class Gost28147Test
: SimpleTest
{
private static string[] cipherTests =
{
"256",
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
"4e6f77206973207468652074696d6520666f7220616c6c20",
"281630d0d5770030068c252d841e84149ccc1912052dbc02",
"256",
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
"4e6f77206973207468652074696d65208a920c6ed1a804f5",
"88e543dfc04dc4f764fa7b624741cec07de49b007bf36065"
};
public override string Name
{
get { return "GOST28147"; }
}
private void doTestEcb(
int strength,
byte[] keyBytes,
byte[] input,
byte[] output)
{
IBufferedCipher inCipher, outCipher;
CipherStream cIn, cOut;
MemoryStream bIn, bOut;
KeyParameter key = ParameterUtilities.CreateKeyParameter("GOST28147", keyBytes);
inCipher = CipherUtilities.GetCipher("GOST28147/ECB/NoPadding");
outCipher = CipherUtilities.GetCipher("GOST28147/ECB/NoPadding");
outCipher.Init(true, key);
inCipher.Init(false, key);
//
// encryption pass
//
bOut = new MemoryStream();
cOut = new CipherStream(bOut, null, outCipher);
for (int i = 0; i != input.Length / 2; i++)
{
cOut.WriteByte(input[i]);
}
cOut.Write(input, input.Length / 2, input.Length - input.Length / 2);
cOut.Close();
byte[] bytes = bOut.ToArray();
if (!AreEqual(bytes, output))
{
Fail("GOST28147 failed encryption - expected "
+ Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes));
}
//
// decryption pass
//
bIn = new MemoryStream(bytes, false);
cIn = new CipherStream(bIn, inCipher, null);
BinaryReader dIn = new BinaryReader(cIn);
bytes = new byte[input.Length];
for (int i = 0; i != input.Length / 2; i++)
{
bytes[i] = dIn.ReadByte();
}
int remaining = bytes.Length - input.Length / 2;
byte[] extra = dIn.ReadBytes(remaining);
if (extra.Length < remaining)
throw new EndOfStreamException();
extra.CopyTo(bytes, input.Length / 2);
if (!AreEqual(bytes, input))
{
Fail("GOST28147 failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes));
}
}
private void doTestCfb(
int strength,
byte[] keyBytes,
byte[] input,
byte[] output)
{
IBufferedCipher inCipher, outCipher;
CipherStream cIn, cOut;
MemoryStream bIn, bOut;
KeyParameter key = ParameterUtilities.CreateKeyParameter("GOST28147", keyBytes);
inCipher = CipherUtilities.GetCipher("GOST28147/CFB8/NoPadding");
outCipher = CipherUtilities.GetCipher("GOST28147/CFB8/NoPadding");
byte[] iv = {1,2,3,4,5,6,7,8};
outCipher.Init(true, new ParametersWithIV(key, iv));
inCipher.Init(false, new ParametersWithIV(key, iv));
//
// encryption pass
//
bOut = new MemoryStream();
cOut = new CipherStream(bOut, null, outCipher);
for (int i = 0; i != input.Length / 2; i++)
{
cOut.WriteByte(input[i]);
}
cOut.Write(input, input.Length / 2, input.Length - input.Length / 2);
cOut.Close();
byte[] bytes = bOut.ToArray();
if (!AreEqual(bytes, output))
{
Fail("GOST28147 failed encryption - expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(bytes));
}
//
// decryption pass
//
bIn = new MemoryStream(bytes, false);
cIn = new CipherStream(bIn, inCipher, null);
BinaryReader dIn = new BinaryReader(cIn);
bytes = new byte[input.Length];
for (int i = 0; i != input.Length / 2; i++)
{
bytes[i] = dIn.ReadByte();
}
int remaining = bytes.Length - input.Length / 2;
byte[] extra = dIn.ReadBytes(remaining);
if (extra.Length < remaining)
throw new EndOfStreamException();
extra.CopyTo(bytes, input.Length / 2);
if (!AreEqual(bytes, input))
{
Fail("GOST28147 failed decryption - expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(bytes));
}
}
private void doOidTest()
{
string[] oids = {
CryptoProObjectIdentifiers.GostR28147Cbc.Id,
};
string[] names = {
"GOST28147/CBC/PKCS7Padding"
};
try
{
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
// IvParameterSpec ivSpec = new IvParameterSpec(new byte[8]);
byte[] iv = new byte[8];
for (int i = 0; i != oids.Length; i++)
{
IBufferedCipher c1 = CipherUtilities.GetCipher(oids[i]);
IBufferedCipher c2 = CipherUtilities.GetCipher(names[i]);
// KeyGenerator kg = KeyGenerator.getInstance(oids[i]);
// SecretKey k = kg.generateKey();
CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator(oids[i]);
KeyParameter k = ParameterUtilities.CreateKeyParameter(oids[i], kg.GenerateKey());
c1.Init(true, new ParametersWithIV(k, iv));
c2.Init(false, new ParametersWithIV(k, iv));
byte[] result = c2.DoFinal(c1.DoFinal(data));
if (!AreEqual(data, result))
{
Fail("failed OID test");
}
}
}
catch (Exception ex)
{
Fail("failed exception " + ex.ToString(), ex);
}
}
public override void PerformTest()
{
for (int i = 0; i != cipherTests.Length; i += 8)
{
doTestEcb(int.Parse(cipherTests[i]),
Hex.Decode(cipherTests[i + 1]),
Hex.Decode(cipherTests[i + 2]),
Hex.Decode(cipherTests[i + 3]));
doTestCfb(int.Parse(cipherTests[i + 4]),
Hex.Decode(cipherTests[i + 4 + 1]),
Hex.Decode(cipherTests[i + 4 + 2]),
Hex.Decode(cipherTests[i + 4 + 3]));
doOidTest();
}
}
public static void Main(
string[] args)
{
RunTest(new Gost28147Test());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
// 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 Microsoft.AspNetCore.Mvc.DataAnnotations;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Localization;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Extension methods for configuring MVC view and data annotations localization services.
/// </summary>
public static class MvcLocalizationMvcBuilderExtensions
{
/// <summary>
/// Adds MVC view localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddViewLocalization(this IMvcBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return AddViewLocalization(builder, LanguageViewLocationExpanderFormat.Suffix);
}
/// <summary>
/// Adds MVC view localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="format">The view format for localized views.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddViewLocalization(
this IMvcBuilder builder,
LanguageViewLocationExpanderFormat format)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
AddViewLocalization(builder, format, setupAction: null);
return builder;
}
/// <summary>
/// Adds MVC view localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="setupAction">An action to configure the <see cref="LocalizationOptions"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddViewLocalization(
this IMvcBuilder builder,
Action<LocalizationOptions>? setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
AddViewLocalization(builder, LanguageViewLocationExpanderFormat.Suffix, setupAction);
return builder;
}
/// <summary>
/// Adds MVC view localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="format">The view format for localized views.</param>
/// <param name="setupAction">An action to configure the <see cref="LocalizationOptions"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddViewLocalization(
this IMvcBuilder builder,
LanguageViewLocationExpanderFormat format,
Action<LocalizationOptions>? setupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
MvcLocalizationServices.AddLocalizationServices(builder.Services, format, setupAction);
return builder;
}
/// <summary>
/// Adds MVC view and data annotations localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
/// <remarks>
/// Adding localization also adds support for views via
/// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine
/// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>.
/// </remarks>
public static IMvcBuilder AddMvcLocalization(this IMvcBuilder builder)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return AddMvcLocalization(
builder,
localizationOptionsSetupAction: null,
format: LanguageViewLocationExpanderFormat.Suffix,
dataAnnotationsLocalizationOptionsSetupAction: null);
}
/// <summary>
/// Adds MVC view and data annotations localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="localizationOptionsSetupAction">An action to configure the <see cref="LocalizationOptions"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
/// <remarks>
/// Adding localization also adds support for views via
/// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine
/// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>.
/// </remarks>
public static IMvcBuilder AddMvcLocalization(
this IMvcBuilder builder,
Action<LocalizationOptions>? localizationOptionsSetupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return AddMvcLocalization(
builder,
localizationOptionsSetupAction,
LanguageViewLocationExpanderFormat.Suffix,
dataAnnotationsLocalizationOptionsSetupAction: null);
}
/// <summary>
/// Adds MVC view and data annotations localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="format">The view format for localized views.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
/// <remarks>
/// Adding localization also adds support for views via
/// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine
/// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>.
/// </remarks>
public static IMvcBuilder AddMvcLocalization(
this IMvcBuilder builder,
LanguageViewLocationExpanderFormat format)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return AddMvcLocalization(
builder,
localizationOptionsSetupAction: null,
format: format,
dataAnnotationsLocalizationOptionsSetupAction: null);
}
/// <summary>
/// Adds MVC view and data annotations localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="localizationOptionsSetupAction">An action to configure the
/// <see cref="LocalizationOptions"/>.</param>
/// <param name="format">The view format for localized views.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
/// <remarks>
/// Adding localization also adds support for views via
/// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine
/// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>.
/// </remarks>
public static IMvcBuilder AddMvcLocalization(
this IMvcBuilder builder,
Action<LocalizationOptions>? localizationOptionsSetupAction,
LanguageViewLocationExpanderFormat format)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return AddMvcLocalization(
builder,
localizationOptionsSetupAction: localizationOptionsSetupAction,
format: format,
dataAnnotationsLocalizationOptionsSetupAction: null);
}
/// <summary>
/// Adds MVC view and data annotations localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="dataAnnotationsLocalizationOptionsSetupAction">An action to configure the
/// <see cref="MvcDataAnnotationsLocalizationOptions"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
/// <remarks>
/// Adding localization also adds support for views via
/// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine
/// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>.
/// </remarks>
public static IMvcBuilder AddMvcLocalization(
this IMvcBuilder builder,
Action<MvcDataAnnotationsLocalizationOptions>? dataAnnotationsLocalizationOptionsSetupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return AddMvcLocalization(
builder,
localizationOptionsSetupAction: null,
format: LanguageViewLocationExpanderFormat.Suffix,
dataAnnotationsLocalizationOptionsSetupAction: dataAnnotationsLocalizationOptionsSetupAction);
}
/// <summary>
/// Adds MVC view and data annotations localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="localizationOptionsSetupAction">An action to configure the
/// <see cref="LocalizationOptions"/>.</param>
/// <param name="dataAnnotationsLocalizationOptionsSetupAction">An action to configure the
/// <see cref="MvcDataAnnotationsLocalizationOptions"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
/// <remarks>
/// Adding localization also adds support for views via
/// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine
/// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>.
/// </remarks>
public static IMvcBuilder AddMvcLocalization(
this IMvcBuilder builder,
Action<LocalizationOptions>? localizationOptionsSetupAction,
Action<MvcDataAnnotationsLocalizationOptions>? dataAnnotationsLocalizationOptionsSetupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return AddMvcLocalization(
builder,
localizationOptionsSetupAction: localizationOptionsSetupAction,
format: LanguageViewLocationExpanderFormat.Suffix,
dataAnnotationsLocalizationOptionsSetupAction: dataAnnotationsLocalizationOptionsSetupAction);
}
/// <summary>
/// Adds MVC view and data annotations localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="format">The view format for localized views.</param>
/// <param name="dataAnnotationsLocalizationOptionsSetupAction">An action to configure the
/// <see cref="MvcDataAnnotationsLocalizationOptions"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
/// <remarks>
/// Adding localization also adds support for views via
/// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine
/// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>.
/// </remarks>
public static IMvcBuilder AddMvcLocalization(
this IMvcBuilder builder,
LanguageViewLocationExpanderFormat format,
Action<MvcDataAnnotationsLocalizationOptions>? dataAnnotationsLocalizationOptionsSetupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return AddMvcLocalization(
builder,
localizationOptionsSetupAction: null,
format: format,
dataAnnotationsLocalizationOptionsSetupAction: dataAnnotationsLocalizationOptionsSetupAction);
}
/// <summary>
/// Adds MVC view and data annotations localization services to the application.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <param name="localizationOptionsSetupAction">An action to configure the <see cref="LocalizationOptions"/>.
/// Can be <c>null</c>.</param>
/// <param name="format">The view format for localized views.</param>
/// <param name="dataAnnotationsLocalizationOptionsSetupAction">An action to configure
/// the <see cref="MvcDataAnnotationsLocalizationOptions"/>. Can be <c>null</c>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
/// <remarks>
/// Adding localization also adds support for views via
/// <see cref="MvcViewFeaturesMvcCoreBuilderExtensions.AddViews(IMvcCoreBuilder)"/> and the Razor view engine
/// via <see cref="MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder)"/>.
/// </remarks>
public static IMvcBuilder AddMvcLocalization(
this IMvcBuilder builder,
Action<LocalizationOptions>? localizationOptionsSetupAction,
LanguageViewLocationExpanderFormat format,
Action<MvcDataAnnotationsLocalizationOptions>? dataAnnotationsLocalizationOptionsSetupAction)
{
if (builder == null)
{
throw new ArgumentNullException(nameof(builder));
}
return builder
.AddViewLocalization(format, localizationOptionsSetupAction)
.AddDataAnnotationsLocalization(dataAnnotationsLocalizationOptionsSetupAction);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Logging;
using Orleans.CodeGeneration;
using Orleans.Serialization;
using Orleans.Transactions;
namespace Orleans.Runtime
{
internal class Message : IOutgoingMessage
{
public const int LENGTH_HEADER_SIZE = 8;
public const int LENGTH_META_HEADER = 4;
[NonSerialized]
private string _targetHistory;
[NonSerialized]
private DateTime? _queuedTime;
[NonSerialized]
private int _retryCount;
public string TargetHistory
{
get { return _targetHistory; }
set { _targetHistory = value; }
}
public DateTime? QueuedTime
{
get { return _queuedTime; }
set { _queuedTime = value; }
}
public int RetryCount
{
get { return _retryCount; }
set { _retryCount = value; }
}
// Cache values of TargetAddess and SendingAddress as they are used very frequently
private ActivationAddress targetAddress;
private ActivationAddress sendingAddress;
static Message()
{
}
public enum Categories
{
Ping,
System,
Application,
}
public enum Directions
{
Request,
Response,
OneWay
}
public enum ResponseTypes
{
Success,
Error,
Rejection
}
public enum RejectionTypes
{
Transient,
Overloaded,
DuplicateRequest,
Unrecoverable,
GatewayTooBusy,
CacheInvalidation
}
internal HeadersContainer Headers { get; set; } = new HeadersContainer();
public Categories Category
{
get { return Headers.Category; }
set { Headers.Category = value; }
}
public Directions Direction
{
get { return Headers.Direction ?? default(Directions); }
set { Headers.Direction = value; }
}
public bool HasDirection => Headers.Direction.HasValue;
public bool IsReadOnly
{
get { return Headers.IsReadOnly; }
set { Headers.IsReadOnly = value; }
}
public bool IsAlwaysInterleave
{
get { return Headers.IsAlwaysInterleave; }
set { Headers.IsAlwaysInterleave = value; }
}
public bool IsUnordered
{
get { return Headers.IsUnordered; }
set { Headers.IsUnordered = value; }
}
public bool IsReturnedFromRemoteCluster
{
get { return Headers.IsReturnedFromRemoteCluster; }
set { Headers.IsReturnedFromRemoteCluster = value; }
}
public bool IsTransactionRequired
{
get { return Headers.IsTransactionRequired; }
set { Headers.IsTransactionRequired = value; }
}
public CorrelationId Id
{
get { return Headers.Id; }
set { Headers.Id = value; }
}
public int ForwardCount
{
get { return Headers.ForwardCount; }
set { Headers.ForwardCount = value; }
}
public SiloAddress TargetSilo
{
get { return Headers.TargetSilo; }
set
{
Headers.TargetSilo = value;
targetAddress = null;
}
}
public GrainId TargetGrain
{
get { return Headers.TargetGrain; }
set
{
Headers.TargetGrain = value;
targetAddress = null;
}
}
public ActivationId TargetActivation
{
get { return Headers.TargetActivation; }
set
{
Headers.TargetActivation = value;
targetAddress = null;
}
}
public ActivationAddress TargetAddress
{
get { return targetAddress ?? (targetAddress = ActivationAddress.GetAddress(TargetSilo, TargetGrain, TargetActivation)); }
set
{
TargetGrain = value.Grain;
TargetActivation = value.Activation;
TargetSilo = value.Silo;
targetAddress = value;
}
}
public GuidId TargetObserverId
{
get { return Headers.TargetObserverId; }
set
{
Headers.TargetObserverId = value;
targetAddress = null;
}
}
public SiloAddress SendingSilo
{
get { return Headers.SendingSilo; }
set
{
Headers.SendingSilo = value;
sendingAddress = null;
}
}
public GrainId SendingGrain
{
get { return Headers.SendingGrain; }
set
{
Headers.SendingGrain = value;
sendingAddress = null;
}
}
public ActivationId SendingActivation
{
get { return Headers.SendingActivation; }
set
{
Headers.SendingActivation = value;
sendingAddress = null;
}
}
public CorrelationId CallChainId
{
get { return Headers.CallChainId; }
set { Headers.CallChainId = value; }
}
public TraceContext TraceContext {
get { return Headers.TraceContext; }
set { Headers.TraceContext = value; }
}
public ActivationAddress SendingAddress
{
get { return sendingAddress ?? (sendingAddress = ActivationAddress.GetAddress(SendingSilo, SendingGrain, SendingActivation)); }
set
{
SendingGrain = value.Grain;
SendingActivation = value.Activation;
SendingSilo = value.Silo;
sendingAddress = value;
}
}
public bool IsNewPlacement
{
get { return Headers.IsNewPlacement; }
set
{
Headers.IsNewPlacement = value;
}
}
public bool IsUsingInterfaceVersions
{
get { return Headers.IsUsingIfaceVersion; }
set
{
Headers.IsUsingIfaceVersion = value;
}
}
public ResponseTypes Result
{
get { return Headers.Result; }
set { Headers.Result = value; }
}
public TimeSpan? TimeToLive
{
get { return Headers.TimeToLive; }
set { Headers.TimeToLive = value; }
}
public bool IsExpired
{
get
{
if (!TimeToLive.HasValue)
return false;
return TimeToLive <= TimeSpan.Zero;
}
}
public bool IsExpirableMessage(bool dropExpiredMessages)
{
if (!dropExpiredMessages) return false;
GrainId id = TargetGrain;
if (id == null) return false;
// don't set expiration for one way, system target and system grain messages.
return Direction != Directions.OneWay && !id.IsSystemTarget;
}
public ITransactionInfo TransactionInfo
{
get { return Headers.TransactionInfo; }
set { Headers.TransactionInfo = value; }
}
public string DebugContext
{
get { return GetNotNullString(Headers.DebugContext); }
set { Headers.DebugContext = value; }
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return Headers.CacheInvalidationHeader; }
set { Headers.CacheInvalidationHeader = value; }
}
public bool HasCacheInvalidationHeader => this.CacheInvalidationHeader != null
&& this.CacheInvalidationHeader.Count > 0;
internal void AddToCacheInvalidationHeader(ActivationAddress address)
{
var list = new List<ActivationAddress>();
if (CacheInvalidationHeader != null)
{
list.AddRange(CacheInvalidationHeader);
}
list.Add(address);
CacheInvalidationHeader = list;
}
/// <summary>
/// Set by sender's placement logic when NewPlacementRequested is true
/// so that receiver knows desired grain type
/// </summary>
public string NewGrainType
{
get { return GetNotNullString(Headers.NewGrainType); }
set { Headers.NewGrainType = value; }
}
/// <summary>
/// Set by caller's grain reference
/// </summary>
public string GenericGrainType
{
get { return GetNotNullString(Headers.GenericGrainType); }
set { Headers.GenericGrainType = value; }
}
public RejectionTypes RejectionType
{
get { return Headers.RejectionType; }
set { Headers.RejectionType = value; }
}
public string RejectionInfo
{
get { return GetNotNullString(Headers.RejectionInfo); }
set { Headers.RejectionInfo = value; }
}
public Dictionary<string, object> RequestContextData
{
get { return Headers.RequestContextData; }
set { Headers.RequestContextData = value; }
}
public object BodyObject { get; set; }
public void ClearTargetAddress()
{
targetAddress = null;
}
private static string GetNotNullString(string s)
{
return s ?? string.Empty;
}
/// <summary>
/// Tell whether two messages are duplicates of one another
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool IsDuplicate(Message other)
{
return Equals(SendingSilo, other.SendingSilo) && Equals(Id, other.Id);
}
// For testing and logging/tracing
public string ToLongString()
{
var sb = new StringBuilder();
string debugContex = DebugContext;
if (!string.IsNullOrEmpty(debugContex))
{
// if DebugContex is present, print it first.
sb.Append(debugContex).Append(".");
}
AppendIfExists(HeadersContainer.Headers.CACHE_INVALIDATION_HEADER, sb, (m) => m.CacheInvalidationHeader);
AppendIfExists(HeadersContainer.Headers.CATEGORY, sb, (m) => m.Category);
AppendIfExists(HeadersContainer.Headers.DIRECTION, sb, (m) => m.Direction);
AppendIfExists(HeadersContainer.Headers.TIME_TO_LIVE, sb, (m) => m.TimeToLive);
AppendIfExists(HeadersContainer.Headers.FORWARD_COUNT, sb, (m) => m.ForwardCount);
AppendIfExists(HeadersContainer.Headers.GENERIC_GRAIN_TYPE, sb, (m) => m.GenericGrainType);
AppendIfExists(HeadersContainer.Headers.CORRELATION_ID, sb, (m) => m.Id);
AppendIfExists(HeadersContainer.Headers.ALWAYS_INTERLEAVE, sb, (m) => m.IsAlwaysInterleave);
AppendIfExists(HeadersContainer.Headers.IS_NEW_PLACEMENT, sb, (m) => m.IsNewPlacement);
AppendIfExists(HeadersContainer.Headers.IS_RETURNED_FROM_REMOTE_CLUSTER, sb, (m) => m.IsReturnedFromRemoteCluster);
AppendIfExists(HeadersContainer.Headers.READ_ONLY, sb, (m) => m.IsReadOnly);
AppendIfExists(HeadersContainer.Headers.IS_UNORDERED, sb, (m) => m.IsUnordered);
AppendIfExists(HeadersContainer.Headers.NEW_GRAIN_TYPE, sb, (m) => m.NewGrainType);
AppendIfExists(HeadersContainer.Headers.REJECTION_INFO, sb, (m) => m.RejectionInfo);
AppendIfExists(HeadersContainer.Headers.REJECTION_TYPE, sb, (m) => m.RejectionType);
AppendIfExists(HeadersContainer.Headers.REQUEST_CONTEXT, sb, (m) => m.RequestContextData);
AppendIfExists(HeadersContainer.Headers.RESULT, sb, (m) => m.Result);
AppendIfExists(HeadersContainer.Headers.SENDING_ACTIVATION, sb, (m) => m.SendingActivation);
AppendIfExists(HeadersContainer.Headers.SENDING_GRAIN, sb, (m) => m.SendingGrain);
AppendIfExists(HeadersContainer.Headers.SENDING_SILO, sb, (m) => m.SendingSilo);
AppendIfExists(HeadersContainer.Headers.TARGET_ACTIVATION, sb, (m) => m.TargetActivation);
AppendIfExists(HeadersContainer.Headers.TARGET_GRAIN, sb, (m) => m.TargetGrain);
AppendIfExists(HeadersContainer.Headers.TARGET_OBSERVER, sb, (m) => m.TargetObserverId);
AppendIfExists(HeadersContainer.Headers.CALL_CHAIN_ID, sb, (m) => m.CallChainId);
AppendIfExists(HeadersContainer.Headers.TRACE_CONTEXT, sb, (m) => m.TraceContext);
AppendIfExists(HeadersContainer.Headers.TARGET_SILO, sb, (m) => m.TargetSilo);
return sb.ToString();
}
private void AppendIfExists(HeadersContainer.Headers header, StringBuilder sb, Func<Message, object> valueProvider)
{
// used only under log3 level
if ((Headers.GetHeadersMask() & header) != HeadersContainer.Headers.NONE)
{
sb.AppendFormat("{0}={1};", header, valueProvider(this));
sb.AppendLine();
}
}
public override string ToString()
{
string response = String.Empty;
if (Direction == Directions.Response)
{
switch (Result)
{
case ResponseTypes.Error:
response = "Error ";
break;
case ResponseTypes.Rejection:
response = string.Format("{0} Rejection (info: {1}) ", RejectionType, RejectionInfo);
break;
default:
break;
}
}
return String.Format("{0}{1}{2}{3}{4} {5}->{6} #{7}{8}: {9}",
IsReadOnly ? "ReadOnly " : "", //0
IsAlwaysInterleave ? "IsAlwaysInterleave " : "", //1
IsNewPlacement ? "NewPlacement " : "", // 2
response, //3
Direction, //4
String.Format("{0}{1}{2}", SendingSilo, SendingGrain, SendingActivation), //5
String.Format("{0}{1}{2}{3}", TargetSilo, TargetGrain, TargetActivation, TargetObserverId), //6
Id, //7
ForwardCount > 0 ? "[ForwardCount=" + ForwardCount + "]" : "", //8
DebugContext); //9
}
internal void SetTargetPlacement(PlacementResult value)
{
TargetActivation = value.Activation;
TargetSilo = value.Silo;
if (value.IsNewPlacement)
IsNewPlacement = true;
if (!String.IsNullOrEmpty(value.GrainType))
NewGrainType = value.GrainType;
}
public string GetTargetHistory()
{
var history = new StringBuilder();
history.Append("<");
if (TargetSilo != null)
{
history.Append(TargetSilo).Append(":");
}
if (TargetGrain != null)
{
history.Append(TargetGrain).Append(":");
}
if (TargetActivation != null)
{
history.Append(TargetActivation);
}
history.Append(">");
if (!string.IsNullOrEmpty(TargetHistory))
{
history.Append(" ").Append(TargetHistory);
}
return history.ToString();
}
public bool IsSameDestination(IOutgoingMessage other)
{
var msg = (Message)other;
return msg != null && Object.Equals(TargetSilo, msg.TargetSilo);
}
// For statistical measuring of time spent in queues.
private ITimeInterval timeInterval;
public void Start()
{
timeInterval = TimeIntervalFactory.CreateTimeInterval(true);
timeInterval.Start();
}
public void Stop()
{
timeInterval.Stop();
}
public void Restart()
{
timeInterval.Restart();
}
public TimeSpan Elapsed
{
get { return timeInterval.Elapsed; }
}
public static Message CreatePromptExceptionResponse(Message request, Exception exception)
{
return new Message
{
Category = request.Category,
Direction = Message.Directions.Response,
Result = Message.ResponseTypes.Error,
BodyObject = Response.ExceptionResponse(exception)
};
}
internal void DropExpiredMessage(ILogger logger, MessagingStatisticsGroup.Phase phase)
{
logger.LogWarning((int)ErrorCode.Messaging_DroppingExpiredMessage, "Dropped expired message during {Phase} phase. Message: {Message}", phase.ToString(), logger.IsEnabled(LogLevel.Trace) ? this.ToLongString() : this.ToString());
MessagingStatisticsGroup.OnMessageExpired(phase);
}
private static int BufferLength(List<ArraySegment<byte>> buffer)
{
var result = 0;
for (var i = 0; i < buffer.Count; i++)
{
result += buffer[i].Count;
}
return result;
}
[Serializable]
public class HeadersContainer
{
[Flags]
public enum Headers
{
NONE = 0,
ALWAYS_INTERLEAVE = 1 << 0,
CACHE_INVALIDATION_HEADER = 1 << 1,
CATEGORY = 1 << 2,
CORRELATION_ID = 1 << 3,
DEBUG_CONTEXT = 1 << 4,
DIRECTION = 1 << 5,
TIME_TO_LIVE = 1 << 6,
FORWARD_COUNT = 1 << 7,
NEW_GRAIN_TYPE = 1 << 8,
GENERIC_GRAIN_TYPE = 1 << 9,
RESULT = 1 << 10,
REJECTION_INFO = 1 << 11,
REJECTION_TYPE = 1 << 12,
READ_ONLY = 1 << 13,
RESEND_COUNT = 1 << 14, // Support removed. Value retained for backwards compatibility.
SENDING_ACTIVATION = 1 << 15,
SENDING_GRAIN = 1 <<16,
SENDING_SILO = 1 << 17,
IS_NEW_PLACEMENT = 1 << 18,
TARGET_ACTIVATION = 1 << 19,
TARGET_GRAIN = 1 << 20,
TARGET_SILO = 1 << 21,
TARGET_OBSERVER = 1 << 22,
IS_UNORDERED = 1 << 23,
REQUEST_CONTEXT = 1 << 24,
IS_RETURNED_FROM_REMOTE_CLUSTER = 1 << 25,
IS_USING_INTERFACE_VERSION = 1 << 26,
// transactions
TRANSACTION_INFO = 1 << 27,
IS_TRANSACTION_REQUIRED = 1 << 28,
CALL_CHAIN_ID = 1 << 29,
TRACE_CONTEXT = 1 << 30
// Do not add over int.MaxValue of these.
}
private Categories _category;
private Directions? _direction;
private bool _isReadOnly;
private bool _isAlwaysInterleave;
private bool _isUnordered;
private bool _isReturnedFromRemoteCluster;
private bool _isTransactionRequired;
private CorrelationId _id;
private int _forwardCount;
private SiloAddress _targetSilo;
private GrainId _targetGrain;
private ActivationId _targetActivation;
private GuidId _targetObserverId;
private SiloAddress _sendingSilo;
private GrainId _sendingGrain;
private ActivationId _sendingActivation;
private bool _isNewPlacement;
private bool _isUsingIfaceVersion;
private ResponseTypes _result;
private ITransactionInfo _transactionInfo;
private TimeSpan? _timeToLive;
private string _debugContext;
private List<ActivationAddress> _cacheInvalidationHeader;
private string _newGrainType;
private string _genericGrainType;
private RejectionTypes _rejectionType;
private string _rejectionInfo;
private Dictionary<string, object> _requestContextData;
private CorrelationId _callChainId;
private readonly DateTime _localCreationTime;
private TraceContext traceContext;
public HeadersContainer()
{
_localCreationTime = DateTime.UtcNow;
}
public TraceContext TraceContext
{
get { return traceContext; }
set { traceContext = value; }
}
public Categories Category
{
get { return _category; }
set
{
_category = value;
}
}
public Directions? Direction
{
get { return _direction; }
set
{
_direction = value;
}
}
public bool IsReadOnly
{
get { return _isReadOnly; }
set
{
_isReadOnly = value;
}
}
public bool IsAlwaysInterleave
{
get { return _isAlwaysInterleave; }
set
{
_isAlwaysInterleave = value;
}
}
public bool IsUnordered
{
get { return _isUnordered; }
set
{
_isUnordered = value;
}
}
public bool IsReturnedFromRemoteCluster
{
get { return _isReturnedFromRemoteCluster; }
set
{
_isReturnedFromRemoteCluster = value;
}
}
public bool IsTransactionRequired
{
get { return _isTransactionRequired; }
set
{
_isTransactionRequired = value;
}
}
public CorrelationId Id
{
get { return _id; }
set
{
_id = value;
}
}
public int ForwardCount
{
get { return _forwardCount; }
set
{
_forwardCount = value;
}
}
public SiloAddress TargetSilo
{
get { return _targetSilo; }
set
{
_targetSilo = value;
}
}
public GrainId TargetGrain
{
get { return _targetGrain; }
set
{
_targetGrain = value;
}
}
public ActivationId TargetActivation
{
get { return _targetActivation; }
set
{
_targetActivation = value;
}
}
public GuidId TargetObserverId
{
get { return _targetObserverId; }
set
{
_targetObserverId = value;
}
}
public SiloAddress SendingSilo
{
get { return _sendingSilo; }
set
{
_sendingSilo = value;
}
}
public GrainId SendingGrain
{
get { return _sendingGrain; }
set
{
_sendingGrain = value;
}
}
public ActivationId SendingActivation
{
get { return _sendingActivation; }
set
{
_sendingActivation = value;
}
}
public bool IsNewPlacement
{
get { return _isNewPlacement; }
set
{
_isNewPlacement = value;
}
}
public bool IsUsingIfaceVersion
{
get { return _isUsingIfaceVersion; }
set
{
_isUsingIfaceVersion = value;
}
}
public ResponseTypes Result
{
get { return _result; }
set
{
_result = value;
}
}
public ITransactionInfo TransactionInfo
{
get { return _transactionInfo; }
set
{
_transactionInfo = value;
}
}
public TimeSpan? TimeToLive
{
get
{
return _timeToLive - (DateTime.UtcNow - _localCreationTime);
}
set
{
_timeToLive = value;
}
}
public string DebugContext
{
get { return _debugContext; }
set
{
_debugContext = value;
}
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return _cacheInvalidationHeader; }
set
{
_cacheInvalidationHeader = value;
}
}
/// <summary>
/// Set by sender's placement logic when NewPlacementRequested is true
/// so that receiver knows desired grain type
/// </summary>
public string NewGrainType
{
get { return _newGrainType; }
set
{
_newGrainType = value;
}
}
/// <summary>
/// Set by caller's grain reference
/// </summary>
public string GenericGrainType
{
get { return _genericGrainType; }
set
{
_genericGrainType = value;
}
}
public RejectionTypes RejectionType
{
get { return _rejectionType; }
set
{
_rejectionType = value;
}
}
public string RejectionInfo
{
get { return _rejectionInfo; }
set
{
_rejectionInfo = value;
}
}
public Dictionary<string, object> RequestContextData
{
get { return _requestContextData; }
set
{
_requestContextData = value;
}
}
public CorrelationId CallChainId
{
get { return _callChainId; }
set
{
_callChainId = value;
}
}
internal Headers GetHeadersMask()
{
Headers headers = Headers.NONE;
if(Category != default(Categories))
headers = headers | Headers.CATEGORY;
headers = _direction == null ? headers & ~Headers.DIRECTION : headers | Headers.DIRECTION;
if (IsReadOnly)
headers = headers | Headers.READ_ONLY;
if (IsAlwaysInterleave)
headers = headers | Headers.ALWAYS_INTERLEAVE;
if(IsUnordered)
headers = headers | Headers.IS_UNORDERED;
headers = _id == null ? headers & ~Headers.CORRELATION_ID : headers | Headers.CORRELATION_ID;
if(_forwardCount != default (int))
headers = headers | Headers.FORWARD_COUNT;
headers = _targetSilo == null ? headers & ~Headers.TARGET_SILO : headers | Headers.TARGET_SILO;
headers = _targetGrain == null ? headers & ~Headers.TARGET_GRAIN : headers | Headers.TARGET_GRAIN;
headers = _targetActivation == null ? headers & ~Headers.TARGET_ACTIVATION : headers | Headers.TARGET_ACTIVATION;
headers = _targetObserverId == null ? headers & ~Headers.TARGET_OBSERVER : headers | Headers.TARGET_OBSERVER;
headers = _sendingSilo == null ? headers & ~Headers.SENDING_SILO : headers | Headers.SENDING_SILO;
headers = _sendingGrain == null ? headers & ~Headers.SENDING_GRAIN : headers | Headers.SENDING_GRAIN;
headers = _sendingActivation == null ? headers & ~Headers.SENDING_ACTIVATION : headers | Headers.SENDING_ACTIVATION;
headers = _isNewPlacement == default(bool) ? headers & ~Headers.IS_NEW_PLACEMENT : headers | Headers.IS_NEW_PLACEMENT;
headers = _isReturnedFromRemoteCluster == default(bool) ? headers & ~Headers.IS_RETURNED_FROM_REMOTE_CLUSTER : headers | Headers.IS_RETURNED_FROM_REMOTE_CLUSTER;
headers = _isUsingIfaceVersion == default(bool) ? headers & ~Headers.IS_USING_INTERFACE_VERSION : headers | Headers.IS_USING_INTERFACE_VERSION;
headers = _result == default(ResponseTypes)? headers & ~Headers.RESULT : headers | Headers.RESULT;
headers = _timeToLive == null ? headers & ~Headers.TIME_TO_LIVE : headers | Headers.TIME_TO_LIVE;
headers = string.IsNullOrEmpty(_debugContext) ? headers & ~Headers.DEBUG_CONTEXT : headers | Headers.DEBUG_CONTEXT;
headers = _cacheInvalidationHeader == null || _cacheInvalidationHeader.Count == 0 ? headers & ~Headers.CACHE_INVALIDATION_HEADER : headers | Headers.CACHE_INVALIDATION_HEADER;
headers = string.IsNullOrEmpty(_newGrainType) ? headers & ~Headers.NEW_GRAIN_TYPE : headers | Headers.NEW_GRAIN_TYPE;
headers = string.IsNullOrEmpty(GenericGrainType) ? headers & ~Headers.GENERIC_GRAIN_TYPE : headers | Headers.GENERIC_GRAIN_TYPE;
headers = _rejectionType == default(RejectionTypes) ? headers & ~Headers.REJECTION_TYPE : headers | Headers.REJECTION_TYPE;
headers = string.IsNullOrEmpty(_rejectionInfo) ? headers & ~Headers.REJECTION_INFO : headers | Headers.REJECTION_INFO;
headers = _requestContextData == null || _requestContextData.Count == 0 ? headers & ~Headers.REQUEST_CONTEXT : headers | Headers.REQUEST_CONTEXT;
headers = _callChainId == null ? headers & ~Headers.CALL_CHAIN_ID : headers | Headers.CALL_CHAIN_ID;
headers = traceContext == null? headers & ~Headers.TRACE_CONTEXT : headers | Headers.TRACE_CONTEXT;
headers = IsTransactionRequired ? headers | Headers.IS_TRANSACTION_REQUIRED : headers & ~Headers.IS_TRANSACTION_REQUIRED;
headers = _transactionInfo == null ? headers & ~Headers.TRANSACTION_INFO : headers | Headers.TRANSACTION_INFO;
return headers;
}
[CopierMethod]
public static object DeepCopier(object original, ICopyContext context)
{
return original;
}
[SerializerMethod]
public static void Serializer(object untypedInput, ISerializationContext context, Type expected)
{
HeadersContainer input = (HeadersContainer)untypedInput;
var sm = context.GetSerializationManager();
var headers = input.GetHeadersMask();
var writer = context.StreamWriter;
writer.Write((int)headers);
if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE)
{
var count = input.CacheInvalidationHeader.Count;
writer.Write(input.CacheInvalidationHeader.Count);
for (int i = 0; i < count; i++)
{
WriteObj(sm, context, typeof(ActivationAddress), input.CacheInvalidationHeader[i]);
}
}
if ((headers & Headers.CATEGORY) != Headers.NONE)
{
writer.Write((byte)input.Category);
}
if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE)
writer.Write(input.DebugContext);
if ((headers & Headers.DIRECTION) != Headers.NONE)
writer.Write((byte)input.Direction.Value);
if ((headers & Headers.TIME_TO_LIVE) != Headers.NONE)
writer.Write(input.TimeToLive.Value);
if ((headers & Headers.FORWARD_COUNT) != Headers.NONE)
writer.Write(input.ForwardCount);
if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE)
writer.Write(input.GenericGrainType);
if ((headers & Headers.CORRELATION_ID) != Headers.NONE)
writer.Write(input.Id);
if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE)
writer.Write(input.IsAlwaysInterleave);
if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE)
writer.Write(input.IsNewPlacement);
if ((headers & Headers.IS_RETURNED_FROM_REMOTE_CLUSTER) != Headers.NONE)
writer.Write(input.IsReturnedFromRemoteCluster);
// Nothing to do with Headers.IS_USING_INTERFACE_VERSION since the value in
// the header is sufficient
if ((headers & Headers.READ_ONLY) != Headers.NONE)
writer.Write(input.IsReadOnly);
if ((headers & Headers.IS_UNORDERED) != Headers.NONE)
writer.Write(input.IsUnordered);
if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE)
writer.Write(input.NewGrainType);
if ((headers & Headers.REJECTION_INFO) != Headers.NONE)
writer.Write(input.RejectionInfo);
if ((headers & Headers.REJECTION_TYPE) != Headers.NONE)
writer.Write((byte)input.RejectionType);
if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE)
{
var requestData = input.RequestContextData;
var count = requestData.Count;
writer.Write(count);
foreach (var d in requestData)
{
writer.Write(d.Key);
SerializationManager.SerializeInner(d.Value, context, typeof(object));
}
}
if ((headers & Headers.RESULT) != Headers.NONE)
writer.Write((byte)input.Result);
if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE)
{
writer.Write(input.SendingActivation);
}
if ((headers & Headers.SENDING_GRAIN) != Headers.NONE)
{
writer.Write(input.SendingGrain);
}
if ((headers & Headers.SENDING_SILO) != Headers.NONE)
{
writer.Write(input.SendingSilo);
}
if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE)
{
writer.Write(input.TargetActivation);
}
if ((headers & Headers.TARGET_GRAIN) != Headers.NONE)
{
writer.Write(input.TargetGrain);
}
if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE)
{
WriteObj(sm, context, typeof(GuidId), input.TargetObserverId);
}
if ((headers & Headers.CALL_CHAIN_ID) != Headers.NONE)
{
writer.Write(input.CallChainId);
}
if ((headers & Headers.TARGET_SILO) != Headers.NONE)
{
writer.Write(input.TargetSilo);
}
if ((headers & Headers.TRANSACTION_INFO) != Headers.NONE)
SerializationManager.SerializeInner(input.TransactionInfo, context, typeof(ITransactionInfo));
if ((headers & Headers.TRACE_CONTEXT) != Headers.NONE)
{
SerializationManager.SerializeInner(input.traceContext, context, typeof(TraceContext));
}
}
[DeserializerMethod]
public static object Deserializer(Type expected, IDeserializationContext context)
{
var sm = context.GetSerializationManager();
var result = new HeadersContainer();
var reader = context.StreamReader;
context.RecordObject(result);
var headers = (Headers)reader.ReadInt();
if ((headers & Headers.CACHE_INVALIDATION_HEADER) != Headers.NONE)
{
var n = reader.ReadInt();
if (n > 0)
{
var list = result.CacheInvalidationHeader = new List<ActivationAddress>(n);
for (int i = 0; i < n; i++)
{
list.Add((ActivationAddress)ReadObj(sm, typeof(ActivationAddress), context));
}
}
}
if ((headers & Headers.CATEGORY) != Headers.NONE)
result.Category = (Categories)reader.ReadByte();
if ((headers & Headers.DEBUG_CONTEXT) != Headers.NONE)
result.DebugContext = reader.ReadString();
if ((headers & Headers.DIRECTION) != Headers.NONE)
result.Direction = (Message.Directions)reader.ReadByte();
if ((headers & Headers.TIME_TO_LIVE) != Headers.NONE)
result.TimeToLive = reader.ReadTimeSpan();
if ((headers & Headers.FORWARD_COUNT) != Headers.NONE)
result.ForwardCount = reader.ReadInt();
if ((headers & Headers.GENERIC_GRAIN_TYPE) != Headers.NONE)
result.GenericGrainType = reader.ReadString();
if ((headers & Headers.CORRELATION_ID) != Headers.NONE)
result.Id = (Orleans.Runtime.CorrelationId)ReadObj(sm, typeof(CorrelationId), context);
if ((headers & Headers.ALWAYS_INTERLEAVE) != Headers.NONE)
result.IsAlwaysInterleave = ReadBool(reader);
if ((headers & Headers.IS_NEW_PLACEMENT) != Headers.NONE)
result.IsNewPlacement = ReadBool(reader);
if ((headers & Headers.IS_RETURNED_FROM_REMOTE_CLUSTER) != Headers.NONE)
result.IsReturnedFromRemoteCluster = ReadBool(reader);
if ((headers & Headers.IS_USING_INTERFACE_VERSION) != Headers.NONE)
result.IsUsingIfaceVersion = true;
if ((headers & Headers.READ_ONLY) != Headers.NONE)
result.IsReadOnly = ReadBool(reader);
if ((headers & Headers.IS_UNORDERED) != Headers.NONE)
result.IsUnordered = ReadBool(reader);
if ((headers & Headers.NEW_GRAIN_TYPE) != Headers.NONE)
result.NewGrainType = reader.ReadString();
if ((headers & Headers.REJECTION_INFO) != Headers.NONE)
result.RejectionInfo = reader.ReadString();
if ((headers & Headers.REJECTION_TYPE) != Headers.NONE)
result.RejectionType = (RejectionTypes)reader.ReadByte();
if ((headers & Headers.REQUEST_CONTEXT) != Headers.NONE)
{
var c = reader.ReadInt();
var requestData = new Dictionary<string, object>(c);
for (int i = 0; i < c; i++)
{
requestData[reader.ReadString()] = SerializationManager.DeserializeInner(null, context);
}
result.RequestContextData = requestData;
}
// Read for backwards compatibility but ignore the value.
if ((headers & Headers.RESEND_COUNT) != Headers.NONE) reader.ReadInt();
if ((headers & Headers.RESULT) != Headers.NONE)
result.Result = (Orleans.Runtime.Message.ResponseTypes)reader.ReadByte();
if ((headers & Headers.SENDING_ACTIVATION) != Headers.NONE)
result.SendingActivation = reader.ReadActivationId();
if ((headers & Headers.SENDING_GRAIN) != Headers.NONE)
result.SendingGrain = reader.ReadGrainId();
if ((headers & Headers.SENDING_SILO) != Headers.NONE)
result.SendingSilo = reader.ReadSiloAddress();
if ((headers & Headers.TARGET_ACTIVATION) != Headers.NONE)
result.TargetActivation = reader.ReadActivationId();
if ((headers & Headers.TARGET_GRAIN) != Headers.NONE)
result.TargetGrain = reader.ReadGrainId();
if ((headers & Headers.TARGET_OBSERVER) != Headers.NONE)
result.TargetObserverId = (GuidId)ReadObj(sm, typeof(GuidId), context);
if ((headers & Headers.CALL_CHAIN_ID) != Headers.NONE)
result.CallChainId = reader.ReadCorrelationId();
if ((headers & Headers.TARGET_SILO) != Headers.NONE)
result.TargetSilo = reader.ReadSiloAddress();
result.IsTransactionRequired = (headers & Headers.IS_TRANSACTION_REQUIRED) != Headers.NONE;
if ((headers & Headers.TRANSACTION_INFO) != Headers.NONE)
result.TransactionInfo = SerializationManager.DeserializeInner<ITransactionInfo>(context);
if ((headers & Headers.TRACE_CONTEXT) != Headers.NONE)
result.TraceContext = SerializationManager.DeserializeInner<TraceContext>(context);
return result;
}
private static bool ReadBool(IBinaryTokenStreamReader stream)
{
return stream.ReadByte() == (byte) SerializationTokenType.True;
}
private static void WriteObj(SerializationManager sm, ISerializationContext context, Type type, object input)
{
var ser = sm.GetSerializer(type);
ser.Invoke(input, context, type);
}
private static object ReadObj(SerializationManager sm, Type t, IDeserializationContext context)
{
var des = sm.GetDeserializer(t);
return des.Invoke(t, context);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Cci;
using Microsoft.Cci.Extensions;
using Microsoft.Cci.Filters;
using Microsoft.Cci.Writers;
using Microsoft.Cci.Writers.Syntax;
using Microsoft.Fx.CommandLine;
namespace GenAPI
{
internal class Program
{
private static int Main(string[] args)
{
ParseCommandLine(args);
HostEnvironment host = new HostEnvironment();
host.UnableToResolve += host_UnableToResolve;
host.UnifyToLibPath = true;
if (!string.IsNullOrWhiteSpace(s_libPath))
host.AddLibPaths(HostEnvironment.SplitPaths(s_libPath));
IEnumerable<IAssembly> assemblies = host.LoadAssemblies(HostEnvironment.SplitPaths(s_assembly));
if (!assemblies.Any())
{
Console.WriteLine("ERROR: Failed to load any assemblies from '{0}'", s_assembly);
return 1;
}
string headerText = GetHeaderText();
bool loopPerAssembly = Directory.Exists(s_out);
if (loopPerAssembly)
{
foreach (var assembly in assemblies)
{
using (TextWriter output = GetOutput(GetFilename(assembly)))
using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output))
{
if (headerText != null)
output.Write(headerText);
ICciWriter writer = GetWriter(output, syntaxWriter);
writer.WriteAssemblies(new IAssembly[] { assembly });
}
}
}
else
{
using (TextWriter output = GetOutput())
using (IStyleSyntaxWriter syntaxWriter = GetSyntaxWriter(output))
{
if (headerText != null)
output.Write(headerText);
ICciWriter writer = GetWriter(output, syntaxWriter);
writer.WriteAssemblies(assemblies);
}
}
return 0;
}
private static void host_UnableToResolve(object sender, UnresolvedReference<IUnit, AssemblyIdentity> e)
{
Console.WriteLine("Unable to resolve assembly '{0}' referenced by '{1}'.", e.Unresolved.ToString(), e.Referrer.ToString());
}
private static string GetHeaderText()
{
if (!String.IsNullOrEmpty(s_headerFile))
{
if (!File.Exists(s_headerFile))
{
Console.WriteLine("ERROR: header file '{0}' does not exist", s_headerFile);
}
using (TextReader headerText = File.OpenText(s_headerFile))
{
return headerText.ReadToEnd();
}
}
return null;
}
private static TextWriter GetOutput(string filename = "")
{
// If this is a null, empty, whitespace, or a directory use console
if (string.IsNullOrWhiteSpace(s_out))
return Console.Out;
if (Directory.Exists(s_out) && !string.IsNullOrEmpty(filename))
{
return File.CreateText(Path.Combine(s_out, filename));
}
return File.CreateText(s_out);
}
private static string GetFilename(IAssembly assembly)
{
string name = assembly.Name.Value;
switch (s_writer)
{
case WriterType.DocIds:
case WriterType.TypeForwards:
return name + ".txt";
case WriterType.TypeList:
case WriterType.CSDecl:
default:
switch (s_syntaxWriter)
{
case SyntaxWriterType.Xml:
return name + ".xml";
case SyntaxWriterType.Html:
return name + ".html";
case SyntaxWriterType.Text:
default:
return name + ".cs";
}
}
}
private static ICciWriter GetWriter(TextWriter output, IStyleSyntaxWriter syntaxWriter)
{
ICciFilter filter = GetFilter();
switch (s_writer)
{
case WriterType.DocIds:
return new DocumentIdWriter(output, filter);
case WriterType.TypeForwards:
return new TypeForwardWriter(output, filter)
{
IncludeForwardedTypes = true
};
case WriterType.TypeList:
return new TypeListWriter(syntaxWriter, filter);
default:
case WriterType.CSDecl:
{
CSharpWriter writer = new CSharpWriter(syntaxWriter, filter, s_apiOnly);
writer.IncludeSpaceBetweenMemberGroups = writer.IncludeMemberGroupHeadings = s_memberHeadings;
writer.HighlightBaseMembers = s_hightlightBaseMembers;
writer.HighlightInterfaceMembers = s_hightlightInterfaceMembers;
writer.PutBraceOnNewLine = true;
writer.PlatformNotSupportedExceptionMessage = s_exceptionMessage;
writer.IncludeGlobalPrefixForCompilation = s_global;
return writer;
}
}
}
private static ICciFilter GetFilter()
{
ICciFilter includeFilter = null;
if (string.IsNullOrWhiteSpace(s_apiList))
{
if (s_all)
{
includeFilter = new IncludeAllFilter();
}
else
{
includeFilter = new PublicOnlyCciFilter(excludeAttributes: s_apiOnly);
}
}
else
{
includeFilter = new DocIdIncludeListFilter(s_apiList);
}
if (!string.IsNullOrWhiteSpace(s_excludeApiList))
{
includeFilter = new IntersectionFilter(includeFilter, new DocIdExcludeListFilter(s_excludeApiList));
}
if (!string.IsNullOrWhiteSpace(s_excludeAttributesList))
{
includeFilter = new IntersectionFilter(includeFilter, new ExcludeAttributesFilter(s_excludeAttributesList));
}
return includeFilter;
}
private static IStyleSyntaxWriter GetSyntaxWriter(TextWriter output)
{
if (s_writer != WriterType.CSDecl && s_writer != WriterType.TypeList)
return null;
switch (s_syntaxWriter)
{
case SyntaxWriterType.Xml:
return new OpenXmlSyntaxWriter(output);
case SyntaxWriterType.Html:
return new HtmlSyntaxWriter(output);
case SyntaxWriterType.Text:
default:
return new TextSyntaxWriter(output) { SpacesInIndent = 4 };
}
}
private enum WriterType
{
CSDecl,
DocIds,
TypeForwards,
TypeList,
}
private enum SyntaxWriterType
{
Text,
Html,
Xml
}
private static string s_assembly;
private static WriterType s_writer = WriterType.CSDecl;
private static SyntaxWriterType s_syntaxWriter = SyntaxWriterType.Text;
private static string s_apiList;
private static string s_excludeApiList;
private static string s_excludeAttributesList;
private static string s_headerFile;
private static string s_out;
private static string s_libPath;
private static bool s_apiOnly;
private static bool s_memberHeadings;
private static bool s_hightlightBaseMembers;
private static bool s_hightlightInterfaceMembers;
private static bool s_all;
private static string s_exceptionMessage;
private static bool s_global;
private static void ParseCommandLine(string[] args)
{
CommandLineParser.ParseForConsoleApplication((parser) =>
{
parser.DefineOptionalQualifier("libPath", ref s_libPath, "Delimited (',' or ';') set of paths to use for resolving assembly references");
parser.DefineAliases("apiList", "al");
parser.DefineOptionalQualifier("apiList", ref s_apiList, "(-al) Specify a api list in the DocId format of which APIs to include.");
parser.DefineAliases("excludeApiList", "xal");
parser.DefineOptionalQualifier("excludeApiList", ref s_excludeApiList, "(-xal) Specify a api list in the DocId format of which APIs to exclude.");
parser.DefineOptionalQualifier("excludeAttributesList", ref s_excludeAttributesList, "Specify a list in the DocId format of which attributes should be excluded from being applied on apis.");
parser.DefineAliases("writer", "w");
parser.DefineOptionalQualifier<WriterType>("writer", ref s_writer, "(-w) Specify the writer type to use.");
parser.DefineAliases("syntax", "s");
parser.DefineOptionalQualifier<SyntaxWriterType>("syntax", ref s_syntaxWriter, "(-s) Specific the syntax writer type. Only used if the writer is CSDecl");
parser.DefineOptionalQualifier("out", ref s_out, "Output path. Default is the console. Can specify an existing directory as well and then a file will be created for each assembly with the matching name of the assembly.");
parser.DefineAliases("headerFile", "h");
parser.DefineOptionalQualifier("headerFile", ref s_headerFile, "(-h) Specify a file with header content to prepend to output.");
parser.DefineAliases("apiOnly", "api");
parser.DefineOptionalQualifier("apiOnly", ref s_apiOnly, "(-api) [CSDecl] Include only API's not CS code that compiles.");
parser.DefineOptionalQualifier("all", ref s_all, "Include all API's not just public APIs. Default is public only.");
parser.DefineAliases("memberHeadings", "mh");
parser.DefineOptionalQualifier("memberHeadings", ref s_memberHeadings, "(-mh) [CSDecl] Include member headings for each type of member.");
parser.DefineAliases("hightlightBaseMembers", "hbm");
parser.DefineOptionalQualifier("hightlightBaseMembers", ref s_hightlightBaseMembers, "(-hbm) [CSDecl] Highlight overridden base members.");
parser.DefineAliases("hightlightInterfaceMembers", "him");
parser.DefineOptionalQualifier("hightlightInterfaceMembers", ref s_hightlightInterfaceMembers, "(-him) [CSDecl] Highlight interface implementation members.");
parser.DefineAliases("throw", "t");
parser.DefineOptionalQualifier("throw", ref s_exceptionMessage, "(-t) Method bodies should throw PlatformNotSupportedException.");
parser.DefineAliases("global", "g");
parser.DefineOptionalQualifier("global", ref s_global, "(-g) Include global prefix for compilation.");
parser.DefineQualifier("assembly", ref s_assembly, "Path for an specific assembly or a directory to get all assemblies.");
}, args);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Xml.XPath;
namespace MS.Internal.Xml.Cache
{
/// <summary>
/// Library of XPathNode helper routines.
/// </summary>
internal abstract class XPathNodeHelper
{
/// <summary>
/// Return chain of namespace nodes. If specified node has no local namespaces, then 0 will be
/// returned. Otherwise, the first node in the chain is guaranteed to be a local namespace (its
/// parent is this node). Subsequent nodes may not have the same node as parent, so the caller will
/// need to test the parent in order to terminate a search that processes only local namespaces.
/// </summary>
public static int GetLocalNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp)
{
if (pageElem[idxElem].HasNamespaceDecls)
{
// Only elements have namespace nodes
Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element);
return pageElem[idxElem].Document.LookupNamespaces(pageElem, idxElem, out pageNmsp);
}
pageNmsp = null;
return 0;
}
/// <summary>
/// Return chain of in-scope namespace nodes for nodes of type Element. Nodes in the chain might not
/// have this element as their parent. Since the xmlns:xml namespace node is always in scope, this
/// method will never return 0 if the specified node is an element.
/// </summary>
public static int GetInScopeNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp)
{
XPathDocument doc;
// Only elements have namespace nodes
if (pageElem[idxElem].NodeType == XPathNodeType.Element)
{
doc = pageElem[idxElem].Document;
// Walk ancestors, looking for an ancestor that has at least one namespace declaration
while (!pageElem[idxElem].HasNamespaceDecls)
{
idxElem = pageElem[idxElem].GetParent(out pageElem);
if (idxElem == 0)
{
// There are no namespace nodes declared on ancestors, so return xmlns:xml node
return doc.GetXmlNamespaceNode(out pageNmsp);
}
}
// Return chain of in-scope namespace nodes
return doc.LookupNamespaces(pageElem, idxElem, out pageNmsp);
}
pageNmsp = null;
return 0;
}
/// <summary>
/// Return the first attribute of the specified node. If no attribute exist, do not
/// set pageNode or idxNode and return false.
/// </summary>
public static bool GetFirstAttribute(ref XPathNode[] pageNode, ref int idxNode)
{
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (pageNode[idxNode].HasAttribute)
{
GetChild(ref pageNode, ref idxNode);
Debug.Assert(pageNode[idxNode].NodeType == XPathNodeType.Attribute);
return true;
}
return false;
}
/// <summary>
/// Return the next attribute sibling of the specified node. If the node is not itself an
/// attribute, or if there are no siblings, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetNextAttribute(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page;
int idx;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
idx = pageNode[idxNode].GetSibling(out page);
if (idx != 0 && page[idx].NodeType == XPathNodeType.Attribute)
{
pageNode = page;
idxNode = idx;
return true;
}
return false;
}
/// <summary>
/// Return the first content-typed child of the specified node. If the node has no children, or
/// if the node is not content-typed, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentChild(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (page[idx].HasContentChild)
{
GetChild(ref page, ref idx);
// Skip past attribute children
while (page[idx].NodeType == XPathNodeType.Attribute)
{
idx = page[idx].GetSibling(out page);
Debug.Assert(idx != 0);
}
pageNode = page;
idxNode = idx;
return true;
}
return false;
}
/// <summary>
/// Return the next content-typed sibling of the specified node. If the node has no siblings, or
/// if the node is not content-typed, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentSibling(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (!page[idx].IsAttrNmsp)
{
idx = page[idx].GetSibling(out page);
if (idx != 0)
{
pageNode = page;
idxNode = idx;
return true;
}
}
return false;
}
/// <summary>
/// Return the parent of the specified node. If the node has no parent, do not set pageNode
/// or idxNode and return false.
/// </summary>
public static bool GetParent(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
idx = page[idx].GetParent(out page);
if (idx != 0)
{
pageNode = page;
idxNode = idx;
return true;
}
return false;
}
/// <summary>
/// Return a location integer that can be easily compared with other locations from the same document
/// in order to determine the relative document order of two nodes.
/// </summary>
public static int GetLocation(XPathNode[] pageNode, int idxNode)
{
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
Debug.Assert(idxNode <= UInt16.MaxValue);
Debug.Assert(pageNode[0].PageInfo.PageNumber <= Int16.MaxValue);
return (pageNode[0].PageInfo.PageNumber << 16) | idxNode;
}
/// <summary>
/// Return the first element child of the specified node that has the specified name. If no such child exists,
/// then do not set pageNode or idxNode and return false. Assume that the localName has been atomized with respect
/// to this document's name table, but not the namespaceName.
/// </summary>
public static bool GetElementChild(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Only check children if at least one element child exists
if (page[idx].HasElementChild)
{
GetChild(ref page, ref idx);
Debug.Assert(idx != 0);
// Find element with specified localName and namespaceName
do
{
if (page[idx].ElementMatch(localName, namespaceName))
{
pageNode = page;
idxNode = idx;
return true;
}
idx = page[idx].GetSibling(out page);
}
while (idx != 0);
}
return false;
}
/// <summary>
/// Return a following sibling element of the specified node that has the specified name. If no such
/// sibling exists, or if the node is not content-typed, then do not set pageNode or idxNode and
/// return false. Assume that the localName has been atomized with respect to this document's name table,
/// but not the namespaceName.
/// </summary>
public static bool GetElementSibling(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Elements should not be returned as "siblings" of attributes (namespaces don't link to elements, so don't need to check them)
if (page[idx].NodeType != XPathNodeType.Attribute)
{
while (true)
{
idx = page[idx].GetSibling(out page);
if (idx == 0)
break;
if (page[idx].ElementMatch(localName, namespaceName))
{
pageNode = page;
idxNode = idx;
return true;
}
}
}
return false;
}
/// <summary>
/// Return the first child of the specified node that has the specified type (must be a content type). If no such
/// child exists, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentChild(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ)
{
XPathNode[] page = pageNode;
int idx = idxNode;
int mask;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Only check children if at least one content-typed child exists
if (page[idx].HasContentChild)
{
mask = XPathNavigator.GetContentKindMask(typ);
GetChild(ref page, ref idx);
do
{
if (((1 << (int)page[idx].NodeType) & mask) != 0)
{
// Never return attributes, as Attribute is not a content type
if (typ == XPathNodeType.Attribute)
return false;
pageNode = page;
idxNode = idx;
return true;
}
idx = page[idx].GetSibling(out page);
}
while (idx != 0);
}
return false;
}
/// <summary>
/// Return a following sibling of the specified node that has the specified type. If no such
/// sibling exists, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetContentSibling(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ)
{
XPathNode[] page = pageNode;
int idx = idxNode;
int mask = XPathNavigator.GetContentKindMask(typ);
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (page[idx].NodeType != XPathNodeType.Attribute)
{
while (true)
{
idx = page[idx].GetSibling(out page);
if (idx == 0)
break;
if (((1 << (int)page[idx].NodeType) & mask) != 0)
{
Debug.Assert(typ != XPathNodeType.Attribute && typ != XPathNodeType.Namespace);
pageNode = page;
idxNode = idx;
return true;
}
}
}
return false;
}
/// <summary>
/// Return the first preceding sibling of the specified node. If no such sibling exists, then do not set
/// pageNode or idxNode and return false.
/// </summary>
public static bool GetPreviousContentSibling(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] pageParent = pageNode, pagePrec, pageAnc;
int idxParent = idxNode, idxPrec, idxAnc;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
Debug.Assert(pageNode[idxNode].NodeType != XPathNodeType.Attribute);
// Since nodes are laid out in document order on pages, the algorithm is:
// 1. Get parent of current node
// 2. If no parent, then there is no previous sibling, so return false
// 3. Get node that immediately precedes the current node in document order
// 4. If preceding node is parent, then there is no previous sibling, so return false
// 5. Walk ancestors of preceding node, until parent of current node is found
idxParent = pageParent[idxParent].GetParent(out pageParent);
if (idxParent != 0)
{
idxPrec = idxNode - 1;
if (idxPrec == 0)
{
// Need to get previous page
pagePrec = pageNode[0].PageInfo.PreviousPage;
idxPrec = pagePrec.Length - 1;
}
else
{
// Previous node is on the same page
pagePrec = pageNode;
}
// If parent node is previous node, then no previous sibling
if (idxParent == idxPrec && pageParent == pagePrec)
return false;
// Find child of parent node by walking ancestor chain
pageAnc = pagePrec;
idxAnc = idxPrec;
do
{
pagePrec = pageAnc;
idxPrec = idxAnc;
idxAnc = pageAnc[idxAnc].GetParent(out pageAnc);
Debug.Assert(idxAnc != 0 && pageAnc != null);
}
while (idxAnc != idxParent || pageAnc != pageParent);
// We found the previous sibling, but if it's an attribute node, then return false
if (pagePrec[idxPrec].NodeType != XPathNodeType.Attribute)
{
pageNode = pagePrec;
idxNode = idxPrec;
return true;
}
}
return false;
}
/// <summary>
/// Return a previous sibling element of the specified node that has the specified name. If no such
/// sibling exists, or if the node is not content-typed, then do not set pageNode or idxNode and
/// return false. Assume that the localName has been atomized with respect to this document's name table,
/// but not the namespaceName.
/// </summary>
public static bool GetPreviousElementSibling(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
if (page[idx].NodeType != XPathNodeType.Attribute)
{
while (true)
{
if (!GetPreviousContentSibling(ref page, ref idx))
break;
if (page[idx].ElementMatch(localName, namespaceName))
{
pageNode = page;
idxNode = idx;
return true;
}
}
}
return false;
}
/// <summary>
/// Return a previous sibling of the specified node that has the specified type. If no such
/// sibling exists, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetPreviousContentSibling(ref XPathNode[] pageNode, ref int idxNode, XPathNodeType typ)
{
XPathNode[] page = pageNode;
int idx = idxNode;
int mask = XPathNavigator.GetContentKindMask(typ);
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
while (true)
{
if (!GetPreviousContentSibling(ref page, ref idx))
break;
if (((1 << (int)page[idx].NodeType) & mask) != 0)
{
pageNode = page;
idxNode = idx;
return true;
}
}
return false;
}
/// <summary>
/// Return the attribute of the specified node that has the specified name. If no such attribute exists,
/// then do not set pageNode or idxNode and return false. Assume that the localName has been atomized with respect
/// to this document's name table, but not the namespaceName.
/// </summary>
public static bool GetAttribute(ref XPathNode[] pageNode, ref int idxNode, string localName, string namespaceName)
{
XPathNode[] page = pageNode;
int idx = idxNode;
Debug.Assert(pageNode != null && idxNode != 0, "Cannot pass null argument(s)");
// Find attribute with specified localName and namespaceName
if (page[idx].HasAttribute)
{
GetChild(ref page, ref idx);
do
{
if (page[idx].NameMatch(localName, namespaceName))
{
pageNode = page;
idxNode = idx;
return true;
}
idx = page[idx].GetSibling(out page);
}
while (idx != 0 && page[idx].NodeType == XPathNodeType.Attribute);
}
return false;
}
/// <summary>
/// Get the next non-virtual (not collapsed text, not namespaces) node that follows the specified node in document order.
/// If no such node exists, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetFollowing(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
do
{
// Next non-virtual node is in next slot within the page
if (++idx < page[0].PageInfo.NodeCount)
{
pageNode = page;
idxNode = idx;
return true;
}
// Otherwise, start at the beginning of the next page
page = page[0].PageInfo.NextPage;
idx = 0;
}
while (page != null);
return false;
}
/// <summary>
/// Get the next element node that:
/// 1. Follows the current node in document order (includes descendants, unlike XPath following axis)
/// 2. Precedes the ending node in document order (if pageEnd is null, then all following nodes in the document are considered)
/// 3. Has the specified QName
/// If no such element exists, then do not set pageCurrent or idxCurrent and return false.
/// Assume that the localName has been atomized with respect to this document's name table, but not the namespaceName.
/// </summary>
public static bool GetElementFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd, string localName, string namespaceName)
{
XPathNode[] page = pageCurrent;
int idx = idxCurrent;
Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)");
// If current node is an element having a matching name,
if (page[idx].NodeType == XPathNodeType.Element && (object)page[idx].LocalName == (object)localName)
{
// Then follow similar element name pointers
int idxPageEnd = 0;
int idxPageCurrent;
if (pageEnd != null)
{
idxPageEnd = pageEnd[0].PageInfo.PageNumber;
idxPageCurrent = page[0].PageInfo.PageNumber;
// If ending node is <= starting node in document order, then scan to end of document
if (idxPageCurrent > idxPageEnd || (idxPageCurrent == idxPageEnd && idx >= idxEnd))
pageEnd = null;
}
while (true)
{
idx = page[idx].GetSimilarElement(out page);
if (idx == 0)
break;
// Only scan to ending node
if (pageEnd != null)
{
idxPageCurrent = page[0].PageInfo.PageNumber;
if (idxPageCurrent > idxPageEnd)
break;
if (idxPageCurrent == idxPageEnd && idx >= idxEnd)
break;
}
if ((object)page[idx].LocalName == (object)localName && page[idx].NamespaceUri == namespaceName)
goto FoundNode;
}
return false;
}
// Since nodes are laid out in document order on pages, scan them sequentially
// rather than following links.
idx++;
do
{
if ((object)page == (object)pageEnd && idx <= idxEnd)
{
// Only scan to termination point
while (idx != idxEnd)
{
if (page[idx].ElementMatch(localName, namespaceName))
goto FoundNode;
idx++;
}
break;
}
else
{
// Scan all nodes in the page
while (idx < page[0].PageInfo.NodeCount)
{
if (page[idx].ElementMatch(localName, namespaceName))
goto FoundNode;
idx++;
}
}
page = page[0].PageInfo.NextPage;
idx = 1;
}
while (page != null);
return false;
FoundNode:
// Found match
pageCurrent = page;
idxCurrent = idx;
return true;
}
/// <summary>
/// Get the next node that:
/// 1. Follows the current node in document order (includes descendants, unlike XPath following axis)
/// 2. Precedes the ending node in document order (if pageEnd is null, then all following nodes in the document are considered)
/// 3. Has the specified XPathNodeType (but Attributes and Namespaces never match)
/// If no such node exists, then do not set pageCurrent or idxCurrent and return false.
/// </summary>
public static bool GetContentFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd, XPathNodeType typ)
{
XPathNode[] page = pageCurrent;
int idx = idxCurrent;
int mask = XPathNavigator.GetContentKindMask(typ);
Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)");
Debug.Assert(typ != XPathNodeType.Text, "Text should be handled by GetTextFollowing in order to take into account collapsed text.");
Debug.Assert(page[idx].NodeType != XPathNodeType.Attribute, "Current node should never be an attribute or namespace--caller should handle this case.");
// Since nodes are laid out in document order on pages, scan them sequentially
// rather than following sibling/child/parent links.
idx++;
do
{
if ((object)page == (object)pageEnd && idx <= idxEnd)
{
// Only scan to termination point
while (idx != idxEnd)
{
if (((1 << (int)page[idx].NodeType) & mask) != 0)
goto FoundNode;
idx++;
}
break;
}
else
{
// Scan all nodes in the page
while (idx < page[0].PageInfo.NodeCount)
{
if (((1 << (int)page[idx].NodeType) & mask) != 0)
goto FoundNode;
idx++;
}
}
page = page[0].PageInfo.NextPage;
idx = 1;
}
while (page != null);
return false;
FoundNode:
Debug.Assert(!page[idx].IsAttrNmsp, "GetContentFollowing should never return attributes or namespaces.");
// Found match
pageCurrent = page;
idxCurrent = idx;
return true;
}
/// <summary>
/// Scan all nodes that follow the current node in document order, but precede the ending node in document order.
/// Return two types of nodes with non-null text:
/// 1. Element parents of collapsed text nodes (since it is the element parent that has the collapsed text)
/// 2. Non-collapsed text nodes
/// If no such node exists, then do not set pageCurrent or idxCurrent and return false.
/// </summary>
public static bool GetTextFollowing(ref XPathNode[] pageCurrent, ref int idxCurrent, XPathNode[] pageEnd, int idxEnd)
{
XPathNode[] page = pageCurrent;
int idx = idxCurrent;
Debug.Assert(pageCurrent != null && idxCurrent != 0, "Cannot pass null argument(s)");
Debug.Assert(!page[idx].IsAttrNmsp, "Current node should never be an attribute or namespace--caller should handle this case.");
// Since nodes are laid out in document order on pages, scan them sequentially
// rather than following sibling/child/parent links.
idx++;
do
{
if ((object)page == (object)pageEnd && idx <= idxEnd)
{
// Only scan to termination point
while (idx != idxEnd)
{
if (page[idx].IsText || (page[idx].NodeType == XPathNodeType.Element && page[idx].HasCollapsedText))
goto FoundNode;
idx++;
}
break;
}
else
{
// Scan all nodes in the page
while (idx < page[0].PageInfo.NodeCount)
{
if (page[idx].IsText || (page[idx].NodeType == XPathNodeType.Element && page[idx].HasCollapsedText))
goto FoundNode;
idx++;
}
}
page = page[0].PageInfo.NextPage;
idx = 1;
}
while (page != null);
return false;
FoundNode:
// Found match
pageCurrent = page;
idxCurrent = idx;
return true;
}
/// <summary>
/// Get the next non-virtual (not collapsed text, not namespaces) node that follows the specified node in document order,
/// but is not a descendant. If no such node exists, then do not set pageNode or idxNode and return false.
/// </summary>
public static bool GetNonDescendant(ref XPathNode[] pageNode, ref int idxNode)
{
XPathNode[] page = pageNode;
int idx = idxNode;
// Get page, idx at which to end sequential scan of nodes
do
{
// If the current node has a sibling,
if (page[idx].HasSibling)
{
// Then that is the first non-descendant
pageNode = page;
idxNode = page[idx].GetSibling(out pageNode);
return true;
}
// Otherwise, try finding a sibling at the parent level
idx = page[idx].GetParent(out page);
}
while (idx != 0);
return false;
}
/// <summary>
/// Return the page and index of the first child (attribute or content) of the specified node.
/// </summary>
private static void GetChild(ref XPathNode[] pageNode, ref int idxNode)
{
Debug.Assert(pageNode[idxNode].HasAttribute || pageNode[idxNode].HasContentChild, "Caller must check HasAttribute/HasContentChild on parent before calling GetChild.");
Debug.Assert(pageNode[idxNode].HasAttribute || !pageNode[idxNode].HasCollapsedText, "Text child is virtualized and therefore is not present in the physical node page.");
if (++idxNode >= pageNode.Length)
{
// Child is first node on next page
pageNode = pageNode[0].PageInfo.NextPage;
idxNode = 1;
}
// Else child is next node on this page
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers.Binary;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace System.Collections
{
// A vector of bits. Use this to store bits efficiently, without having to do bit
// shifting yourself.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class BitArray : ICollection, ICloneable
{
private int[] m_array; // Do not rename (binary serialization)
private int m_length; // Do not rename (binary serialization)
private int _version; // Do not rename (binary serialization)
private const int _ShrinkThreshold = 256;
/*=========================================================================
** Allocates space to hold length bit values. All of the values in the bit
** array are set to false.
**
** Exceptions: ArgumentException if length < 0.
=========================================================================*/
public BitArray(int length)
: this(length, false)
{
}
/*=========================================================================
** Allocates space to hold length bit values. All of the values in the bit
** array are set to defaultValue.
**
** Exceptions: ArgumentOutOfRangeException if length < 0.
=========================================================================*/
public BitArray(int length, bool defaultValue)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), length, SR.ArgumentOutOfRange_NeedNonNegNum);
}
m_array = new int[GetInt32ArrayLengthFromBitLength(length)];
m_length = length;
if (defaultValue)
{
m_array.AsSpan().Fill(-1);
}
_version = 0;
}
/*=========================================================================
** Allocates space to hold the bit values in bytes. bytes[0] represents
** bits 0 - 7, bytes[1] represents bits 8 - 15, etc. The LSB of each byte
** represents the lowest index value; bytes[0] & 1 represents bit 0,
** bytes[0] & 2 represents bit 1, bytes[0] & 4 represents bit 2, etc.
**
** Exceptions: ArgumentException if bytes == null.
=========================================================================*/
public BitArray(byte[] bytes)
{
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes));
}
// this value is chosen to prevent overflow when computing m_length.
// m_length is of type int32 and is exposed as a property, so
// type of m_length can't be changed to accommodate.
if (bytes.Length > int.MaxValue / BitsPerByte)
{
throw new ArgumentException(SR.Format(SR.Argument_ArrayTooLarge, BitsPerByte), nameof(bytes));
}
m_array = new int[GetInt32ArrayLengthFromByteLength(bytes.Length)];
m_length = bytes.Length * BitsPerByte;
uint totalCount = (uint)bytes.Length / 4;
ReadOnlySpan<byte> byteSpan = bytes;
for (int i = 0; i < totalCount; i++)
{
m_array[i] = BinaryPrimitives.ReadInt32LittleEndian(byteSpan);
byteSpan = byteSpan.Slice(4);
}
Debug.Assert(byteSpan.Length >= 0 && byteSpan.Length < 4);
int last = 0;
switch (byteSpan.Length)
{
case 3:
last = byteSpan[2] << 16;
goto case 2;
// fall through
case 2:
last |= byteSpan[1] << 8;
goto case 1;
// fall through
case 1:
m_array[totalCount] = last | byteSpan[0];
break;
}
_version = 0;
}
public BitArray(bool[] values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
m_array = new int[GetInt32ArrayLengthFromBitLength(values.Length)];
m_length = values.Length;
for (int i = 0; i < values.Length; i++)
{
if (values[i])
{
int elementIndex = Div32Rem(i, out int extraBits);
m_array[elementIndex] |= 1 << extraBits;
}
}
_version = 0;
}
/*=========================================================================
** Allocates space to hold the bit values in values. values[0] represents
** bits 0 - 31, values[1] represents bits 32 - 63, etc. The LSB of each
** integer represents the lowest index value; values[0] & 1 represents bit
** 0, values[0] & 2 represents bit 1, values[0] & 4 represents bit 2, etc.
**
** Exceptions: ArgumentException if values == null.
=========================================================================*/
public BitArray(int[] values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
// this value is chosen to prevent overflow when computing m_length
if (values.Length > int.MaxValue / BitsPerInt32)
{
throw new ArgumentException(SR.Format(SR.Argument_ArrayTooLarge, BitsPerInt32), nameof(values));
}
m_array = new int[values.Length];
Array.Copy(values, 0, m_array, 0, values.Length);
m_length = values.Length * BitsPerInt32;
_version = 0;
}
/*=========================================================================
** Allocates a new BitArray with the same length and bit values as bits.
**
** Exceptions: ArgumentException if bits == null.
=========================================================================*/
public BitArray(BitArray bits)
{
if (bits == null)
{
throw new ArgumentNullException(nameof(bits));
}
int arrayLength = GetInt32ArrayLengthFromBitLength(bits.m_length);
m_array = new int[arrayLength];
Debug.Assert(bits.m_array.Length <= arrayLength);
Array.Copy(bits.m_array, 0, m_array, 0, arrayLength);
m_length = bits.m_length;
_version = bits._version;
}
public bool this[int index]
{
get => Get(index);
set => Set(index, value);
}
/*=========================================================================
** Returns the bit value at position index.
**
** Exceptions: ArgumentOutOfRangeException if index < 0 or
** index >= GetLength().
=========================================================================*/
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Get(int index)
{
if ((uint)index >= (uint)m_length)
ThrowArgumentOutOfRangeException(index);
return (m_array[index >> 5] & (1 << index)) != 0;
}
/*=========================================================================
** Sets the bit value at position index to value.
**
** Exceptions: ArgumentOutOfRangeException if index < 0 or
** index >= GetLength().
=========================================================================*/
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Set(int index, bool value)
{
if ((uint)index >= (uint)m_length)
ThrowArgumentOutOfRangeException(index);
int bitMask = 1 << index;
ref int segment = ref m_array[index >> 5];
if (value)
{
segment |= bitMask;
}
else
{
segment &= ~bitMask;
}
_version++;
}
/*=========================================================================
** Sets all the bit values to value.
=========================================================================*/
public void SetAll(bool value)
{
int fillValue = value ? -1 : 0;
int[] array = m_array;
for (int i = 0; i < array.Length; i++)
{
array[i] = fillValue;
}
_version++;
}
/*=========================================================================
** Returns a reference to the current instance ANDed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
public unsafe BitArray And(BitArray value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (Length != value.Length)
throw new ArgumentException(SR.Arg_ArrayLengthsDiffer);
int count = m_array.Length;
switch (count)
{
case 3: m_array[2] &= value.m_array[2]; goto case 2;
case 2: m_array[1] &= value.m_array[1]; goto case 1;
case 1: m_array[0] &= value.m_array[0]; goto Done;
case 0: goto Done;
}
int i = 0;
if (Sse2.IsSupported)
{
fixed (int* leftPtr = m_array)
fixed (int* rightPtr = value.m_array)
{
for (; i < count - (Vector128<int>.Count - 1); i += Vector128<int>.Count)
{
Vector128<int> leftVec = Sse2.LoadVector128(leftPtr + i);
Vector128<int> rightVec = Sse2.LoadVector128(rightPtr + i);
Sse2.Store(leftPtr + i, Sse2.And(leftVec, rightVec));
}
}
}
for (; i < count; i++)
m_array[i] &= value.m_array[i];
Done:
_version++;
return this;
}
/*=========================================================================
** Returns a reference to the current instance ORed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
public unsafe BitArray Or(BitArray value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (Length != value.Length)
throw new ArgumentException(SR.Arg_ArrayLengthsDiffer);
int count = m_array.Length;
switch (count)
{
case 3: m_array[2] |= value.m_array[2]; goto case 2;
case 2: m_array[1] |= value.m_array[1]; goto case 1;
case 1: m_array[0] |= value.m_array[0]; goto Done;
case 0: goto Done;
}
int i = 0;
if (Sse2.IsSupported)
{
fixed (int* leftPtr = m_array)
fixed (int* rightPtr = value.m_array)
{
for (; i < count - (Vector128<int>.Count - 1); i += Vector128<int>.Count)
{
Vector128<int> leftVec = Sse2.LoadVector128(leftPtr + i);
Vector128<int> rightVec = Sse2.LoadVector128(rightPtr + i);
Sse2.Store(leftPtr + i, Sse2.Or(leftVec, rightVec));
}
}
}
for (; i < count; i++)
m_array[i] |= value.m_array[i];
Done:
_version++;
return this;
}
/*=========================================================================
** Returns a reference to the current instance XORed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
public unsafe BitArray Xor(BitArray value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (Length != value.Length)
throw new ArgumentException(SR.Arg_ArrayLengthsDiffer);
int count = m_array.Length;
switch (count)
{
case 3: m_array[2] ^= value.m_array[2]; goto case 2;
case 2: m_array[1] ^= value.m_array[1]; goto case 1;
case 1: m_array[0] ^= value.m_array[0]; goto Done;
case 0: goto Done;
}
int i = 0;
if (Sse2.IsSupported)
{
fixed (int* leftPtr = m_array)
fixed (int* rightPtr = value.m_array)
{
for (; i < count - (Vector128<int>.Count - 1); i += Vector128<int>.Count)
{
Vector128<int> leftVec = Sse2.LoadVector128(leftPtr + i);
Vector128<int> rightVec = Sse2.LoadVector128(rightPtr + i);
Sse2.Store(leftPtr + i, Sse2.Xor(leftVec, rightVec));
}
}
}
for (; i < count; i++)
m_array[i] ^= value.m_array[i];
Done:
_version++;
return this;
}
/*=========================================================================
** Inverts all the bit values. On/true bit values are converted to
** off/false. Off/false bit values are turned on/true. The current instance
** is updated and returned.
=========================================================================*/
public BitArray Not()
{
int[] array = m_array;
for (int i = 0; i < array.Length; i++)
{
array[i] = ~array[i];
}
_version++;
return this;
}
/*=========================================================================
** Shift all the bit values to right on count bits. The current instance is
** updated and returned.
*
** Exceptions: ArgumentOutOfRangeException if count < 0
=========================================================================*/
public BitArray RightShift(int count)
{
if (count <= 0)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum);
}
_version++;
return this;
}
int toIndex = 0;
int ints = GetInt32ArrayLengthFromBitLength(m_length);
if (count < m_length)
{
// We can not use Math.DivRem without taking a dependency on System.Runtime.Extensions
int fromIndex = Div32Rem(count, out int shiftCount);
Div32Rem(m_length, out int extraBits);
if (shiftCount == 0)
{
unchecked
{
// Cannot use `(1u << extraBits) - 1u` as the mask
// because for extraBits == 0, we need the mask to be 111...111, not 0.
// In that case, we are shifting a uint by 32, which could be considered undefined.
// The result of a shift operation is undefined ... if the right operand
// is greater than or equal to the width in bits of the promoted left operand,
// https://docs.microsoft.com/en-us/cpp/c-language/bitwise-shift-operators?view=vs-2017
// However, the compiler protects us from undefined behaviour by constraining the
// right operand to between 0 and width - 1 (inclusive), i.e. right_operand = (right_operand % width).
uint mask = uint.MaxValue >> (BitsPerInt32 - extraBits);
m_array[ints - 1] &= (int)mask;
}
Array.Copy(m_array, fromIndex, m_array, 0, ints - fromIndex);
toIndex = ints - fromIndex;
}
else
{
int lastIndex = ints - 1;
unchecked
{
while (fromIndex < lastIndex)
{
uint right = (uint)m_array[fromIndex] >> shiftCount;
int left = m_array[++fromIndex] << (BitsPerInt32 - shiftCount);
m_array[toIndex++] = left | (int)right;
}
uint mask = uint.MaxValue >> (BitsPerInt32 - extraBits);
mask &= (uint)m_array[fromIndex];
m_array[toIndex++] = (int)(mask >> shiftCount);
}
}
}
m_array.AsSpan(toIndex, ints - toIndex).Clear();
_version++;
return this;
}
/*=========================================================================
** Shift all the bit values to left on count bits. The current instance is
** updated and returned.
*
** Exceptions: ArgumentOutOfRangeException if count < 0
=========================================================================*/
public BitArray LeftShift(int count)
{
if (count <= 0)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum);
}
_version++;
return this;
}
int lengthToClear;
if (count < m_length)
{
int lastIndex = (m_length - 1) >> BitShiftPerInt32; // Divide by 32.
// We can not use Math.DivRem without taking a dependency on System.Runtime.Extensions
lengthToClear = Div32Rem(count, out int shiftCount);
if (shiftCount == 0)
{
Array.Copy(m_array, 0, m_array, lengthToClear, lastIndex + 1 - lengthToClear);
}
else
{
int fromindex = lastIndex - lengthToClear;
unchecked
{
while (fromindex > 0)
{
int left = m_array[fromindex] << shiftCount;
uint right = (uint)m_array[--fromindex] >> (BitsPerInt32 - shiftCount);
m_array[lastIndex] = left | (int)right;
lastIndex--;
}
m_array[lastIndex] = m_array[fromindex] << shiftCount;
}
}
}
else
{
lengthToClear = GetInt32ArrayLengthFromBitLength(m_length); // Clear all
}
m_array.AsSpan(0, lengthToClear).Clear();
_version++;
return this;
}
public int Length
{
get
{
return m_length;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedNonNegNum);
}
int newints = GetInt32ArrayLengthFromBitLength(value);
if (newints > m_array.Length || newints + _ShrinkThreshold < m_array.Length)
{
// grow or shrink (if wasting more than _ShrinkThreshold ints)
Array.Resize(ref m_array, newints);
}
if (value > m_length)
{
// clear high bit values in the last int
int last = (m_length - 1) >> BitShiftPerInt32;
Div32Rem(m_length, out int bits);
if (bits > 0)
{
m_array[last] &= (1 << bits) - 1;
}
// clear remaining int values
m_array.AsSpan(last + 1, newints - last - 1).Clear();
}
m_length = value;
_version++;
}
}
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
if (array is int[] intArray)
{
Div32Rem(m_length, out int extraBits);
if (extraBits == 0)
{
// we have perfect bit alignment, no need to sanitize, just copy
Array.Copy(m_array, 0, intArray, index, m_array.Length);
}
else
{
int last = (m_length - 1) >> BitShiftPerInt32;
// do not copy the last int, as it is not completely used
Array.Copy(m_array, 0, intArray, index, last);
// the last int needs to be masked
intArray[index + last] = m_array[last] & unchecked((1 << extraBits) - 1);
}
}
else if (array is byte[] byteArray)
{
int arrayLength = GetByteArrayLengthFromBitLength(m_length);
if ((array.Length - index) < arrayLength)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
// equivalent to m_length % BitsPerByte, since BitsPerByte is a power of 2
uint extraBits = (uint)m_length & (BitsPerByte - 1);
if (extraBits > 0)
{
// last byte is not aligned, we will directly copy one less byte
arrayLength -= 1;
}
Span<byte> span = byteArray.AsSpan(index);
int quotient = Div4Rem(arrayLength, out int remainder);
for (int i = 0; i < quotient; i++)
{
BinaryPrimitives.WriteInt32LittleEndian(span, m_array[i]);
span = span.Slice(4);
}
if (extraBits > 0)
{
Debug.Assert(span.Length > 0);
Debug.Assert(m_array.Length > quotient);
// mask the final byte
span[span.Length - 1] = (byte)((m_array[quotient] >> (remainder * 8)) & ((1 << (int)extraBits) - 1));
}
switch (remainder)
{
case 3:
span[2] = (byte)(m_array[quotient] >> 16);
goto case 2;
// fall through
case 2:
span[1] = (byte)(m_array[quotient] >> 8);
goto case 1;
// fall through
case 1:
span[0] = (byte)m_array[quotient];
break;
}
}
else if (array is bool[] boolArray)
{
if (array.Length - index < m_length)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
for (int i = 0; i < m_length; i++)
{
int elementIndex = Div32Rem(i, out int extraBits);
boolArray[index + i] = ((m_array[elementIndex] >> extraBits) & 0x00000001) != 0;
}
}
else
{
throw new ArgumentException(SR.Arg_BitArrayTypeUnsupported, nameof(array));
}
}
public int Count => m_length;
public object SyncRoot => this;
public bool IsSynchronized => false;
public bool IsReadOnly => false;
public object Clone() => new BitArray(this);
public IEnumerator GetEnumerator() => new BitArrayEnumeratorSimple(this);
// XPerY=n means that n Xs can be stored in 1 Y.
private const int BitsPerInt32 = 32;
private const int BytesPerInt32 = 4;
private const int BitsPerByte = 8;
private const int BitShiftPerInt32 = 5;
private const int BitShiftPerByte = 3;
private const int BitShiftForBytesPerInt32 = 2;
/// <summary>
/// Used for conversion between different representations of bit array.
/// Returns (n + (32 - 1)) / 32, rearranged to avoid arithmetic overflow.
/// For example, in the bit to int case, the straightforward calc would
/// be (n + 31) / 32, but that would cause overflow. So instead it's
/// rearranged to ((n - 1) / 32) + 1.
/// Due to sign extension, we don't need to special case for n == 0, if we use
/// bitwise operations (since ((n - 1) >> 5) + 1 = 0).
/// This doesn't hold true for ((n - 1) / 32) + 1, which equals 1.
///
/// Usage:
/// GetArrayLength(77): returns how many ints must be
/// allocated to store 77 bits.
/// </summary>
/// <param name="n"></param>
/// <returns>how many ints are required to store n bytes</returns>
private static int GetInt32ArrayLengthFromBitLength(int n)
{
Debug.Assert(n >= 0);
return (int)((uint)(n - 1 + (1 << BitShiftPerInt32)) >> BitShiftPerInt32);
}
private static int GetInt32ArrayLengthFromByteLength(int n)
{
Debug.Assert(n >= 0);
// Due to sign extension, we don't need to special case for n == 0, since ((n - 1) >> 2) + 1 = 0
// This doesn't hold true for ((n - 1) / 4) + 1, which equals 1.
return (int)((uint)(n - 1 + (1 << BitShiftForBytesPerInt32)) >> BitShiftForBytesPerInt32);
}
private static int GetByteArrayLengthFromBitLength(int n)
{
Debug.Assert(n >= 0);
// Due to sign extension, we don't need to special case for n == 0, since ((n - 1) >> 3) + 1 = 0
// This doesn't hold true for ((n - 1) / 8) + 1, which equals 1.
return (int)((uint)(n - 1 + (1 << BitShiftPerByte)) >> BitShiftPerByte);
}
private static int Div32Rem(int number, out int remainder)
{
uint quotient = (uint)number / 32;
remainder = number & (32 - 1); // equivalent to number % 32, since 32 is a power of 2
return (int)quotient;
}
private static int Div4Rem(int number, out int remainder)
{
uint quotient = (uint)number / 4;
remainder = number & (4 - 1); // equivalent to number % 4, since 4 is a power of 2
return (int)quotient;
}
private static void ThrowArgumentOutOfRangeException(int index)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
private class BitArrayEnumeratorSimple : IEnumerator, ICloneable
{
private BitArray _bitarray;
private int _index;
private readonly int _version;
private bool _currentElement;
internal BitArrayEnumeratorSimple(BitArray bitarray)
{
_bitarray = bitarray;
_index = -1;
_version = bitarray._version;
}
public object Clone() => MemberwiseClone();
public virtual bool MoveNext()
{
ICollection bitarrayAsICollection = _bitarray;
if (_version != _bitarray._version)
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index < (bitarrayAsICollection.Count - 1))
{
_index++;
_currentElement = _bitarray.Get(_index);
return true;
}
else
{
_index = bitarrayAsICollection.Count;
}
return false;
}
public virtual object Current
{
get
{
if ((uint)_index >= (uint)_bitarray.Count)
throw GetInvalidOperationException(_index);
return _currentElement;
}
}
public void Reset()
{
if (_version != _bitarray._version)
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -1;
}
private InvalidOperationException GetInvalidOperationException(int index)
{
if (index == -1)
{
return new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
}
else
{
Debug.Assert(index >= _bitarray.Count);
return new InvalidOperationException(SR.InvalidOperation_EnumEnded);
}
}
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Core.Portal;
using ArcGIS.Desktop.Core;
using System.Windows.Input;
namespace UploadItem
{
internal class UploadItemViewModel : DockPane
{
private const string _dockPaneID = "UploadItem_UploadItem";
protected UploadItemViewModel()
{
_submitItemCommand = new RelayCommand(() => UploadToAGOLAsync(), () => CanExecute());
}
/// <summary>
/// Show the DockPane.
/// </summary>
internal static void Show()
{
DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
if (pane == null)
return;
pane.Activate();
}
#region Properies for binding
/// <summary>
/// Text shown near the top of the DockPane.
/// </summary>
private string _heading = "Upload AGOL item";
public string Heading
{
get { return _heading; }
set
{
SetProperty(ref _heading, value, () => Heading);
}
}
/// <summary>
/// Url of the ArcGIS Online or active portal
/// </summary>
private string _baseUrl;
public string BaseUrl
{
get { return _baseUrl; }
set { SetProperty(ref _baseUrl, value, () => BaseUrl); }
}
/// <summary>
/// Full path to the item on disk that is to be uploaded.
/// </summary>
private string _itemPath;
public string ItemPath
{
get { return _itemPath; }
set { SetProperty(ref _itemPath, value, () => ItemPath); }
}
/// <summary>
/// Full path to the thumbnail image of the item
/// </summary>
private string _thumbnailPath;
public string ItemThumbnailPath
{
get { return _thumbnailPath; }
set { SetProperty(ref _thumbnailPath, value, () => ItemThumbnailPath); }
}
/// <summary>
/// Tags for the item to upload
/// </summary>
private string _itemTags;
public string ItemTags
{
get { return _itemTags; }
set { SetProperty(ref _itemTags, value, () => ItemTags); }
}
/// <summary>
/// ID of the uploaded item
/// </summary>
private string _itemID;
public string ItemID
{
get { return _itemID; }
set { SetProperty(ref _itemID, value, () => ItemID); }
}
#endregion
#region Commands
/// <summary>
/// Command to get the active portal
/// </summary>
private RelayCommand _getActivePortalCommand;
public ICommand GetActivePortalCommand
{
get {
if (_getActivePortalCommand == null)
_getActivePortalCommand = new RelayCommand(() => GetActivePortal(), () => true);
return _getActivePortalCommand;
}
}
/// <summary>
/// Command to browse for item and thumbnail
/// </summary>
private RelayCommand _browseCommand;
public ICommand BrowseCommand
{
get
{
if (_browseCommand == null)
_browseCommand = new RelayCommand(BrowseImpl, () => true);
return _browseCommand;
}
}
/// <summary>
/// Submit command - Uploads to active portal
/// </summary>
private RelayCommand _submitItemCommand;
public RelayCommand SubmitItemCommand
{
get
{
return _submitItemCommand;
}
}
#endregion
#region private methods
/// <summary>
/// Uploads the items to Active portal
/// </summary>
/// <returns></returns>
private async Task UploadToAGOLAsync()
{
var uploadResult = await UploadItemAsync(BaseUrl, ItemPath, ItemThumbnailPath, ItemTags);
ItemID = uploadResult.Item2;
}
/// <summary>
/// Uploads a local item to online with its parameters
/// </summary>
/// <param name="baseURI"></param>
/// <param name="itemPathStr"></param>
/// <param name="thumbnail"></param>
/// <param name="tags"></param>
/// <returns></returns>
async Task<Tuple<bool, string>> UploadItemAsync(string baseURI, string itemPathStr, string thumbnail, string tags)
{
String[] tags_arr = tags.Split(new Char[] { ',', ':', '\t' });
EsriHttpClient myClient = new EsriHttpClient();
Tuple<bool, string> response = null;
var itemToUpload = ItemFactory.Instance.Create(itemPathStr);
if (itemToUpload != null)
{
//Create the upload defintion
var uploadDfn = new UploadDefinition(baseURI, itemToUpload, tags_arr);
uploadDfn.Thumbnail = thumbnail;
//upload item
response = myClient.Upload(uploadDfn);
//response = myClient.Upload(baseURI, itemToUpload, thumbnail, tags_arr); //obsolete
if (response.Item1) //Upload was successfull
{
//Search for the uploaded item to get its ID.
Tuple<bool, PortalItem> result = await SearchPortalForItemsAsync(baseURI, itemToUpload);
if (result.Item1) //search successful
{
ItemID = result.Item2.ToString();
return new Tuple<bool, string>(true, result.Item2.ID);
}
else //item not found
{
ItemID = "Cannot find item online";
return new Tuple<bool, string>(true, "Cannot find item online");
}
}
else //Upload failed
{
ItemID = "Upload failed";
return new Tuple<bool, String>(false, "Upload failed");
}
}
else //Item was not created
{
ItemID = "Item cannot be created";
return new Tuple<bool, String>(false, "Item cannot be created");
}
}
/// <summary>
/// Searches the active portal for the item that has been uploaded.
/// </summary>
/// <param name="portalUrl"></param>
/// <param name="item"></param>
/// <returns></returns>
private async Task<Tuple<bool, PortalItem>> SearchPortalForItemsAsync(string portalUrl, Item item)
{
var portal = ArcGISPortalManager.Current.GetPortal(new Uri(portalUrl));
//Get the PortalItemType of the item
var portalItemType = GetProtalItemTypeFromItem(item);
//Get the item name without the extension
var portalItemName = System.IO.Path.GetFileNameWithoutExtension(item.Name);
//Create the Query and the params
var pqp = PortalQueryParameters.CreateForItemsOfType(portalItemType, $@"""{portalItemName}"" tags:""{ItemTags}""");
//Search active portal
PortalQueryResultSet<PortalItem> results = await ArcGISPortalExtensions.SearchForContentAsync(portal, pqp);
//Iterate through the returned items for THE item.
var myPortalItem = results.Results?.OfType<PortalItem>().FirstOrDefault();
if (myPortalItem == null)
return null;
return new Tuple<bool, PortalItem>(true, myPortalItem);
}
/// <summary>
/// Gets the active portal
/// </summary>
private void GetActivePortal()
{
BaseUrl = ArcGISPortalManager.Current.GetActivePortal().PortalUri.ToString();
}
/// <summary>
/// Displayes the Browse dialog.
/// </summary>
/// <remarks>The parameter is passed in to see if the dialog should browse for an item or the thumbnail</remarks>
/// <param name="param"></param>
private void BrowseImpl(object param)
{
if (param == null)
return;
string title = "Browse";
string filter = "";
string defaultExt = "";
switch (param.ToString()) //Item or thumbnail browse?
{
case "ItemPath":
defaultExt = ".lyr";
filter = "Layer|*.lyr|Excel (.xlsx)|*.xlsx|KML|*.kml|Layer Package|*.lpk|Map Document|*.mxd|Map Package|*.mpk|Tile Package|*.tpk|Geoprocessing Package|*.gpk|Address Locator|*.gcpk|Basemap Package|*.bpk|Mobile Package|*.mmpk|Vector Tile Package|*.vtpk|All files (*.*)|*.*";
title = "Browse to item";
break;
case "ItemThumbnailPath":
defaultExt = ".bmp";
filter = "BMP|*.bmp|GIF|*.gif|JPG(*.jpg,*.jpeg)|*.jpg;*.jpeg|PNG|*.png |TIFF(*.tif,*.tiff)|*.tif; .tiff";
title = "Browse to image";
break;
}
var filename = OpenBrowseDialog(title, filter, defaultExt);
switch (param.ToString())
{
case "ItemPath":
ItemPath = filename;
break;
case "ItemThumbnailPath":
ItemThumbnailPath = filename;
break;
}
}
/// <summary>
/// Display the browse dialog with the filters
/// </summary>
/// <param name="title"></param>
/// <param name="filter"></param>
/// <param name="defaultExt"></param>
/// <returns></returns>
private string OpenBrowseDialog(string title, string filter, string defaultExt)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
//Dialog title
dlg.Title = title;
// Set filter for file extension and default file extension
dlg.DefaultExt = defaultExt;
dlg.Filter = filter;
// Display OpenFileDialog by calling ShowDialog method
var result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
return dlg.FileName;
}
else
return null;
}
/// <summary>
/// Gets the PortalItemType of an Item object that has been uploaded
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
private PortalItemType GetProtalItemTypeFromItem(Item item)
{
PortalItemType portalItemType = PortalItemType.WebMap; //default
var itemExtension = System.IO.Path.GetExtension(item.Name);
//Get the PortalItemType based on the file extension
switch (itemExtension)
{
case ".lyr":
portalItemType = PortalItemType.Layer;
break;
case ".xlsx":
portalItemType = PortalItemType.MicrosoftExcel;
break;
case ".kml":
portalItemType = PortalItemType.KML;
break;
case ".lpk":
portalItemType = PortalItemType.LayerPackage;
break;
case ".mxd":
portalItemType = PortalItemType.MapDocument;
break;
case ".mpk":
portalItemType = PortalItemType.MapPackage;
break;
case ".tpk":
portalItemType = PortalItemType.TilePackage;
break;
case ".gpk":
portalItemType = PortalItemType.GeoprocessingPackage;
break;
case ".gcpk":
portalItemType = PortalItemType.LocatorPackage;
break;
case ".bpk":
portalItemType = PortalItemType.BasemapPackage;
break;
case ".mmpk":
portalItemType = PortalItemType.MobileMapPackage;
break;
case ".vtpk":
portalItemType = PortalItemType.VectorTilePackage;
break;
case ".rpk":
portalItemType = PortalItemType.RulePackage;
break;
}
return portalItemType;
}
private bool CanExecute()
{
if (!string.IsNullOrEmpty(BaseUrl) && !string.IsNullOrEmpty(ItemPath) && !string.IsNullOrEmpty(ItemThumbnailPath) && !string.IsNullOrEmpty(ItemTags))
return true;
else return false;
}
#endregion
}
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class UploadItem_ShowButton : Button
{
protected override void OnClick()
{
UploadItemViewModel.Show();
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
namespace UnitySampleAssets.Vehicles.Car
{
[RequireComponent(typeof (CarController))]
public class CarAIControl : MonoBehaviour
{
// This script provides input to the car controller in the same way that the user control script does.
// As such, it is really 'driving' the car, with no special physics or animation tricks to make the car behave properly.
// "wandering" is used to give the cars a more human, less robotic feel. They can waver slightly
// in speed and direction while driving towards their target.
[SerializeField] [Range(0, 1)] private float cautiousSpeedFactor = 0.05f;// percentage of max speed to use when being maximally cautious
[SerializeField] [Range(0, 180)] private float cautiousMaxAngle = 50f;// angle of approaching corner to treat as warranting maximum caution
[SerializeField] private float cautiousMaxDistance = 100f;// distance at which distance-based cautiousness begins
[SerializeField] private float cautiousAngularVelocityFactor = 30f;// how cautious the AI should be when considering its own current angular velocity (i.e. easing off acceleration if spinning!)
[SerializeField] private float steerSensitivity = 0.05f;// how sensitively the AI uses steering input to turn to the desired direction
[SerializeField] private float accelSensitivity = 0.04f;// How sensitively the AI uses the accelerator to reach the current desired speed
[SerializeField] private float brakeSensitivity = 1f;// How sensitively the AI uses the brake to reach the current desired speed
[SerializeField] private float lateralWanderDistance = 3f;// how far the car will wander laterally towards its target
[SerializeField] private float lateralWanderSpeed = 0.1f; // how fast the lateral wandering will fluctuate
[SerializeField] [Range(0, 1)] public float accelWanderAmount = 0.1f;// how much the cars acceleration will wander
[SerializeField] private float accelWanderSpeed = 0.1f;// how fast the cars acceleration wandering will fluctuate
[SerializeField] private BrakeCondition brakeCondition = BrakeCondition.TargetDistance;// what should the AI consider when accelerating/braking?
[SerializeField] private bool driving = false; // whether the AI is currently actively driving or stopped.
[SerializeField] private Transform target; // 'target' the target object to aim for.
[SerializeField] private bool stopWhenTargetReached; // should we stop driving when we reach the target?
[SerializeField] private float reachTargetThreshold = 2;// proximity to target to consider we 'reached' it, and stop driving.
public enum BrakeCondition
{
NeverBrake,// the car simply accelerates at full throttle all the time.
TargetDirectionDifference,// the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners.
TargetDistance,// the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to
// head for a stationary target and come to rest when it arrives there.
}
private float randomPerlin;// A random value for the car to base its wander on (so that AI cars don't all wander in the same pattern)
private CarController carController; // Reference to actual car controller we are controlling
// if this AI car collides with another car, it can take evasive action for a short duration:
private float avoidOtherCarTime; // time until which to avoid the car we recently collided with
private float avoidOtherCarSlowdown; // how much to slow down due to colliding with another car, whilst avoiding
private float avoidPathOffset;// direction (-1 or 1) in which to offset path to avoid other car, whilst avoiding
private void Awake()
{
// get the car controller reference
carController = GetComponent<CarController>();
// give the random perlin a random value
randomPerlin = Random.value*100;
}
private void FixedUpdate()
{
if (target == null || !driving)
{
// Car should not be moving,
// (so use accel/brake to get to zero speed)
float accel = Mathf.Clamp(-carController.CurrentSpeed, -1, 1);
carController.Move(0, accel);
}
else
{
Vector3 fwd = transform.forward;
if (GetComponent<Rigidbody>().velocity.magnitude > carController.MaxSpeed*0.1f)
{
fwd = GetComponent<Rigidbody>().velocity;
}
float desiredSpeed = carController.MaxSpeed;
// now it's time to decide if we should be slowing down...
switch (brakeCondition)
{
case BrakeCondition.TargetDirectionDifference:
{
// the car will brake according to the upcoming change in direction of the target. Useful for route-based AI, slowing for corners.
// check out the angle of our target compared to the current direction of the car
float approachingCornerAngle = Vector3.Angle(target.forward, fwd);
// also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle
float spinningAngle = GetComponent<Rigidbody>().angularVelocity.magnitude*cautiousAngularVelocityFactor;
// if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount
float cautiousnessRequired = Mathf.InverseLerp(0, cautiousMaxAngle,
Mathf.Max(spinningAngle,
approachingCornerAngle));
desiredSpeed = Mathf.Lerp(carController.MaxSpeed, carController.MaxSpeed*cautiousSpeedFactor,
cautiousnessRequired);
break;
}
case BrakeCondition.TargetDistance:
{
// the car will brake as it approaches its target, regardless of the target's direction. Useful if you want the car to
// head for a stationary target and come to rest when it arrives there.
// check out the distance to target
Vector3 delta = target.position - transform.position;
float distanceCautiousFactor = Mathf.InverseLerp(cautiousMaxDistance, 0, delta.magnitude);
// also consider the current amount we're turning, multiplied up and then compared in the same way as an upcoming corner angle
float spinningAngle = GetComponent<Rigidbody>().angularVelocity.magnitude*cautiousAngularVelocityFactor;
// if it's different to our current angle, we need to be cautious (i.e. slow down) a certain amount
float cautiousnessRequired = Mathf.Max(
Mathf.InverseLerp(0, cautiousMaxAngle, spinningAngle), distanceCautiousFactor);
desiredSpeed = Mathf.Lerp(carController.MaxSpeed, carController.MaxSpeed*cautiousSpeedFactor,
cautiousnessRequired);
break;
}
case BrakeCondition.NeverBrake:
break; // blarg!
}
// Evasive action due to collision with other cars:
// our target position starts off as the 'real' target position
Vector3 offsetTargetPos = target.position;
// if are we currently taking evasive action to prevent being stuck against another car:
if (Time.time < avoidOtherCarTime)
{
// slow down if necessary (if we were behind the other car when collision occured)
desiredSpeed *= avoidOtherCarSlowdown;
// and veer towards the side of our path-to-target that is away from the other car
offsetTargetPos += target.right*avoidPathOffset;
}
else
{
// no need for evasive action, we can just wander across the path-to-target in a random way,
// which can help prevent AI from seeming too uniform and robotic in their driving
offsetTargetPos += target.right*
(Mathf.PerlinNoise(Time.time*lateralWanderSpeed, randomPerlin)*2 - 1)*
lateralWanderDistance;
}
// use different sensitivity depending on whether accelerating or braking:
float accelBrakeSensitivity = (desiredSpeed < carController.CurrentSpeed)
? brakeSensitivity
: accelSensitivity;
// decide the actual amount of accel/brake input to achieve desired speed.
float accel = Mathf.Clamp((desiredSpeed - carController.CurrentSpeed)*accelBrakeSensitivity, -1, 1);
// add acceleration 'wander', which also prevents AI from seeming too uniform and robotic in their driving
// i.e. increasing the accel wander amount can introduce jostling and bumps between AI cars in a race
accel *= (1 - accelWanderAmount) +
(Mathf.PerlinNoise(Time.time*accelWanderSpeed, randomPerlin)*accelWanderAmount);
// calculate the local-relative position of the target, to steer towards
Vector3 localTarget = transform.InverseTransformPoint(offsetTargetPos);
// work out the local angle towards the target
float targetAngle = Mathf.Atan2(localTarget.x, localTarget.z)*Mathf.Rad2Deg;
// get the amount of steering needed to aim the car towards the target
float steer = Mathf.Clamp(targetAngle*steerSensitivity, -1, 1)*Mathf.Sign(carController.CurrentSpeed);
// feed input to the car controller.
carController.Move(steer, accel);
// if appropriate, stop driving when we're close enough to the target.
if (stopWhenTargetReached && localTarget.magnitude < reachTargetThreshold)
{
driving = false;
}
}
}
private void OnCollisionStay(Collision col)
{
// detect collision against other cars, so that we can take evasive action
if (col.rigidbody != null)
{
var otherAI = col.rigidbody.GetComponent<CarAIControl>();
if (otherAI != null)
{
// we'll take evasive action for 1 second
avoidOtherCarTime = Time.time + 1;
// but who's in front?...
if (Vector3.Angle(transform.forward, otherAI.transform.position - transform.position) < 90)
{
// the other ai is in front, so it is only good manners that we ought to brake...
avoidOtherCarSlowdown = 0.5f;
}
else
{
// we're in front! ain't slowing down for anybody...
avoidOtherCarSlowdown = 1;
}
// both cars should take evasive action by driving along an offset from the path centre,
// away from the other car
var otherCarLocalDelta = transform.InverseTransformPoint(otherAI.transform.position);
float otherCarAngle = Mathf.Atan2(otherCarLocalDelta.x, otherCarLocalDelta.z);
avoidPathOffset = lateralWanderDistance*-Mathf.Sign(otherCarAngle);
}
}
}
public void SetTarget(Transform target)
{
this.target = target;
driving = true;
}
}
}
| |
//
// Created by Shopify.
// Copyright (c) 2016 Shopify Inc. All rights reserved.
//
// 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 CoreGraphics;
using Foundation;
using PassKit;
using SafariServices;
using UIKit;
using Shopify;
namespace ShopifyiOSSample
{
public class CheckoutViewController : UITableViewController, ISFSafariViewControllerDelegate
{
private readonly BUYClient client;
private BUYCheckout _checkout;
private BUYShop shop;
private PKPaymentSummaryItem[] summaryItems;
private BUYApplePayHelpers applePayHelper;
private static BUYCreditCard CreditCard {
get {
var creditCard = new BUYCreditCard ();
creditCard.Number = "4242424242424242";
creditCard.ExpiryMonth = "12";
creditCard.ExpiryYear = "2020";
creditCard.Cvv = "123";
creditCard.NameOnCard = "John Smith";
return creditCard;
}
}
public CheckoutViewController (BUYClient client, BUYCheckout checkout)
: base (UITableViewStyle.Grouped)
{
this.client = client;
this.checkout = checkout;
}
public NSNumberFormatter CurrencyFormatter { get; set; }
private BUYCheckout checkout {
get { return _checkout; }
set {
_checkout = value;
// We can take advantage of the PKPaymentSummaryItems used for
// Apple Pay to display summary items natively in our own
// checkout
summaryItems = _checkout.ApplePaySummaryItems ();
}
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
Title = "Checkout";
var footerView = new UIView (new CGRect (0, 0, View.Bounds.Width, 164));
var creditCardButton = new UIButton (UIButtonType.RoundedRect);
creditCardButton.SetTitle ("Checkout with Credit Card", UIControlState.Normal);
creditCardButton.BackgroundColor = UIColor.FromRGBA (0.48f, 0.71f, 0.36f, 1.0f);
creditCardButton.Layer.CornerRadius = 6;
creditCardButton.SetTitleColor (UIColor.White, UIControlState.Normal);
creditCardButton.TranslatesAutoresizingMaskIntoConstraints = false;
creditCardButton.TouchUpInside += CheckoutWithCreditCard;
footerView.AddSubview (creditCardButton);
var webCheckoutButton = new UIButton (UIButtonType.RoundedRect);
webCheckoutButton.SetTitle ("Web Checkout", UIControlState.Normal);
webCheckoutButton.BackgroundColor = UIColor.FromRGBA (0.48f, 0.71f, 0.36f, 1.0f);
webCheckoutButton.Layer.CornerRadius = 6;
webCheckoutButton.SetTitleColor (UIColor.White, UIControlState.Normal);
webCheckoutButton.TranslatesAutoresizingMaskIntoConstraints = false;
webCheckoutButton.TouchUpInside += CheckoutOnWeb;
footerView.AddSubview (webCheckoutButton);
var applePayButton = BUYPaymentButton.Create (BUYPaymentButtonType.Buy, BUYPaymentButtonStyle.Black);
applePayButton.TranslatesAutoresizingMaskIntoConstraints = false;
applePayButton.TouchUpInside += CheckoutWithApplePay;
footerView.AddSubview (applePayButton);
var views = NSDictionary.FromObjectsAndKeys (new [] {
creditCardButton,
webCheckoutButton,
applePayButton
}, new [] {
"creditCardButton",
"webCheckoutButton",
"applePayButton"
});
footerView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-[creditCardButton]-|", 0, null, views));
footerView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-[webCheckoutButton]-|", 0, null, views));
footerView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-[applePayButton]-|", 0, null, views));
footerView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-[creditCardButton(44)]-[webCheckoutButton(==creditCardButton)]-[applePayButton(==creditCardButton)]-|", 0, null, views));
TableView.TableFooterView = footerView;
// Prefetch the shop object for Apple Pay
client.GetShop ((shop, error) => {
this.shop = shop;
});
}
public override nint RowsInSection (UITableView tableView, nint section)
{
return summaryItems == null ? 0 : summaryItems.Length;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell ("SummaryCell") ?? new SummaryItemsTableViewCell ("SummaryCell");
var summaryItem = summaryItems [indexPath.Row];
cell.TextLabel.Text = summaryItem.Label;
cell.DetailTextLabel.Text = CurrencyFormatter.StringFromNumber (summaryItem.Amount);
// Only show a line above the last cell
if (indexPath.Row != summaryItems.Length - 2) {
cell.SeparatorInset = new UIEdgeInsets (0.0f, 0.0f, 0.0f, cell.Bounds.Size.Width);
}
return cell;
}
private void AddCreditCardToCheckout (Action<bool> callback)
{
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
client.StoreCreditCard (CreditCard, checkout, (checkout, paymentSessionId, error) => {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
if (error == null && checkout != null) {
Console.WriteLine ("Successfully added credit card to checkout");
this.checkout = checkout;
TableView.ReloadData ();
} else {
Console.WriteLine ("Error applying credit card: {0}", error);
}
callback (error == null && checkout != null);
});
}
private void ShowCheckoutConfirmation ()
{
var alertController = UIAlertController.Create ("Checkout complete", null, UIAlertControllerStyle.Alert);
alertController.AddAction (UIAlertAction.Create ("Start over", UIAlertActionStyle.Default, action => {
NavigationController.PopToRootViewController (true);
}));
alertController.AddAction (UIAlertAction.Create ("Show order status page", UIAlertActionStyle.Default, action => {
var safariViewController = new SFSafariViewController (checkout.Order.StatusURL);
safariViewController.Delegate = this;
PresentViewController (safariViewController, true, null);
}));
PresentViewController (alertController, true, null);
}
[Export ("safariViewControllerDidFinish:")]
public virtual void SafariViewControllerDidFinish (SFSafariViewController controller)
{
GetCompletedCheckout (() => {
if (checkout.Order != null) {
InvokeOnMainThread (() => {
ShowCheckoutConfirmation ();
});
}
});
}
private void CheckoutWithCreditCard (object sender, EventArgs e)
{
// First, the credit card must be stored on the checkout
AddCreditCardToCheckout (success => {
if (success) {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
// Upon successfully adding the credit card to the checkout, complete checkout must be called immediately
client.CompleteCheckout (checkout, (checkout, error) => {
if (error == null && checkout != null) {
Console.WriteLine ("Successfully completed checkout");
this.checkout = checkout;
var completionOperation = new GetCompletionStatusOperation (client, checkout);
completionOperation.DidReceiveCompletionStatus += (op, status) => {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
Console.WriteLine ("Successfully got completion status: {0}", status);
GetCompletedCheckout (null);
};
completionOperation.FailedToReceiveCompletionStatus += (op, err) => {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
Console.WriteLine ("Error getting completion status: {0}", err);
};
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
NSOperationQueue.MainQueue.AddOperation (completionOperation);
} else {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
Console.WriteLine ("Error completing checkout: {0}", error);
}
});
}
});
}
private void CheckoutWithApplePay (object sender, EventArgs e)
{
var request = GetPaymentRequest ();
applePayHelper = new BUYApplePayHelpers (client, checkout, shop);
var paymentController = new PKPaymentAuthorizationViewController (request);
// Add additional methods if needed and forward the callback to BUYApplePayHelpers
paymentController.DidAuthorizePayment += (_, args) => {
applePayHelper.DidAuthorizePayment (paymentController, args.Payment, args.Completion);
checkout = applePayHelper.Checkout;
GetCompletedCheckout (null);
};
paymentController.PaymentAuthorizationViewControllerDidFinish += (_, args) => {
applePayHelper.PaymentAuthorizationViewControllerDidFinish (paymentController);
};
paymentController.DidSelectShippingAddress += (_, args) => {
applePayHelper.DidSelectShippingAddress (paymentController, args.Address, args.Completion);
};
paymentController.DidSelectShippingContact += (_, args) => {
applePayHelper.DidSelectShippingContact (paymentController, args.Contact, args.Completion);
};
paymentController.DidSelectShippingMethod += (_, args) => {
applePayHelper.DidSelectShippingMethod (paymentController, args.ShippingMethod, args.Completion);
};
/**
*
* Alternatively we can set the delegate to applePayHelper.
*
* If you do not care about any IPKPaymentAuthorizationViewControllerDelegate callbacks
* uncomment the code below to let BUYApplePayHelpers take care of them automatically.
* You can then also safely remove the IPKPaymentAuthorizationViewControllerDelegate
* events above.
*
* // paymentController.Delegate = applePayHelper;
*
* If you keep the events as the delegate, you have a chance to intercept the
* IPKPaymentAuthorizationViewControllerDelegate callbacks and add any additional logging
* and method calls as you need. Ensure that you forward them to the BUYApplePayHelpers
* class by calling the delegate methods on BUYApplePayHelpers which already implements
* the IPKPaymentAuthorizationViewControllerDelegate interface.
*
*/
PresentViewController (paymentController, true, null);
}
private PKPaymentRequest GetPaymentRequest ()
{
var paymentRequest = new PKPaymentRequest ();
paymentRequest.MerchantIdentifier = AppDelegate.MERCHANT_ID;
paymentRequest.RequiredBillingAddressFields = PKAddressField.All;
paymentRequest.RequiredShippingAddressFields = checkout.RequiresShipping ? PKAddressField.All : PKAddressField.Email | PKAddressField.Phone;
paymentRequest.SupportedNetworks = new [] {
PKPaymentNetwork.Visa,
PKPaymentNetwork.MasterCard
};
paymentRequest.MerchantCapabilities = PKMerchantCapability.ThreeDS;
paymentRequest.CountryCode = shop != null ? shop.Country : "US";
paymentRequest.CurrencyCode = shop != null ? shop.Currency : "USD";
paymentRequest.PaymentSummaryItems = checkout.ApplePaySummaryItems (shop.Name);
return paymentRequest;
}
private void CheckoutOnWeb (object sender, EventArgs e)
{
IDisposable observer = null;
observer = NSNotificationCenter.DefaultCenter.AddObserver (AppDelegate.CheckoutCallbackNotification, notification => {
var url = (NSUrl)notification.UserInfo ["url"];
if (PresentedViewController is SFSafariViewController) {
DismissViewController (true, () => {
GetCompletionStatusAndCompletedCheckoutWithURL (url);
});
} else {
GetCompletionStatusAndCompletedCheckoutWithURL (url);
}
observer.Dispose ();
});
// On iOS 9+ we should use the SafariViewController to display the checkout in-app
if (UIDevice.CurrentDevice.CheckSystemVersion (9, 0)) {
var safariViewController = new SFSafariViewController (checkout.WebCheckoutURL);
safariViewController.Delegate = this;
PresentViewController (safariViewController, true, null);
} else {
UIApplication.SharedApplication.OpenUrl (checkout.WebCheckoutURL);
}
}
private void GetCompletionStatusAndCompletedCheckoutWithURL (NSUrl url)
{
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
client.GetCompletionStatusOfCheckoutURL (url, (status, error) => {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
if (error == null && status == BUYStatus.Complete) {
Console.WriteLine ("Successfully completed checkout");
GetCompletedCheckout (() => {
InvokeOnMainThread (() => {
ShowCheckoutConfirmation ();
});
});
} else {
Console.WriteLine ("Error completing checkout: {0}", error);
}
});
}
private void GetCompletedCheckout (Action completionBlock)
{
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
client.GetCheckout (checkout, (checkout, error) => {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
if (error != null) {
Console.WriteLine ("Unable to get completed checkout");
Console.WriteLine (error);
}
if (checkout != null) {
this.checkout = checkout;
Console.WriteLine (checkout);
}
if (completionBlock != null) {
completionBlock ();
}
});
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001;
using System;
using System.Collections.Generic;
public class C
{
}
public interface I
{
}
public class MyClass
{
public int Field = 0;
}
public struct MyStruct
{
public int Number;
}
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public class MemberClass<T>
{
#region Instance methods
public bool Method_ReturnBool()
{
return false;
}
public T Method_ReturnsT()
{
return default(T);
}
public T Method_ReturnsT(T t)
{
return t;
}
public T Method_ReturnsT(out T t)
{
t = default(T);
return t;
}
public T Method_ReturnsT(ref T t, T tt)
{
t = default(T);
return t;
}
public T Method_ReturnsT(params T[] t)
{
return default(T);
}
public T Method_ReturnsT(float x, T t)
{
return default(T);
}
public int Method_ReturnsInt(T t)
{
return 1;
}
public float Method_ReturnsFloat(T t, dynamic d)
{
return 3.4f;
}
public float Method_ReturnsFloat(T t, dynamic d, ref decimal dec)
{
dec = 3m;
return 3.4f;
}
public dynamic Method_ReturnsDynamic(T t)
{
return t;
}
public dynamic Method_ReturnsDynamic(T t, dynamic d)
{
return t;
}
public dynamic Method_ReturnsDynamic(T t, int x, dynamic d)
{
return t;
}
// Multiple params
// Constraints
// Nesting
#endregion
#region Static methods
public static bool? StaticMethod_ReturnBoolNullable()
{
return (bool?)false;
}
#endregion
}
public class MemberClassMultipleParams<T, U, V>
{
public T Method_ReturnsT(V v, U u)
{
return default(T);
}
}
public class MemberClassWithClassConstraint<T>
where T : class
{
public int Method_ReturnsInt()
{
return 1;
}
public T Method_ReturnsT(decimal dec, dynamic d)
{
return null;
}
}
public class MemberClassWithNewConstraint<T>
where T : new()
{
public T Method_ReturnsT()
{
return new T();
}
public dynamic Method_ReturnsDynamic(T t)
{
return new T();
}
}
public class MemberClassWithAnotherTypeConstraint<T, U>
where T : U
{
public U Method_ReturnsU(dynamic d)
{
return default(U);
}
public dynamic Method_ReturnsDynamic(int x, U u, dynamic d)
{
return default(T);
}
}
#region Negative tests - you should not be able to construct this with a dynamic object
public class MemberClassWithUDClassConstraint<T>
where T : C, new()
{
public C Method_ReturnsC()
{
return new T();
}
}
public class MemberClassWithStructConstraint<T>
where T : struct
{
public dynamic Method_ReturnsDynamic(int x)
{
return x;
}
}
public class MemberClassWithInterfaceConstraint<T>
where T : I
{
public dynamic Method_ReturnsDynamic(int x, T v)
{
return default(T);
}
}
#endregion
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001;
// <Title> Tests generic class regular method used in regular method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
if (t.TestMethod() == true)
return 1;
return 0;
}
public bool TestMethod()
{
dynamic mc = new MemberClass<string>();
return (bool)mc.Method_ReturnBool();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass002.genclass002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass002.genclass002;
// <Title> Tests generic class regular method used in arguments of method invocation.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
dynamic mc1 = new MemberClass<int>();
int result1 = t.TestMethod((int)mc1.Method_ReturnsT());
dynamic mc2 = new MemberClass<string>();
int result2 = Test.TestMethod((string)mc2.Method_ReturnsT());
if (result1 == 0 && result2 == 0)
return 0;
else
return 1;
}
public int TestMethod(int i)
{
if (i == default(int))
{
return 0;
}
else
{
return 1;
}
}
public static int TestMethod(string s)
{
if (s == default(string))
{
return 0;
}
else
{
return 1;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass003.genclass003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass003.genclass003;
// <Title> Tests generic class regular method used in static variable.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static dynamic s_mc = new MemberClass<string>();
private static float s_loc = (float)s_mc.Method_ReturnsFloat(null, 1);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (s_loc != 3.4f)
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass005.genclass005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass005.genclass005;
// <Title> Tests generic class regular method used in unsafe.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//using System;
//[TestClass]public class Test
//{
//[Test][Priority(Priority.Priority1)]public void DynamicCSharpRunTest(){Assert.AreEqual(0, MainMethod());} public static unsafe int MainMethod()
//{
//dynamic dy = new MemberClass<int>();
//int value = 1;
//int* valuePtr = &value;
//int result = dy.Method_ReturnsT(out *valuePtr);
//if (result == 0 && value == 0)
//return 0;
//return 1;
//}
//}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass006.genclass006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass006.genclass006;
// <Title> Tests generic class regular method used in generic method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
string s1 = "";
string s2 = "";
string result = t.TestMethod<string>(ref s1, s2);
if (result == null && s1 == null)
return 0;
return 1;
}
public T TestMethod<T>(ref T t1, T t2)
{
dynamic mc = new MemberClass<T>();
return (T)mc.Method_ReturnsT(ref t1, t2);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass008.genclass008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass008.genclass008;
// <Title> Tests generic class regular method used in extension method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public int Field = 10;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = 1.ExReturnTest();
if (t.Field == 1)
return 0;
return 1;
}
}
static public class Extension
{
public static Test ExReturnTest(this int t)
{
dynamic dy = new MemberClass<int>();
float x = 3.3f;
int i = -1;
return new Test()
{
Field = t + (int)dy.Method_ReturnsT(x, i)
}
;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009.genclass009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009.genclass009;
// <Title> Tests generic class regular method used in for loop.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<MyEnum>();
int result = 0;
for (int i = (int)dy.Method_ReturnsInt(MyEnum.Third); i < 10; i++)
{
result += (int)dy.Method_ReturnsInt((MyEnum)(i % 3 + 1));
}
if (result == 9)
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009a.genclass009a
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009a.genclass009a;
// <Title> Tests generic class regular method used in for loop.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<MyEnum>();
int result = 0;
for (int i = dy.Method_ReturnsInt(MyEnum.Third); i < 10; i++)
{
result += dy.Method_ReturnsInt((MyEnum)(i % 3 + 1));
}
if (result == 9)
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass010.genclass010
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass010.genclass010;
// <Title> Tests generic class regular method used in static constructor.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test : I
{
private static decimal s_dec = 0M;
private static float s_result = 0f;
static Test()
{
dynamic dy = new MemberClass<I>();
s_result = (float)dy.Method_ReturnsFloat(new Test(), dy, ref s_dec);
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (Test.s_dec == 3M && Test.s_result == 3.4f)
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass012.genclass012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass012.genclass012;
// <Title> Tests generic class regular method used in lambda.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<string>();
dynamic d1 = 3;
dynamic d2 = "Test";
Func<string, string, string> fun = (x, y) => (y + x.ToString());
string result = fun((string)dy.Method_ReturnsDynamic("foo", d1), (string)dy.Method_ReturnsDynamic("bar", d2));
if (result == "barfoo")
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass013.genclass013
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass013.genclass013;
// <Title> Tests generic class regular method used in array initializer list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<string>();
string[] array = new string[]
{
(string)dy.Method_ReturnsDynamic(string.Empty, 1, dy), (string)dy.Method_ReturnsDynamic(null, 0, dy), (string)dy.Method_ReturnsDynamic("a", -1, dy)}
;
if (array.Length == 3 && array[0] == string.Empty && array[1] == null && array[2] == "a")
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass014.genclass014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass014.genclass014;
// <Title> Tests generic class regular method used in null coalescing operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = MemberClass<string>.StaticMethod_ReturnBoolNullable();
if (!((bool?)dy ?? false))
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass015.genclass015
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass015.genclass015;
// <Title> Tests generic class regular method used in static method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassMultipleParams<MyEnum, MyStruct, MyClass>();
MyEnum me = dy.Method_ReturnsT(null, new MyStruct());
return (int)me;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass016.genclass016
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass016.genclass016;
// <Title> Tests generic class regular method used in query expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
private class M
{
public int Field1;
public int Field2;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassWithClassConstraint<MyClass>();
var list = new List<M>()
{
new M()
{
Field1 = 1, Field2 = 2
}
, new M()
{
Field1 = 2, Field2 = 1
}
}
;
return list.Any(p => p.Field1 == (int)dy.Method_ReturnsInt()) ? 0 : 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass017.genclass017
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass017.genclass017;
// <Title> Tests generic class regular method used in ternary operator expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassWithClassConstraint<string>();
string result = (string)dy.Method_ReturnsT(decimal.MaxValue, dy) == null ? string.Empty : (string)dy.Method_ReturnsT(decimal.MaxValue, dy);
return result == string.Empty ? 0 : 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass018.genclass018
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass018.genclass018;
// <Title> Tests generic class regular method used in lock expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassWithNewConstraint<C>();
int result = 1;
lock (dy.Method_ReturnsT())
{
result = 0;
}
return result;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass019.genclass019
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass019.genclass019;
// <Title> Tests generic class regular method used in switch section statement list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy1 = new MemberClassWithNewConstraint<C>();
dynamic dy2 = new MemberClassWithAnotherTypeConstraint<int, int>();
C result = new C();
int result2 = -1;
switch ((int)dy2.Method_ReturnsU(dy1)) // 0
{
case 0:
result = (C)dy1.Method_ReturnsDynamic(result); // called
break;
default:
result2 = (int)dy2.Method_ReturnsDynamic(0, 0, dy2); // not called
break;
}
return (result.GetType() == typeof(C) && result2 == -1) ? 0 : 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.implicit01.implicit01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.implicit01.implicit01;
// <Title> Tests generic class regular method used in regular method body.</Title>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Ta
{
public static int i = 2;
}
public class A<T>
{
public static implicit operator A<List<string>>(A<T> x)
{
return new A<List<string>>();
}
}
public class B
{
public static void Foo<T>(A<List<T>> x, string y)
{
Ta.i--;
}
public static void Foo<T>(object x, string y)
{
Ta.i++;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var x = new A<Action<object>>();
Foo<string>(x, "");
Foo<string>(x, (dynamic)"");
return Ta.i;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Diagnostics;
using System.Globalization;
namespace System.DirectoryServices.AccountManagement
{
internal enum PrincipalAccessMask
{
ChangePassword
}
internal abstract class StoreCtx : IDisposable
{
//
// StoreCtx information
//
// Retrieves the Path (ADsPath) of the object used as the base of the StoreCtx
internal abstract string BasePath { get; }
// The PrincipalContext object to which this StoreCtx belongs. Initialized by PrincipalContext after it creates
// this StoreCtx instance.
private PrincipalContext _owningContext = null;
internal PrincipalContext OwningContext
{
get
{
return _owningContext;
}
set
{
Debug.Assert(value != null);
_owningContext = value;
}
}
//
// CRUD
//
// Used to perform the specified operation on the Principal. They also make any needed security subsystem
// calls to obtain digitial signatures (e..g, to sign the Principal Extension/GroupMember Relationship for
// WinFS).
//
// Insert() and Update() must check to make sure no properties not supported by this StoreCtx
// have been set, prior to persisting the Principal.
internal abstract void Insert(Principal p);
internal abstract void Update(Principal p);
internal abstract void Delete(Principal p);
internal abstract void Move(StoreCtx originalStore, Principal p);
//
// Native <--> Principal
//
// For modified object, pushes any changes (including IdentityClaim changes)
// into the underlying store-specific object (e.g., DirectoryEntry) and returns the underlying object.
// For unpersisted object, creates a underlying object if one doesn't already exist (in
// Principal.UnderlyingObject), then pushes any changes into the underlying object.
internal abstract object PushChangesToNative(Principal p);
// Given a underlying store object (e.g., DirectoryEntry), further narrowed down a discriminant
// (if applicable for the StoreCtx type), returns a fresh instance of a Principal
// object based on it. The WinFX Principal API follows ADSI-style semantics, where you get multiple
// in-memory objects all referring to the same store pricipal, rather than WinFS semantics, where
// multiple searches all return references to the same in-memory object.
// Used to implement the reverse wormhole. Also, used internally by FindResultEnumerator
// to construct Principals from the store objects returned by a store query.
//
// The Principal object produced by this method does not have all the properties
// loaded. The Principal object will call the Load method on demand to load its properties
// from its Principal.UnderlyingObject.
//
//
// This method works for native objects from the store corresponding to _this_ StoreCtx.
// Each StoreCtx will also have its own internal algorithms used for dealing with cross-store objects, e.g.,
// for use when iterating over group membership. These routines are exposed as
// ResolveCrossStoreRefToPrincipal, and will be called by the StoreCtx's associated ResultSet
// classes when iterating over a representation of a "foreign" principal.
internal abstract Principal GetAsPrincipal(object storeObject, object discriminant);
// Loads the store values from p.UnderlyingObject into p, performing schema mapping as needed.
internal abstract void Load(Principal p);
// Loads only the psecified property into the principal object. The object should have already been persisted or searched for this to happen.
internal abstract void Load(Principal p, string principalPropertyName);
// Performs store-specific resolution of an IdentityReference to a Principal
// corresponding to the IdentityReference. Returns null if no matching object found.
// principalType can be used to scope the search to principals of a specified type, e.g., users or groups.
// Specify typeof(Principal) to search all principal types.
internal abstract Principal FindPrincipalByIdentRef(
Type principalType, string urnScheme, string urnValue, DateTime referenceDate);
// Returns a type indicating the type of object that would be returned as the wormhole for the specified
// Principal. For some StoreCtxs, this method may always return a constant (e.g., typeof(DirectoryEntry)
// for ADStoreCtx). For others, it may vary depending on the Principal passed in.
internal abstract Type NativeType(Principal p);
//
// Special operations: the Principal classes delegate their implementation of many of the
// special methods to their underlying StoreCtx
//
// methods for manipulating accounts
internal abstract void InitializeUserAccountControl(AuthenticablePrincipal p);
internal abstract bool IsLockedOut(AuthenticablePrincipal p);
internal abstract void UnlockAccount(AuthenticablePrincipal p);
// methods for manipulating passwords
internal abstract void SetPassword(AuthenticablePrincipal p, string newPassword);
internal abstract void ChangePassword(AuthenticablePrincipal p, string oldPassword, string newPassword);
internal abstract void ExpirePassword(AuthenticablePrincipal p);
internal abstract void UnexpirePassword(AuthenticablePrincipal p);
internal abstract bool AccessCheck(Principal p, PrincipalAccessMask targetPermission);
// the various FindBy* methods
internal abstract ResultSet FindByLockoutTime(
DateTime dt, MatchType matchType, Type principalType);
internal abstract ResultSet FindByLogonTime(
DateTime dt, MatchType matchType, Type principalType);
internal abstract ResultSet FindByPasswordSetTime(
DateTime dt, MatchType matchType, Type principalType);
internal abstract ResultSet FindByBadPasswordAttempt(
DateTime dt, MatchType matchType, Type principalType);
internal abstract ResultSet FindByExpirationTime(
DateTime dt, MatchType matchType, Type principalType);
// Get groups of which p is a direct member
internal abstract ResultSet GetGroupsMemberOf(Principal p);
// Get groups from this ctx which contain a principal corresponding to foreignPrincipal
// (which is a principal from foreignContext)
internal abstract ResultSet GetGroupsMemberOf(Principal foreignPrincipal, StoreCtx foreignContext);
// Get groups of which p is a member, using AuthZ S4U APIs for recursive membership
internal abstract ResultSet GetGroupsMemberOfAZ(Principal p);
// Get members of group g
internal abstract BookmarkableResultSet GetGroupMembership(GroupPrincipal g, bool recursive);
// Is p a member of g in the store?
internal abstract bool SupportsNativeMembershipTest { get; }
internal abstract bool IsMemberOfInStore(GroupPrincipal g, Principal p);
// Can a Clear() operation be performed on the specified group? If not, also returns
// a string containing a human-readable explanation of why not, suitable for use in an exception.
internal abstract bool CanGroupBeCleared(GroupPrincipal g, out string explanationForFailure);
// Can the given member be removed from the specified group? If not, also returns
// a string containing a human-readable explanation of why not, suitable for use in an exception.
internal abstract bool CanGroupMemberBeRemoved(GroupPrincipal g, Principal member, out string explanationForFailure);
//
// Query operations
//
// Returns true if this store has native support for search (and thus a wormhole).
// Returns true for everything but SAM (both reg-SAM and MSAM).
internal abstract bool SupportsSearchNatively { get; }
// Returns a type indicating the type of object that would be returned as the wormhole for the specified
// PrincipalSearcher.
internal abstract Type SearcherNativeType();
// Pushes the query represented by the QBE filter into the PrincipalSearcher's underlying native
// searcher object (creating a fresh native searcher and assigning it to the PrincipalSearcher if one
// doesn't already exist) and returns the native searcher.
// If the PrincipalSearcher does not have a query filter set (PrincipalSearcher.QueryFilter == null),
// produces a query that will match all principals in the store.
//
// For stores which don't have a native searcher (SAM), the StoreCtx
// is free to create any type of object it chooses to use as its internal representation of the query.
//
// Also adds in any clauses to the searcher to ensure that only principals, not mere
// contacts, are retrieved from the store.
internal abstract object PushFilterToNativeSearcher(PrincipalSearcher ps);
// The core query operation.
// Given a PrincipalSearcher containg a query filter, transforms it into the store schema
// and performs the query to get a collection of matching native objects (up to a maximum of sizeLimit,
// or uses the sizelimit already set on the DirectorySearcher if sizeLimit == -1).
// If the PrincipalSearcher does not have a query filter (PrincipalSearcher.QueryFilter == null),
// matches all principals in the store.
//
// The collection may not be complete, i.e., paging - the returned ResultSet will automatically
// page in additional results as needed.
internal abstract ResultSet Query(PrincipalSearcher ps, int sizeLimit);
//
// Cross-store support
//
// Given a native store object that represents a "foreign" principal (e.g., a FPO object in this store that
// represents a pointer to another store), maps that representation to the other store's StoreCtx and returns
// a Principal from that other StoreCtx. The implementation of this method is highly dependent on the
// details of the particular store, and must have knowledge not only of this StoreCtx, but also of how to
// interact with other StoreCtxs to fulfill the request.
//
// This method is typically used by ResultSet implementations, when they're iterating over a collection
// (e.g., of group membership) and encounter an entry that represents a foreign principal.
internal abstract Principal ResolveCrossStoreRefToPrincipal(object o);
//
// Data Validation
//
// Validiate the passed property name to determine if it is valid for the store and Principal type.
// used by the principal objects to determine if a property is valid in the property before
// save is called.
internal abstract bool IsValidProperty(Principal p, string propertyName);
// Returns true if AccountInfo is supported for the specified principal, false otherwise.
// Used when an application tries to access the AccountInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
internal abstract bool SupportsAccounts(AuthenticablePrincipal p);
// Returns the set of credential types supported by this store for the specified principal.
// Used when an application tries to access the PasswordInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
// Also used to implement AuthenticablePrincipal.SupportedCredentialTypes.
internal abstract CredentialTypes SupportedCredTypes(AuthenticablePrincipal p);
//
// Construct a fake Principal to represent a well-known SID like
// "\Everyone" or "NT AUTHORITY\NETWORK SERVICE"
//
internal abstract Principal ConstructFakePrincipalFromSID(byte[] sid);
//
// IDisposable implementation
//
// Disposes of this instance of a StoreCtx. Calling this method more than once is allowed, and all but
// the first call should be ignored.
public virtual void Dispose()
{
// Nothing to do in the base class
}
//
// QBE Filter parsing
//
// These property sets include only the properties used to build QBE filters,
// e.g., the Group.Members property is not included
internal static string[] principalProperties = new string[]
{
PropertyNames.PrincipalDisplayName,
PropertyNames.PrincipalDescription,
PropertyNames.PrincipalSamAccountName,
PropertyNames.PrincipalUserPrincipalName,
PropertyNames.PrincipalGuid,
PropertyNames.PrincipalSid,
PropertyNames.PrincipalStructuralObjectClass,
PropertyNames.PrincipalName,
PropertyNames.PrincipalDistinguishedName,
PropertyNames.PrincipalExtensionCache
};
internal static string[] authenticablePrincipalProperties = new string[]
{
PropertyNames.AuthenticablePrincipalEnabled,
PropertyNames.AuthenticablePrincipalCertificates,
PropertyNames.PwdInfoLastBadPasswordAttempt,
PropertyNames.AcctInfoExpirationDate,
PropertyNames.AcctInfoExpiredAccount,
PropertyNames.AcctInfoLastLogon,
PropertyNames.AcctInfoAcctLockoutTime,
PropertyNames.AcctInfoBadLogonCount,
PropertyNames.PwdInfoLastPasswordSet
};
// includes AccountInfo and PasswordInfo
internal static string[] userProperties = new string[]
{
PropertyNames.UserGivenName,
PropertyNames.UserMiddleName,
PropertyNames.UserSurname,
PropertyNames.UserEmailAddress,
PropertyNames.UserVoiceTelephoneNumber,
PropertyNames.UserEmployeeID,
PropertyNames.AcctInfoPermittedWorkstations,
PropertyNames.AcctInfoPermittedLogonTimes,
PropertyNames.AcctInfoSmartcardRequired,
PropertyNames.AcctInfoDelegationPermitted,
PropertyNames.AcctInfoHomeDirectory,
PropertyNames.AcctInfoHomeDrive,
PropertyNames.AcctInfoScriptPath,
PropertyNames.PwdInfoPasswordNotRequired,
PropertyNames.PwdInfoPasswordNeverExpires,
PropertyNames.PwdInfoCannotChangePassword,
PropertyNames.PwdInfoAllowReversiblePasswordEncryption
};
internal static string[] groupProperties = new string[]
{
PropertyNames.GroupIsSecurityGroup,
PropertyNames.GroupGroupScope
};
internal static string[] computerProperties = new string[]
{
PropertyNames.ComputerServicePrincipalNames
};
protected QbeFilterDescription BuildQbeFilterDescription(Principal p)
{
QbeFilterDescription qbeFilterDescription = new QbeFilterDescription();
// We don't have to check to make sure the application didn't try to set any
// disallowed properties (i..e, referential properties, such as Group.Members),
// because that check was enforced by the PrincipalSearcher in its
// FindAll() and GetUnderlyingSearcher() methods, by calling
// PrincipalSearcher.HasReferentialPropertiesSet().
if (p is Principal)
BuildFilterSet(p, principalProperties, qbeFilterDescription);
if (p is AuthenticablePrincipal)
BuildFilterSet(p, authenticablePrincipalProperties, qbeFilterDescription);
if (p is UserPrincipal) // includes AccountInfo and PasswordInfo
{
// AcctInfoExpirationDate and AcctInfoExpiredAccount represent filters on the same property
// check that only one is specified
if (p.GetChangeStatusForProperty(PropertyNames.AcctInfoExpirationDate) &&
p.GetChangeStatusForProperty(PropertyNames.AcctInfoExpiredAccount))
{
throw new InvalidOperationException(
SR.Format(
SR.StoreCtxMultipleFiltersForPropertyUnsupported,
PropertyNamesExternal.GetExternalForm(ExpirationDateFilter.PropertyNameStatic)));
}
BuildFilterSet(p, userProperties, qbeFilterDescription);
}
if (p is GroupPrincipal)
BuildFilterSet(p, groupProperties, qbeFilterDescription);
if (p is ComputerPrincipal)
BuildFilterSet(p, computerProperties, qbeFilterDescription);
return qbeFilterDescription;
}
// Applies to supplied propertySet to the supplied Principal, and adds any resulting filters
// to qbeFilterDescription.
private void BuildFilterSet(Principal p, string[] propertySet, QbeFilterDescription qbeFilterDescription)
{
foreach (string propertyName in propertySet)
{
if (p.GetChangeStatusForProperty(propertyName))
{
// Property has changed. Add it to the filter set.
object value = p.GetValueForProperty(propertyName);
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"StoreCtx",
"BuildFilterSet: type={0}, property name={1}, property value={2} of type {3}",
p.GetType().ToString(),
propertyName,
value.ToString(),
value.GetType().ToString());
// Build the right filter based on type of the property value
if (value is PrincipalValueCollection<string>)
{
PrincipalValueCollection<string> trackingList = (PrincipalValueCollection<string>)value;
foreach (string s in trackingList.Inserted)
{
object filter = FilterFactory.CreateFilter(propertyName);
((FilterBase)filter).Value = (string)s;
qbeFilterDescription.FiltersToApply.Add(filter);
}
}
else if (value is X509Certificate2Collection)
{
// Since QBE filter objects are always unpersisted, any certs in the collection
// must have been inserted by the application.
X509Certificate2Collection certCollection = (X509Certificate2Collection)value;
foreach (X509Certificate2 cert in certCollection)
{
object filter = FilterFactory.CreateFilter(propertyName);
((FilterBase)filter).Value = (X509Certificate2)cert;
qbeFilterDescription.FiltersToApply.Add(filter);
}
}
else
{
// It's not one of the multivalued cases. Try the scalar cases.
object filter = FilterFactory.CreateFilter(propertyName);
if (value == null)
{
((FilterBase)filter).Value = null;
}
else if (value is bool)
{
((FilterBase)filter).Value = (bool)value;
}
else if (value is string)
{
((FilterBase)filter).Value = (string)value;
}
else if (value is GroupScope)
{
((FilterBase)filter).Value = (GroupScope)value;
}
else if (value is byte[])
{
((FilterBase)filter).Value = (byte[])value;
}
else if (value is Nullable<DateTime>)
{
((FilterBase)filter).Value = (Nullable<DateTime>)value;
}
else if (value is ExtensionCache)
{
((FilterBase)filter).Value = (ExtensionCache)value;
}
else if (value is QbeMatchType)
{
((FilterBase)filter).Value = (QbeMatchType)value;
}
else
{
// Internal error. Didn't match either the known multivalued or scalar cases.
Debug.Fail($"StoreCtx.BuildFilterSet: fell off end looking for {propertyName} of type {value.GetType()}");
}
qbeFilterDescription.FiltersToApply.Add(filter);
}
}
}
}
}
}
| |
#region Copyright (C) 2009 by Pavel Savara
/*
This file is part of jni4net library - bridge between Java and .NET
http://jni4net.sourceforge.net/
This program 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 3
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#endregion
using System;
using System.Diagnostics;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using Exception=System.Exception;
namespace MonoJavaBridge
{
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.Execution | SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.SkipVerification)]
public unsafe partial class JNIEnv
{
#region JNI methods
public int GetVersion()
{
int version = getVersion(envPtr);
ExceptionTest();
return version;
}
public JavaVM GetJavaVM()
{
if (javaVM == null)
{
IntPtr jvm;
getJavaVM.Invoke(envPtr, out jvm);
ExceptionTest();
javaVM = new JavaVM(jvm);
}
return javaVM;
}
#endregion
#region reflection
public JniLocalHandle FindClassPtr(string name)
{
JniLocalHandle clazz = findClass.Invoke(envPtr, name);
ExceptionTest();
return clazz;
}
public JniLocalHandle FindClass(string name)
{
JniLocalHandle clazz = findClass.Invoke(envPtr, name);
ExceptionTest();
return clazz;
}
public JniLocalHandle FindClassPtrNoThrow(string name)
{
JniLocalHandle clazz = findClass.Invoke(envPtr, name);
if (ExceptionRead())
{
return JniLocalHandle.Zero;
}
return clazz;
}
public JniLocalHandle FindClassNoThrow(string name)
{
JniLocalHandle clazz = findClass.Invoke(envPtr, name);
if (ExceptionRead())
{
return JniLocalHandle.Zero;
}
return clazz;
}
public JniLocalHandle GetObjectClass(JniHandle obj)
{
if (JniHandle.IsNull(obj))
{
return JniLocalHandle.Zero;
}
JniLocalHandle res = getObjectClass.Invoke(envPtr, obj);
ExceptionTest();
return res;
}
public MethodId GetStaticMethodID(JniHandle clazz, string name, string sig)
{
IntPtr res = getStaticMethodID.Invoke(envPtr, clazz, name, sig);
ExceptionTest();
return new MethodId(res);
}
public MethodId GetStaticMethodIDNoThrow(JniHandle clazz, string name, string sig)
{
IntPtr res = getStaticMethodID.Invoke(envPtr, clazz, name, sig);
if (ExceptionRead())
{
return new MethodId(IntPtr.Zero);
}
return new MethodId(res);
}
public MethodId GetMethodID(JniHandle clazz, string name, string sig)
{
IntPtr res = getMethodID.Invoke(envPtr, clazz, name, sig);
ExceptionTest();
return new MethodId(res);
}
public MethodId GetMethodIDNoThrow(JniHandle clazz, string name, string sig)
{
IntPtr res = getMethodID.Invoke(envPtr, clazz, name, sig);
if (ExceptionRead())
{
return new MethodId(IntPtr.Zero);
}
return new MethodId(res);
}
public FieldId GetFieldID(JniHandle clazz, string name, string sig)
{
IntPtr res = getFieldID.Invoke(envPtr, clazz, name, sig);
ExceptionTest();
return new FieldId(res);
}
#if !JNI4NET_MINI
public JniLocalHandle ToReflectedField(JniHandle cls, FieldId fieldID, bool isStatic)
{
JniLocalHandle res = toReflectedField.Invoke(envPtr, cls, fieldID.native,
isStatic ? (byte) 1 : (byte) 0);
ExceptionTest();
return res;
}
public JniLocalHandle ToReflectedMethod(JniHandle cls, MethodId methodId, bool isStatic)
{
JniLocalHandle res = toReflectedMethod.Invoke(envPtr, cls, methodId.native,
isStatic ? (byte) 1 : (byte) 0);
ExceptionTest();
return res;
}
public MethodId FromReflectedMethod(JniLocalHandle methodId)
{
IntPtr res = fromReflectedMethod.Invoke(envPtr, methodId);
ExceptionTest();
return new MethodId(res);
}
public FieldId FromReflectedField(JavaObject field)
{
IntPtr res = fromReflectedField.Invoke(envPtr, field.mJvmHandle);
ExceptionTest();
return new FieldId(res);
}
#endif
public IntPtr GetStaticFieldIDPtr(JniHandle clazz, string name, string sig)
{
IntPtr res = getStaticFieldID.Invoke(envPtr, clazz, name, sig);
ExceptionTest();
return res;
}
public FieldId GetStaticFieldID(JniHandle clazz, string name, string sig)
{
IntPtr res = GetStaticFieldIDPtr(clazz, name, sig);
return new FieldId(res);
}
public JNIResult RegisterNatives(JniHandle clazz, JNINativeMethod* methods, int nMethods)
{
JNIResult natives = registerNatives.Invoke(envPtr, clazz, methods, nMethods);
ExceptionTest();
return natives;
}
public JNIResult UnregisterNatives(JniHandle clazz)
{
JNIResult natives = unregisterNatives.Invoke(envPtr, clazz);
ExceptionTest();
return natives;
}
#endregion
#region call static
public void CallStaticVoidMethod(JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
callStaticVoidMethod(envPtr, clazz, methodIdNative.native, args);
//TODO result could be tested in Java 1.6
ExceptionTest();
}
public int CallStaticIntMethod(JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
int res = callStaticIntMethod(envPtr, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public long CallStaticLongMethod(JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
long res = callStaticLongMethod(envPtr, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public double CallStaticDoubleMethod(JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
double res = callStaticDoubleMethod(envPtr, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public float CallStaticFloatMethod(JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
float res = callStaticFloatMethod(envPtr, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public short CallStaticShortMethod(JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
short res = callStaticShortMethod(envPtr, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public char CallStaticCharMethod(JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = (char) callStaticCharMethod(envPtr, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public bool CallStaticBooleanMethod(JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
bool res = callStaticBooleanMethod(envPtr, clazz, methodIdNative.native, args) != 0;
ExceptionTest();
return res;
}
public byte CallStaticByteMethod(JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
byte res = callStaticByteMethod(envPtr, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
internal void CallStaticVoidMethod(JniHandle clazz, string method, string sig, params Value[] args)
{
MethodId idNative = GetStaticMethodID(clazz, method, sig);
CallStaticVoidMethod(clazz, idNative, args);
}
#endregion
#region call instance
public bool CallNonVirtualBooleanMethod(JavaObject obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = 0 != callNonvirtualBooleanMethod(envPtr, obj.JvmHandle, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public bool CallNonVirtualBooleanMethod(JniHandle obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = 0 != callNonvirtualBooleanMethod(envPtr, obj, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public void CallNonVirtualVoidMethod(JavaObject obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
callNonvirtualVoidMethod(envPtr, obj.JvmHandle, clazz, methodIdNative.native, args);
ExceptionTest();
}
public void CallNonVirtualVoidMethod(JniHandle obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
callNonvirtualVoidMethod(envPtr, obj, clazz, methodIdNative.native, args);
ExceptionTest();
}
public IntPtr CallNonVirtualObjectMethodPtr(JavaObject obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualObjectMethod(envPtr, obj.JvmHandle, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public IntPtr CallNonVirtualObjectMethod(JniHandle obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualObjectMethod(envPtr, obj, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public byte CallNonVirtualByteMethod(JavaObject obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualByteMethod(envPtr, obj.JvmHandle, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public byte CallNonVirtualByteMethod(JniHandle obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualByteMethod(envPtr, obj, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public char CallNonVirtualCharMethod(JavaObject obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = (char)callNonvirtualCharMethod(envPtr, obj.JvmHandle, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public char CallNonVirtualCharMethod(JniHandle obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = (char)callNonvirtualCharMethod(envPtr, obj, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public short CallNonVirtualShortMethod(JavaObject obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualShortMethod(envPtr, obj.JvmHandle, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public short CallNonVirtualShortMethod(JniHandle obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualShortMethod(envPtr, obj, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public int CallNonVirtualIntMethod(JavaObject obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualIntMethod(envPtr, obj.JvmHandle, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public int CallNonVirtualIntMethod(JniHandle obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualIntMethod(envPtr, obj, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public long CallNonVirtualLongMethod(JavaObject obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualLongMethod(envPtr, obj.JvmHandle, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public long CallNonVirtualLongMethod(JniHandle obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualLongMethod(envPtr, obj, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public float CallNonVirtualFloatMethod(JavaObject obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualFloatMethod(envPtr, obj.JvmHandle, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public float CallNonVirtualFloatMethod(JniHandle obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualFloatMethod(envPtr, obj, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public double CallNonVirtualDoubleMethod(JavaObject obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualDoubleMethod(envPtr, obj.JvmHandle, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public double CallNonVirtualDoubleMethod(JniHandle obj, JniHandle clazz, MethodId methodIdNative, params Value[] args)
{
var res = callNonvirtualDoubleMethod(envPtr, obj, clazz, methodIdNative.native, args);
ExceptionTest();
return res;
}
public void CallVoidMethod(JniHandle obj, MethodId methodId, params Value[] args)
{
callVoidMethod(envPtr, obj, methodId.native, args);
//TODO result could be tested in Java 1.6
ExceptionTest();
}
public bool CallBooleanMethod(JavaObject obj, MethodId methodIdNative, params Value[] args)
{
bool res = callBooleanMethod(envPtr, obj.JvmHandle, methodIdNative.native, args) != 0;
ExceptionTest();
return res;
}
public bool CallBooleanMethod(JniHandle obj, MethodId methodIdNative, params Value[] args)
{
bool res = callBooleanMethod(envPtr, obj, methodIdNative.native, args) != 0;
ExceptionTest();
return res;
}
public int CallIntMethod(JavaObject obj, MethodId methodIdNative, params Value[] args)
{
int res = callIntMethod(envPtr, obj.JvmHandle, methodIdNative.native, args);
ExceptionTest();
return res;
}
public int CallIntMethod(JniHandle obj, MethodId methodIdNative, params Value[] args)
{
int res = callIntMethod(envPtr, obj, methodIdNative.native, args);
ExceptionTest();
return res;
}
public short CallShortMethod(JavaObject obj, MethodId methodIdNative, params Value[] args)
{
short res = callShortMethod(envPtr, obj.JvmHandle, methodIdNative.native, args);
ExceptionTest();
return res;
}
public short CallShortMethod(JniHandle obj, MethodId methodIdNative, params Value[] args)
{
short res = callShortMethod(envPtr, obj, methodIdNative.native, args);
ExceptionTest();
return res;
}
public long CallLongMethod(JavaObject obj, MethodId methodIdNative, params Value[] args)
{
long res = callLongMethod(envPtr, obj.JvmHandle, methodIdNative.native, args);
ExceptionTest();
return res;
}
public long CallLongMethod(JniHandle obj, MethodId methodIdNative, params Value[] args)
{
long res = callLongMethod(envPtr, obj, methodIdNative.native, args);
ExceptionTest();
return res;
}
public byte CallByteMethod(JavaObject obj, MethodId methodIdNative, params Value[] args)
{
byte res = callByteMethod(envPtr, obj.JvmHandle, methodIdNative.native, args);
ExceptionTest();
return res;
}
public byte CallByteMethod(JniHandle obj, MethodId methodIdNative, params Value[] args)
{
byte res = callByteMethod(envPtr, obj, methodIdNative.native, args);
ExceptionTest();
return res;
}
public double CallDoubleMethod(JavaObject obj, MethodId methodIdNative, params Value[] args)
{
double res = callDoubleMethod(envPtr, obj.JvmHandle, methodIdNative.native, args);
ExceptionTest();
return res;
}
public double CallDoubleMethod(JniHandle obj, MethodId methodIdNative, params Value[] args)
{
double res = callDoubleMethod(envPtr, obj, methodIdNative.native, args);
ExceptionTest();
return res;
}
public float CallFloatMethod(JavaObject obj, MethodId methodIdNative, params Value[] args)
{
float res = callFloatMethod(envPtr, obj.JvmHandle, methodIdNative.native, args);
ExceptionTest();
return res;
}
public float CallFloatMethod(JniHandle obj, MethodId methodIdNative, params Value[] args)
{
float res = callFloatMethod(envPtr, obj, methodIdNative.native, args);
ExceptionTest();
return res;
}
public char CallCharMethod(JavaObject obj, MethodId methodIdNative, params Value[] args)
{
var res = (char)callCharMethod(envPtr, obj.JvmHandle, methodIdNative.native, args);
ExceptionTest();
return res;
}
public char CallCharMethod(JniHandle obj, MethodId methodIdNative, params Value[] args)
{
var res = (char) callCharMethod(envPtr, obj, methodIdNative.native, args);
ExceptionTest();
return res;
}
#endregion
#region getters instance
public bool GetBooleanField(JavaObject obj, FieldId fieldID)
{
bool res = getBooleanField(envPtr, obj.JvmHandle, fieldID.native) != 0;
ExceptionTest();
return res;
}
public byte GetByteField(JavaObject obj, FieldId fieldID)
{
byte res = getByteField(envPtr, obj.JvmHandle, fieldID.native);
ExceptionTest();
return res;
}
public short GetShortField(JavaObject obj, FieldId fieldID)
{
short res = getShortField(envPtr, obj.JvmHandle, fieldID.native);
ExceptionTest();
return res;
}
public long GetLongField(JavaObject obj, FieldId fieldID)
{
long res = getLongField(envPtr, obj.JvmHandle, fieldID.native);
ExceptionTest();
return res;
}
public int GetIntField(JavaObject obj, FieldId fieldID)
{
return GetIntField(obj.JvmHandle, fieldID);
}
public int GetIntField(JniHandle obj, FieldId fieldID)
{
int res = getIntField(envPtr, obj, fieldID.native);
ExceptionTest();
return res;
}
public double GetDoubleField(JavaObject obj, FieldId fieldID)
{
double res = getDoubleField(envPtr, obj.JvmHandle, fieldID.native);
ExceptionTest();
return res;
}
public float GetFloatField(JavaObject obj, FieldId fieldID)
{
float res = getFloatField(envPtr, obj.JvmHandle, fieldID.native);
ExceptionTest();
return res;
}
public char GetCharField(JavaObject obj, FieldId fieldID)
{
var res = (char) getCharField(envPtr, obj.JvmHandle, fieldID.native);
ExceptionTest();
return res;
}
#endregion
#region setters instance
internal void SetObjectFieldPtr(JniLocalHandle obj, FieldId fieldID, JniHandle value)
{
setObjectField(envPtr, obj, fieldID.native, value);
ExceptionTest();
}
internal void SetObjectField(JavaObject obj, FieldId fieldID, JavaObject value)
{
setObjectField(envPtr, obj.JvmHandle, fieldID.native, value.JvmHandle);
ExceptionTest();
}
internal void SetIntField(JavaObject obj, FieldId fieldID, int value)
{
setIntField(envPtr, obj.JvmHandle, fieldID.native, value);
ExceptionTest();
}
internal void SetBooleanField(JavaObject obj, FieldId fieldID, bool value)
{
setBooleanField(envPtr, obj.JvmHandle, fieldID.native, value ? (byte) 1 : (byte) 0);
ExceptionTest();
}
internal void SetByteField(JavaObject obj, FieldId fieldID, byte value)
{
setByteField(envPtr, obj.JvmHandle, fieldID.native, value);
ExceptionTest();
}
internal void SetCharField(JavaObject obj, FieldId fieldID, char value)
{
setCharField(envPtr, obj.JvmHandle, fieldID.native, value);
ExceptionTest();
}
internal void SetShortField(JavaObject obj, FieldId fieldID, short value)
{
setShortField(envPtr, obj.JvmHandle, fieldID.native, value);
ExceptionTest();
}
internal void SetLongField(JavaObject obj, FieldId fieldID, long value)
{
setLongField(envPtr, obj.JvmHandle, fieldID.native, value);
ExceptionTest();
}
internal void SetFloatField(JavaObject obj, FieldId fieldID, float value)
{
setFloatField(envPtr, obj.JvmHandle, fieldID.native, value);
ExceptionTest();
}
internal void SetDoubleField(JavaObject obj, FieldId fieldID, double value)
{
setDoubleField(envPtr, obj.JvmHandle, fieldID.native, value);
ExceptionTest();
}
#endregion
#region setters static
internal void SetStaticObjectField(JniHandle clazz, FieldId fieldID, JavaObject value)
{
setStaticObjectField(envPtr, clazz, fieldID.native, value.JvmHandle);
ExceptionTest();
}
internal void SetStaticIntField(JniHandle clazz, FieldId fieldID, int value)
{
setStaticIntField(envPtr, clazz, fieldID.native, value);
ExceptionTest();
}
internal void SetStaticBooleanField(JniHandle clazz, IntPtr fieldID, bool value)
{
setStaticBooleanField(envPtr, clazz, fieldID, value ? (byte)1 : (byte)0);
ExceptionTest();
}
internal void SetStaticBooleanField(JniHandle clazz, FieldId fieldID, bool value)
{
SetStaticBooleanField(clazz, fieldID.native, value);
}
internal void SetStaticByteField(JniHandle clazz, FieldId fieldID, byte value)
{
setStaticByteField(envPtr, clazz, fieldID.native, value);
ExceptionTest();
}
internal void SetStaticCharField(JniHandle clazz, FieldId fieldID, char value)
{
setStaticCharField(envPtr, clazz, fieldID.native, value);
ExceptionTest();
}
internal void SetStaticShortField(JniHandle clazz, FieldId fieldID, short value)
{
setStaticShortField(envPtr, clazz, fieldID.native, value);
ExceptionTest();
}
internal void SetStaticLongField(JniHandle clazz, FieldId fieldID, long value)
{
setStaticLongField(envPtr, clazz, fieldID.native, value);
ExceptionTest();
}
internal void SetStaticFloatField(JniHandle clazz, FieldId fieldID, float value)
{
setStaticFloatField(envPtr, clazz, fieldID.native, value);
ExceptionTest();
}
internal void SetStaticDoubleField(JniHandle clazz, FieldId fieldID, double value)
{
setStaticDoubleField(envPtr, clazz, fieldID.native, value);
ExceptionTest();
}
#endregion
#region getters static
public bool GetStaticBooleanField(JniHandle clazz, IntPtr fieldID)
{
bool res = getStaticBooleanField(envPtr, clazz, fieldID) != 0;
ExceptionTest();
return res;
}
public bool GetStaticBooleanField(JniHandle clazz, FieldId fieldID)
{
return GetStaticBooleanField(clazz, fieldID.native);
}
public byte GetStaticByteField(JniHandle clazz, FieldId fieldID)
{
byte res = getStaticByteField(envPtr, clazz, fieldID.native);
ExceptionTest();
return res;
}
public short GetStaticShortField(JniHandle clazz, FieldId fieldID)
{
short res = getStaticShortField(envPtr, clazz, fieldID.native);
ExceptionTest();
return res;
}
public long GetStaticLongField(JniHandle clazz, FieldId fieldID)
{
long res = getStaticLongField(envPtr, clazz, fieldID.native);
ExceptionTest();
return res;
}
public int GetStaticIntField(JniHandle clazz, FieldId fieldID)
{
int res = getStaticIntField(envPtr, clazz, fieldID.native);
ExceptionTest();
return res;
}
public double GetStaticDoubleField(JniHandle clazz, FieldId fieldID)
{
double res = getStaticDoubleField(envPtr, clazz, fieldID.native);
ExceptionTest();
return res;
}
public float GetStaticFloatField(JniHandle clazz, FieldId fieldID)
{
float res = getStaticFloatField(envPtr, clazz, fieldID.native);
ExceptionTest();
return res;
}
public char GetStaticCharField(JniHandle clazz, FieldId fieldID)
{
var res = (char) getStaticCharField(envPtr, clazz, fieldID.native);
ExceptionTest();
return res;
}
#endregion
#region buffer
public JniLocalHandle NewDirectByteBuffer(IntPtr address, long capacity)
{
JniLocalHandle res = newDirectByteBuffer.Invoke(envPtr, address, capacity);
ExceptionTest();
return res;
}
public IntPtr GetDirectBufferAddress(JniGlobalHandle buf)
{
IntPtr res = getDirectBufferAddress.Invoke(envPtr, buf);
ExceptionTest();
return res;
}
public long GetDirectBufferCapacity(JniGlobalHandle buf)
{
long res = getDirectBufferCapacity.Invoke(envPtr, buf);
ExceptionTest();
return res;
}
#endregion
#region string
public string ConvertToString(JniHandle javaString)
{
byte b = 0;
IntPtr chars = GetStringChars(javaString, &b);
string result = Marshal.PtrToStringUni(chars, getStringLength(envPtr, javaString));
ReleaseStringChars(javaString, chars);
return result;
}
#endregion
#region references
[SuppressUnmanagedCodeSecurity]
public JniGlobalHandle NewGlobalRef(JniHandle lobj)
{
if (JniLocalHandle.IsNull(lobj))
{
throw new ArgumentNullException("lobj");
}
JniGlobalHandleNs res = newGlobalRef(envPtr, lobj);
return new JniGlobalHandle(res.handle, GetJavaVM());
}
[SuppressUnmanagedCodeSecurity]
internal JniLocalHandle NewLocalRef(JniHandle lobj)
{
if (JniHandle.IsNull(lobj))
{
throw new ArgumentNullException("lobj");
}
JniLocalHandle res = newLocalRef(envPtr, lobj);
//optimized away ExceptionTest();
return res;
}
internal JniLocalHandle PopLocalFrame(JniHandle result)
{
JniLocalHandle res = popLocalFrame(envPtr, result);
ExceptionTest();
return res;
}
internal void PushLocalFrame(int capacity)
{
int res = pushLocalFrame(envPtr, capacity);
ExceptionTest();
if (res != 0)
{
throw new JNIException("Can't allocate local frame" + res);
}
}
internal void EnsureLocalCapacity(int capacity)
{
int res = ensureLocalCapacity(envPtr, capacity);
ExceptionTest();
if (res != 0)
{
throw new JNIException("Can't allocate local frame" + res);
}
}
[SuppressUnmanagedCodeSecurity]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal void DeleteGlobalRef(JniGlobalHandle gref)
{
if (JniGlobalHandle.IsNull(gref))
{
throw new ArgumentNullException("gref");
}
deleteGlobalRef(envPtr, gref);
//optimized away ExceptionTest();
}
[SuppressUnmanagedCodeSecurity]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal void DeleteLocalRef(JniLocalHandle lref)
{
if (JniLocalHandle.IsNull(lref))
{
throw new ArgumentNullException("lref");
}
deleteLocalRef(envPtr, lref);
//optimized away ExceptionTest();
}
[SuppressUnmanagedCodeSecurity]
public bool IsSameObject(JniGlobalHandle o1, JniGlobalHandle o2)
{
bool res = isSameObject(envPtr, o1, o2) != 0;
ExceptionTest();
return res;
}
#endregion
#region allocation
internal JniLocalHandle AllocObject(JniHandle clazz)
{
JniLocalHandle res = allocObject(envPtr, clazz);
ExceptionTest();
return res;
}
public JniLocalHandle NewObject(JniHandle clazz, MethodId methodID, params Value[] args)
{
JniLocalHandle res = newObject(envPtr, clazz, methodID.native, args);
ExceptionTest();
return res;
}
#endregion
#region exceptions
public void Throw(JavaException ex)
{
JniHandle ptr = ex.mJvmHandle;
Throw(ptr);
}
internal void Throw(JniHandle ptr)
{
if (@throw(envPtr, ptr) != JNIResult.JNI_OK)
{
throw new JNIException("Can't throw");
}
}
public void ThrowNew(JniHandle clazz, string message)
{
IntPtr uni = Marshal.StringToHGlobalUni(message);
if (throwNew(envPtr, clazz, uni) != JNIResult.JNI_OK)
{
throw new JNIException("Can't throw");
}
Marshal.FreeHGlobal(uni);
}
public JniLocalHandle ExceptionOccurred()
{
return exceptionOccurred(envPtr);
}
public void FatalError(string message)
{
fatalError(envPtr, Marshal.StringToHGlobalUni(message));
}
public void ExceptionClear()
{
exceptionClear(envPtr);
}
public void ExceptionDescribe()
{
exceptionDescribe(envPtr);
}
public void ExceptionTest()
{
JniLocalHandle occurred = ExceptionOccurred();
if (!JniLocalHandle.IsNull(occurred))
{
ExceptionDescribe();
ExceptionClear();
throw new Exception("fail in exception test. need to use typed exception");
//Exception exception = Convertor.FullJ2C<Exception>(this, occurred);
//throw exception;
}
}
public bool ExceptionRead()
{
JniLocalHandle occurred = ExceptionOccurred();
if (!JniLocalHandle.IsNull(occurred))
{
#if DEBUG
ExceptionDescribe();
#endif
ExceptionClear();
return true;
}
return false;
}
public bool ExceptionCheck()
{
return exceptionCheck(envPtr) != 0;
}
#endregion
}
}
| |
using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using smg.Common.Exceptions;
using smg.Common.StateDescription.Attributes;
using smg.StateGeneration.ExtensionMethods;
namespace smg.StateGeneration
{
/// <summary>
/// Represents a method which decorates a method of a specific <see cref="Type"/> which is in a specific state.
/// </summary>
class DecoratorMethod
{
#region Constructors
/// <summary>
/// Creates a new isntance of <see cref="DecoratorMethod"/>.
/// </summary>
/// <param name="methodInfo">The method being decorated.</param>
/// <param name="type">The stateful <see cref="Type"/> whos method is being decorated.</param>
/// <param name="groupToStates">Contains the available states of the provided <see cref="Type"/>.</param>
/// <param name="permutation">A permutation of states of the <see cref="Type"/> whos method is being decorated.</param>
private DecoratorMethod(MethodInfo methodInfo, Type type, Dictionary<string, string[]> groupToStates, string[] permutation)
{
mMethodInfo = methodInfo;
mType = type;
mGroupsToStates = groupToStates;
mPermutation = permutation;
}
#endregion
#region Static Methods
/// <summary>
/// Initializes a new instance of <see cref="DecoratorMethod"/>.
/// </summary>
/// <param name="methodInfo">The method being decorated.</param>
/// <param name="type">The stateful <see cref="Type"/> whos method is being decorated.</param>
/// <param name="groupToStates">Contains the available states of the provided <see cref="Type"/>.</param>
/// <param name="permutation">A permutation of states of the <see cref="Type"/> whos method is being decorated.</param>
/// <returns>An initialized instance of <see cref="DecoratorMethod"/>.</returns>
public static DecoratorMethod CreateDecorator(MethodInfo methodInfo, Type type, Dictionary<string, string[]> groupToStates, string[] permutation)
{
return new DecoratorMethod(methodInfo, type, groupToStates, permutation);
}
#endregion
#region Public Methods
/// <summary>
/// Provides a <see cref="CodeMemberMethod"/> which represents the decorated method which this <see cref="DecoratorMethod"/> represents.
/// </summary>
/// <returns>A <see cref="CodeMemberMethod"/> which represents the decorated method which this <see cref="DecoratorMethod"/> represents.</returns>
public CodeMemberMethod GetMemberMethod()
{
CodeMemberMethod method = new CodeMemberMethod
{
Name = mMethodInfo.Name,
Attributes = MemberAttributes.Public
};
method.Parameters.AddRange(mMethodInfo.GetParameters()
.Select(x => new CodeParameterDeclarationExpression(x.ParameterType, x.Name))
.ToArray());
method.TypeParameters.AddRange(mMethodInfo.GetGenericArguments()
.Select(x => x.GetCodeTypeParameter())
.ToArray());
bool stateChanged;
method.ReturnType = GetMethodReturnType(out stateChanged);
GenerateMethodBody(method, !stateChanged);
return method;
}
#endregion
#region Private Methods
/// <summary>
/// Generates a method body matching to this instance of <see cref="DecoratorMethod"/> in a given <see cref="CodeMemberMethod"/>.
/// </summary>
/// <param name="method">The method for which the code will be generated.</param>
/// <param name="returnThis">A value indicating whether the method should return the instance in which it is invoked.</param>
private void GenerateMethodBody(CodeMemberMethod method, bool returnThis)
{
CodeFieldReferenceExpression fieldReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
StateWrapper.WRAPPED_FIELD_NAME);
CodeMethodReferenceExpression methodReference = new CodeMethodReferenceExpression(fieldReference, method.Name);
foreach (CodeTypeParameter codeTypeParameter in method.TypeParameters)
{
methodReference.TypeArguments.Add(new CodeTypeReference(codeTypeParameter));
}
List<CodeExpression> parameters = new List<CodeExpression>();
foreach (CodeParameterDeclarationExpression codeParameterDeclarationExpression in method.Parameters)
{
parameters.Add(codeParameterDeclarationExpression);
}
CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(methodReference,
parameters.ToArray());
if (mMethodInfo.ReturnType == typeof(void))
{
method.Statements.Add(methodInvoke);
if (!returnThis)
{
CodeObjectCreateExpression constructorCall = new CodeObjectCreateExpression(method.ReturnType, fieldReference);
method.Statements.Add(new CodeMethodReturnStatement(constructorCall));
}
else
{
method.Statements.Add(new CodeMethodReturnStatement(new CodeThisReferenceExpression()));
}
}
else
{
method.Statements.Add(new CodeMethodReturnStatement(methodInvoke));
}
}
/// <summary>
/// Provides the return type that the decorator method should have.
/// </summary>
/// <param name="stateChanged">A value indicating whether the state of the wrapper containing this method has changed due to its invocation.</param>
/// <returns>The return type that the decorator method should have.</returns>
private CodeTypeReference GetMethodReturnType(out bool stateChanged)
{
if (mMethodInfo.ReturnType != typeof(void))
{
stateChanged = false;
return new CodeTypeReference(mMethodInfo.ReturnType);
}
IEnumerable<string> statesChanges = mMethodInfo.GetCustomAttributesReflectionOnly<ChangeToStateAttribute>()
.Where(x => RelationHelpers.IsPermutationValid(mPermutation, x.ConditionRelation, x.ConditionStates, mGroupsToStates))
.Select(x => x.TargetState);
IEnumerable<string> doesntExists = statesChanges.Where(state => mGroupsToStates.Values.All(group => !group.Contains(state)));
if (doesntExists.Any())
{
throw new InvalidStateRepresentationException($"A method calld '{mMethodInfo.Name}' decoraded by a {nameof(ChangeToStateAttribute)}/s that contain a state to change to which does not exists. States: {string.Join(", ", doesntExists)}");
}
var statesFromSameGroup = statesChanges.GroupBy(x => mGroupsToStates.Single(y => y.Value.Contains(x)).Key)
.Where(x => x.Count() > 1);
if (statesFromSameGroup.Any())
{
throw new InvalidStateRepresentationException($"A method calld '{mMethodInfo.Name}' decoraded by a {nameof(ChangeToStateAttribute)}s that should change to different states from the samge group. States: {string.Join(" And ", statesFromSameGroup.Select(x => $"[{string.Join(", ", x)}]"))}");
}
string[] newState = mPermutation.Select(x => ReplaceStateIfNeeded(x, statesChanges)).ToArray();
stateChanged = !newState.SequenceEqual(mPermutation);
string typeName = string.Join(string.Empty, newState) + StateWrapper.NAME_POSTFIX;
if (mType.IsGenericType)
{
return new CodeTypeReference(typeName, mType.GetGenericArguments().Select(x => new CodeTypeReference(x)).ToArray());
}
return new CodeTypeReference(typeName);
}
/// <summary>
/// Returns the state from the state changes which should replace the given state if they are from the same group. If no such state was found, returns the original state.
/// </summary>
/// <param name="originalState">A state to be changed by the given state changes.</param>
/// <param name="statesChanges">A collection of states that can possibly replace the given state.</param>
/// <returns>The state from the state changes which should replace the given state if they are from the same group. If no such state was found, returns the original state.</returns>
private string ReplaceStateIfNeeded(string originalState, IEnumerable<string> statesChanges)
{
string stateToReplace = statesChanges.SingleOrDefault(state => mGroupsToStates.Values
.Single(group => group.Contains(state))
.Contains(originalState));
if (stateToReplace == null)
{
return originalState;
}
return stateToReplace;
}
#endregion
#region Private Fields
/// <summary>
/// The <see cref="Type"/> whos method is being decorated.
/// </summary>
private readonly Type mType;
/// <summary>
/// Contains the available states of the <see cref="Type"/> whos method is being decorated.
/// </summary>
private readonly Dictionary<string, string[]> mGroupsToStates;
/// <summary>
/// The method being decorated by this instance of <see cref="DecoratorMethod"/>,
/// </summary>
private readonly MethodInfo mMethodInfo;
/// <summary>
/// A
/// </summary>
private readonly string[] mPermutation;
#endregion
}
}
| |
/*
Copyright (c) 2012 Ant Micro <www.antmicro.com>
Authors:
* Konrad Kruczynski ([email protected])
* Piotr Zierhoffer ([email protected])
* Mateusz Holenko ([email protected])
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using Antmicro.Migrant.Customization;
using System.Reflection.Emit;
using Antmicro.Migrant.Utilities;
using Antmicro.Migrant.BultinSurrogates;
namespace Antmicro.Migrant
{
/// <summary>
/// Provides the mechanism for binary serialization and deserialization of objects.
/// </summary>
/// <remarks>
/// Please consult the general serializer documentation to find the limitations
/// and constraints which serialized objects must fullfill.
/// </remarks>
public class Serializer
{
/// <summary>
/// Initializes a new instance of the <see cref="Antmicro.Migrant.Serializer"/> class.
/// </summary>
/// <param name='settings'>
/// Serializer's settings, can be null or not given, in that case default settings are
/// used.
/// </param>
public Serializer(Settings settings = null)
{
if(settings == null)
{
settings = new Settings(); // default settings
}
this.settings = settings;
writeMethodCache = new Dictionary<Type, DynamicMethod>();
objectsForSurrogates = new InheritanceAwareList<Delegate>();
surrogatesForObjects = new InheritanceAwareList<Delegate>();
readMethodCache = new Dictionary<Type, DynamicMethod>();
if(settings.SupportForISerializable)
{
ForObject<System.Runtime.Serialization.ISerializable>().SetSurrogate(x => new SurrogateForISerializable(x));
ForSurrogate<SurrogateForISerializable>().SetObject(x => x.Restore());
ForObject<Delegate>().SetSurrogate<Func<Delegate, object>>(null); //because Delegate implements ISerializable but we support it directly.
}
if(settings.SupportForIXmlSerializable)
{
ForObject<System.Xml.Serialization.IXmlSerializable>().SetSurrogate(x => new SurrogateForIXmlSerializable(x));
ForSurrogate<SurrogateForIXmlSerializable>().SetObject(x => x.Restore());
}
}
/// <summary>
/// Serializes the specified object to a given stream.
/// </summary>
/// <param name='obj'>
/// Object to serialize along with its references.
/// </param>
/// <param name='stream'>
/// Stream to which the given object should be serialized. Has to be writeable.
/// </param>
public void Serialize(object obj, Stream stream)
{
WriteHeader(stream);
using(var writer = ObtainWriter(stream))
{
writer.WriteObject(obj);
}
serializationDone = true;
}
/// <summary>
/// Returns the open stream serializer, which can be used to do consecutive serializations
/// </summary>
/// <returns>The open stream serializer.</returns>
/// <param name="stream">Stream.</param>
public OpenStreamSerializer ObtainOpenStreamSerializer(Stream stream)
{
WriteHeader(stream);
serializationDone = true;
return new OpenStreamSerializer(ObtainWriter(stream));
}
/// <summary>
/// Returns the open stream serializer, which can be used to do consecutive deserializations when
/// same technique was used to serialize data.
/// </summary>
/// <returns>The open stream deserializer.</returns>
/// <param name="stream">Stream.</param>
public OpenStreamDeserializer ObtainOpenStreamDeserializer(Stream stream)
{
bool preserveReferences;
ThrowOnWrongResult(TryReadHeader(stream, out preserveReferences));
if(!settings.UseBuffering)
{
stream = new PeekableStream(stream);
}
return new OpenStreamDeserializer(ObtainReader(stream, preserveReferences), settings, stream);
}
/// <summary>
/// Gives the ability to set callback providing object for surrogate of given type. The object will be provided instead of such
/// surrogate in the effect of deserialization.
/// </summary>
/// <returns>
/// Object letting you set the object for the given surrogate type.
/// </returns>
/// <typeparam name='TSurrogate'>
/// The type for which callback will be invoked.
/// </typeparam>
public ObjectForSurrogateSetter<TSurrogate> ForSurrogate<TSurrogate>()
{
return new ObjectForSurrogateSetter<TSurrogate>(this);
}
/// <summary>
/// Gives the ability to set callback providing surrogate for objects of given type. The surrogate will be serialized instead of
/// the object of that type.
/// </summary>
/// <returns>
/// Object letting you set the surrogate for the given type.
/// </returns>
/// <typeparam name='TObject'>
/// The type for which callback will be invoked.
/// </typeparam>
public SurrogateForObjectSetter<TObject> ForObject<TObject>()
{
return new SurrogateForObjectSetter<TObject>(this);
}
/// <summary>
/// Deserializes object from the specified stream.
/// </summary>
/// <param name='stream'>
/// The stream to read data from. Must be readable.
/// </param>
/// <typeparam name='T'>
/// The expected type of the deserialized object. The deserialized object must be
/// convertible to this type.
/// </typeparam>
public T Deserialize<T>(Stream stream)
{
T result;
ThrowOnWrongResult(TryDeserialize(stream, out result));
return result;
}
/// <summary>
/// Tries to deserialize object from specified stream.
/// </summary>
/// <returns>Operation result status.</returns>
/// <param name="stream">
/// The stream to read data from. Must be readable.
/// </param>
/// <param name="obj">Deserialized object.</param>
/// <typeparam name="T">
/// The expected type of the deserialized object. The deserialized object must be
/// convertible to this type.
/// </typeparam>
public DeserializationResult TryDeserialize<T>(Stream stream, out T obj)
{
bool unused;
obj = default(T);
var headerResult = TryReadHeader(stream, out unused);
if(headerResult != DeserializationResult.OK)
{
return headerResult;
}
using(var objectReader = ObtainReader(stream, unused))
{
try
{
obj = objectReader.ReadObject<T>();
deserializationDone = true;
return DeserializationResult.OK;
}
catch(Exception ex)
{
lastException = ex;
return DeserializationResult.StreamCorrupted;
}
}
}
/// <summary>
/// Is invoked before serialization, once for every unique, serialized object. Provides this
/// object in its single parameter.
/// </summary>
public event Action<object> OnPreSerialization;
/// <summary>
/// Is invoked after serialization, once for every unique, serialized object. Provides this
/// object in its single parameter.
/// </summary>
public event Action<object> OnPostSerialization;
/// <summary>
/// Is invoked before deserialization, once for every unique, serialized object. Provides this
/// object in its single parameter.
/// </summary>
public event Action<object> OnPostDeserialization;
/// <summary>
/// Makes a deep copy of a given object using the serializer.
/// </summary>
/// <returns>
/// The deep copy of a given object.
/// </returns>
/// <param name='toClone'>
/// The object to make a deep copy of.
/// </param>
/// <param name='settings'>
/// Settings used for serializer which does deep clone.
/// </param>
public static T DeepClone<T>(T toClone, Settings settings = null)
{
var serializer = new Serializer(settings);
var stream = new MemoryStream();
serializer.Serialize(toClone, stream);
var position = stream.Position;
stream.Seek(0, SeekOrigin.Begin);
var result = serializer.Deserialize<T>(stream);
if(position != stream.Position)
{
throw new InvalidOperationException(
string.Format("Internal error in serializer: {0} bytes were written, but only {1} were read.",
position, stream.Position));
}
return result;
}
private void WriteHeader(Stream stream)
{
stream.WriteByte(Magic1);
stream.WriteByte(Magic2);
stream.WriteByte(Magic3);
stream.WriteByte(VersionNumber);
stream.WriteByte(settings.ReferencePreservation == ReferencePreservation.DoNotPreserve ? (byte)0 : (byte)1);
}
private ObjectWriter ObtainWriter(Stream stream)
{
var writer = new ObjectWriter(stream, OnPreSerialization, OnPostSerialization,
writeMethodCache, surrogatesForObjects, settings.SerializationMethod == Method.Generated,
settings.TreatCollectionAsUserObject, settings.UseBuffering, settings.ReferencePreservation);
return writer;
}
private DeserializationResult TryReadHeader(Stream stream, out bool preserveReferences)
{
preserveReferences = false;
// Read header
var magic1 = stream.ReadByte();
var magic2 = stream.ReadByte();
var magic3 = stream.ReadByte();
if(magic1 != Magic1 || magic2 != Magic2 || magic3 != Magic3)
{
return DeserializationResult.WrongMagic;
}
var version = stream.ReadByte();
if(version != VersionNumber)
{
return DeserializationResult.WrongVersion;
}
preserveReferences = stream.ReadByteOrThrow() != 0;
return DeserializationResult.OK;
}
private void ThrowOnWrongResult(DeserializationResult result)
{
switch(result)
{
case DeserializationResult.OK:
return;
case DeserializationResult.WrongMagic:
throw new InvalidOperationException("Cound not find proper magic.");
case DeserializationResult.WrongVersion:
throw new InvalidOperationException("Could not deserialize data serialized with another version of serializer.");
case DeserializationResult.StreamCorrupted:
throw lastException;
default:
throw new ArgumentOutOfRangeException();
}
}
private ObjectReader ObtainReader(Stream stream, bool preserveReferences)
{
// user can only tell whether to use weak or strong reference preservation
ReferencePreservation eventualPreservation;
if(!preserveReferences)
{
eventualPreservation = ReferencePreservation.DoNotPreserve;
}
else
{
eventualPreservation = settings.ReferencePreservation == ReferencePreservation.UseWeakReference ?
ReferencePreservation.UseWeakReference : ReferencePreservation.Preserve;
}
return new ObjectReader(stream, objectsForSurrogates, OnPostDeserialization, readMethodCache,
settings.DeserializationMethod == Method.Generated, settings.TreatCollectionAsUserObject,
settings.VersionTolerance, settings.UseBuffering, eventualPreservation);
}
private Exception lastException;
private bool serializationDone;
private bool deserializationDone;
private readonly Settings settings;
private readonly Dictionary<Type, DynamicMethod> writeMethodCache;
private readonly Dictionary<Type, DynamicMethod> readMethodCache;
private readonly InheritanceAwareList<Delegate> surrogatesForObjects;
private readonly InheritanceAwareList<Delegate> objectsForSurrogates;
private const byte VersionNumber = 6;
private const byte Magic1 = 0x32;
private const byte Magic2 = 0x66;
private const byte Magic3 = 0x34;
/// <summary>
/// Lets you set a callback providing object for type of the surrogate given to method that provided
/// this object on a serializer that provided this object.
/// </summary>
public class ObjectForSurrogateSetter<TSurrogate>
{
internal ObjectForSurrogateSetter(Serializer serializer)
{
this.serializer = serializer;
}
/// <summary>
/// Sets the callback proividing object for surrogate.
/// </summary>
/// <param name='callback'>
/// Callback proividing object for surrogate. The callback can be null, in that case surrogate of the type
/// <typeparamref name="TSurrogate" /> will be deserialized as is even if there is an object for the more
/// general type.
/// </param>
/// <typeparam name='TObject'>
/// The type of the object returned by callback.
/// </typeparam>
public void SetObject<TObject>(Func<TSurrogate, TObject> callback) where TObject : class
{
if(serializer.deserializationDone)
{
throw new InvalidOperationException("Cannot set objects for surrogates after any deserialization is done.");
}
serializer.objectsForSurrogates.AddOrReplace(typeof(TSurrogate), callback);
}
private readonly Serializer serializer;
}
/// <summary>
/// Lets you set a callback providing surrogate for type of the object given to method that provided
/// this object on a serializer that provided this object.
/// </summary>
public class SurrogateForObjectSetter<TObject>
{
internal SurrogateForObjectSetter(Serializer serializer)
{
this.serializer = serializer;
}
/// <summary>
/// Sets the callback providing surrogate for object.
/// </summary>
/// <param name='callback'>
/// Callback providing surrogate for object. The callback can be null, in that case object of the type
/// <typeparamref name="TObject" /> will be serialized as is even if there is a surrogate for the more
/// general type.
/// </param>
/// <typeparam name='TSurrogate'>
/// The type of the object returned by callback.
/// </typeparam>
public void SetSurrogate<TSurrogate>(Func<TObject, TSurrogate> callback) where TSurrogate : class
{
if(serializer.serializationDone)
{
throw new InvalidOperationException("Cannot set surrogates for objects after any serialization is done.");
}
serializer.surrogatesForObjects.AddOrReplace(typeof(TObject), callback);
}
private readonly Serializer serializer;
}
/// <summary>
/// Serializer that is attached to one stream and can do consecutive serializations that are aware of the data written
/// by previous ones.
/// </summary>
public class OpenStreamSerializer : IDisposable
{
internal OpenStreamSerializer(ObjectWriter writer)
{
this.writer = writer;
}
/// <summary>
/// Serialize the specified object.
/// </summary>
/// <param name="obj">Object.</param>
public void Serialize(object obj)
{
writer.WriteObject(new Box(obj));
}
/// <summary>
/// Flushes the buffer and necessary padding. Not necessary when buffering is not used.
/// </summary>
public void Dispose()
{
writer.Dispose();
}
private readonly ObjectWriter writer;
}
/// <summary>
/// Deserializer that is attached to one stream and can do consecutive deserializations that are aware of the data written
/// by previous ones.
/// </summary>
public class OpenStreamDeserializer : IDisposable
{
internal OpenStreamDeserializer(ObjectReader reader, Settings settings, Stream stream)
{
this.reader = reader;
this.settings = settings;
this.stream = stream;
}
/// <summary>
/// Deserializes next object waiting in the stream.
/// </summary>
/// <typeparam name="T">The expected formal type of object to deserialize.</typeparam>
public T Deserialize<T>()
{
var box = reader.ReadObject<Box>();
return (T)box.Value;
}
/// <summary>
/// Deserializes objects until end of the stream is reached. All objects have to be castable to T.
/// This method is only available when buffering is disabled.
/// </summary>
/// <returns>Lazy collection of deserialized objects.</returns>
/// <typeparam name="T">The expected type of object to deserialize.</typeparam>
public IEnumerable<T> DeserializeMany<T>()
{
if(settings.UseBuffering)
{
throw new NotSupportedException("DeserializeMany can be only used if buffering is disabled.");
}
var peekableStream = stream as PeekableStream;
if(peekableStream == null)
{
throw new NotSupportedException("Internal error: stream is not peekable.");
}
while(peekableStream.Peek() != -1)
{
yield return Deserialize<T>();
}
}
/// <summary>
/// Reads leftover padding. Not necessary if buffering is not used.
/// </summary>
public void Dispose()
{
reader.Dispose();
}
private readonly ObjectReader reader;
private readonly Settings settings;
private readonly Stream stream;
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// AvailabilityResponse
/// </summary>
[DataContract]
public partial class AvailabilityResponse : IEquatable<AvailabilityResponse>, IValidatableObject
{
/// <summary>
/// Gets or Sets UnitType
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum UnitTypeEnum
{
/// <summary>
/// Enum Cover for "Cover"
/// </summary>
[EnumMember(Value = "Cover")]
Cover,
/// <summary>
/// Enum Table for "Table"
/// </summary>
[EnumMember(Value = "Table")]
Table,
/// <summary>
/// Enum Default for "Default"
/// </summary>
[EnumMember(Value = "Default")]
Default
}
/// <summary>
/// Gets or Sets UnitType
/// </summary>
[DataMember(Name="unitType", EmitDefaultValue=true)]
public UnitTypeEnum? UnitType { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="AvailabilityResponse" /> class.
/// </summary>
/// <param name="Availabilities">Availabilities.</param>
/// <param name="RequestedTime">RequestedTime.</param>
/// <param name="TotalCovers">TotalCovers.</param>
/// <param name="TotalReservationCovers">TotalReservationCovers.</param>
/// <param name="TotalWaitCovers">TotalWaitCovers.</param>
/// <param name="UnitType">UnitType.</param>
public AvailabilityResponse(List<Availability> Availabilities = null, DateTimeOffset? RequestedTime = null, int? TotalCovers = null, int? TotalReservationCovers = null, int? TotalWaitCovers = null, UnitTypeEnum? UnitType = null)
{
this.Availabilities = Availabilities;
this.RequestedTime = RequestedTime;
this.TotalCovers = TotalCovers;
this.TotalReservationCovers = TotalReservationCovers;
this.TotalWaitCovers = TotalWaitCovers;
this.UnitType = UnitType;
}
/// <summary>
/// Gets or Sets Availabilities
/// </summary>
[DataMember(Name="availabilities", EmitDefaultValue=true)]
public List<Availability> Availabilities { get; set; }
/// <summary>
/// Gets or Sets RequestedTime
/// </summary>
[DataMember(Name="requestedTime", EmitDefaultValue=true)]
public DateTimeOffset? RequestedTime { get; set; }
/// <summary>
/// Gets or Sets TotalCovers
/// </summary>
[DataMember(Name="totalCovers", EmitDefaultValue=true)]
public int? TotalCovers { get; set; }
/// <summary>
/// Gets or Sets TotalReservationCovers
/// </summary>
[DataMember(Name="totalReservationCovers", EmitDefaultValue=true)]
public int? TotalReservationCovers { get; set; }
/// <summary>
/// Gets or Sets TotalWaitCovers
/// </summary>
[DataMember(Name="totalWaitCovers", EmitDefaultValue=true)]
public int? TotalWaitCovers { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class AvailabilityResponse {\n");
sb.Append(" Availabilities: ").Append(Availabilities).Append("\n");
sb.Append(" RequestedTime: ").Append(RequestedTime).Append("\n");
sb.Append(" TotalCovers: ").Append(TotalCovers).Append("\n");
sb.Append(" TotalReservationCovers: ").Append(TotalReservationCovers).Append("\n");
sb.Append(" TotalWaitCovers: ").Append(TotalWaitCovers).Append("\n");
sb.Append(" UnitType: ").Append(UnitType).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as AvailabilityResponse);
}
/// <summary>
/// Returns true if AvailabilityResponse instances are equal
/// </summary>
/// <param name="other">Instance of AvailabilityResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(AvailabilityResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Availabilities == other.Availabilities ||
this.Availabilities != null &&
this.Availabilities.SequenceEqual(other.Availabilities)
) &&
(
this.RequestedTime == other.RequestedTime ||
this.RequestedTime != null &&
this.RequestedTime.Equals(other.RequestedTime)
) &&
(
this.TotalCovers == other.TotalCovers ||
this.TotalCovers != null &&
this.TotalCovers.Equals(other.TotalCovers)
) &&
(
this.TotalReservationCovers == other.TotalReservationCovers ||
this.TotalReservationCovers != null &&
this.TotalReservationCovers.Equals(other.TotalReservationCovers)
) &&
(
this.TotalWaitCovers == other.TotalWaitCovers ||
this.TotalWaitCovers != null &&
this.TotalWaitCovers.Equals(other.TotalWaitCovers)
) &&
(
this.UnitType == other.UnitType ||
this.UnitType != null &&
this.UnitType.Equals(other.UnitType)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Availabilities != null)
hash = hash * 59 + this.Availabilities.GetHashCode();
if (this.RequestedTime != null)
hash = hash * 59 + this.RequestedTime.GetHashCode();
if (this.TotalCovers != null)
hash = hash * 59 + this.TotalCovers.GetHashCode();
if (this.TotalReservationCovers != null)
hash = hash * 59 + this.TotalReservationCovers.GetHashCode();
if (this.TotalWaitCovers != null)
hash = hash * 59 + this.TotalWaitCovers.GetHashCode();
if (this.UnitType != null)
hash = hash * 59 + this.UnitType.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using AutoRest.Core;
using AutoRest.Core.ClientModel;
using AutoRest.Core.Utilities;
using AutoRest.Swagger.Model;
namespace AutoRest.Swagger
{
/// <summary>
/// The builder for building a generic swagger object into parameters,
/// service types or Json serialization types.
/// </summary>
public class ObjectBuilder
{
protected SwaggerObject SwaggerObject { get; set; }
protected SwaggerModeler Modeler { get; set; }
public ObjectBuilder(SwaggerObject swaggerObject, SwaggerModeler modeler)
{
SwaggerObject = swaggerObject;
Modeler = modeler;
}
public virtual IType ParentBuildServiceType(string serviceTypeName)
{
// Should not try to get parent from generic swagger object builder
throw new InvalidOperationException();
}
/// <summary>
/// The visitor method for building service types. This is called when an instance of this class is
/// visiting a _swaggerModeler to build a service type.
/// </summary>
/// <param name="serviceTypeName">name for the service type</param>
/// <returns>built service type</returns>
public virtual IType BuildServiceType(string serviceTypeName)
{
PrimaryType type = SwaggerObject.ToType();
Debug.Assert(type != null);
if (type.Type == KnownPrimaryType.Object && "file".Equals(SwaggerObject.Format, StringComparison.OrdinalIgnoreCase))
{
type = new PrimaryType(KnownPrimaryType.Stream);
}
type.Format = SwaggerObject.Format;
if (SwaggerObject.Enum != null && type.Type == KnownPrimaryType.String && !(IsSwaggerObjectConstant(SwaggerObject)))
{
var enumType = new EnumType();
SwaggerObject.Enum.ForEach(v => enumType.Values.Add(new EnumValue { Name = v, SerializedName = v }));
if (SwaggerObject.Extensions.ContainsKey(CodeGenerator.EnumObject))
{
var enumObject = SwaggerObject.Extensions[CodeGenerator.EnumObject] as Newtonsoft.Json.Linq.JContainer;
if (enumObject != null)
{
enumType.Name= enumObject["name"].ToString();
if (enumObject["modelAsString"] != null)
{
enumType.ModelAsString = bool.Parse(enumObject["modelAsString"].ToString());
}
}
enumType.SerializedName = enumType.Name;
if (string.IsNullOrEmpty(enumType.Name))
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture,
"{0} extension needs to specify an enum name.",
CodeGenerator.EnumObject));
}
var existingEnum =
Modeler.ServiceClient.EnumTypes.FirstOrDefault(
e => e.Name.Equals(enumType.Name, StringComparison.OrdinalIgnoreCase));
if (existingEnum != null)
{
if (!existingEnum.Equals(enumType))
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture,
"Swagger document contains two or more {0} extensions with the same name '{1}' and different values.",
CodeGenerator.EnumObject,
enumType.Name));
}
}
else
{
Modeler.ServiceClient.EnumTypes.Add(enumType);
}
}
else
{
enumType.ModelAsString = true;
enumType.Name = string.Empty;
enumType.SerializedName = string.Empty;
}
return enumType;
}
if (SwaggerObject.Type == DataType.Array)
{
string itemServiceTypeName;
if (SwaggerObject.Items.Reference != null)
{
itemServiceTypeName = SwaggerObject.Items.Reference.StripDefinitionPath();
}
else
{
itemServiceTypeName = serviceTypeName + "Item";
}
var elementType =
SwaggerObject.Items.GetBuilder(Modeler).BuildServiceType(itemServiceTypeName);
return new SequenceType
{
ElementType = elementType
};
}
if (SwaggerObject.AdditionalProperties != null)
{
string dictionaryValueServiceTypeName;
if (SwaggerObject.AdditionalProperties.Reference != null)
{
dictionaryValueServiceTypeName = SwaggerObject.AdditionalProperties.Reference.StripDefinitionPath();
}
else
{
dictionaryValueServiceTypeName = serviceTypeName + "Value";
}
return new DictionaryType
{
ValueType =
SwaggerObject.AdditionalProperties.GetBuilder(Modeler)
.BuildServiceType((dictionaryValueServiceTypeName))
};
}
return type;
}
public static void PopulateParameter(IParameter parameter, SwaggerObject swaggerObject)
{
if (swaggerObject == null)
{
throw new ArgumentNullException("swaggerObject");
}
if (parameter == null)
{
throw new ArgumentNullException("parameter");
}
parameter.IsRequired = swaggerObject.IsRequired;
parameter.DefaultValue = swaggerObject.Default;
if (IsSwaggerObjectConstant(swaggerObject))
{
parameter.DefaultValue = swaggerObject.Enum[0];
parameter.IsConstant = true;
}
var compositeType = parameter.Type as CompositeType;
if (compositeType != null && compositeType.ComposedProperties.Any())
{
if (compositeType.ComposedProperties.All(p => p.IsConstant))
{
parameter.DefaultValue = "{}";
parameter.IsConstant = true;
}
}
parameter.Documentation = swaggerObject.Description;
parameter.CollectionFormat = swaggerObject.CollectionFormat;
var enumType = parameter.Type as EnumType;
if (enumType != null)
{
if (parameter.Documentation == null)
{
parameter.Documentation = string.Empty;
}
else
{
parameter.Documentation = parameter.Documentation.TrimEnd('.') + ". ";
}
parameter.Documentation += "Possible values include: " +
string.Join(", ", enumType.Values.Select(v =>
string.Format(CultureInfo.InvariantCulture,
"'{0}'", v.Name)));
}
swaggerObject.Extensions.ForEach(e => parameter.Extensions[e.Key] = e.Value);
SetConstraints(parameter.Constraints, swaggerObject);
}
private static bool IsSwaggerObjectConstant(SwaggerObject swaggerObject)
{
return (swaggerObject.Enum != null && swaggerObject.Enum.Count == 1 && swaggerObject.IsRequired);
}
public static void SetConstraints(Dictionary<Constraint, string> constraints, SwaggerObject swaggerObject)
{
if (constraints == null)
{
throw new ArgumentNullException("constraints");
}
if (swaggerObject == null)
{
throw new ArgumentNullException("swaggerObject");
}
if (!string.IsNullOrEmpty(swaggerObject.Maximum)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.Maximum))
&& !swaggerObject.ExclusiveMaximum)
{
constraints[Constraint.InclusiveMaximum] = swaggerObject.Maximum;
}
if (!string.IsNullOrEmpty(swaggerObject.Maximum)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.Maximum))
&& swaggerObject.ExclusiveMaximum
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.ExclusiveMaximum)))
{
constraints[Constraint.ExclusiveMaximum] = swaggerObject.Maximum;
}
if (!string.IsNullOrEmpty(swaggerObject.Minimum)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.Minimum))
&& !swaggerObject.ExclusiveMinimum)
{
constraints[Constraint.InclusiveMinimum] = swaggerObject.Minimum;
}
if (!string.IsNullOrEmpty(swaggerObject.Minimum)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.Minimum))
&& swaggerObject.ExclusiveMinimum
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.ExclusiveMinimum)))
{
constraints[Constraint.ExclusiveMinimum] = swaggerObject.Minimum;
}
if (!string.IsNullOrEmpty(swaggerObject.MaxLength)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.MaxLength)))
{
constraints[Constraint.MaxLength] = swaggerObject.MaxLength;
}
if (!string.IsNullOrEmpty(swaggerObject.MinLength)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.MinLength)))
{
constraints[Constraint.MinLength] = swaggerObject.MinLength;
}
if (!string.IsNullOrEmpty(swaggerObject.Pattern)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.Pattern)))
{
constraints[Constraint.Pattern] = swaggerObject.Pattern;
}
if (!string.IsNullOrEmpty(swaggerObject.MaxItems)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.MaxItems)))
{
constraints[Constraint.MaxItems] = swaggerObject.MaxItems;
}
if (!string.IsNullOrEmpty(swaggerObject.MinItems)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.MinItems)))
{
constraints[Constraint.MinItems] = swaggerObject.MinItems;
}
if (!string.IsNullOrEmpty(swaggerObject.MultipleOf)
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.MultipleOf)))
{
constraints[Constraint.MultipleOf] = swaggerObject.MultipleOf;
}
if (swaggerObject.UniqueItems
&& swaggerObject.IsConstraintSupported(nameof(swaggerObject.UniqueItems)))
{
constraints[Constraint.UniqueItems] = "true";
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the RemTipoCobertura class.
/// </summary>
[Serializable]
public partial class RemTipoCoberturaCollection : ActiveList<RemTipoCobertura, RemTipoCoberturaCollection>
{
public RemTipoCoberturaCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>RemTipoCoberturaCollection</returns>
public RemTipoCoberturaCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
RemTipoCobertura o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Rem_TipoCobertura table.
/// </summary>
[Serializable]
public partial class RemTipoCobertura : ActiveRecord<RemTipoCobertura>, IActiveRecord
{
#region .ctors and Default Settings
public RemTipoCobertura()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public RemTipoCobertura(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public RemTipoCobertura(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public RemTipoCobertura(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Rem_TipoCobertura", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdTipoCobertura = new TableSchema.TableColumn(schema);
colvarIdTipoCobertura.ColumnName = "idTipoCobertura";
colvarIdTipoCobertura.DataType = DbType.Int32;
colvarIdTipoCobertura.MaxLength = 0;
colvarIdTipoCobertura.AutoIncrement = true;
colvarIdTipoCobertura.IsNullable = false;
colvarIdTipoCobertura.IsPrimaryKey = true;
colvarIdTipoCobertura.IsForeignKey = false;
colvarIdTipoCobertura.IsReadOnly = false;
colvarIdTipoCobertura.DefaultSetting = @"";
colvarIdTipoCobertura.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTipoCobertura);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.String;
colvarNombre.MaxLength = 50;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"('')";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Rem_TipoCobertura",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdTipoCobertura")]
[Bindable(true)]
public int IdTipoCobertura
{
get { return GetColumnValue<int>(Columns.IdTipoCobertura); }
set { SetColumnValue(Columns.IdTipoCobertura, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.SysRelFormularioCoberturaCollection colSysRelFormularioCoberturaRecords;
public DalSic.SysRelFormularioCoberturaCollection SysRelFormularioCoberturaRecords
{
get
{
if(colSysRelFormularioCoberturaRecords == null)
{
colSysRelFormularioCoberturaRecords = new DalSic.SysRelFormularioCoberturaCollection().Where(SysRelFormularioCobertura.Columns.IdTipoCobertura, IdTipoCobertura).Load();
colSysRelFormularioCoberturaRecords.ListChanged += new ListChangedEventHandler(colSysRelFormularioCoberturaRecords_ListChanged);
}
return colSysRelFormularioCoberturaRecords;
}
set
{
colSysRelFormularioCoberturaRecords = value;
colSysRelFormularioCoberturaRecords.ListChanged += new ListChangedEventHandler(colSysRelFormularioCoberturaRecords_ListChanged);
}
}
void colSysRelFormularioCoberturaRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colSysRelFormularioCoberturaRecords[e.NewIndex].IdTipoCobertura = IdTipoCobertura;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre)
{
RemTipoCobertura item = new RemTipoCobertura();
item.Nombre = varNombre;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdTipoCobertura,string varNombre)
{
RemTipoCobertura item = new RemTipoCobertura();
item.IdTipoCobertura = varIdTipoCobertura;
item.Nombre = varNombre;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdTipoCoberturaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdTipoCobertura = @"idTipoCobertura";
public static string Nombre = @"nombre";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colSysRelFormularioCoberturaRecords != null)
{
foreach (DalSic.SysRelFormularioCobertura item in colSysRelFormularioCoberturaRecords)
{
if (item.IdTipoCobertura != IdTipoCobertura)
{
item.IdTipoCobertura = IdTipoCobertura;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colSysRelFormularioCoberturaRecords != null)
{
colSysRelFormularioCoberturaRecords.SaveAll();
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Cci.Filters;
using Microsoft.Cci.Writers.CSharp;
using Microsoft.Cci.Writers.Syntax;
namespace Microsoft.Cci.Extensions.CSharp
{
public static class CSharpCciExtensions
{
public static string GetCSharpDeclaration(this IDefinition definition, bool includeAttributes = false)
{
using (var stringWriter = new StringWriter())
{
using (var syntaxWriter = new TextSyntaxWriter(stringWriter))
{
var writer = new CSDeclarationWriter(syntaxWriter, new AttributesFilter(includeAttributes), false, true);
var nsp = definition as INamespaceDefinition;
var typeDefinition = definition as ITypeDefinition;
var member = definition as ITypeDefinitionMember;
if (nsp != null)
writer.WriteNamespaceDeclaration(nsp);
else if (typeDefinition != null)
writer.WriteTypeDeclaration(typeDefinition);
else if (member != null)
{
var method = member as IMethodDefinition;
if (method != null && method.IsPropertyOrEventAccessor())
WriteAccessor(syntaxWriter, method);
else
writer.WriteMemberDeclaration(member);
}
}
return stringWriter.ToString();
}
}
private static void WriteAccessor(ISyntaxWriter syntaxWriter, IMethodDefinition method)
{
var accessorKeyword = GetAccessorKeyword(method);
syntaxWriter.WriteKeyword(accessorKeyword);
syntaxWriter.WriteSymbol(";");
}
private static string GetAccessorKeyword(IMethodDefinition method)
{
switch (method.GetAccessorType())
{
case AccessorType.EventAdder:
return "add";
case AccessorType.EventRemover:
return "remove";
case AccessorType.PropertySetter:
return "set";
case AccessorType.PropertyGetter:
return "get";
default:
throw new ArgumentOutOfRangeException();
}
}
public static bool IsDefaultCSharpBaseType(this ITypeReference baseType, ITypeDefinition type)
{
Contract.Requires(baseType != null);
Contract.Requires(type != null);
if (baseType.AreEquivalent("System.Object"))
return true;
if (type.IsValueType && baseType.AreEquivalent("System.ValueType"))
return true;
if (type.IsEnum && baseType.AreEquivalent("System.Enum"))
return true;
return false;
}
public static IMethodDefinition GetInvokeMethod(this ITypeDefinition type)
{
if (!type.IsDelegate)
return null;
foreach (var method in type.Methods)
if (method.Name.Value == "Invoke")
return method;
throw new InvalidOperationException(String.Format("All delegates should have an Invoke method, but {0} doesn't have one.", type.FullName()));
}
public static ITypeReference GetEnumType(this ITypeDefinition type)
{
if (!type.IsEnum)
return null;
foreach (var field in type.Fields)
if (field.Name.Value == "value__")
return field.Type;
throw new InvalidOperationException("All enums should have a value__ field!");
}
public static bool IsOrContainsReferenceType(this ITypeReference type)
{
Queue<ITypeReference> typesToCheck = new Queue<ITypeReference>();
HashSet<ITypeReference> visited = new HashSet<ITypeReference>();
typesToCheck.Enqueue(type);
while (typesToCheck.Count != 0)
{
var typeToCheck = typesToCheck.Dequeue();
visited.Add(typeToCheck);
var resolvedType = typeToCheck.ResolvedType;
// If it is dummy we cannot really check so assume it does because that is will be the most conservative
if (resolvedType is Dummy)
return true;
if (resolvedType.IsReferenceType)
return true;
// ByReference<T> is a special type understood by runtime to hold a ref T.
if (resolvedType.AreEquivalent("System.ByReference<T>"))
return true;
foreach (var field in resolvedType.Fields.Where(f => !f.IsStatic))
{
if (!visited.Contains(field.Type))
{
typesToCheck.Enqueue(field.Type);
}
}
}
return false;
}
public static bool IsConversionOperator(this IMethodDefinition method)
{
return (method.IsSpecialName &&
(method.Name.Value == "op_Explicit" || method.Name.Value == "op_Implicit"));
}
public static bool IsExplicitInterfaceMember(this ITypeDefinitionMember member)
{
var method = member as IMethodDefinition;
if (method != null)
{
return method.IsExplicitInterfaceMethod();
}
var property = member as IPropertyDefinition;
if (property != null)
{
return property.IsExplicitInterfaceProperty();
}
return false;
}
public static bool IsExplicitInterfaceMethod(this IMethodDefinition method)
{
return MemberHelper.GetExplicitlyOverriddenMethods(method).Any();
}
public static bool IsExplicitInterfaceProperty(this IPropertyDefinition property)
{
if (property.Getter != null && property.Getter.ResolvedMethod != null)
{
return property.Getter.ResolvedMethod.IsExplicitInterfaceMethod();
}
if (property.Setter != null && property.Setter.ResolvedMethod != null)
{
return property.Setter.ResolvedMethod.IsExplicitInterfaceMethod();
}
return false;
}
public static bool IsInterfaceImplementation(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsInterfaceImplementation();
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsInterfaceImplementation());
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsInterfaceImplementation());
return false;
}
public static bool IsInterfaceImplementation(this IMethodDefinition method)
{
return MemberHelper.GetImplicitlyImplementedInterfaceMethods(method).Any()
|| MemberHelper.GetExplicitlyOverriddenMethods(method).Any();
}
public static bool IsAbstract(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsAbstract;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsAbstract);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsAbstract);
return false;
}
public static bool IsVirtual(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsVirtual;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsVirtual);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsVirtual);
return false;
}
public static bool IsNewSlot(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsNewSlot;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsNewSlot);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsNewSlot);
return false;
}
public static bool IsSealed(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsSealed;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsSealed);
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsSealed);
return false;
}
public static bool IsOverride(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.IsOverride();
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Accessors.Any(m => m.ResolvedMethod.IsOverride());
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Accessors.Any(m => m.ResolvedMethod.IsOverride());
return false;
}
public static bool IsOverride(this IMethodDefinition method)
{
return method.IsVirtual && !method.IsNewSlot;
}
public static bool IsUnsafeType(this ITypeReference type)
{
return type.TypeCode == PrimitiveTypeCode.Pointer;
}
public static bool IsMethodUnsafe(this IMethodDefinition method)
{
foreach (var p in method.Parameters)
{
if (p.Type.IsUnsafeType())
return true;
}
if (method.Type.IsUnsafeType())
return true;
return false;
}
public static bool IsDestructor(this IMethodDefinition methodDefinition)
{
if (methodDefinition.ContainingTypeDefinition.IsValueType) return false; //only classes can have destructors
if (methodDefinition.ParameterCount == 0 && methodDefinition.IsVirtual &&
methodDefinition.Visibility == TypeMemberVisibility.Family && methodDefinition.Name.Value == "Finalize")
{
// Should we make sure that this Finalize method overrides the protected System.Object.Finalize?
return true;
}
return false;
}
public static bool IsAssembly(this ITypeDefinitionMember member)
{
return member.Visibility == TypeMemberVisibility.FamilyAndAssembly ||
member.Visibility == TypeMemberVisibility.Assembly;
}
public static bool InSameUnit(ITypeDefinitionMember member1, ITypeDefinitionMember member2)
{
IUnit unit1 = TypeHelper.GetDefiningUnit(member1.ContainingTypeDefinition);
IUnit unit2 = TypeHelper.GetDefiningUnit(member2.ContainingTypeDefinition);
return UnitHelper.UnitsAreEquivalent(unit1, unit2);
}
public static ITypeReference GetReturnType(this ITypeDefinitionMember member)
{
IMethodDefinition method = member as IMethodDefinition;
if (method != null)
return method.Type;
IPropertyDefinition property = member as IPropertyDefinition;
if (property != null)
return property.Type;
IEventDefinition evnt = member as IEventDefinition;
if (evnt != null)
return evnt.Type;
IFieldDefinition field = member as IFieldDefinition;
if (field != null)
return field.Type;
return null;
}
public static IFieldDefinition GetHiddenBaseField(this IFieldDefinition field, ICciFilter filter = null)
{
foreach (ITypeReference baseClassRef in field.ContainingTypeDefinition.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IFieldDefinition baseField in baseClass.GetMembersNamed(field.Name, false).OfType<IFieldDefinition>())
{
if (baseField.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseField) && !InSameUnit(baseField, field))
continue;
if (filter != null && !filter.Include(baseField))
continue;
return baseField;
}
}
return Dummy.Field;
}
public static IEventDefinition GetHiddenBaseEvent(this IEventDefinition evnt, ICciFilter filter = null)
{
IMethodDefinition eventRep = evnt.Adder.ResolvedMethod;
if (eventRep.IsVirtual && !eventRep.IsNewSlot) return Dummy.Event; // an override
foreach (ITypeReference baseClassRef in evnt.ContainingTypeDefinition.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IEventDefinition baseEvent in baseClass.GetMembersNamed(evnt.Name, false).OfType<IEventDefinition>())
{
if (baseEvent.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseEvent) && !InSameUnit(baseEvent, evnt))
continue;
if (filter != null && !filter.Include(baseEvent))
continue;
return baseEvent;
}
}
return Dummy.Event;
}
public static IPropertyDefinition GetHiddenBaseProperty(this IPropertyDefinition property, ICciFilter filter = null)
{
IMethodDefinition propertyRep = property.Accessors.First().ResolvedMethod;
if (propertyRep.IsVirtual && !propertyRep.IsNewSlot) return Dummy.Property; // an override
ITypeDefinition type = property.ContainingTypeDefinition;
foreach (ITypeReference baseClassRef in type.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IPropertyDefinition baseProperty in baseClass.GetMembersNamed(property.Name, false).OfType<IPropertyDefinition>())
{
if (baseProperty.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseProperty) && !InSameUnit(baseProperty, property))
continue;
if (filter != null && !filter.Include(baseProperty))
continue;
if (SignaturesParametersAreEqual(property, baseProperty))
return baseProperty;
}
}
return Dummy.Property;
}
public static IMethodDefinition GetHiddenBaseMethod(this IMethodDefinition method, ICciFilter filter = null)
{
if (method.IsConstructor) return Dummy.Method;
if (method.IsVirtual && !method.IsNewSlot) return Dummy.Method; // an override
ITypeDefinition type = method.ContainingTypeDefinition;
foreach (ITypeReference baseClassRef in type.GetAllBaseTypes())
{
ITypeDefinition baseClass = baseClassRef.ResolvedType;
foreach (IMethodDefinition baseMethod in baseClass.GetMembersNamed(method.Name, false).OfType<IMethodDefinition>())
{
if (baseMethod.Visibility == TypeMemberVisibility.Private) continue;
if (IsAssembly(baseMethod) && !InSameUnit(baseMethod, method))
continue;
if (filter != null && !filter.Include(baseMethod.UnWrapMember()))
continue;
// NOTE: Do not check method.IsHiddenBySignature here. C# is *always* hide-by-signature regardless of the metadata flag.
// Do not check return type here, C# hides based on parameter types alone.
if (SignaturesParametersAreEqual(method, baseMethod))
{
if (!method.IsGeneric && !baseMethod.IsGeneric)
return baseMethod;
if (method.GenericParameterCount == baseMethod.GenericParameterCount)
return baseMethod;
}
}
}
return Dummy.Method;
}
public static bool SignaturesParametersAreEqual(this ISignature sig1, ISignature sig2)
{
return IteratorHelper.EnumerablesAreEqual<IParameterTypeInformation>(sig1.Parameters, sig2.Parameters, new ParameterInformationComparer());
}
private static Regex s_isKeywordRegex;
public static bool IsKeyword(string s)
{
if (s_isKeywordRegex == null)
s_isKeywordRegex = new Regex("^(abstract|as|break|case|catch|checked|class|const|continue|default|delegate|do|else|enum|event|explicit|extern|finally|foreach|for|get|goto|if|implicit|interface|internal|in|is|lock|namespace|new|operator|out|override|params|partial|private|protected|public|readonly|ref|return|sealed|set|sizeof|stackalloc|static|struct|switch|this|throw|try|typeof|unchecked|unsafe|using|virtual|volatile|while|yield|bool|byte|char|decimal|double|fixed|float|int|long|object|sbyte|short|string|uint|ulong|ushort|void)$", RegexOptions.Compiled);
return s_isKeywordRegex.IsMatch(s);
}
public static string GetMethodName(this IMethodDefinition method)
{
if (method.IsConstructor)
{
INamedEntity named = method.ContainingTypeDefinition.UnWrap() as INamedEntity;
if (named != null)
return named.Name.Value;
}
switch (method.Name.Value)
{
case "op_Decrement": return "operator --";
case "op_Increment": return "operator ++";
case "op_UnaryNegation": return "operator -";
case "op_UnaryPlus": return "operator +";
case "op_LogicalNot": return "operator !";
case "op_OnesComplement": return "operator ~";
case "op_True": return "operator true";
case "op_False": return "operator false";
case "op_Addition": return "operator +";
case "op_Subtraction": return "operator -";
case "op_Multiply": return "operator *";
case "op_Division": return "operator /";
case "op_Modulus": return "operator %";
case "op_ExclusiveOr": return "operator ^";
case "op_BitwiseAnd": return "operator &";
case "op_BitwiseOr": return "operator |";
case "op_LeftShift": return "operator <<";
case "op_RightShift": return "operator >>";
case "op_Equality": return "operator ==";
case "op_GreaterThan": return "operator >";
case "op_LessThan": return "operator <";
case "op_Inequality": return "operator !=";
case "op_GreaterThanOrEqual": return "operator >=";
case "op_LessThanOrEqual": return "operator <=";
case "op_Explicit": return "explicit operator";
case "op_Implicit": return "implicit operator";
default: return method.Name.Value; // return just the name
}
}
public static string GetNameWithoutExplicitType(this ITypeDefinitionMember member)
{
string name = member.Name.Value;
int index = name.LastIndexOf(".");
if (index < 0)
return name;
return name.Substring(index + 1);
}
public static bool IsExtensionMethod(this IMethodDefinition method)
{
if (!method.IsStatic)
return false;
return method.Attributes.HasAttributeOfType("System.Runtime.CompilerServices.ExtensionAttribute");
}
public static bool IsEffectivelySealed(this ITypeDefinition type)
{
if (type.IsSealed)
return true;
if (type.IsInterface)
return false;
// Types with only private constructors are effectively sealed
if (!type.Methods
.Any(m =>
m.IsConstructor &&
!m.IsStaticConstructor &&
m.IsVisibleOutsideAssembly()))
return true;
return false;
}
public static bool IsException(this ITypeDefinition type)
{
foreach (var baseTypeRef in type.GetBaseTypes())
{
if (baseTypeRef.AreEquivalent("System.Exception"))
return true;
}
return false;
}
public static bool IsAttribute(this ITypeDefinition type)
{
foreach (var baseTypeRef in type.GetBaseTypes())
{
if (baseTypeRef.AreEquivalent("System.Attribute"))
return true;
}
return false;
}
public static bool HasAttributeOfType(this IEnumerable<ICustomAttribute> attributes, string attributeName)
{
return attributes.Any(a => a.Type.AreEquivalent(attributeName));
}
public static bool HasIsByRefLikeAttribute(this IEnumerable<ICustomAttribute> attributes)
{
return attributes.HasAttributeOfType("System.Runtime.CompilerServices.IsByRefLikeAttribute");
}
public static bool HasIsReadOnlyAttribute(this IEnumerable<ICustomAttribute> attributes)
{
return attributes.HasAttributeOfType("System.Runtime.CompilerServices.IsReadOnlyAttribute");
}
private static IEnumerable<ITypeReference> GetBaseTypes(this ITypeReference typeRef)
{
ITypeDefinition type = typeRef.GetDefinitionOrNull();
if (type == null)
yield break;
foreach (var baseTypeRef in type.BaseClasses)
{
yield return baseTypeRef;
foreach (var nestedBaseTypeRef in GetBaseTypes(baseTypeRef))
yield return nestedBaseTypeRef;
}
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System.Linq;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
using UnitTest.Issues.TestProtos;
namespace Google.Protobuf.Reflection
{
/// <summary>
/// Tests for descriptors. (Not in its own namespace or broken up into individual classes as the
/// size doesn't warrant it. On the other hand, this makes me feel a bit dirty...)
/// </summary>
public class DescriptorsTest
{
[Test]
public void FileDescriptor()
{
FileDescriptor file = UnittestProto3Reflection.Descriptor;
Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Name);
Assert.AreEqual("protobuf_unittest", file.Package);
Assert.AreEqual("UnittestProto", file.Proto.Options.JavaOuterClassname);
Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Proto.Name);
// unittest.proto doesn't have any public imports, but unittest_import.proto does.
Assert.AreEqual(0, file.PublicDependencies.Count);
Assert.AreEqual(1, UnittestImportProto3Reflection.Descriptor.PublicDependencies.Count);
Assert.AreEqual(UnittestImportPublicProto3Reflection.Descriptor, UnittestImportProto3Reflection.Descriptor.PublicDependencies[0]);
Assert.AreEqual(1, file.Dependencies.Count);
Assert.AreEqual(UnittestImportProto3Reflection.Descriptor, file.Dependencies[0]);
MessageDescriptor messageType = TestAllTypes.Descriptor;
Assert.AreSame(typeof(TestAllTypes), messageType.ClrType);
Assert.AreSame(TestAllTypes.Parser, messageType.Parser);
Assert.AreEqual(messageType, file.MessageTypes[0]);
Assert.AreEqual(messageType, file.FindTypeByName<MessageDescriptor>("TestAllTypes"));
Assert.Null(file.FindTypeByName<MessageDescriptor>("NoSuchType"));
Assert.Null(file.FindTypeByName<MessageDescriptor>("protobuf_unittest.TestAllTypes"));
for (int i = 0; i < file.MessageTypes.Count; i++)
{
Assert.AreEqual(i, file.MessageTypes[i].Index);
}
Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName<EnumDescriptor>("ForeignEnum"));
Assert.Null(file.FindTypeByName<EnumDescriptor>("NoSuchType"));
Assert.Null(file.FindTypeByName<EnumDescriptor>("protobuf_unittest.ForeignEnum"));
Assert.AreEqual(1, UnittestImportProto3Reflection.Descriptor.EnumTypes.Count);
Assert.AreEqual("ImportEnum", UnittestImportProto3Reflection.Descriptor.EnumTypes[0].Name);
for (int i = 0; i < file.EnumTypes.Count; i++)
{
Assert.AreEqual(i, file.EnumTypes[i].Index);
}
Assert.AreEqual(10, file.SerializedData[0]);
}
[Test]
public void MessageDescriptor()
{
MessageDescriptor messageType = TestAllTypes.Descriptor;
MessageDescriptor nestedType = TestAllTypes.Types.NestedMessage.Descriptor;
Assert.AreEqual("TestAllTypes", messageType.Name);
Assert.AreEqual("protobuf_unittest.TestAllTypes", messageType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, messageType.File);
Assert.IsNull(messageType.ContainingType);
Assert.IsNull(messageType.Proto.Options);
Assert.AreEqual("TestAllTypes", messageType.Name);
Assert.AreEqual("NestedMessage", nestedType.Name);
Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedMessage", nestedType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File);
Assert.AreEqual(messageType, nestedType.ContainingType);
FieldDescriptor field = messageType.Fields.InDeclarationOrder()[0];
Assert.AreEqual("single_int32", field.Name);
Assert.AreEqual(field, messageType.FindDescriptor<FieldDescriptor>("single_int32"));
Assert.Null(messageType.FindDescriptor<FieldDescriptor>("no_such_field"));
Assert.AreEqual(field, messageType.FindFieldByNumber(1));
Assert.Null(messageType.FindFieldByNumber(571283));
var fieldsInDeclarationOrder = messageType.Fields.InDeclarationOrder();
for (int i = 0; i < fieldsInDeclarationOrder.Count; i++)
{
Assert.AreEqual(i, fieldsInDeclarationOrder[i].Index);
}
Assert.AreEqual(nestedType, messageType.NestedTypes[0]);
Assert.AreEqual(nestedType, messageType.FindDescriptor<MessageDescriptor>("NestedMessage"));
Assert.Null(messageType.FindDescriptor<MessageDescriptor>("NoSuchType"));
for (int i = 0; i < messageType.NestedTypes.Count; i++)
{
Assert.AreEqual(i, messageType.NestedTypes[i].Index);
}
Assert.AreEqual(messageType.EnumTypes[0], messageType.FindDescriptor<EnumDescriptor>("NestedEnum"));
Assert.Null(messageType.FindDescriptor<EnumDescriptor>("NoSuchType"));
for (int i = 0; i < messageType.EnumTypes.Count; i++)
{
Assert.AreEqual(i, messageType.EnumTypes[i].Index);
}
}
[Test]
public void FieldDescriptor()
{
MessageDescriptor messageType = TestAllTypes.Descriptor;
FieldDescriptor primitiveField = messageType.FindDescriptor<FieldDescriptor>("single_int32");
FieldDescriptor enumField = messageType.FindDescriptor<FieldDescriptor>("single_nested_enum");
FieldDescriptor messageField = messageType.FindDescriptor<FieldDescriptor>("single_foreign_message");
Assert.AreEqual("single_int32", primitiveField.Name);
Assert.AreEqual("protobuf_unittest.TestAllTypes.single_int32",
primitiveField.FullName);
Assert.AreEqual(1, primitiveField.FieldNumber);
Assert.AreEqual(messageType, primitiveField.ContainingType);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, primitiveField.File);
Assert.AreEqual(FieldType.Int32, primitiveField.FieldType);
Assert.IsNull(primitiveField.Proto.Options);
Assert.AreEqual("single_nested_enum", enumField.Name);
Assert.AreEqual(FieldType.Enum, enumField.FieldType);
// Assert.AreEqual(TestAllTypes.Types.NestedEnum.DescriptorProtoFile, enumField.EnumType);
Assert.AreEqual("single_foreign_message", messageField.Name);
Assert.AreEqual(FieldType.Message, messageField.FieldType);
Assert.AreEqual(ForeignMessage.Descriptor, messageField.MessageType);
}
[Test]
public void FieldDescriptorLabel()
{
FieldDescriptor singleField =
TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("single_int32");
FieldDescriptor repeatedField =
TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_int32");
Assert.IsFalse(singleField.IsRepeated);
Assert.IsTrue(repeatedField.IsRepeated);
}
[Test]
public void EnumDescriptor()
{
// Note: this test is a bit different to the Java version because there's no static way of getting to the descriptor
EnumDescriptor enumType = UnittestProto3Reflection.Descriptor.FindTypeByName<EnumDescriptor>("ForeignEnum");
EnumDescriptor nestedType = TestAllTypes.Descriptor.FindDescriptor<EnumDescriptor>("NestedEnum");
Assert.AreEqual("ForeignEnum", enumType.Name);
Assert.AreEqual("protobuf_unittest.ForeignEnum", enumType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, enumType.File);
Assert.Null(enumType.ContainingType);
Assert.Null(enumType.Proto.Options);
Assert.AreEqual("NestedEnum", nestedType.Name);
Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedEnum",
nestedType.FullName);
Assert.AreEqual(UnittestProto3Reflection.Descriptor, nestedType.File);
Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType);
EnumValueDescriptor value = enumType.FindValueByName("FOREIGN_FOO");
Assert.AreEqual(value, enumType.Values[1]);
Assert.AreEqual("FOREIGN_FOO", value.Name);
Assert.AreEqual(4, value.Number);
Assert.AreEqual((int) ForeignEnum.ForeignFoo, value.Number);
Assert.AreEqual(value, enumType.FindValueByNumber(4));
Assert.Null(enumType.FindValueByName("NO_SUCH_VALUE"));
for (int i = 0; i < enumType.Values.Count; i++)
{
Assert.AreEqual(i, enumType.Values[i].Index);
}
}
[Test]
public void OneofDescriptor()
{
OneofDescriptor descriptor = TestAllTypes.Descriptor.FindDescriptor<OneofDescriptor>("oneof_field");
Assert.AreEqual("oneof_field", descriptor.Name);
Assert.AreEqual("protobuf_unittest.TestAllTypes.oneof_field", descriptor.FullName);
var expectedFields = new[] {
TestAllTypes.OneofBytesFieldNumber,
TestAllTypes.OneofNestedMessageFieldNumber,
TestAllTypes.OneofStringFieldNumber,
TestAllTypes.OneofUint32FieldNumber }
.Select(fieldNumber => TestAllTypes.Descriptor.FindFieldByNumber(fieldNumber))
.ToList();
foreach (var field in expectedFields)
{
Assert.AreSame(descriptor, field.ContainingOneof);
}
CollectionAssert.AreEquivalent(expectedFields, descriptor.Fields);
}
[Test]
public void MapEntryMessageDescriptor()
{
var descriptor = MapWellKnownTypes.Descriptor.NestedTypes[0];
Assert.IsNull(descriptor.Parser);
Assert.IsNull(descriptor.ClrType);
Assert.IsNull(descriptor.Fields[1].Accessor);
}
// From TestFieldOrdering:
// string my_string = 11;
// int64 my_int = 1;
// float my_float = 101;
// NestedMessage single_nested_message = 200;
[Test]
public void FieldListOrderings()
{
var fields = TestFieldOrderings.Descriptor.Fields;
Assert.AreEqual(new[] { 11, 1, 101, 200 }, fields.InDeclarationOrder().Select(x => x.FieldNumber));
Assert.AreEqual(new[] { 1, 11, 101, 200 }, fields.InFieldNumberOrder().Select(x => x.FieldNumber));
}
[Test]
public void DescriptorProtoFileDescriptor()
{
var descriptor = Google.Protobuf.Reflection.FileDescriptor.DescriptorProtoFileDescriptor;
Assert.AreEqual("google/protobuf/descriptor.proto", descriptor.Name);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
//
// EncryptedReference.cs
//
// This object implements the EncryptedReference element.
//
// 04/01/2002
//
namespace System.Security.Cryptography.Xml
{
using System;
using System.Collections;
using System.Xml;
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public abstract class EncryptedReference {
private string m_uri;
private string m_referenceType;
private TransformChain m_transformChain;
internal XmlElement m_cachedXml = null;
protected EncryptedReference () : this (String.Empty, new TransformChain()) {
}
protected EncryptedReference (string uri) : this (uri, new TransformChain()) {
}
protected EncryptedReference (string uri, TransformChain transformChain) {
this.TransformChain = transformChain;
this.Uri = uri;
m_cachedXml = null;
}
public string Uri {
get { return m_uri; }
set {
if (value == null)
throw new ArgumentNullException(SecurityResources.GetResourceString("Cryptography_Xml_UriRequired"));
m_uri = value;
m_cachedXml = null;
}
}
public TransformChain TransformChain {
get {
if (m_transformChain == null)
m_transformChain = new TransformChain();
return m_transformChain;
}
set {
m_transformChain = value;
m_cachedXml = null;
}
}
public void AddTransform (Transform transform) {
this.TransformChain.Add(transform);
}
protected string ReferenceType {
get { return m_referenceType; }
set {
m_referenceType = value;
m_cachedXml = null;
}
}
internal protected bool CacheValid {
get {
return (m_cachedXml != null);
}
}
public virtual XmlElement GetXml () {
if (CacheValid) return m_cachedXml;
XmlDocument document = new XmlDocument();
document.PreserveWhitespace = true;
return GetXml(document);
}
internal XmlElement GetXml (XmlDocument document) {
if (ReferenceType == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_ReferenceTypeRequired"));
// Create the Reference
XmlElement referenceElement = document.CreateElement(ReferenceType, EncryptedXml.XmlEncNamespaceUrl);
if (!String.IsNullOrEmpty(m_uri))
referenceElement.SetAttribute("URI", m_uri);
// Add the transforms to the CipherReference
if (this.TransformChain.Count > 0)
referenceElement.AppendChild(this.TransformChain.GetXml(document, SignedXml.XmlDsigNamespaceUrl));
return referenceElement;
}
public virtual void LoadXml (XmlElement value) {
if (value == null)
throw new ArgumentNullException("value");
this.ReferenceType = value.LocalName;
this.Uri = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl);
// Transforms
XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);
nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
XmlNode transformsNode = value.SelectSingleNode("ds:Transforms", nsm);
if (transformsNode != null)
this.TransformChain.LoadXml(transformsNode as XmlElement);
// cache the Xml
m_cachedXml = value;
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class CipherReference : EncryptedReference {
private byte[] m_cipherValue;
public CipherReference () : base () {
ReferenceType = "CipherReference";
}
public CipherReference (string uri) : base(uri) {
ReferenceType = "CipherReference";
}
public CipherReference (string uri, TransformChain transformChain) : base(uri, transformChain) {
ReferenceType = "CipherReference";
}
// This method is used to cache results from resolved cipher references.
internal byte[] CipherValue {
get {
if (!CacheValid)
return null;
return m_cipherValue;
}
set {
m_cipherValue = value;
}
}
public override XmlElement GetXml () {
if (CacheValid) return m_cachedXml;
XmlDocument document = new XmlDocument();
document.PreserveWhitespace = true;
return GetXml(document);
}
new internal XmlElement GetXml (XmlDocument document) {
if (ReferenceType == null)
throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_ReferenceTypeRequired"));
// Create the Reference
XmlElement referenceElement = document.CreateElement(ReferenceType, EncryptedXml.XmlEncNamespaceUrl);
if (!String.IsNullOrEmpty(this.Uri))
referenceElement.SetAttribute("URI", this.Uri);
// Add the transforms to the CipherReference
if (this.TransformChain.Count > 0)
referenceElement.AppendChild(this.TransformChain.GetXml(document, EncryptedXml.XmlEncNamespaceUrl));
return referenceElement;
}
public override void LoadXml (XmlElement value) {
if (value == null)
throw new ArgumentNullException("value");
this.ReferenceType = value.LocalName;
this.Uri = Utils.GetAttribute(value, "URI", EncryptedXml.XmlEncNamespaceUrl);
// Transforms
XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);
nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
XmlNode transformsNode = value.SelectSingleNode("enc:Transforms", nsm);
if (transformsNode != null)
this.TransformChain.LoadXml(transformsNode as XmlElement);
// cache the Xml
m_cachedXml = value;
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class DataReference : EncryptedReference {
public DataReference () : base () {
ReferenceType = "DataReference";
}
public DataReference (string uri) : base(uri) {
ReferenceType = "DataReference";
}
public DataReference (string uri, TransformChain transformChain) : base(uri, transformChain) {
ReferenceType = "DataReference";
}
}
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
public sealed class KeyReference : EncryptedReference {
public KeyReference () : base () {
ReferenceType = "KeyReference";
}
public KeyReference (string uri) : base(uri) {
ReferenceType = "KeyReference";
}
public KeyReference (string uri, TransformChain transformChain) : base(uri, transformChain) {
ReferenceType = "KeyReference";
}
}
}
| |
// 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.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Globalization;
namespace System.Net.WebSockets
{
internal class WinHttpWebSocket : WebSocket
{
#region Constants
// TODO: This code needs to be shared with WinHttpClientHandler
private const string HeaderNameCookie = "Cookie";
private const string HeaderNameWebSocketProtocol = "Sec-WebSocket-Protocol";
#endregion
// TODO (Issue 2503): move System.Net.* strings to resources as appropriate.
// NOTE: All WinHTTP operations must be called while holding the _operation.Lock.
// It is critical that no handle gets closed while a WinHTTP function is running.
private WebSocketCloseStatus? _closeStatus = null;
private string _closeStatusDescription = null;
private string _subProtocol = null;
private bool _disposed = false;
private WinHttpWebSocketState _operation = new WinHttpWebSocketState();
public WinHttpWebSocket()
{
}
#region Properties
public override WebSocketCloseStatus? CloseStatus
{
get
{
return _closeStatus;
}
}
public override string CloseStatusDescription
{
get
{
return _closeStatusDescription;
}
}
public override WebSocketState State
{
get
{
return _operation.State;
}
}
public override string SubProtocol
{
get
{
return _subProtocol;
}
}
#endregion
readonly static WebSocketState[] s_validConnectStates = { WebSocketState.None };
readonly static WebSocketState[] s_validConnectingStates = { WebSocketState.Connecting };
public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.Connecting, s_validConnectStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validConnectingStates);
// Must grab lock until RequestHandle is populated, otherwise we risk resource leaks on Abort.
//
// TODO (Issue 2506): Alternatively, release the lock between WinHTTP operations and check, under lock, that the
// state is still valid to continue operation.
_operation.SessionHandle = InitializeWinHttp(options);
_operation.ConnectionHandle = Interop.WinHttp.WinHttpConnectWithCallback(
_operation.SessionHandle,
uri.IdnHost,
(ushort)uri.Port,
0);
ThrowOnInvalidHandle(_operation.ConnectionHandle);
bool secureConnection = uri.Scheme == UriScheme.Https || uri.Scheme == UriScheme.Wss;
_operation.RequestHandle = Interop.WinHttp.WinHttpOpenRequestWithCallback(
_operation.ConnectionHandle,
"GET",
uri.PathAndQuery,
null,
Interop.WinHttp.WINHTTP_NO_REFERER,
null,
secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0);
ThrowOnInvalidHandle(_operation.RequestHandle);
_operation.IncrementHandlesOpenWithCallback();
if (!Interop.WinHttp.WinHttpSetOption(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET,
IntPtr.Zero,
0))
{
WinHttpException.ThrowExceptionUsingLastError();
}
// We need the address of the IntPtr to the GCHandle.
IntPtr context = _operation.ToIntPtr();
IntPtr contextAddress;
unsafe
{
contextAddress = (IntPtr)(void*)&context;
}
if (!Interop.WinHttp.WinHttpSetOption(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE,
contextAddress,
(uint)IntPtr.Size))
{
WinHttpException.ThrowExceptionUsingLastError();
}
const uint notificationFlags =
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES |
Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SECURE_FAILURE;
if (Interop.WinHttp.WinHttpSetStatusCallback(
_operation.RequestHandle,
WinHttpWebSocketCallback.s_StaticCallbackDelegate,
notificationFlags,
IntPtr.Zero) == (IntPtr)Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK)
{
WinHttpException.ThrowExceptionUsingLastError();
}
_operation.RequestHandle.AttachCallback();
// We need to pin the operation object at this point in time since the WinHTTP callback
// has been fully wired to the request handle and the operation object has been set as
// the context value of the callback. Any notifications from activity on the handle will
// result in the callback being called with the context value.
_operation.Pin();
AddRequestHeaders(uri, options);
_operation.TcsUpgrade = new TaskCompletionSource<bool>();
}
await InternalSendWsUpgradeRequestAsync().ConfigureAwait(false);
await InternalReceiveWsUpgradeResponse().ConfigureAwait(false);
lock (_operation.Lock)
{
VerifyUpgradeResponse();
ThrowOnInvalidConnectState();
_operation.WebSocketHandle =
Interop.WinHttp.WinHttpWebSocketCompleteUpgrade(_operation.RequestHandle, IntPtr.Zero);
ThrowOnInvalidHandle(_operation.WebSocketHandle);
_operation.IncrementHandlesOpenWithCallback();
// We need the address of the IntPtr to the GCHandle.
IntPtr context = _operation.ToIntPtr();
IntPtr contextAddress;
unsafe
{
contextAddress = (IntPtr)(void*)&context;
}
if (!Interop.WinHttp.WinHttpSetOption(
_operation.WebSocketHandle,
Interop.WinHttp.WINHTTP_OPTION_CONTEXT_VALUE,
contextAddress,
(uint)IntPtr.Size))
{
WinHttpException.ThrowExceptionUsingLastError();
}
_operation.WebSocketHandle.AttachCallback();
_operation.UpdateState(WebSocketState.Open);
if (_operation.RequestHandle != null)
{
_operation.RequestHandle.Dispose();
// RequestHandle will be set to null in the callback.
}
_operation.TcsUpgrade = null;
ctr.Dispose();
}
}
}
// Requires lock taken.
private Interop.WinHttp.SafeWinHttpHandle InitializeWinHttp(ClientWebSocketOptions options)
{
Interop.WinHttp.SafeWinHttpHandle sessionHandle;
sessionHandle = Interop.WinHttp.WinHttpOpen(
IntPtr.Zero,
Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
null,
null,
(int)Interop.WinHttp.WINHTTP_FLAG_ASYNC);
ThrowOnInvalidHandle(sessionHandle);
uint optionAssuredNonBlockingTrue = 1; // TRUE
if (!Interop.WinHttp.WinHttpSetOption(
sessionHandle,
Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS,
ref optionAssuredNonBlockingTrue,
(uint)Marshal.SizeOf<uint>()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return sessionHandle;
}
private Task<bool> InternalSendWsUpgradeRequestAsync()
{
lock (_operation.Lock)
{
ThrowOnInvalidConnectState();
if (!Interop.WinHttp.WinHttpSendRequest(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_NO_ADDITIONAL_HEADERS,
0,
IntPtr.Zero,
0,
0,
_operation.ToIntPtr()))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return _operation.TcsUpgrade.Task;
}
private Task<bool> InternalReceiveWsUpgradeResponse()
{
// TODO (Issue 2507): Potential optimization: move this in WinHttpWebSocketCallback.
lock (_operation.Lock)
{
ThrowOnInvalidConnectState();
_operation.TcsUpgrade = new TaskCompletionSource<bool>();
if (!Interop.WinHttp.WinHttpReceiveResponse(_operation.RequestHandle, IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
return _operation.TcsUpgrade.Task;
}
private void ThrowOnInvalidConnectState()
{
// A special behavior for WebSocket upgrade: throws ConnectFailure instead of other Abort messages.
if (_operation.State != WebSocketState.Connecting)
{
throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
}
private readonly static WebSocketState[] s_validSendStates = { WebSocketState.Open, WebSocketState.CloseReceived };
public override Task SendAsync(
ArraySegment<byte> buffer,
WebSocketMessageType messageType,
bool endOfMessage,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckValidStates(s_validSendStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
var bufferType = WebSocketMessageTypeAdapter.GetWinHttpMessageType(messageType, endOfMessage);
_operation.PinSendBuffer(buffer);
bool sendOperationAlreadyPending = false;
if (_operation.PendingWriteOperation == false)
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validSendStates);
if (_operation.PendingWriteOperation == false)
{
_operation.PendingWriteOperation = true;
_operation.TcsSend = new TaskCompletionSource<bool>();
uint ret = Interop.WinHttp.WinHttpWebSocketSend(
_operation.WebSocketHandle,
bufferType,
buffer.Count > 0 ? Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset) : IntPtr.Zero,
(uint)buffer.Count);
if (Interop.WinHttp.ERROR_SUCCESS != ret)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
else
{
sendOperationAlreadyPending = true;
}
}
}
else
{
sendOperationAlreadyPending = true;
}
if (sendOperationAlreadyPending)
{
var exception = new InvalidOperationException(
SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "SendAsync"));
_operation.TcsSend.TrySetException(exception);
Abort();
}
return _operation.TcsSend.Task;
}
}
private readonly static WebSocketState[] s_validReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent };
private readonly static WebSocketState[] s_validAfterReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent, WebSocketState.CloseReceived };
public override async Task<WebSocketReceiveResult> ReceiveAsync(
ArraySegment<byte> buffer,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckValidStates(s_validReceiveStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
_operation.PinReceiveBuffer(buffer);
await InternalReceiveAsync(buffer).ConfigureAwait(false);
// Check for abort.
_operation.InterlockedCheckValidStates(s_validAfterReceiveStates);
WebSocketMessageType bufferType;
bool endOfMessage;
bufferType = WebSocketMessageTypeAdapter.GetWebSocketMessageType(_operation.BufferType, out endOfMessage);
int bytesTransferred = 0;
checked
{
bytesTransferred = (int)_operation.BytesTransferred;
}
WebSocketReceiveResult ret;
if (bufferType == WebSocketMessageType.Close)
{
UpdateServerCloseStatus();
ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage, _closeStatus, _closeStatusDescription);
}
else
{
ret = new WebSocketReceiveResult(bytesTransferred, bufferType, endOfMessage);
}
return ret;
}
}
private Task<bool> InternalReceiveAsync(ArraySegment<byte> buffer)
{
bool receiveOperationAlreadyPending = false;
if (_operation.PendingReadOperation == false)
{
lock (_operation.Lock)
{
if (_operation.PendingReadOperation == false)
{
_operation.CheckValidState(s_validReceiveStates);
_operation.TcsReceive = new TaskCompletionSource<bool>();
_operation.PendingReadOperation = true;
uint bytesRead = 0;
Interop.WinHttp.WINHTTP_WEB_SOCKET_BUFFER_TYPE winHttpBufferType = 0;
uint status = Interop.WinHttp.WinHttpWebSocketReceive(
_operation.WebSocketHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset),
(uint)buffer.Count,
out bytesRead, // Unused in async mode: ignore.
out winHttpBufferType); // Unused in async mode: ignore.
if (Interop.WinHttp.ERROR_SUCCESS != status)
{
throw WinHttpException.CreateExceptionUsingError((int)status);
}
}
else
{
receiveOperationAlreadyPending = true;
}
}
}
else
{
receiveOperationAlreadyPending = true;
}
if (receiveOperationAlreadyPending)
{
var exception = new InvalidOperationException(
SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "ReceiveAsync"));
_operation.TcsReceive.TrySetException(exception);
Abort();
}
return _operation.TcsReceive.Task;
}
private static readonly WebSocketState[] s_validCloseStates = { WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent };
public override async Task CloseAsync(
WebSocketCloseStatus closeStatus,
string statusDescription,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
_operation.TcsClose = new TaskCompletionSource<bool>();
await InternalCloseAsync(closeStatus, statusDescription).ConfigureAwait(false);
UpdateServerCloseStatus();
}
}
private Task<bool> InternalCloseAsync(WebSocketCloseStatus closeStatus, string statusDescription)
{
uint ret;
_operation.TcsClose = new TaskCompletionSource<bool>();
lock (_operation.Lock)
{
_operation.CheckValidState(s_validCloseStates);
if (!string.IsNullOrEmpty(statusDescription))
{
byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription);
ret = Interop.WinHttp.WinHttpWebSocketClose(
_operation.WebSocketHandle,
(ushort)closeStatus,
statusDescriptionBuffer,
(uint)statusDescriptionBuffer.Length);
}
else
{
ret = Interop.WinHttp.WinHttpWebSocketClose(
_operation.WebSocketHandle,
(ushort)closeStatus,
IntPtr.Zero,
0);
}
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
return _operation.TcsClose.Task;
}
private void UpdateServerCloseStatus()
{
uint ret;
ushort serverStatus;
var closeDescription = new byte[WebSocketValidate.MaxControlFramePayloadLength];
uint closeDescriptionConsumed;
lock (_operation.Lock)
{
ret = Interop.WinHttp.WinHttpWebSocketQueryCloseStatus(
_operation.WebSocketHandle,
out serverStatus,
closeDescription,
(uint)closeDescription.Length,
out closeDescriptionConsumed);
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
_closeStatus = (WebSocketCloseStatus)serverStatus;
_closeStatusDescription = Encoding.UTF8.GetString(closeDescription, 0, (int)closeDescriptionConsumed);
}
}
private readonly static WebSocketState[] s_validCloseOutputStates = { WebSocketState.Open, WebSocketState.CloseReceived };
private readonly static WebSocketState[] s_validCloseOutputStatesAfterUpdate = { WebSocketState.CloseReceived, WebSocketState.CloseSent };
public override Task CloseOutputAsync(
WebSocketCloseStatus closeStatus,
string statusDescription,
CancellationToken cancellationToken)
{
_operation.InterlockedCheckAndUpdateState(WebSocketState.CloseSent, s_validCloseOutputStates);
using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken))
{
lock (_operation.Lock)
{
_operation.CheckValidState(s_validCloseOutputStatesAfterUpdate);
uint ret;
_operation.TcsCloseOutput = new TaskCompletionSource<bool>();
if (!string.IsNullOrEmpty(statusDescription))
{
byte[] statusDescriptionBuffer = Encoding.UTF8.GetBytes(statusDescription);
ret = Interop.WinHttp.WinHttpWebSocketShutdown(
_operation.WebSocketHandle,
(ushort)closeStatus,
statusDescriptionBuffer,
(uint)statusDescriptionBuffer.Length);
}
else
{
ret = Interop.WinHttp.WinHttpWebSocketShutdown(
_operation.WebSocketHandle,
(ushort)closeStatus,
IntPtr.Zero,
0);
}
if (ret != Interop.WinHttp.ERROR_SUCCESS)
{
throw WinHttpException.CreateExceptionUsingError((int)ret);
}
}
return _operation.TcsCloseOutput.Task;
}
}
private void VerifyUpgradeResponse()
{
// Check the status code
var statusCode = GetHttpStatusCode();
if (statusCode != HttpStatusCode.SwitchingProtocols)
{
Abort();
return;
}
_subProtocol = GetResponseHeader(HeaderNameWebSocketProtocol);
}
private void AddRequestHeaders(Uri uri, ClientWebSocketOptions options)
{
var requestHeadersBuffer = new StringBuilder();
// Manually add cookies.
if (options.Cookies != null)
{
string cookieHeader = GetCookieHeader(uri, options.Cookies);
if (!string.IsNullOrEmpty(cookieHeader))
{
requestHeadersBuffer.AppendLine(cookieHeader);
}
}
// Serialize general request headers.
requestHeadersBuffer.AppendLine(options.RequestHeaders.ToString());
var subProtocols = options.RequestedSubProtocols;
if (subProtocols.Count > 0)
{
requestHeadersBuffer.AppendLine(string.Format("{0}: {1}", HeaderNameWebSocketProtocol,
string.Join(", ", subProtocols)));
}
// Add request headers to WinHTTP request handle.
if (!Interop.WinHttp.WinHttpAddRequestHeaders(
_operation.RequestHandle,
requestHeadersBuffer,
(uint)requestHeadersBuffer.Length,
Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private static string GetCookieHeader(Uri uri, CookieContainer cookies)
{
string cookieHeader = null;
Debug.Assert(cookies != null);
string cookieValues = cookies.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
cookieHeader = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", HeaderNameCookie, cookieValues);
}
return cookieHeader;
}
private HttpStatusCode GetHttpStatusCode()
{
uint infoLevel = Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE | Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER;
uint result = 0;
uint resultSize = sizeof(uint);
if (!Interop.WinHttp.WinHttpQueryHeaders(
_operation.RequestHandle,
infoLevel,
Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX,
ref result,
ref resultSize,
IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return (HttpStatusCode)result;
}
private unsafe string GetResponseHeader(string headerName, char[] buffer = null)
{
const int StackLimit = 128;
Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit));
int bufferLength;
if (buffer == null)
{
bufferLength = StackLimit;
char* pBuffer = stackalloc char[bufferLength];
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return new string(pBuffer, 0, bufferLength);
}
}
else
{
bufferLength = buffer.Length;
fixed (char* pBuffer = buffer)
{
if (QueryHeaders(headerName, pBuffer, ref bufferLength))
{
return new string(pBuffer, 0, bufferLength);
}
}
}
int lastError = Marshal.GetLastWin32Error();
if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND)
{
return null;
}
if (lastError == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER)
{
buffer = new char[bufferLength];
return GetResponseHeader(headerName, buffer);
}
throw WinHttpException.CreateExceptionUsingError(lastError);
}
private unsafe bool QueryHeaders(string headerName, char* buffer, ref int bufferLength)
{
Debug.Assert(bufferLength >= 0, "bufferLength must not be negative.");
uint index = 0;
// Convert the char buffer length to the length in bytes.
uint bufferLengthInBytes = (uint)bufferLength * sizeof(char);
// The WinHttpQueryHeaders buffer length is in bytes,
// but the API actually returns Unicode characters.
bool result = Interop.WinHttp.WinHttpQueryHeaders(
_operation.RequestHandle,
Interop.WinHttp.WINHTTP_QUERY_CUSTOM,
headerName,
new IntPtr(buffer),
ref bufferLengthInBytes,
ref index);
// Convert the byte buffer length back to the length in chars.
bufferLength = (int)bufferLengthInBytes / sizeof(char);
return result;
}
public override void Dispose()
{
if (!_disposed)
{
lock (_operation.Lock)
{
// Disposing will involve calling WinHttpClose on handles. It is critical that no other WinHttp
// function is running at the same time.
if (!_disposed)
{
_operation.Dispose();
_disposed = true;
}
}
}
// No need to suppress finalization since the finalizer is not overridden.
}
public override void Abort()
{
lock (_operation.Lock)
{
if ((State != WebSocketState.None) && (State != WebSocketState.Connecting))
{
_operation.UpdateState(WebSocketState.Aborted);
}
else
{
// ClientWebSocket Desktop behavior: a ws that was not connected will not switch state to Aborted.
_operation.UpdateState(WebSocketState.Closed);
}
Dispose();
}
CancelAllOperations();
}
private void CancelAllOperations()
{
if (_operation.TcsClose != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsClose.TrySetException(exception);
}
if (_operation.TcsCloseOutput != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsCloseOutput.TrySetException(exception);
}
if (_operation.TcsReceive != null)
{
var exception = new WebSocketException(
WebSocketError.InvalidState,
SR.Format(
SR.net_WebSockets_InvalidState_ClosedOrAborted,
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"));
_operation.TcsReceive.TrySetException(exception);
}
if (_operation.TcsSend != null)
{
var exception = new OperationCanceledException();
_operation.TcsSend.TrySetException(exception);
}
if (_operation.TcsUpgrade != null)
{
var exception = new WebSocketException(SR.net_webstatus_ConnectFailure);
_operation.TcsUpgrade.TrySetException(exception);
}
}
private void ThrowOnInvalidHandle(Interop.WinHttp.SafeWinHttpHandle value)
{
if (value.IsInvalid)
{
Abort();
throw new WebSocketException(
SR.net_webstatus_ConnectFailure,
WinHttpException.CreateExceptionUsingLastError());
}
}
private CancellationTokenRegistration ThrowOrRegisterCancellation(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
Abort();
cancellationToken.ThrowIfCancellationRequested();
}
CancellationTokenRegistration cancellationRegistration =
cancellationToken.Register(s => ((WinHttpWebSocket)s).Abort(), this);
return cancellationRegistration;
}
}
}
| |
// Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Annotations;
using NodaTime.Globalization;
using NodaTime.Text.Patterns;
using NodaTime.Utility;
using System.Globalization;
using System.Text;
namespace NodaTime.Text
{
/// <summary>
/// Represents a pattern for parsing and formatting <see cref="OffsetDateTime"/> values.
/// </summary>
/// <threadsafety>
/// When used with a read-only <see cref="CultureInfo" />, this type is immutable and instances
/// may be shared freely between threads. We recommend only using read-only cultures for patterns, although this is
/// not currently enforced.
/// </threadsafety>
[Immutable] // Well, assuming an immutable culture...
public sealed class OffsetDateTimePattern : IPattern<OffsetDateTime>
{
internal static readonly OffsetDateTime DefaultTemplateValue = new LocalDateTime(2000, 1, 1, 0, 0).WithOffset(Offset.Zero);
/// <summary>
/// Gets an invariant offset date/time pattern based on ISO-8601 (down to the second), including offset from UTC.
/// </summary>
/// <remarks>
/// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of
/// "uuuu'-'MM'-'dd'T'HH':'mm':'sso<G>". This pattern is available as the "G"
/// standard pattern (even though it is invariant).
/// </remarks>
/// <value>An invariant offset date/time pattern based on ISO-8601 (down to the second), including offset from UTC.</value>
public static OffsetDateTimePattern GeneralIso => Patterns.GeneralIsoPatternImpl;
/// <summary>
/// Gets an invariant offset date/time pattern based on ISO-8601 (down to the nanosecond), including offset from UTC.
/// </summary>
/// <remarks>
/// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of
/// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G>". This will round-trip any values
/// in the ISO calendar, and is available as the "o" standard pattern.
/// </remarks>
/// <value>An invariant offset date/time pattern based on ISO-8601 (down to the nanosecond), including offset from UTC.</value>
public static OffsetDateTimePattern ExtendedIso => Patterns.ExtendedIsoPatternImpl;
/// <summary>
/// Gets an invariant offset date/time pattern based on RFC 3339 (down to the nanosecond), including offset from UTC
/// as hours and minutes only.
/// </summary>
/// <remarks>
/// The minutes part of the offset is always included, but any sub-minute component
/// of the offset is lost. An offset of zero is formatted as 'Z', but all of 'Z', '+00:00' and '-00:00' are parsed
/// the same way. The RFC 3339 meaning of '-00:00' is not supported by Noda Time.
/// Note that parsing is case-sensitive (so 'T' and 'Z' must be upper case).
/// The calendar system is not parsed or formatted as part of this pattern. It corresponds to a custom pattern of
/// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<Z+HH:mm>".
/// </remarks>
/// <value>An invariant offset date/time pattern based on RFC 3339 (down to the nanosecond), including offset from UTC
/// as hours and minutes only.</value>
public static OffsetDateTimePattern Rfc3339 => Patterns.Rfc3339PatternImpl;
/// <summary>
/// Gets an invariant offset date/time pattern based on ISO-8601 (down to the nanosecond)
/// including offset from UTC and calendar ID.
/// </summary>
/// <remarks>
/// The returned pattern corresponds to a custom pattern of
/// "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> '('c')'". This will round-trip any value in any calendar,
/// and is available as the "r" standard pattern.
/// </remarks>
/// <value>An invariant offset date/time pattern based on ISO-8601 (down to the nanosecond)
/// including offset from UTC and calendar ID.</value>
public static OffsetDateTimePattern FullRoundtrip => Patterns.FullRoundtripPatternImpl;
/// <summary>
/// Class whose existence is solely to avoid type initialization order issues, most of which stem
/// from needing NodaFormatInfo.InvariantInfo...
/// </summary>
internal static class Patterns
{
internal static readonly OffsetDateTimePattern GeneralIsoPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'sso<G>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue);
internal static readonly OffsetDateTimePattern ExtendedIsoPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue);
internal static readonly OffsetDateTimePattern Rfc3339PatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<Z+HH:mm>", NodaFormatInfo.InvariantInfo, DefaultTemplateValue);
internal static readonly OffsetDateTimePattern FullRoundtripPatternImpl = Create("uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<G> '('c')'", NodaFormatInfo.InvariantInfo, DefaultTemplateValue);
internal static readonly PatternBclSupport<OffsetDateTime> BclSupport = new PatternBclSupport<OffsetDateTime>("G", fi => fi.OffsetDateTimePatternParser);
}
private readonly IPattern<OffsetDateTime> pattern;
/// <summary>
/// Gets the pattern text for this pattern, as supplied on creation.
/// </summary>
/// <value>The pattern text for this pattern, as supplied on creation.</value>
public string PatternText { get; }
// Visible for testing
/// <summary>
/// Gets the localization information used in this pattern.
/// </summary>
internal NodaFormatInfo FormatInfo { get; }
/// <summary>
/// Gets the value used as a template for parsing: any field values unspecified
/// in the pattern are taken from the template.
/// </summary>
/// <value>The value used as a template for parsing.</value>
public OffsetDateTime TemplateValue { get; }
private OffsetDateTimePattern(string patternText, NodaFormatInfo formatInfo, OffsetDateTime templateValue,
IPattern<OffsetDateTime> pattern)
{
this.PatternText = patternText;
this.FormatInfo = formatInfo;
this.TemplateValue = templateValue;
this.pattern = pattern;
}
/// <summary>
/// Parses the given text value according to the rules of this pattern.
/// </summary>
/// <remarks>
/// This method never throws an exception (barring a bug in Noda Time itself). Even errors such as
/// the argument being null are wrapped in a parse result.
/// </remarks>
/// <param name="text">The text value to parse.</param>
/// <returns>The result of parsing, which may be successful or unsuccessful.</returns>
public ParseResult<OffsetDateTime> Parse([SpecialNullHandling] string text) => pattern.Parse(text);
/// <summary>
/// Formats the given offset date/time as text according to the rules of this pattern.
/// </summary>
/// <param name="value">The offset date/time to format.</param>
/// <returns>The offset date/time formatted according to this pattern.</returns>
public string Format(OffsetDateTime value) => pattern.Format(value);
/// <summary>
/// Formats the given value as text according to the rules of this pattern,
/// appending to the given <see cref="StringBuilder"/>.
/// </summary>
/// <param name="value">The value to format.</param>
/// <param name="builder">The <c>StringBuilder</c> to append to.</param>
/// <returns>The builder passed in as <paramref name="builder"/>.</returns>
public StringBuilder AppendFormat(OffsetDateTime value, StringBuilder builder) => pattern.AppendFormat(value, builder);
/// <summary>
/// Creates a pattern for the given pattern text, format info, and template value.
/// </summary>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <param name="formatInfo">The format info to use in the pattern</param>
/// <param name="templateValue">Template value to use for unspecified fields</param>
/// <returns>A pattern for parsing and formatting offset date/times.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
private static OffsetDateTimePattern Create(string patternText, NodaFormatInfo formatInfo,
OffsetDateTime templateValue)
{
Preconditions.CheckNotNull(patternText, nameof(patternText));
Preconditions.CheckNotNull(formatInfo, nameof(formatInfo));
var pattern = new OffsetDateTimePatternParser(templateValue).ParsePattern(patternText, formatInfo);
return new OffsetDateTimePattern(patternText, formatInfo, templateValue, pattern);
}
/// <summary>
/// Creates a pattern for the given pattern text, culture, and template value.
/// </summary>
/// <remarks>
/// See the user guide for the available pattern text options.
/// </remarks>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <param name="cultureInfo">The culture to use in the pattern</param>
/// <param name="templateValue">Template value to use for unspecified fields</param>
/// <returns>A pattern for parsing and formatting local date/times.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
public static OffsetDateTimePattern Create(string patternText, CultureInfo cultureInfo, OffsetDateTime templateValue) =>
Create(patternText, NodaFormatInfo.GetFormatInfo(cultureInfo), templateValue);
/// <summary>
/// Creates a pattern for the given pattern text in the invariant culture, using the default
/// template value of midnight January 1st 2000 at an offset of 0.
/// </summary>
/// <remarks>
/// See the user guide for the available pattern text options.
/// </remarks>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <returns>A pattern for parsing and formatting local date/times.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
public static OffsetDateTimePattern CreateWithInvariantCulture(string patternText) =>
Create(patternText, NodaFormatInfo.InvariantInfo, DefaultTemplateValue);
/// <summary>
/// Creates a pattern for the given pattern text in the current culture, using the default
/// template value of midnight January 1st 2000 at an offset of 0.
/// </summary>
/// <remarks>
/// See the user guide for the available pattern text options. Note that the current culture
/// is captured at the time this method is called - it is not captured at the point of parsing
/// or formatting values.
/// </remarks>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <returns>A pattern for parsing and formatting local date/times.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
public static OffsetDateTimePattern CreateWithCurrentCulture(string patternText) =>
Create(patternText, NodaFormatInfo.CurrentInfo, DefaultTemplateValue);
/// <summary>
/// Creates a pattern for the same original localization information as this pattern, but with the specified
/// pattern text.
/// </summary>
/// <param name="patternText">The pattern text to use in the new pattern.</param>
/// <returns>A new pattern with the given pattern text.</returns>
public OffsetDateTimePattern WithPatternText(string patternText) =>
Create(patternText, FormatInfo, TemplateValue);
/// <summary>
/// Creates a pattern for the same original pattern text as this pattern, but with the specified
/// localization information.
/// </summary>
/// <param name="formatInfo">The localization information to use in the new pattern.</param>
/// <returns>A new pattern with the given localization information.</returns>
private OffsetDateTimePattern WithFormatInfo(NodaFormatInfo formatInfo) =>
Create(PatternText, formatInfo, TemplateValue);
/// <summary>
/// Creates a pattern for the same original pattern text as this pattern, but with the specified
/// culture.
/// </summary>
/// <param name="cultureInfo">The culture to use in the new pattern.</param>
/// <returns>A new pattern with the given culture.</returns>
public OffsetDateTimePattern WithCulture(CultureInfo cultureInfo) =>
WithFormatInfo(NodaFormatInfo.GetFormatInfo(cultureInfo));
/// <summary>
/// Creates a pattern for the same original pattern text and culture as this pattern, but with
/// the specified template value.
/// </summary>
/// <param name="newTemplateValue">The template value to use in the new pattern.</param>
/// <returns>A new pattern with the given template value.</returns>
public OffsetDateTimePattern WithTemplateValue(OffsetDateTime newTemplateValue) =>
Create(PatternText, FormatInfo, newTemplateValue);
/// <summary>
/// Creates a pattern like this one, but with the template value modified to use
/// the specified calendar system.
/// </summary>
/// <remarks>
/// <para>
/// Care should be taken in two (relatively rare) scenarios. Although the default template value
/// is supported by all Noda Time calendar systems, if a pattern is created with a different
/// template value and then this method is called with a calendar system which doesn't support that
/// date, an exception will be thrown. Additionally, if the pattern only specifies some date fields,
/// it's possible that the new template value will not be suitable for all values.
/// </para>
/// </remarks>
/// <param name="calendar">The calendar system to convert the template value into.</param>
/// <returns>A new pattern with a template value in the specified calendar system.</returns>
public OffsetDateTimePattern WithCalendar(CalendarSystem calendar) =>
WithTemplateValue(TemplateValue.WithCalendar(calendar));
}
}
| |
namespace FakeItEasy.Core
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
#if !FEATURE_REFLECTION_GETASSEMBLIES
using System.Runtime.Loader;
using Microsoft.Extensions.DependencyModel;
#endif
/// <summary>
/// Provides access to all types in:
/// <list type="bullet">
/// <item>FakeItEasy,</item>
/// <item>currently loaded assemblies that reference FakeItEasy and</item>
/// <item>assemblies whose paths are supplied to the constructor, that also reference FakeItEasy.</item>
/// </list>
/// </summary>
internal class TypeCatalogue : ITypeCatalogue
{
private readonly List<Type> availableTypes = new List<Type>();
/// <summary>
/// Gets the <c>FakeItEasy</c> assembly.
/// </summary>
#if FEATURE_REFLECTION_GETASSEMBLIES
public static Assembly FakeItEasyAssembly { get; } = Assembly.GetExecutingAssembly();
#else
public static Assembly FakeItEasyAssembly { get; } = typeof(TypeCatalogue).GetTypeInfo().Assembly;
#endif
/// <summary>
/// Loads the available types into the <see cref="TypeCatalogue"/>.
/// </summary>
/// <param name="extraAssemblyFiles">
/// The full paths to assemblies from which to load types,
/// as well as currently loaded assemblies.
/// </param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Defensive and performed on best effort basis.")]
public void Load(IEnumerable<string> extraAssemblyFiles)
{
foreach (var assembly in GetAllAssemblies(extraAssemblyFiles))
{
try
{
foreach (var type in assembly.GetTypes())
{
this.availableTypes.Add(type);
}
}
catch (ReflectionTypeLoadException ex)
{
// In this case, some types failed to load.
// Just keep the types that were successfully loaded, and warn about the rest.
foreach (var type in ex.Types.Where(t => t is object))
{
this.availableTypes.Add(type);
}
WarnFailedToGetSomeTypes(assembly, ex);
}
catch (Exception ex)
{
WarnFailedToGetTypes(assembly, ex);
}
}
}
/// <summary>
/// Gets a collection of available types.
/// </summary>
/// <returns>The available types.</returns>
public IEnumerable<Type> GetAvailableTypes()
{
return this.availableTypes;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Appropriate in try methods.")]
private static IEnumerable<Assembly> GetAllAssemblies(IEnumerable<string> extraAssemblyFiles)
{
#if FEATURE_REFLECTION_GETASSEMBLIES
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
#else
var context = DependencyContext.Default;
var loadedAssemblies = context.RuntimeLibraries
.SelectMany(library => library.GetDefaultAssemblyNames(context))
.Distinct()
.Select(Assembly.Load)
.ToArray();
#endif
var loadedAssembliesReferencingFakeItEasy = loadedAssemblies.Where(assembly => assembly.ReferencesFakeItEasy());
// Find the paths of already loaded assemblies so we don't double scan them.
var loadedAssemblyFiles = new HashSet<string>(
loadedAssemblies
#if FEATURE_REFLECTIONONLYLOAD
// Exclude the ReflectionOnly assemblies because we may fully load them later.
.Where(a => !a.ReflectionOnly)
#endif
.Where(a => !a.IsDynamic)
.Select(a => a.Location),
StringComparer.OrdinalIgnoreCase);
// Skip assemblies that have already been loaded.
// This optimization can be fooled by test runners that make shadow copies of the assemblies but it's a start.
return GetAssemblies(extraAssemblyFiles.Except(loadedAssemblyFiles))
.Concat(loadedAssembliesReferencingFakeItEasy)
.Concat(FakeItEasyAssembly)
.Distinct();
}
[SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Defensive and performed on best effort basis.")]
private static IEnumerable<Assembly> GetAssemblies(IEnumerable<string> files)
{
foreach (var file in files)
{
Assembly assembly;
try
{
#if FEATURE_REFLECTIONONLYLOAD
assembly = Assembly.ReflectionOnlyLoadFrom(file);
#elif USE_RUNTIMELOADER
assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file);
#else
assembly = Assembly.LoadFrom(file);
#endif
}
catch (Exception ex)
{
WarnFailedToLoadAssembly(file, ex);
continue;
}
if (!assembly.ReferencesFakeItEasy())
{
continue;
}
#if FEATURE_REFLECTIONONLYLOAD
// A reflection-only loaded assembly can't be scanned for types, so fully load it before returning it.
try
{
assembly = Assembly.Load(assembly.GetName());
}
catch (Exception ex)
{
WarnFailedToLoadAssembly(file, ex);
continue;
}
#endif
yield return assembly;
}
}
private static void WarnFailedToLoadAssembly(string path, Exception ex)
{
Write(
ex,
$"Warning: FakeItEasy failed to load assembly '{path}' while scanning for extension points. Any IArgumentValueFormatters, IDummyFactories, and IFakeOptionsBuilders in that assembly will not be available.");
}
private static void WarnFailedToGetTypes(Assembly assembly, Exception ex)
{
Write(
ex,
$"Warning: FakeItEasy failed to get types from assembly '{assembly}' while scanning for extension points. Any IArgumentValueFormatters, IDummyFactories, and IFakeOptionsBuilders in that assembly will not be available.");
}
private static void WarnFailedToGetSomeTypes(Assembly assembly, ReflectionTypeLoadException ex)
{
var writer = CreateConsoleWriter();
Write(
writer,
ex,
$"Warning: FakeItEasy failed to get some types from assembly '{assembly}' while scanning for extension points. Some IArgumentValueFormatters, IDummyFactories, and IFakeOptionsBuilders in that assembly might not be available.");
using (writer.Indent())
{
int notLoadedCount = ex.Types.Count(t => t is null);
writer.Write($"{notLoadedCount} type(s) were not loaded for the following reasons:");
writer.WriteLine();
foreach (var loaderException in ex.LoaderExceptions)
{
writer.Write(" - ");
writer.Write(loaderException.GetType());
writer.Write(": ");
writer.Write(loaderException.Message);
writer.WriteLine();
}
}
}
private static void Write(Exception ex, string message)
{
var writer = CreateConsoleWriter();
Write(writer, ex, message);
}
private static void Write(IOutputWriter writer, Exception ex, string message)
{
writer.Write(message);
writer.WriteLine();
using (writer.Indent())
{
writer.Write(ex.GetType());
writer.Write(": ");
writer.Write(ex.Message);
writer.WriteLine();
}
}
private static IOutputWriter CreateConsoleWriter()
{
// We can pass null as the ArgumentValueFormatter, because we never call
// WriteArgumentValue on this writer.
return new DefaultOutputWriter(Console.Write, null!);
}
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Common;
using Mosa.Compiler.Framework.IR;
using Mosa.Compiler.MosaTypeSystem;
using Mosa.Compiler.Trace;
using System.Collections.Generic;
using System.Diagnostics;
namespace Mosa.Compiler.Framework.Stages
{
/// <summary>
///
/// </summary>
public sealed class IROptimizationStage : BaseMethodCompilerStage
{
private int instructionsRemovedCount = 0;
private int simplifyExtendedMoveWithConstantCount = 0;
private int arithmeticSimplificationSubtractionCount = 0;
private int arithmeticSimplificationMultiplicationCount = 0;
private int arithmeticSimplificationDivisionCount = 0;
private int arithmeticSimplificationAdditionAndSubstractionCount = 0;
private int arithmeticSimplificationLogicalOperatorsCount = 0;
private int arithmeticSimplificationShiftOperators = 0;
private int constantFoldingIntegerOperationsCount = 0;
private int simpleConstantPropagationCount = 0;
private int simpleForwardCopyPropagationCount = 0;
private int constantFoldingIntegerCompareCount = 0;
private int strengthReductionIntegerCompareBranchCount = 0;
private int deadCodeEliminationCount = 0;
private int reduceTruncationAndExpansionCount = 0;
private int constantFoldingAdditionAndSubstractionCount = 0;
private int constantFoldingMultiplicationCount = 0;
private int constantFoldingDivisionCount = 0;
private int blockRemovedCount = 0;
private int foldIntegerCompareBranchCount = 0;
private int reduceZeroExtendedMoveCount = 0;
private int foldIntegerCompareCount = 0;
private int simplifyExtendedMoveCount = 0;
private int foldLoadStoreOffsetsCount = 0;
private int constantMoveToRightCount = 0;
private int foldConstantPhiCount = 0;
private int simplifyPhiCount = 0;
private int removeUselessPhiCount = 0;
private int reduce64BitOperationsTo32BitCount = 0;
private int promoteLocalVariableCount = 0;
private int constantFoldingLogicalOrCount = 0;
private int constantFoldingLogicalAndCount = 0;
private Stack<InstructionNode> worklist = new Stack<InstructionNode>();
private HashSet<Operand> virtualRegisters = new HashSet<Operand>();
private TraceLog trace;
protected override void Run()
{
// Method is empty - must be a plugged method
if (!HasCode)
return;
if (HasProtectedRegions)
return;
//if (MethodCompiler.Method.FullName.Contains(" Mosa.Platform.Internal.x86.Runtime::GetProtectedRegionEntryByAddress"))
// return;
trace = CreateTraceLog();
if (MethodCompiler.Compiler.CompilerOptions.EnableVariablePromotion)
PromoteLocalVariable();
// initialize worklist
foreach (var block in BasicBlocks)
{
for (var node = block.First; !node.IsBlockEndInstruction; node = node.Next)
{
if (node.IsEmpty)
continue;
if (node.ResultCount == 0 && node.OperandCount == 0)
continue;
Do(node);
ProcessWorkList();
// Collect virtual registers
if (node.IsEmpty)
continue;
// add virtual registers
foreach (var op in node.Results)
{
if (op.IsVirtualRegister)
virtualRegisters.AddIfNew(op);
}
foreach (var op in node.Operands)
{
if (op.IsVirtualRegister)
virtualRegisters.AddIfNew(op);
}
}
}
bool change = true;
while (change)
{
change = false;
if (MethodCompiler.Compiler.CompilerOptions.EnableVariablePromotion)
if (PromoteLocalVariable())
change = true;
//if (Reduce64BitOperationsTo32Bit())
// change = true;
if (change)
{
ProcessWorkList();
}
}
UpdateCounter("IROptimizations.IRInstructionRemoved", instructionsRemovedCount);
UpdateCounter("IROptimizations.ConstantFoldingIntegerOperations", constantFoldingIntegerOperationsCount);
UpdateCounter("IROptimizations.ConstantMoveToRight", constantMoveToRightCount);
UpdateCounter("IROptimizations.ArithmeticSimplificationSubtraction", arithmeticSimplificationSubtractionCount);
UpdateCounter("IROptimizations.ArithmeticSimplificationMultiplication", arithmeticSimplificationMultiplicationCount);
UpdateCounter("IROptimizations.ArithmeticSimplificationDivision", arithmeticSimplificationDivisionCount);
UpdateCounter("IROptimizations.ArithmeticSimplificationAdditionAndSubstraction", arithmeticSimplificationAdditionAndSubstractionCount);
UpdateCounter("IROptimizations.ArithmeticSimplificationLogicalOperators", arithmeticSimplificationLogicalOperatorsCount);
UpdateCounter("IROptimizations.ArithmeticSimplificationShiftOperators", arithmeticSimplificationShiftOperators);
UpdateCounter("IROptimizations.SimpleConstantPropagation", simpleConstantPropagationCount);
UpdateCounter("IROptimizations.SimpleForwardCopyPropagation", simpleForwardCopyPropagationCount);
UpdateCounter("IROptimizations.ConstantFoldingIntegerCompare", constantFoldingIntegerCompareCount);
UpdateCounter("IROptimizations.ConstantFoldingAdditionAndSubstraction", constantFoldingAdditionAndSubstractionCount);
UpdateCounter("IROptimizations.ConstantFoldingMultiplication", constantFoldingMultiplicationCount);
UpdateCounter("IROptimizations.ConstantFoldingDivision", constantFoldingDivisionCount);
UpdateCounter("IROptimizations.ConstantFoldingLogicalOr", constantFoldingLogicalOrCount);
UpdateCounter("IROptimizations.ConstantFoldingLogicalAnd", constantFoldingLogicalAndCount);
UpdateCounter("IROptimizations.StrengthReductionIntegerCompareBranch", strengthReductionIntegerCompareBranchCount);
UpdateCounter("IROptimizations.DeadCodeElimination", deadCodeEliminationCount);
UpdateCounter("IROptimizations.ReduceTruncationAndExpansion", reduceTruncationAndExpansionCount);
UpdateCounter("IROptimizations.FoldIntegerCompareBranch", foldIntegerCompareBranchCount);
UpdateCounter("IROptimizations.FoldIntegerCompare", foldIntegerCompareCount);
UpdateCounter("IROptimizations.FoldLoadStoreOffsets", foldLoadStoreOffsetsCount);
UpdateCounter("IROptimizations.FoldConstantPhi", foldConstantPhiCount);
UpdateCounter("IROptimizations.ReduceZeroExtendedMove", reduceZeroExtendedMoveCount);
UpdateCounter("IROptimizations.SimplifyExtendedMove", simplifyExtendedMoveCount);
UpdateCounter("IROptimizations.SimplifyExtendedMoveWithConstant", simplifyExtendedMoveWithConstantCount);
UpdateCounter("IROptimizations.SimplifyPhi", simplifyPhiCount);
UpdateCounter("IROptimizations.BlockRemoved", blockRemovedCount);
UpdateCounter("IROptimizations.RemoveUselessPhi", removeUselessPhiCount);
UpdateCounter("IROptimizations.PromoteLocalVariable", promoteLocalVariableCount);
UpdateCounter("IROptimizations.Reduce64BitOperationsTo32Bit", reduce64BitOperationsTo32BitCount);
worklist = null;
}
/// <summary>
/// Finishes this instance.
/// </summary>
protected override void Finish()
{
virtualRegisters = null;
worklist = null;
}
private void ProcessWorkList()
{
while (worklist.Count != 0)
{
var node = worklist.Pop();
Do(node);
}
}
private void Do(InstructionNode node)
{
if (node.IsEmpty)
return;
SimpleConstantPropagation(node);
SimpleForwardCopyPropagation(node);
DeadCodeElimination(node);
ConstantFoldingIntegerOperations(node);
ConstantMoveToRight(node);
ArithmeticSimplificationSubtraction(node);
ArithmeticSimplificationMultiplication(node);
ArithmeticSimplificationDivision(node);
ArithmeticSimplificationAdditionAndSubstraction(node);
ArithmeticSimplificationLogicalOperators(node);
ArithmeticSimplificationShiftOperators(node);
ReduceZeroExtendedMove(node);
ConstantFoldingAdditionAndSubstraction(node);
ConstantFoldingMultiplication(node);
ConstantFoldingDivision(node);
ConstantFoldingIntegerCompare(node);
ConstantFoldingLogicalOr(node);
ConstantFoldingLogicalAnd(node);
FoldIntegerCompare(node);
FoldIntegerCompareBranch(node);
SimplifyExtendedMoveWithConstant(node);
StrengthReductionIntegerCompareBranch(node);
ReduceTruncationAndExpansion(node);
SimplifyExtendedMove(node);
FoldLoadStoreOffsets(node);
FoldConstantPhi(node);
SimplifyPhi(node);
RemoveUselessPhi(node);
NormalizeConstantTo32Bit(node);
}
private void AddToWorkList(InstructionNode node)
{
if (node.IsEmpty)
return;
// work list stays small, so the check is inexpensive
if (worklist.Contains(node))
return;
worklist.Push(node);
}
/// <summary>
/// Adds the operand usage and definitions to work list.
/// </summary>
/// <param name="operand">The operand.</param>
private void AddOperandUsageToWorkList(Operand operand)
{
if (!operand.IsVirtualRegister)
return;
foreach (var index in operand.Uses)
{
AddToWorkList(index);
}
foreach (var index in operand.Definitions)
{
AddToWorkList(index);
}
}
/// <summary>
/// Adds the all the operands usage and definitions to work list.
/// </summary>
/// <param name="node">The node.</param>
private void AddOperandUsageToWorkList(InstructionNode node)
{
if (node.Result != null)
{
AddOperandUsageToWorkList(node.Result);
}
foreach (var operand in node.Operands)
{
AddOperandUsageToWorkList(operand);
}
}
private bool ContainsAddressOf(Operand local)
{
foreach (var node in local.Uses)
{
if (node.Instruction == IRInstruction.AddressOf)
return true;
}
return false;
}
private bool PromoteLocalVariable()
{
//HACK!!! HACK!!! HACK!!!
//if (MethodCompiler.Method.FullName.Contains(" Mosa.Platform.Internal.x86.Runtime::GetProtectedRegionEntryByAddress"))
// return false;
bool change = false;
foreach (var local in MethodCompiler.LocalVariables)
{
if (local.IsVirtualRegister)
continue;
if (local.IsParameter)
continue;
if (!local.IsStackLocal)
continue;
if (local.Definitions.Count != 1)
continue;
if (!local.IsReferenceType && !local.IsInteger && !local.IsR && !local.IsChar && !local.IsBoolean && !local.IsPointer && !local.IsI && !local.IsU)
continue;
if (ContainsAddressOf(local))
continue;
var v = MethodCompiler.CreateVirtualRegister(local.Type.GetStackType());
if (trace.Active) trace.Log("*** PromoteLocalVariable");
ReplaceVirtualRegister(local, v);
promoteLocalVariableCount++;
change = true;
}
return change;
}
/// <summary>
/// Removes the useless move and dead code
/// </summary>
/// <param name="node">The node.</param>
private void DeadCodeElimination(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.ResultCount != 1)
return;
if (!node.Result.IsVirtualRegister)
return;
if (node.Result.Definitions.Count != 1)
return;
if (node.Instruction == IRInstruction.Call || node.Instruction == IRInstruction.IntrinsicMethodCall)
return;
if (node.Instruction == IRInstruction.Move && node.Operand1.IsVirtualRegister && node.Operand1 == node.Result)
{
if (trace.Active) trace.Log("*** DeadCodeElimination");
if (trace.Active) trace.Log("REMOVED:\t" + node.ToString());
AddOperandUsageToWorkList(node);
node.SetInstruction(IRInstruction.Nop);
instructionsRemovedCount++;
deadCodeEliminationCount++;
return;
}
if (node.Result.Uses.Count != 0)
return;
if (trace.Active) trace.Log("*** DeadCodeElimination");
if (trace.Active) trace.Log("REMOVED:\t" + node.ToString());
AddOperandUsageToWorkList(node);
node.SetInstruction(IRInstruction.Nop);
instructionsRemovedCount++;
deadCodeEliminationCount++;
return;
}
/// <summary>
/// Simple constant propagation.
/// </summary>
/// <param name="node">The node.</param>
private void SimpleConstantPropagation(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.Move)
return;
if (!node.Result.IsVirtualRegister)
return;
if (node.Result.Definitions.Count != 1)
return;
if (!node.Operand1.IsConstant)
return;
Debug.Assert(node.Result.Definitions.Count == 1);
Operand destination = node.Result;
Operand source = node.Operand1;
// for each statement T that uses operand, substituted c in statement T
foreach (var useNode in destination.Uses.ToArray())
{
if (useNode.Instruction == IRInstruction.AddressOf)
continue;
bool propogated = false;
for (int i = 0; i < useNode.OperandCount; i++)
{
var operand = useNode.GetOperand(i);
if (operand == node.Result)
{
propogated = true;
if (trace.Active) trace.Log("*** SimpleConstantPropagation");
if (trace.Active) trace.Log("BEFORE:\t" + useNode.ToString());
AddOperandUsageToWorkList(operand);
useNode.SetOperand(i, source);
simpleConstantPropagationCount++;
if (trace.Active) trace.Log("AFTER: \t" + useNode.ToString());
}
}
if (propogated)
{
AddToWorkList(useNode);
}
}
}
private bool CanCopyPropagation(Operand source, Operand destination)
{
if (source.IsPointer && destination.IsPointer)
return true;
if (source.IsReferenceType && destination.IsReferenceType)
return true;
if (source.Type.IsArray & destination.Type.IsArray & source.Type.ElementType == destination.Type.ElementType)
return true;
if (source.Type.IsUI1 & destination.Type.IsUI1)
return true;
if (source.Type.IsUI2 & destination.Type.IsUI2)
return true;
if (source.Type.IsUI4 & destination.Type.IsUI4)
return true;
if (source.Type.IsUI8 & destination.Type.IsUI8)
return true;
if (NativePointerSize == 4 && (destination.IsI || destination.IsU || destination.IsPointer) && (source.IsI4 || source.IsU4))
return true;
if (NativePointerSize == 4 && (source.IsI || source.IsU || source.IsPointer) && (destination.IsI4 || destination.IsU4))
return true;
if (NativePointerSize == 8 && (destination.IsI || destination.IsU || destination.IsPointer) && (source.IsI8 || source.IsU8))
return true;
if (NativePointerSize == 8 && (source.IsI || source.IsU || source.IsPointer) && (destination.IsI8 || destination.IsU8))
return true;
if (source.IsR4 && destination.IsR4)
return true;
if (source.IsR8 && destination.IsR8)
return true;
if (source.IsI && destination.IsI)
return true;
if (source.IsValueType || destination.IsValueType)
return false;
if (source.Type == destination.Type)
return true;
return false;
}
/// <summary>
/// Simple copy propagation.
/// </summary>
/// <param name="node">The node.</param>
private void SimpleForwardCopyPropagation(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.Move)
return;
if (!node.Result.IsVirtualRegister)
return;
if (node.Result.Definitions.Count != 1)
return;
if (node.Operand1.Definitions.Count != 1)
return;
if (node.Operand1.IsConstant)
return;
if (!node.Operand1.IsVirtualRegister)
return;
// If the pointer or reference types are different, we can not copy propagation because type information would be lost.
// Also if the operand sign is different, we cannot do it as it requires a signed/unsigned extended move, not a normal move
if (!CanCopyPropagation(node.Result, node.Operand1))
return;
Operand destination = node.Result;
Operand source = node.Operand1;
if (ContainsAddressOf(destination))
return;
//if (destination != source)
//{
// if (trace.Active) trace.Log("REMOVED:\t" + node.ToString());
// AddOperandUsageToWorkList(node);
// node.SetInstruction(IRInstruction.Nop);
// instructionsRemovedCount++;
// return;
//}
// for each statement T that uses operand, substituted c in statement T
AddOperandUsageToWorkList(node);
foreach (var useNode in destination.Uses.ToArray())
{
for (int i = 0; i < useNode.OperandCount; i++)
{
var operand = useNode.GetOperand(i);
if (destination == operand)
{
if (trace.Active) trace.Log("*** SimpleForwardCopyPropagation");
if (trace.Active) trace.Log("BEFORE:\t" + useNode.ToString());
useNode.SetOperand(i, source);
simpleForwardCopyPropagationCount++;
if (trace.Active) trace.Log("AFTER: \t" + useNode.ToString());
}
}
}
Debug.Assert(destination.Uses.Count == 0);
if (trace.Active) trace.Log("REMOVED:\t" + node.ToString());
AddOperandUsageToWorkList(node);
node.SetInstruction(IRInstruction.Nop);
instructionsRemovedCount++;
}
/// <summary>
/// Folds an integer operation on constants
/// </summary>
/// <param name="node">The node.</param>
private void ConstantFoldingIntegerOperations(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.AddSigned || node.Instruction == IRInstruction.AddUnsigned ||
node.Instruction == IRInstruction.SubSigned || node.Instruction == IRInstruction.SubUnsigned ||
node.Instruction == IRInstruction.LogicalAnd || node.Instruction == IRInstruction.LogicalOr ||
node.Instruction == IRInstruction.LogicalXor ||
node.Instruction == IRInstruction.MulSigned || node.Instruction == IRInstruction.MulUnsigned ||
node.Instruction == IRInstruction.DivSigned || node.Instruction == IRInstruction.DivUnsigned ||
node.Instruction == IRInstruction.ArithmeticShiftRight ||
node.Instruction == IRInstruction.ShiftLeft || node.Instruction == IRInstruction.ShiftRight))
return;
if (!node.Result.IsVirtualRegister)
return;
Operand result = node.Result;
Operand op1 = node.Operand1;
Operand op2 = node.Operand2;
if (!op1.IsConstant || !op2.IsConstant)
return;
// Divide by zero!
if ((node.Instruction == IRInstruction.DivSigned || node.Instruction == IRInstruction.DivUnsigned) && op2.IsConstant && op2.IsConstantZero)
return;
Operand constant = null;
if (node.Instruction == IRInstruction.AddSigned || node.Instruction == IRInstruction.AddUnsigned)
{
constant = Operand.CreateConstant(result.Type, op1.ConstantUnsignedLongInteger + op2.ConstantUnsignedLongInteger);
}
else if (node.Instruction == IRInstruction.SubSigned || node.Instruction == IRInstruction.SubUnsigned)
{
constant = Operand.CreateConstant(result.Type, op1.ConstantUnsignedLongInteger - op2.ConstantUnsignedLongInteger);
}
else if (node.Instruction == IRInstruction.LogicalAnd)
{
constant = Operand.CreateConstant(result.Type, op1.ConstantUnsignedLongInteger & op2.ConstantUnsignedLongInteger);
}
else if (node.Instruction == IRInstruction.LogicalOr)
{
constant = Operand.CreateConstant(result.Type, op1.ConstantUnsignedLongInteger | op2.ConstantUnsignedLongInteger);
}
else if (node.Instruction == IRInstruction.LogicalXor)
{
constant = Operand.CreateConstant(result.Type, op1.ConstantUnsignedLongInteger ^ op2.ConstantUnsignedLongInteger);
}
else if (node.Instruction == IRInstruction.MulSigned || node.Instruction == IRInstruction.MulUnsigned)
{
constant = Operand.CreateConstant(result.Type, op1.ConstantUnsignedLongInteger * op2.ConstantUnsignedLongInteger);
}
else if (node.Instruction == IRInstruction.DivUnsigned)
{
constant = Operand.CreateConstant(result.Type, op1.ConstantUnsignedLongInteger / op2.ConstantUnsignedLongInteger);
}
else if (node.Instruction == IRInstruction.DivSigned)
{
constant = Operand.CreateConstant(result.Type, op1.ConstantSignedLongInteger / op2.ConstantSignedLongInteger);
}
else if (node.Instruction == IRInstruction.ArithmeticShiftRight)
{
constant = Operand.CreateConstant(result.Type, ((long)op1.ConstantUnsignedLongInteger) >> (int)op2.ConstantUnsignedLongInteger);
}
else if (node.Instruction == IRInstruction.ShiftRight)
{
constant = Operand.CreateConstant(result.Type, ((ulong)op1.ConstantUnsignedLongInteger) >> (int)op2.ConstantUnsignedLongInteger);
}
else if (node.Instruction == IRInstruction.ShiftLeft)
{
constant = Operand.CreateConstant(result.Type, op1.ConstantUnsignedLongInteger << (int)op2.ConstantUnsignedLongInteger);
}
if (constant == null)
return;
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ConstantFoldingIntegerOperations");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, node.Result, constant);
constantFoldingIntegerOperationsCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
}
/// <summary>
/// Folds the integer compare on constants
/// </summary>
/// <param name="node">The node.</param>
private void ConstantFoldingIntegerCompare(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.IntegerCompare)
return;
if (!node.Result.IsVirtualRegister)
return;
Operand result = node.Result;
Operand op1 = node.Operand1;
Operand op2 = node.Operand2;
if (!op1.IsConstant || !op2.IsConstant)
return;
if (!op1.IsValueType || !op2.IsValueType)
return;
bool compareResult = true;
switch (node.ConditionCode)
{
case ConditionCode.Equal: compareResult = (op1.ConstantUnsignedLongInteger == op2.ConstantUnsignedLongInteger); break;
case ConditionCode.NotEqual: compareResult = (op1.ConstantUnsignedLongInteger != op2.ConstantUnsignedLongInteger); break;
case ConditionCode.GreaterOrEqual: compareResult = (op1.ConstantUnsignedLongInteger >= op2.ConstantUnsignedLongInteger); break;
case ConditionCode.GreaterThan: compareResult = (op1.ConstantUnsignedLongInteger > op2.ConstantUnsignedLongInteger); break;
case ConditionCode.LessOrEqual: compareResult = (op1.ConstantUnsignedLongInteger <= op2.ConstantUnsignedLongInteger); break;
case ConditionCode.LessThan: compareResult = (op1.ConstantUnsignedLongInteger < op2.ConstantUnsignedLongInteger); break;
// TODO: Add more
default: return;
}
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ConstantFoldingIntegerCompare");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, Operand.CreateConstant(result.Type, (int)(compareResult ? 1 : 0)));
constantFoldingIntegerCompareCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
}
/// <summary>
/// Strength reduction for integer addition when one of the constants is zero
/// </summary>
/// <param name="node">The node.</param>
private void ArithmeticSimplificationAdditionAndSubstraction(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.AddSigned || node.Instruction == IRInstruction.AddUnsigned
|| node.Instruction == IRInstruction.SubSigned || node.Instruction == IRInstruction.SubUnsigned))
return;
if (!node.Result.IsVirtualRegister)
return;
Operand result = node.Result;
Operand op1 = node.Operand1;
Operand op2 = node.Operand2;
if (op2.IsConstant && !op1.IsConstant && op2.IsConstantZero)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationAdditionAndSubstraction");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, op1);
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
arithmeticSimplificationAdditionAndSubstractionCount++;
return;
}
}
/// <summary>
/// Strength reduction for multiplication when one of the constants is zero or one
/// </summary>
/// <param name="node">The node.</param>
private void ArithmeticSimplificationMultiplication(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.MulSigned || node.Instruction == IRInstruction.MulUnsigned))
return;
if (!node.Result.IsVirtualRegister)
return;
if (!node.Operand2.IsConstant)
return;
Operand result = node.Result;
Operand op1 = node.Operand1;
Operand op2 = node.Operand2;
if (op2.IsConstantZero)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationMultiplication");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, Operand.CreateConstant(node.Result.Type, 0));
arithmeticSimplificationMultiplicationCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
return;
}
if (op2.IsConstantOne)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationMultiplication");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, op1);
arithmeticSimplificationMultiplicationCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
return;
}
if (IsPowerOfTwo(op2.ConstantUnsignedLongInteger))
{
uint shift = GetPowerOfTwo(op2.ConstantUnsignedLongInteger);
if (shift < 32)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationMultiplication");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.ShiftLeft, result, op1, Operand.CreateConstant(TypeSystem, (int)shift));
arithmeticSimplificationMultiplicationCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
return;
}
}
}
/// <summary>
/// Strength reduction for division when one of the constants is zero or one
/// </summary>
/// <param name="node">The node.</param>
private void ArithmeticSimplificationDivision(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.DivSigned || node.Instruction == IRInstruction.DivUnsigned))
return;
if (!node.Result.IsVirtualRegister)
return;
Operand result = node.Result;
Operand op1 = node.Operand1;
Operand op2 = node.Operand2;
if (!op2.IsConstant || op2.IsConstantZero)
{
// Possible divide by zero
return;
}
if (op1.IsConstant && op1.IsConstantZero)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationDivision");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, Operand.CreateConstant(result.Type, 0));
arithmeticSimplificationDivisionCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
return;
}
if (op2.IsConstant && op2.IsConstantOne)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationDivision");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, op1);
arithmeticSimplificationDivisionCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
return;
}
if (node.Instruction == IRInstruction.DivUnsigned && IsPowerOfTwo(op2.ConstantUnsignedLongInteger))
{
uint shift = GetPowerOfTwo(op2.ConstantUnsignedLongInteger);
if (shift < 32)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationDivision");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.ShiftRight, result, op1, Operand.CreateConstant(TypeSystem, (int)shift));
arithmeticSimplificationDivisionCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
return;
}
}
}
/// <summary>
/// Simplifies extended moves with a constant
/// </summary>
/// <param name="node">The node.</param>
private void SimplifyExtendedMoveWithConstant(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.ZeroExtendedMove || node.Instruction == IRInstruction.SignExtendedMove))
return;
if (!node.Result.IsVirtualRegister)
return;
if (node.Result.Definitions.Count != 1)
return;
if (!node.Operand1.IsConstant)
return;
Operand result = node.Result;
Operand op1 = node.Operand1;
Operand newOperand;
if (node.Instruction == IRInstruction.ZeroExtendedMove && result.IsUnsigned && op1.IsSigned)
{
var newConstant = Unsign(op1.Type, op1.ConstantSignedLongInteger);
newOperand = Operand.CreateConstant(node.Result.Type, newConstant);
}
else
{
newOperand = Operand.CreateConstant(node.Result.Type, op1.ConstantUnsignedLongInteger);
}
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** SimplifyExtendedMoveWithConstant");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, newOperand);
simplifyExtendedMoveWithConstantCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
}
static private ulong Unsign(MosaType type, long value)
{
if (type.IsI1) return (ulong)((sbyte)value);
else if (type.IsI2) return (ulong)((short)value);
else if (type.IsI4) return (ulong)((int)value);
else if (type.IsI8) return (ulong)((long)value);
else return (ulong)value;
}
/// <summary>
/// Simplifies subtraction where both operands are the same
/// </summary>
/// <param name="node">The node.</param>
private void ArithmeticSimplificationSubtraction(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.SubSigned || node.Instruction == IRInstruction.SubUnsigned))
return;
if (!node.Result.IsVirtualRegister)
return;
Operand result = node.Result;
Operand op1 = node.Operand1;
Operand op2 = node.Operand2;
if (op1 != op2)
return;
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationSubtraction");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, Operand.CreateConstant(node.Result.Type, 0));
arithmeticSimplificationSubtractionCount++;
}
/// <summary>
/// Strength reduction for logical operators
/// </summary>
/// <param name="node">The node.</param>
private void ArithmeticSimplificationLogicalOperators(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.LogicalAnd || node.Instruction == IRInstruction.LogicalOr))
return;
if (!node.Result.IsVirtualRegister)
return;
if (!node.Operand2.IsConstant)
return;
Operand result = node.Result;
Operand op1 = node.Operand1;
Operand op2 = node.Operand2;
if (node.Instruction == IRInstruction.LogicalOr)
{
if (op2.IsConstantZero)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationLogicalOperators");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, op1);
arithmeticSimplificationLogicalOperatorsCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
return;
}
}
else if (node.Instruction == IRInstruction.LogicalAnd)
{
if (op2.IsConstantZero)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationLogicalOperators");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, Operand.CreateConstant(node.Result.Type, 0));
arithmeticSimplificationLogicalOperatorsCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
return;
}
if ((result.IsI4 || result.IsU4) && op2.ConstantUnsignedInteger == 0xFFFFFFFF)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationLogicalOperators");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, op1);
arithmeticSimplificationLogicalOperatorsCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
return;
}
if ((result.IsI8 || result.IsU8) && op2.ConstantUnsignedLongInteger == 0xFFFFFFFFFFFFFFFF)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationLogicalOperators");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, op1);
arithmeticSimplificationLogicalOperatorsCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
return;
}
}
// TODO: Add more strength reductions especially for AND w/ 0xFF, 0xFFFF, 0xFFFFFFFF, etc when source or destination are same or smaller
}
/// <summary>
/// Strength reduction shift operators.
/// </summary>
/// <param name="node">The node.</param>
private void ArithmeticSimplificationShiftOperators(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.ShiftLeft || node.Instruction == IRInstruction.ShiftRight || node.Instruction == IRInstruction.ArithmeticShiftRight))
return;
if (!node.Result.IsVirtualRegister)
return;
if (!node.Operand2.IsConstant)
return;
Operand result = node.Result;
Operand op1 = node.Operand1;
Operand op2 = node.Operand2;
if (op2.IsConstantZero || op1.IsConstantZero)
{
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ArithmeticSimplificationShiftOperators");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, result, op1);
arithmeticSimplificationShiftOperators++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
return;
}
}
/// <summary>
/// Strength reduction integer compare branch.
/// </summary>
/// <param name="node">The node.</param>
private void StrengthReductionIntegerCompareBranch(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.IntegerCompareBranch)
return;
if (node.OperandCount != 2)
return;
Operand op1 = node.Operand1;
Operand op2 = node.Operand2;
if (!op1.IsConstant || !op2.IsConstant)
return;
Operand result = node.Result;
InstructionNode nextNode = node.Next;
if (nextNode.Instruction != IRInstruction.Jmp)
return;
if (node.BranchTargets[0] == nextNode.BranchTargets[0])
{
if (trace.Active) trace.Log("*** StrengthReductionIntegerCompareBranch-1");
if (trace.Active) trace.Log("REMOVED:\t" + node.ToString());
AddOperandUsageToWorkList(node);
node.SetInstruction(IRInstruction.Nop);
instructionsRemovedCount++;
strengthReductionIntegerCompareBranchCount++;
return;
}
bool compareResult = true;
switch (node.ConditionCode)
{
case ConditionCode.Equal: compareResult = (op1.ConstantUnsignedLongInteger == op2.ConstantUnsignedLongInteger); break;
case ConditionCode.NotEqual: compareResult = (op1.ConstantUnsignedLongInteger != op2.ConstantUnsignedLongInteger); break;
case ConditionCode.GreaterOrEqual: compareResult = (op1.ConstantUnsignedLongInteger >= op2.ConstantUnsignedLongInteger); break;
case ConditionCode.GreaterThan: compareResult = (op1.ConstantUnsignedLongInteger > op2.ConstantUnsignedLongInteger); break;
case ConditionCode.LessOrEqual: compareResult = (op1.ConstantUnsignedLongInteger <= op2.ConstantUnsignedLongInteger); break;
case ConditionCode.LessThan: compareResult = (op1.ConstantUnsignedLongInteger < op2.ConstantUnsignedLongInteger); break;
// TODO: Add more
default: return;
}
BasicBlock notTaken;
InstructionNode notUsed;
if (trace.Active) trace.Log("*** StrengthReductionIntegerCompareBranch-2");
if (compareResult)
{
notTaken = nextNode.BranchTargets[0];
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Jmp, node.BranchTargets[0]);
if (trace.Active) trace.Log("AFTER:\t" + node.ToString());
notUsed = nextNode;
}
else
{
notTaken = node.BranchTargets[0];
notUsed = node;
}
if (trace.Active) trace.Log("REMOVED:\t" + node.ToString());
AddOperandUsageToWorkList(notUsed);
notUsed.SetInstruction(IRInstruction.Nop);
instructionsRemovedCount++;
strengthReductionIntegerCompareBranchCount++;
// if target block no longer has any predecessors (or the only predecessor is itself), remove all instructions from it.
CheckAndClearEmptyBlock(notTaken);
}
private void CheckAndClearEmptyBlock(BasicBlock block)
{
if (block.PreviousBlocks.Count != 0 || BasicBlocks.HeadBlocks.Contains(block))
return;
if (trace.Active) trace.Log("*** RemoveBlock: " + block.ToString());
blockRemovedCount++;
var nextBlocks = block.NextBlocks.ToArray();
EmptyBlockOfAllInstructions(block);
UpdatePhiList(block, nextBlocks);
Debug.Assert(block.NextBlocks.Count == 0);
Debug.Assert(block.PreviousBlocks.Count == 0);
}
private void ConstantMoveToRight(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.AddSigned || node.Instruction == IRInstruction.AddUnsigned
|| node.Instruction == IRInstruction.MulSigned || node.Instruction == IRInstruction.MulUnsigned
|| node.Instruction == IRInstruction.LogicalAnd || node.Instruction == IRInstruction.LogicalOr
|| node.Instruction == IRInstruction.LogicalXor))
return;
if (node.Operand2.IsConstant)
return;
if (!node.Operand1.IsConstant)
return;
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** ConstantMoveToRight");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
var op1 = node.Operand1;
node.Operand1 = node.Operand2;
node.Operand2 = op1;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
constantMoveToRightCount++;
}
private void ConstantFoldingAdditionAndSubstraction(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.AddSigned || node.Instruction == IRInstruction.AddUnsigned
|| node.Instruction == IRInstruction.SubSigned || node.Instruction == IRInstruction.SubUnsigned))
return;
if (!node.Result.IsVirtualRegister)
return;
if (node.Result.Definitions.Count != 1)
return;
if (!node.Operand2.IsConstant)
return;
if (node.Result.Uses.Count != 1)
return;
var node2 = node.Result.Uses[0];
if (!(node2.Instruction == IRInstruction.AddSigned || node2.Instruction == IRInstruction.AddUnsigned
|| node2.Instruction == IRInstruction.SubSigned || node2.Instruction == IRInstruction.SubUnsigned))
return;
if (!node2.Result.IsVirtualRegister)
return;
if (!node2.Operand2.IsConstant)
return;
Debug.Assert(node2.Result.Definitions.Count == 1);
bool add = true;
if ((node.Instruction == IRInstruction.AddSigned || node.Instruction == IRInstruction.AddUnsigned) &&
(node2.Instruction == IRInstruction.SubSigned || node2.Instruction == IRInstruction.SubUnsigned))
{
add = false;
}
else if ((node.Instruction == IRInstruction.SubSigned || node.Instruction == IRInstruction.SubUnsigned) &&
(node2.Instruction == IRInstruction.AddSigned || node2.Instruction == IRInstruction.AddUnsigned))
{
add = false;
}
ulong r = add ? node.Operand2.ConstantUnsignedLongInteger + node2.Operand2.ConstantUnsignedLongInteger :
node.Operand2.ConstantUnsignedLongInteger - node2.Operand2.ConstantUnsignedLongInteger;
Debug.Assert(node2.Result.Definitions.Count == 1);
if (trace.Active) trace.Log("*** ConstantFoldingAdditionAndSubstraction");
AddOperandUsageToWorkList(node2);
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("BEFORE:\t" + node2.ToString());
node2.SetInstruction(IRInstruction.Move, node2.Result, node.Result);
if (trace.Active) trace.Log("AFTER: \t" + node2.ToString());
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.Operand2 = Operand.CreateConstant(node.Operand2.Type, r);
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
constantFoldingAdditionAndSubstractionCount++;
}
private void ConstantFoldingLogicalOr(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.LogicalOr)
return;
if (!node.Result.IsVirtualRegister)
return;
if (node.Result.Definitions.Count != 1)
return;
if (!node.Operand2.IsConstant)
return;
if (node.Result.Uses.Count != 1)
return;
var node2 = node.Result.Uses[0];
if (node2.Instruction != IRInstruction.LogicalOr)
return;
if (!node2.Result.IsVirtualRegister)
return;
if (!node2.Operand2.IsConstant)
return;
Debug.Assert(node2.Result.Definitions.Count == 1);
ulong r = node.Operand2.ConstantUnsignedLongInteger | node2.Operand2.ConstantUnsignedLongInteger;
if (trace.Active) trace.Log("*** ConstantFoldingLogicalOr");
AddOperandUsageToWorkList(node2);
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("BEFORE:\t" + node2.ToString());
node2.SetInstruction(IRInstruction.Move, node2.Result, node.Result);
if (trace.Active) trace.Log("AFTER: \t" + node2.ToString());
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.Operand2 = Operand.CreateConstant(node.Operand2.Type, r);
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
constantFoldingLogicalOrCount++;
}
private void ConstantFoldingLogicalAnd(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.LogicalAnd)
return;
if (!node.Result.IsVirtualRegister)
return;
if (node.Result.Definitions.Count != 1)
return;
if (!node.Operand2.IsConstant)
return;
if (node.Result.Uses.Count != 1)
return;
var node2 = node.Result.Uses[0];
if (node2.Instruction != IRInstruction.LogicalAnd)
return;
if (!node2.Result.IsVirtualRegister)
return;
if (!node2.Operand2.IsConstant)
return;
Debug.Assert(node2.Result.Definitions.Count == 1);
ulong r = node.Operand2.ConstantUnsignedLongInteger & node2.Operand2.ConstantUnsignedLongInteger;
if (trace.Active) trace.Log("*** ConstantFoldingLogicalOr");
AddOperandUsageToWorkList(node2);
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("BEFORE:\t" + node2.ToString());
node2.SetInstruction(IRInstruction.Move, node2.Result, node.Result);
if (trace.Active) trace.Log("AFTER: \t" + node2.ToString());
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.Operand2 = Operand.CreateConstant(node.Operand2.Type, r);
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
constantFoldingLogicalAndCount++;
}
private void ConstantFoldingMultiplication(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.MulSigned || node.Instruction == IRInstruction.MulUnsigned))
return;
if (!node.Result.IsVirtualRegister)
return;
if (node.Result.Definitions.Count != 1)
return;
if (!node.Operand2.IsConstant)
return;
if (node.Result.Uses.Count != 1)
return;
var node2 = node.Result.Uses[0];
if (!(node2.Instruction == IRInstruction.MulSigned || node2.Instruction == IRInstruction.MulUnsigned))
return;
if (!node2.Result.IsVirtualRegister)
return;
if (!node2.Operand2.IsConstant)
return;
Debug.Assert(node2.Result.Definitions.Count == 1);
ulong r = node.Operand2.ConstantUnsignedLongInteger * node2.Operand2.ConstantUnsignedLongInteger;
if (trace.Active) trace.Log("*** ConstantFoldingMultiplication");
AddOperandUsageToWorkList(node2);
if (trace.Active) trace.Log("BEFORE:\t" + node2.ToString());
node2.SetInstruction(IRInstruction.Move, node2.Result, node.Result);
if (trace.Active) trace.Log("AFTER: \t" + node2.ToString());
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.Operand2 = Operand.CreateConstant(node.Operand2.Type, r);
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
constantFoldingMultiplicationCount++;
}
private void ConstantFoldingDivision(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.DivSigned || node.Instruction == IRInstruction.DivUnsigned))
return;
if (!node.Result.IsVirtualRegister)
return;
if (node.Result.Definitions.Count != 1)
return;
if (!node.Operand2.IsConstant)
return;
if (node.Result.Uses.Count != 1)
return;
var node2 = node.Result.Uses[0];
if (!(node2.Instruction == IRInstruction.DivSigned || node2.Instruction == IRInstruction.DivUnsigned))
return;
if (!node2.Result.IsVirtualRegister)
return;
if (!node2.Operand2.IsConstant)
return;
Debug.Assert(node2.Result.Definitions.Count == 1);
ulong r = (node2.Instruction == IRInstruction.DivSigned) ?
(ulong)(node.Operand2.ConstantSignedLongInteger / node2.Operand2.ConstantSignedLongInteger) :
node.Operand2.ConstantUnsignedLongInteger / node2.Operand2.ConstantUnsignedLongInteger;
if (trace.Active) trace.Log("*** ConstantFoldingDivision");
AddOperandUsageToWorkList(node2);
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("BEFORE:\t" + node2.ToString());
node2.SetInstruction(IRInstruction.Move, node2.Result, node.Result);
if (trace.Active) trace.Log("AFTER: \t" + node2.ToString());
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.Operand2 = Operand.CreateConstant(node.Operand2.Type, r);
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
constantFoldingDivisionCount++;
}
private void ReduceZeroExtendedMove(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.ZeroExtendedMove)
return;
if (!node.Operand1.IsVirtualRegister)
return;
if (!node.Result.IsVirtualRegister)
return;
if (trace.Active) trace.Log("*** ReduceZeroExtendedMove");
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, node.Result, node.Operand1);
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
reduceZeroExtendedMoveCount++;
}
private void ReduceTruncationAndExpansion(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.ZeroExtendedMove)
return;
if (!node.Operand1.IsVirtualRegister)
return;
if (!node.Result.IsVirtualRegister)
return;
if (node.Result.Uses.Count != 1)
return;
if (node.Result.Definitions.Count != 1)
return;
if (node.Operand1.Uses.Count != 1 || node.Operand1.Definitions.Count != 1)
return;
var node2 = node.Operand1.Definitions[0];
if (node2.Instruction != IRInstruction.Move)
return;
if (node2.Result.Uses.Count != 1)
return;
Debug.Assert(node2.Result.Definitions.Count == 1);
if (node2.Operand1.Type != node.Result.Type)
return;
if (trace.Active) trace.Log("*** ReduceTruncationAndExpansion");
AddOperandUsageToWorkList(node2);
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("BEFORE:\t" + node2.ToString());
node2.Result = node.Result;
if (trace.Active) trace.Log("AFTER: \t" + node2.ToString());
if (trace.Active) trace.Log("REMOVED:\t" + node2.ToString());
node.SetInstruction(IRInstruction.Nop);
reduceTruncationAndExpansionCount++;
instructionsRemovedCount++;
}
private void FoldIntegerCompareBranch(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.IntegerCompareBranch)
return;
if (!(node.ConditionCode == ConditionCode.NotEqual || node.ConditionCode == ConditionCode.Equal))
return;
if (!((node.Operand1.IsVirtualRegister && node.Operand2.IsConstant && node.Operand2.IsConstantZero) ||
(node.Operand2.IsVirtualRegister && node.Operand1.IsConstant && node.Operand1.IsConstantZero)))
return;
var operand = (node.Operand2.IsConstant && node.Operand2.IsConstantZero) ? node.Operand1 : node.Operand2;
if (operand.Uses.Count != 1)
return;
if (operand.Definitions.Count != 1)
return;
var node2 = operand.Definitions[0];
if (node2.Instruction != IRInstruction.IntegerCompare)
return;
AddOperandUsageToWorkList(node2);
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** FoldIntegerCompareBranch");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.ConditionCode = node.ConditionCode == ConditionCode.NotEqual ? node2.ConditionCode : node2.ConditionCode.GetOpposite();
node.Operand1 = node2.Operand1;
node.Operand2 = node2.Operand2;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
if (trace.Active) trace.Log("REMOVED:\t" + node2.ToString());
node2.SetInstruction(IRInstruction.Nop);
foldIntegerCompareBranchCount++;
instructionsRemovedCount++;
}
private void FoldIntegerCompare(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.IntegerCompare)
return;
if (!(node.ConditionCode == ConditionCode.NotEqual || node.ConditionCode == ConditionCode.Equal))
return;
if (!((node.Operand1.IsVirtualRegister && node.Operand2.IsConstant && node.Operand2.IsConstantZero) ||
(node.Operand2.IsVirtualRegister && node.Operand1.IsConstant && node.Operand1.IsConstantZero)))
return;
var operand = (node.Operand2.IsConstant && node.Operand2.IsConstantZero) ? node.Operand1 : node.Operand2;
if (operand.Uses.Count != 1)
return;
if (operand.Definitions.Count != 1)
return;
Debug.Assert(operand.Definitions.Count == 1);
var node2 = operand.Definitions[0];
if (node2.Instruction != IRInstruction.IntegerCompare)
return;
AddOperandUsageToWorkList(node2);
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** FoldIntegerCompare");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.ConditionCode = node.ConditionCode == ConditionCode.NotEqual ? node2.ConditionCode : node2.ConditionCode.GetOpposite();
node.Operand1 = node2.Operand1;
node.Operand2 = node2.Operand2;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
if (trace.Active) trace.Log("REMOVED:\t" + node2.ToString());
node2.SetInstruction(IRInstruction.Nop);
foldIntegerCompareCount++;
instructionsRemovedCount++;
}
/// <summary>
/// Simplifies sign/zero extended move
/// </summary>
/// <param name="node">The node.</param>
private void SimplifyExtendedMove(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.ZeroExtendedMove || node.Instruction == IRInstruction.SignExtendedMove))
return;
if (!node.Result.IsVirtualRegister || !node.Operand1.IsVirtualRegister)
return;
if (!((NativePointerSize == 4 && node.Result.IsInt && (node.Operand1.IsInt || node.Operand1.IsU || node.Operand1.IsI)) ||
(NativePointerSize == 4 && node.Operand1.IsInt && (node.Result.IsInt || node.Result.IsU || node.Result.IsI)) ||
(NativePointerSize == 8 && node.Result.IsLong && (node.Operand1.IsLong || node.Operand1.IsU || node.Operand1.IsI)) ||
(NativePointerSize == 8 && node.Operand1.IsLong && (node.Result.IsLong || node.Result.IsU || node.Result.IsI))))
return;
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("*** SimplifyExtendedMove");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetInstruction(IRInstruction.Move, node.Result, node.Operand1);
simplifyExtendedMoveCount++;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
}
private void FoldLoadStoreOffsets(InstructionNode node)
{
if (node.IsEmpty)
return;
if (!(node.Instruction == IRInstruction.Load || node.Instruction == IRInstruction.Store
|| node.Instruction == IRInstruction.LoadSignExtended || node.Instruction == IRInstruction.LoadZeroExtended))
return;
if (!node.Operand2.IsConstant)
return;
if (!node.Operand1.IsVirtualRegister)
return;
if (node.Operand1.Uses.Count != 1)
return;
var node2 = node.Operand1.Definitions[0];
if (!(node2.Instruction == IRInstruction.AddSigned || node2.Instruction == IRInstruction.SubSigned ||
node2.Instruction == IRInstruction.AddUnsigned || node2.Instruction == IRInstruction.SubUnsigned))
return;
if (!node2.Operand2.IsConstant)
return;
Operand constant;
if (node2.Instruction == IRInstruction.AddUnsigned || node2.Instruction == IRInstruction.AddSigned)
{
constant = Operand.CreateConstant(node.Operand2.Type, node2.Operand2.ConstantSignedLongInteger + node.Operand2.ConstantSignedLongInteger);
}
else
{
constant = Operand.CreateConstant(node.Operand2.Type, node.Operand2.ConstantSignedLongInteger - node2.Operand2.ConstantSignedLongInteger);
}
if (trace.Active) trace.Log("*** FoldLoadStoreOffsets");
AddOperandUsageToWorkList(node);
AddOperandUsageToWorkList(node2);
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.Operand1 = node2.Operand1;
node.Operand2 = constant;
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
if (trace.Active) trace.Log("REMOVED:\t" + node2.ToString());
node2.SetInstruction(IRInstruction.Nop);
foldLoadStoreOffsetsCount++;
instructionsRemovedCount++;
}
/// <summary>
/// Folds the constant phi instruction.
/// </summary>
/// <param name="node">The node.</param>
private void FoldConstantPhi(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.Phi)
return;
if (node.Result.Definitions.Count != 1)
return;
if (!node.Result.IsInteger)
return;
Operand operand1 = node.Operand1;
Operand result = node.Result;
foreach (var operand in node.Operands)
{
if (!operand.IsConstant)
return;
if (operand.ConstantUnsignedLongInteger != operand1.ConstantUnsignedLongInteger)
return;
}
if (trace.Active) trace.Log("*** FoldConstantPhiInstruction");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
AddOperandUsageToWorkList(node);
node.SetInstruction(IRInstruction.Move, result, operand1);
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
foldConstantPhiCount++;
}
/// <summary>
/// Simplifies the phi.
/// </summary>
/// <param name="node">The node.</param>
private void SimplifyPhi(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.Phi)
return;
if (node.OperandCount != 1)
return;
if (node.Result.Definitions.Count != 1)
return;
if (trace.Active) trace.Log("*** SimplifyPhiInstruction");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
AddOperandUsageToWorkList(node);
node.SetInstruction(IRInstruction.Move, node.Result, node.Operand1);
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
simplifyPhiCount++;
}
private void RemoveUselessPhi(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.Instruction != IRInstruction.Phi)
return;
if (node.Result.Definitions.Count != 1)
return;
var result = node.Result;
foreach (var use in node.Result.Uses)
{
if (use != node)
return;
}
AddOperandUsageToWorkList(node);
if (trace.Active) trace.Log("REMOVED:\t" + node.ToString());
node.SetInstruction(IRInstruction.Nop);
removeUselessPhiCount++;
}
private static bool IsPowerOfTwo(ulong n)
{
return (n & (n - 1)) == 0;
}
private static uint GetPowerOfTwo(ulong n)
{
uint bits = 0;
while (n > 0)
{
bits++;
n >>= 1;
}
return bits - 1;
}
private bool Reduce64BitOperationsTo32Bit()
{
if (Architecture.NativeIntegerSize != 32)
return false;
bool change = false;
foreach (var register in virtualRegisters)
{
Debug.Assert(register.IsVirtualRegister);
if (register.Definitions.Count != 1)
continue;
if (!register.IsLong)
continue;
if (!CanReduceTo32Bit(register))
continue;
var v = MethodCompiler.CreateVirtualRegister(TypeSystem.BuiltIn.U4);
if (trace.Active) trace.Log("*** Reduce64BitOperationsTo32Bit");
ReplaceVirtualRegister(register, v);
reduce64BitOperationsTo32BitCount++;
change = true;
}
return change;
}
private bool CanReduceTo32Bit(Operand local)
{
foreach (var node in local.Uses)
{
if (node.Instruction == IRInstruction.AddressOf)
return false;
if (node.Instruction == IRInstruction.Call)
return false;
if (node.Instruction == IRInstruction.Return)
return false;
if (node.Instruction == IRInstruction.SubSigned)
return false;
if (node.Instruction == IRInstruction.SubUnsigned)
return false;
if (node.Instruction == IRInstruction.DivSigned)
return false;
if (node.Instruction == IRInstruction.DivUnsigned)
return false;
if (node.Instruction == IRInstruction.Load || node.Instruction == IRInstruction.LoadSignExtended || node.Instruction == IRInstruction.LoadZeroExtended)
if (node.Result == local)
return false;
if (node.Instruction == IRInstruction.ShiftRight || node.Instruction == IRInstruction.ArithmeticShiftRight)
if (node.Operand1 == local)
return false;
if (node.Instruction == IRInstruction.Phi)
return false;
if (node.Instruction == IRInstruction.IntegerCompareBranch)
return false;
if (node.Instruction == IRInstruction.IntegerCompare)
return false;
if (node.Instruction == IRInstruction.RemSigned)
return false;
if (node.Instruction == IRInstruction.RemUnsigned)
return false;
if (node.Instruction == IRInstruction.Move)
if (node.Operand1.IsParameter)
return false;
}
return true;
}
private void ReplaceVirtualRegister(Operand local, Operand replacement)
{
if (trace.Active) trace.Log("Replacing: " + local.ToString() + " with " + replacement.ToString());
foreach (var node in local.Uses.ToArray())
{
AddOperandUsageToWorkList(node);
for (int i = 0; i < node.OperandCount; i++)
{
var operand = node.GetOperand(i);
if (local == operand)
{
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetOperand(i, replacement);
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
}
}
}
foreach (var node in local.Definitions.ToArray())
{
AddOperandUsageToWorkList(node);
for (int i = 0; i < node.ResultCount; i++)
{
var operand = node.GetResult(i);
if (local == operand)
{
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.SetResult(i, replacement);
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
}
}
}
}
private void NormalizeConstantTo32Bit(InstructionNode node)
{
if (node.IsEmpty)
return;
if (node.ResultCount != 1)
return;
if (!node.Result.IsInt)
return;
bool changed = false;
if (node.Instruction == IRInstruction.LogicalAnd ||
node.Instruction == IRInstruction.LogicalOr ||
node.Instruction == IRInstruction.LogicalXor ||
node.Instruction == IRInstruction.LogicalNot)
{
if (node.Operand1.IsConstant && node.Operand1.IsLong)
{
if (trace.Active) trace.Log("*** NormalizeConstantTo32Bit");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.Operand1 = Operand.CreateConstant(TypeSystem, (int)(node.Operand1.ConstantUnsignedLongInteger & uint.MaxValue));
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
}
if (node.OperandCount >= 2 && node.Operand2.IsConstant && node.Operand2.IsLong)
{
if (trace.Active) trace.Log("*** NormalizeConstantTo32Bit");
if (trace.Active) trace.Log("BEFORE:\t" + node.ToString());
node.Operand2 = Operand.CreateConstant(TypeSystem, (int)(node.Operand2.ConstantUnsignedLongInteger & uint.MaxValue));
if (trace.Active) trace.Log("AFTER: \t" + node.ToString());
}
}
if (changed)
{
AddOperandUsageToWorkList(node);
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing Policy Snippets.
/// </summary>
internal partial class PolicySnippetsOperations : IServiceOperations<ApiManagementClient>, IPolicySnippetsOperations
{
/// <summary>
/// Initializes a new instance of the PolicySnippetsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal PolicySnippetsOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// List all policy snippets.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='scope'>
/// Required. Polisy scope.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List policy snippets operation response details.
/// </returns>
public async Task<PolicySnippetListResponse> ListAsync(string resourceGroupName, string serviceName, PolicyScopeContract scope, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("scope", scope);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/policySnippets";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
queryParameters.Add("scope=" + Uri.EscapeDataString(scope.ToString()));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
PolicySnippetListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new PolicySnippetListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valuesArray = responseDoc;
if (valuesArray != null && valuesArray.Type != JTokenType.Null)
{
foreach (JToken valuesValue in ((JArray)valuesArray))
{
PolicySnippetContract policySnippetContractInstance = new PolicySnippetContract();
result.Values.Add(policySnippetContractInstance);
JToken nameValue = valuesValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
policySnippetContractInstance.Name = nameInstance;
}
JToken contentValue = valuesValue["content"];
if (contentValue != null && contentValue.Type != JTokenType.Null)
{
string contentInstance = ((string)contentValue);
policySnippetContractInstance.Content = contentInstance;
}
JToken toolTipValue = valuesValue["toolTip"];
if (toolTipValue != null && toolTipValue.Type != JTokenType.Null)
{
string toolTipInstance = ((string)toolTipValue);
policySnippetContractInstance.ToolTip = toolTipInstance;
}
JToken scopeValue = valuesValue["scope"];
if (scopeValue != null && scopeValue.Type != JTokenType.Null)
{
PolicyScopeContract scopeInstance = ((PolicyScopeContract)Enum.Parse(typeof(PolicyScopeContract), ((string)scopeValue), true));
policySnippetContractInstance.Scope = scopeInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
/// <summary>
/// Represents an item's attachment collection.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class AttachmentCollection : ComplexPropertyCollection<Attachment>, IOwnedProperty
{
#region Fields
/// <summary>
/// The item owner that owns this attachment collection
/// </summary>
private Item owner;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of AttachmentCollection.
/// </summary>
internal AttachmentCollection()
: base()
{
}
#endregion
#region Properties
#region IOwnedProperty Members
/// <summary>
/// The owner of this attachment collection.
/// </summary>
ServiceObject IOwnedProperty.Owner
{
get
{
return this.owner;
}
set
{
Item item = value as Item;
EwsUtilities.Assert(
item != null,
"AttachmentCollection.IOwnedProperty.set_Owner",
"value is not a descendant of ItemBase");
this.owner = item;
}
}
#endregion
#endregion
#region Methods
/// <summary>
/// Adds a file attachment to the collection.
/// </summary>
/// <param name="fileName">The name of the file representing the content of the attachment.</param>
/// <returns>A FileAttachment instance.</returns>
public FileAttachment AddFileAttachment(string fileName)
{
return this.AddFileAttachment(Path.GetFileName(fileName), fileName);
}
/// <summary>
/// Adds a file attachment to the collection.
/// </summary>
/// <param name="name">The display name of the new attachment.</param>
/// <param name="fileName">The name of the file representing the content of the attachment.</param>
/// <returns>A FileAttachment instance.</returns>
public FileAttachment AddFileAttachment(string name, string fileName)
{
FileAttachment fileAttachment = new FileAttachment(this.owner);
fileAttachment.Name = name;
fileAttachment.FileName = fileName;
this.InternalAdd(fileAttachment);
return fileAttachment;
}
/// <summary>
/// Adds a file attachment to the collection.
/// </summary>
/// <param name="name">The display name of the new attachment.</param>
/// <param name="contentStream">The stream from which to read the content of the attachment.</param>
/// <returns>A FileAttachment instance.</returns>
public FileAttachment AddFileAttachment(string name, Stream contentStream)
{
FileAttachment fileAttachment = new FileAttachment(this.owner);
fileAttachment.Name = name;
fileAttachment.ContentStream = contentStream;
this.InternalAdd(fileAttachment);
return fileAttachment;
}
/// <summary>
/// Adds a file attachment to the collection.
/// </summary>
/// <param name="name">The display name of the new attachment.</param>
/// <param name="content">A byte arrays representing the content of the attachment.</param>
/// <returns>A FileAttachment instance.</returns>
public FileAttachment AddFileAttachment(string name, byte[] content)
{
FileAttachment fileAttachment = new FileAttachment(this.owner);
fileAttachment.Name = name;
fileAttachment.Content = content;
this.InternalAdd(fileAttachment);
return fileAttachment;
}
/// <summary>
/// Adds a reference attachment to the collection
/// </summary>
/// <param name="name">The display name of the new attachment.</param>
/// <param name="attachLongPathName">The fully-qualified path identifying the attachment</param>
/// <returns>A ReferenceAttachment instance</returns>
public ReferenceAttachment AddReferenceAttachment(
string name,
string attachLongPathName)
{
ReferenceAttachment referenceAttachment = new ReferenceAttachment(this.owner);
referenceAttachment.Name = name;
referenceAttachment.AttachLongPathName = attachLongPathName;
this.InternalAdd(referenceAttachment);
return referenceAttachment;
}
/// <summary>
/// Adds an item attachment to the collection
/// </summary>
/// <typeparam name="TItem">The type of the item to attach.</typeparam>
/// <returns>An ItemAttachment instance.</returns>
public ItemAttachment<TItem> AddItemAttachment<TItem>()
where TItem : Item
{
if (typeof(TItem).GetCustomAttributes(typeof(AttachableAttribute), false).Length == 0)
{
throw new InvalidOperationException(
string.Format(
"Items of type {0} are not supported as attachments.",
typeof(TItem).Name));
}
ItemAttachment<TItem> itemAttachment = new ItemAttachment<TItem>(this.owner);
itemAttachment.Item = (TItem)EwsUtilities.CreateItemFromItemClass(itemAttachment, typeof(TItem), true);
this.InternalAdd(itemAttachment);
return itemAttachment;
}
/// <summary>
/// Removes all attachments from this collection.
/// </summary>
public void Clear()
{
this.InternalClear();
}
/// <summary>
/// Removes the attachment at the specified index.
/// </summary>
/// <param name="index">Index of the attachment to remove.</param>
public void RemoveAt(int index)
{
if (index < 0 || index >= this.Count)
{
throw new ArgumentOutOfRangeException("index", Strings.IndexIsOutOfRange);
}
this.InternalRemoveAt(index);
}
/// <summary>
/// Removes the specified attachment.
/// </summary>
/// <param name="attachment">The attachment to remove.</param>
/// <returns>True if the attachment was successfully removed from the collection, false otherwise.</returns>
public bool Remove(Attachment attachment)
{
EwsUtilities.ValidateParam(attachment, "attachment");
return this.InternalRemove(attachment);
}
/// <summary>
/// Instantiate the appropriate attachment type depending on the current XML element name.
/// </summary>
/// <param name="xmlElementName">The XML element name from which to determine the type of attachment to create.</param>
/// <returns>An Attachment instance.</returns>
internal override Attachment CreateComplexProperty(string xmlElementName)
{
switch (xmlElementName)
{
case XmlElementNames.FileAttachment:
return new FileAttachment(this.owner);
case XmlElementNames.ItemAttachment:
return new ItemAttachment(this.owner);
case XmlElementNames.ReferenceAttachment:
return new ReferenceAttachment(this.owner);
default:
return null;
}
}
/// <summary>
/// Determines the name of the XML element associated with the complexProperty parameter.
/// </summary>
/// <param name="complexProperty">The attachment object for which to determine the XML element name with.</param>
/// <returns>The XML element name associated with the complexProperty parameter.</returns>
internal override string GetCollectionItemXmlElementName(Attachment complexProperty)
{
if (complexProperty is FileAttachment)
{
return XmlElementNames.FileAttachment;
}
else if (complexProperty is ReferenceAttachment)
{
return XmlElementNames.ReferenceAttachment;
}
else
{
return XmlElementNames.ItemAttachment;
}
}
/// <summary>
/// Saves this collection by creating new attachment and deleting removed ones.
/// </summary>
internal void Save()
{
List<Attachment> attachments = new List<Attachment>();
// Retrieve a list of attachments that have to be deleted.
foreach (Attachment attachment in this.RemovedItems)
{
if (!attachment.IsNew)
{
attachments.Add(attachment);
}
}
// If any, delete them by calling the DeleteAttachment web method.
if (attachments.Count > 0)
{
this.InternalDeleteAttachments(attachments);
}
attachments.Clear();
// Retrieve a list of attachments that have to be created.
foreach (Attachment attachment in this)
{
if (attachment.IsNew)
{
attachments.Add(attachment);
}
}
// If there are any, create them by calling the CreateAttachment web method.
if (attachments.Count > 0)
{
if (this.owner.IsAttachment)
{
this.InternalCreateAttachments(this.owner.ParentAttachment.Id, attachments);
}
else
{
this.InternalCreateAttachments(this.owner.Id.UniqueId, attachments);
}
}
// Process all of the item attachments in this collection.
foreach (Attachment attachment in this)
{
ItemAttachment itemAttachment = attachment as ItemAttachment;
if (itemAttachment != null)
{
// Make sure item was created/loaded before trying to create/delete sub-attachments
if (itemAttachment.Item != null)
{
// Create/delete any sub-attachments
itemAttachment.Item.Attachments.Save();
// Clear the item's change log
itemAttachment.Item.ClearChangeLog();
}
}
}
base.ClearChangeLog();
}
/// <summary>
/// Determines whether there are any unsaved attachment collection changes.
/// </summary>
/// <returns>True if attachment adds or deletes haven't been processed yet.</returns>
internal bool HasUnprocessedChanges()
{
// Any new attachments?
foreach (Attachment attachment in this)
{
if (attachment.IsNew)
{
return true;
}
}
// Any pending deletions?
foreach (Attachment attachment in this.RemovedItems)
{
if (!attachment.IsNew)
{
return true;
}
}
// Recurse: process item attachments to check for new or deleted sub-attachments.
foreach (ItemAttachment itemAttachment in this.OfType<ItemAttachment>())
{
if (itemAttachment.Item != null)
{
if (itemAttachment.Item.Attachments.HasUnprocessedChanges())
{
return true;
}
}
}
return false;
}
/// <summary>
/// Disables the change log clearing mechanism. Attachment collections are saved separately
/// from the items they belong to.
/// </summary>
internal override void ClearChangeLog()
{
// Do nothing
}
/// <summary>
/// Validates this instance.
/// </summary>
internal void Validate()
{
// Validate all added attachments
bool contactPhotoFound = false;
for (int attachmentIndex = 0; attachmentIndex < this.AddedItems.Count; attachmentIndex++)
{
Attachment attachment = this.AddedItems[attachmentIndex];
if (attachment.IsNew)
{
// At the server side, only the last attachment with IsContactPhoto is kept, all other IsContactPhoto
// attachments are removed. CreateAttachment will generate AttachmentId for each of such attachments (although
// only the last one is valid).
//
// With E14 SP2 CreateItemWithAttachment, such request will only return 1 AttachmentId; but the client
// expects to see all, so let us prevent such "invalid" request in the first place.
//
// The IsNew check is to still let CreateAttachmentRequest allow multiple IsContactPhoto attachments.
//
if (this.owner.IsNew && this.owner.Service.RequestedServerVersion >= ExchangeVersion.Exchange2010_SP2)
{
FileAttachment fileAttachment = attachment as FileAttachment;
if (fileAttachment != null && fileAttachment.IsContactPhoto)
{
if (contactPhotoFound)
{
throw new ServiceValidationException(Strings.MultipleContactPhotosInAttachment);
}
contactPhotoFound = true;
}
}
attachment.Validate(attachmentIndex);
}
}
}
/// <summary>
/// Calls the DeleteAttachment web method to delete a list of attachments.
/// </summary>
/// <param name="attachments">The attachments to delete.</param>
private void InternalDeleteAttachments(IEnumerable<Attachment> attachments)
{
ServiceResponseCollection<DeleteAttachmentResponse> responses = this.owner.Service.DeleteAttachments(attachments);
foreach (DeleteAttachmentResponse response in responses)
{
// We remove all attachments that were successfully deleted from the change log. We should never
// receive a warning from EWS, so we ignore them.
if (response.Result != ServiceResult.Error)
{
this.RemoveFromChangeLog(response.Attachment);
}
}
// TODO : Should we throw for warnings as well?
if (responses.OverallResult == ServiceResult.Error)
{
throw new DeleteAttachmentException(responses, Strings.AtLeastOneAttachmentCouldNotBeDeleted);
}
}
/// <summary>
/// Calls the CreateAttachment web method to create a list of attachments.
/// </summary>
/// <param name="parentItemId">The Id of the parent item of the new attachments.</param>
/// <param name="attachments">The attachments to create.</param>
private void InternalCreateAttachments(string parentItemId, IEnumerable<Attachment> attachments)
{
ServiceResponseCollection<CreateAttachmentResponse> responses = this.owner.Service.CreateAttachments(parentItemId, attachments);
foreach (CreateAttachmentResponse response in responses)
{
// We remove all attachments that were successfully created from the change log. We should never
// receive a warning from EWS, so we ignore them.
if (response.Result != ServiceResult.Error)
{
this.RemoveFromChangeLog(response.Attachment);
}
}
// TODO : Should we throw for warnings as well?
if (responses.OverallResult == ServiceResult.Error)
{
throw new CreateAttachmentException(responses, Strings.AttachmentCreationFailed);
}
}
#endregion
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using Moq.Protected;
using Xunit;
namespace Moq.Tests
{
public class ProtectedAsMockFixture
{
private Mock<Foo> mock;
private IProtectedAsMock<Foo, Fooish> protectedMock;
public ProtectedAsMockFixture()
{
this.mock = new Mock<Foo>();
this.protectedMock = this.mock.Protected().As<Fooish>();
}
[Fact]
public void Setup_throws_when_expression_null()
{
var actual = Record.Exception(() =>
{
this.protectedMock.Setup(null);
});
Assert.IsType<ArgumentNullException>(actual);
}
[Fact]
public void Setup_throws_ArgumentException_when_expression_contains_nonexistent_method()
{
var actual = Record.Exception(() =>
{
this.protectedMock.Setup(m => m.NonExistentMethod());
});
Assert.IsType<ArgumentException>(actual);
Assert.Contains("does not have matching protected member", actual.Message);
}
[Fact]
public void Setup_throws_ArgumentException_when_expression_contains_nonexistent_property()
{
var actual = Record.Exception(() =>
{
this.protectedMock.Setup(m => m.NonExistentProperty);
});
Assert.IsType<ArgumentException>(actual);
Assert.Contains("does not have matching protected member", actual.Message);
}
[Fact]
public void Setup_TResult_throws_when_expression_null()
{
var actual = Record.Exception(() => this.protectedMock.Setup<object>(null));
Assert.IsType<ArgumentNullException>(actual);
}
[Fact]
public void Setup_can_setup_simple_method()
{
bool doSomethingImplInvoked = false;
this.protectedMock.Setup(m => m.DoSomethingImpl()).Callback(() => doSomethingImplInvoked = true);
this.mock.Object.DoSomething();
Assert.True(doSomethingImplInvoked);
}
[Fact]
public void Setup_TResult_can_setup_simple_method_with_return_value()
{
this.protectedMock.Setup(m => m.GetSomethingImpl()).Returns(() => 42);
var actual = this.mock.Object.GetSomething();
Assert.Equal(42, actual);
}
[Fact]
public void Setup_can_match_exact_arguments()
{
bool doSomethingImplInvoked = false;
this.protectedMock.Setup(m => m.DoSomethingImpl(1)).Callback(() => doSomethingImplInvoked = true);
this.mock.Object.DoSomething(0);
Assert.False(doSomethingImplInvoked);
this.mock.Object.DoSomething(1);
Assert.True(doSomethingImplInvoked);
}
[Fact]
public void Setup_can_involve_matchers()
{
bool doSomethingImplInvoked = false;
this.protectedMock.Setup(m => m.DoSomethingImpl(It.Is<int>(i => i == 1))).Callback(() => doSomethingImplInvoked = true);
this.mock.Object.DoSomething(0);
Assert.False(doSomethingImplInvoked);
this.mock.Object.DoSomething(1);
Assert.True(doSomethingImplInvoked);
}
[Fact]
public void Setup_can_setup_generic_method()
{
var handledMessages = new List<string>();
var mock = new Mock<MessageHandlerBase>();
mock.Protected().As<MessageHandlerBaseish>()
.Setup(m => m.HandleImpl(It.IsAny<string>()))
.Callback((string message) =>
{
handledMessages.Add(message);
});
mock.Object.Handle("Hello world.", 3);
Assert.Contains("Hello world.", handledMessages);
Assert.Equal(3, handledMessages.Count);
}
[Fact]
public void SetupGet_can_setup_readonly_property()
{
this.protectedMock.SetupGet(m => m.ReadOnlyPropertyImpl).Returns(42);
var actual = this.mock.Object.ReadOnlyProperty;
Assert.Equal(42, actual);
}
[Fact]
public void SetupGet_can_setup_readwrite_property()
{
this.protectedMock.SetupGet(m => m.ReadWritePropertyImpl).Returns(42);
var actual = this.mock.Object.ReadWriteProperty;
Assert.Equal(42, actual);
}
[Fact]
public void SetupProperty_can_setup_readwrite_property()
{
this.protectedMock.SetupProperty(m => m.ReadWritePropertyImpl, 42);
var actualBeforeSetting = this.mock.Object.ReadWriteProperty;
this.mock.Object.ReadWriteProperty = 17;
var actualAfterSetting = this.mock.Object.ReadWriteProperty;
Assert.Equal(42, actualBeforeSetting);
Assert.Equal(17, actualAfterSetting);
}
[Fact]
public void SetupProperty_cannot_setup_readonly_property()
{
var exception = Record.Exception(() =>
{
this.protectedMock.SetupProperty(m => m.ReadOnlyPropertyImpl);
});
Assert.NotNull(exception);
}
[Fact]
public void SetupSequence_TResult_can_setup_property()
{
this.protectedMock.SetupSequence(m => m.ReadOnlyPropertyImpl)
.Returns(1)
.Throws(new InvalidOperationException())
.Returns(3);
var actual = new List<int>();
actual.Add(this.mock.Object.ReadOnlyProperty);
var exception = Record.Exception(() =>
{
actual.Add(this.mock.Object.ReadOnlyProperty);
});
actual.Add(this.mock.Object.ReadOnlyProperty);
Assert.Equal(new[] { 1, 3 }, actual);
Assert.IsType<InvalidOperationException>(exception);
}
[Fact]
public void SetupSequence_can_setup_actions()
{
this.protectedMock.SetupSequence(m => m.DoSomethingImpl())
.Pass()
.Pass().
Throws(new InvalidOperationException());
this.mock.Object.DoSomething();
this.mock.Object.DoSomething();
var exception = Record.Exception(() =>
{
this.mock.Object.DoSomething();
});
this.mock.Object.DoSomething();
Assert.IsType<InvalidOperationException>(exception);
}
[Fact]
public void Verify_can_verify_method_invocations()
{
this.mock.Object.DoSomething();
this.protectedMock.Verify(m => m.DoSomethingImpl());
}
[Fact]
public void Verify_throws_if_invocation_not_occurred()
{
var exception = Record.Exception(() =>
{
this.protectedMock.Verify(m => m.DoSomethingImpl());
});
Assert.IsType<MockException>(exception);
}
[Fact]
public void Verify_can_verify_method_invocations_times()
{
this.mock.Object.DoSomething();
this.mock.Object.DoSomething();
this.mock.Object.DoSomething();
this.protectedMock.Verify(m => m.DoSomethingImpl(), Times.Exactly(3));
}
[Fact]
public void Verify_includes_failure_message_in_exception()
{
this.mock.Object.DoSomething();
this.mock.Object.DoSomething();
var exception = Record.Exception(() =>
{
this.protectedMock.Verify(m => m.DoSomethingImpl(), Times.Exactly(3), "Wasn't called three times.");
});
Assert.IsType<MockException>(exception);
Assert.Contains("Wasn't called three times.", exception.Message);
}
[Fact]
public void Verify_can_verify_generic_method()
{
var mock = new Mock<MessageHandlerBase>();
mock.Object.Handle("Hello world.", 3);
mock.Protected().As<MessageHandlerBaseish>().Verify(m => m.HandleImpl("Hello world."), Times.Exactly(3));
}
[Fact]
public void VerifyGet_can_verify_properties()
{
var _ = this.mock.Object.ReadOnlyProperty;
this.protectedMock.VerifyGet(m => m.ReadOnlyPropertyImpl);
}
[Fact]
public void VerifyGet_throws_if_property_query_not_occurred()
{
var _ = this.mock.Object.ReadOnlyProperty;
var exception = Record.Exception(() =>
{
this.protectedMock.VerifyGet(m => m.ReadOnlyPropertyImpl, Times.AtLeast(2));
});
}
[Fact]
public void VerifyGet_includes_failure_message_in_exception()
{
var exception = Record.Exception(() =>
{
this.protectedMock.VerifyGet(m => m.ReadOnlyPropertyImpl, Times.Once(), "Was not queried.");
});
Assert.IsType<MockException>(exception);
Assert.Contains("Was not queried.", exception.Message);
}
public abstract class Foo
{
protected Foo()
{
}
public int ReadOnlyProperty => this.ReadOnlyPropertyImpl;
public int ReadWriteProperty
{
get => this.ReadWritePropertyImpl;
set => this.ReadWritePropertyImpl = value;
}
public void DoSomething()
{
this.DoSomethingImpl();
}
public void DoSomething(int arg)
{
this.DoSomethingImpl(arg);
}
public int GetSomething()
{
return this.GetSomethingImpl();
}
protected abstract int ReadOnlyPropertyImpl { get; }
protected abstract int ReadWritePropertyImpl { get; set; }
protected abstract void DoSomethingImpl();
protected abstract void DoSomethingImpl(int arg);
protected abstract int GetSomethingImpl();
}
public interface Fooish
{
int ReadOnlyPropertyImpl { get; }
int ReadWritePropertyImpl { get; set; }
int NonExistentProperty { get; }
void DoSomethingImpl();
void DoSomethingImpl(int arg);
int GetSomethingImpl();
void NonExistentMethod();
}
public abstract class MessageHandlerBase
{
public void Handle<TMessage>(TMessage message, int count)
{
for (int i = 0; i < count; ++i)
{
this.HandleImpl(message);
}
}
protected abstract void HandleImpl<TMessage>(TMessage message);
}
public interface MessageHandlerBaseish
{
void HandleImpl<TMessage>(TMessage message);
}
}
}
| |
using ReactNative.Bridge;
using System.Collections.Generic;
using System.Diagnostics;
using Windows.Media;
using TrackPlayer.Logic;
namespace TrackPlayer.Players
{
public abstract class Playback
{
protected MediaManager manager;
protected List<Track> queue = new List<Track>();
protected int currentTrack = -1;
protected PlaybackState prevState = PlaybackState.None;
public Playback(MediaManager manager)
{
this.manager = manager;
}
protected void UpdateState(PlaybackState state)
{
if (prevState == state) return;
manager.OnStateChange(state);
prevState = state;
}
protected void UpdateCurrentTrack(int index, IPromise promise)
{
if (queue.Count == 0)
{
Reset();
promise?.Reject("queue_exhausted", "The queue is empty");
return;
}
else if (index < 0)
{
index = 0;
}
else if (index >= queue.Count)
{
index = queue.Count - 1;
}
Track previous = GetCurrentTrack();
double position = GetPosition();
PlaybackState oldState = GetState();
Debug.WriteLine("Updating current track...");
Track track = queue[index];
currentTrack = index;
Load(track, promise);
if (Utils.IsPlaying(oldState))
Play();
else if (Utils.IsPaused(oldState))
Pause();
manager.OnTrackUpdate(previous, position, track, true);
}
public Track GetCurrentTrack()
{
return currentTrack >= 0 && currentTrack < queue.Count ? queue[currentTrack] : null;
}
public Track GetTrack(string id)
{
return queue.Find(track => track.Id == id);
}
public List<Track> GetQueue()
{
return queue;
}
public void Add(List<Track> tracks, string insertBeforeId, IPromise promise)
{
if (insertBeforeId == null)
{
bool empty = queue.Count == 0;
queue.AddRange(tracks);
// Tracks were added, we'll update the current track accordingly
if (empty) UpdateCurrentTrack(0, null);
}
else
{
int index = queue.FindIndex(track => track.Id == insertBeforeId);
if (index == -1) index = queue.Count;
queue.InsertRange(index, tracks);
if (currentTrack >= index)
currentTrack += tracks.Count;
}
promise?.Resolve(null);
}
public void Remove(List<string> ids, IPromise promise)
{
int currTrack = currentTrack;
foreach (string id in ids)
{
int index = queue.FindIndex(track => track.Id == id);
queue.RemoveAt(index);
if(index == currTrack) currTrack += 1;
}
if (currTrack != currentTrack)
UpdateCurrentTrack(currTrack, null);
promise?.Resolve(null);
}
public void UpdateTrack(int index, Track track)
{
queue[index] = track;
if (index == currentTrack)
manager.GetMetadata().UpdateMetadata(track);
}
public abstract SystemMediaTransportControls GetTransportControls();
protected abstract void Load(Track track, IPromise promise);
public abstract void Play();
public abstract void Pause();
public abstract void Stop();
public void Reset()
{
Track prev = GetCurrentTrack();
double pos = GetPosition();
Stop();
currentTrack = -1;
queue.Clear();
manager.OnTrackUpdate(prev, pos, null, true);
}
public void RemoveUpcomingTracks()
{
for (int i = queue.Count - 1; i > currentTrack; i--)
{
queue.RemoveAt(i);
}
}
public void Skip(string id, IPromise promise)
{
int index = queue.FindIndex(track => track.Id == id);
if (index >= 0)
UpdateCurrentTrack(index, promise);
else
promise?.Reject("track_not_in_queue", "Given track ID was not found in queue");
}
protected bool HasNext()
{
return currentTrack < queue.Count - 1;
}
public void SkipToNext(IPromise promise)
{
if (HasNext())
UpdateCurrentTrack(currentTrack + 1, promise);
else
promise?.Reject("queue_exhausted", "There is no tracks left to play");
}
public void SkipToPrevious(IPromise promise)
{
if (currentTrack > 0)
UpdateCurrentTrack(currentTrack - 1, promise);
else
promise?.Reject("no_previous_track", "There is no previous tracks");
}
public abstract void SetVolume(double volume);
public abstract double GetVolume();
public abstract void SetRate(double rate);
public abstract double GetRate();
public abstract void SeekTo(double seconds);
public abstract double GetPosition();
public abstract double GetBufferedPosition();
public abstract double GetDuration();
public abstract PlaybackState GetState();
public abstract void Dispose();
}
public enum PlaybackState
{
None = 0,
Playing = 1,
Paused = 2,
Buffering = 3,
Stopped = 4
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Management.OperationalInsights.Models;
namespace Microsoft.Azure.Management.OperationalInsights.Models
{
/// <summary>
/// Metadata for search results.
/// </summary>
public partial class SearchMetadata
{
private string _aggregatedGroupingFields;
/// <summary>
/// Optional. Gets or sets the aggregated grouping fields.
/// </summary>
public string AggregatedGroupingFields
{
get { return this._aggregatedGroupingFields; }
set { this._aggregatedGroupingFields = value; }
}
private string _aggregatedValueField;
/// <summary>
/// Optional. Gets or sets the aggregated value field.
/// </summary>
public string AggregatedValueField
{
get { return this._aggregatedValueField; }
set { this._aggregatedValueField = value; }
}
private IList<CoreSummary> _coreSummaries;
/// <summary>
/// Optional. Gets or sets the core summaries.
/// </summary>
public IList<CoreSummary> CoreSummaries
{
get { return this._coreSummaries; }
set { this._coreSummaries = value; }
}
private string _eTag;
/// <summary>
/// Optional. Gets or sets the ETag of the search results.
/// </summary>
public string ETag
{
get { return this._eTag; }
set { this._eTag = value; }
}
private System.Guid? _id;
/// <summary>
/// Optional. Gets or sets the id of the search results request.
/// </summary>
public System.Guid? Id
{
get { return this._id; }
set { this._id = value; }
}
private System.DateTime? _lastUpdated;
/// <summary>
/// Optional. Gets or sets the time of last update.
/// </summary>
public System.DateTime? LastUpdated
{
get { return this._lastUpdated; }
set { this._lastUpdated = value; }
}
private long? _max;
/// <summary>
/// Optional. Gets or sets the max.
/// </summary>
public long? Max
{
get { return this._max; }
set { this._max = value; }
}
private long? _requestTime;
/// <summary>
/// Optional. Gets or sets the request time.
/// </summary>
public long? RequestTime
{
get { return this._requestTime; }
set { this._requestTime = value; }
}
private string _resultType;
/// <summary>
/// Optional. Gets or sets the search result type.
/// </summary>
public string ResultType
{
get { return this._resultType; }
set { this._resultType = value; }
}
private MetadataSchema _schema;
/// <summary>
/// Optional. Gets or sets the schema.
/// </summary>
public MetadataSchema Schema
{
get { return this._schema; }
set { this._schema = value; }
}
private string _searchId;
/// <summary>
/// Optional. Gets or sets the request id of the search.
/// </summary>
public string SearchId
{
get { return this._searchId; }
set { this._searchId = value; }
}
private IList<SearchSort> _sort;
/// <summary>
/// Optional. Gets or sets sort.
/// </summary>
public IList<SearchSort> Sort
{
get { return this._sort; }
set { this._sort = value; }
}
private System.DateTime? _startTime;
/// <summary>
/// Optional. Gets or sets the start time for the search.
/// </summary>
public System.DateTime? StartTime
{
get { return this._startTime; }
set { this._startTime = value; }
}
private string _status;
/// <summary>
/// Optional. Gets or sets the status of the search results.
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
private long? _sum;
/// <summary>
/// Optional. Gets or sets the sum.
/// </summary>
public long? Sum
{
get { return this._sum; }
set { this._sum = value; }
}
private long? _top;
/// <summary>
/// Optional. Gets or sets the number of top search results.
/// </summary>
public long? Top
{
get { return this._top; }
set { this._top = value; }
}
private long? _total;
/// <summary>
/// Optional. Gets or sets the total search results.
/// </summary>
public long? Total
{
get { return this._total; }
set { this._total = value; }
}
/// <summary>
/// Initializes a new instance of the SearchMetadata class.
/// </summary>
public SearchMetadata()
{
this.CoreSummaries = new LazyList<CoreSummary>();
this.Sort = new LazyList<SearchSort>();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
/// <summary>
/// Named pipe server
/// </summary>
public sealed partial class NamedPipeServerStream : PipeStream
{
// Use the maximum number of server instances that the system resources allow
private const int MaxAllowedServerInstances = -1;
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName)
: this(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, HandleInheritability.None)
{
}
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName, PipeDirection direction)
: this(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, HandleInheritability.None)
{
}
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances)
: this(pipeName, direction, maxNumberOfServerInstances, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, HandleInheritability.None)
{
}
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, PipeOptions.None, 0, 0, HandleInheritability.None)
{
}
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, 0, 0, HandleInheritability.None)
{
}
[SecuritySafeCritical]
public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize)
: this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, HandleInheritability.None)
{
}
/// <summary>
/// Full named pipe server constructor
/// </summary>
/// <param name="pipeName">Pipe name</param>
/// <param name="direction">Pipe direction: In, Out or InOut (duplex).
/// Win32 note: this gets OR'd into dwOpenMode to CreateNamedPipe
/// </param>
/// <param name="maxNumberOfServerInstances">Maximum number of server instances. Specify a fixed value between
/// 1 and 254 (Windows)/greater than 1 (Unix), or use NamedPipeServerStream.MaxAllowedServerInstances to use the
/// maximum amount allowed by system resources.</param>
/// <param name="transmissionMode">Byte mode or message mode.
/// Win32 note: this gets used for dwPipeMode. CreateNamedPipe allows you to specify PIPE_TYPE_BYTE/MESSAGE
/// and PIPE_READMODE_BYTE/MESSAGE independently, but this sets type and readmode to match.
/// </param>
/// <param name="options">PipeOption enum: None, Asynchronous, or Writethrough
/// Win32 note: this gets passed in with dwOpenMode to CreateNamedPipe. Asynchronous corresponds to
/// FILE_FLAG_OVERLAPPED option. PipeOptions enum doesn't expose FIRST_PIPE_INSTANCE option because
/// this sets that automatically based on the number of instances specified.
/// </param>
/// <param name="inBufferSize">Incoming buffer size, 0 or higher.
/// Note: this size is always advisory; OS uses a suggestion.
/// </param>
/// <param name="outBufferSize">Outgoing buffer size, 0 or higher (see above)</param>
/// <param name="pipeSecurity">PipeSecurity, or null for default security descriptor</param>
/// <param name="inheritability">Whether handle is inheritable</param>
/// <param name="additionalAccessRights">Combination (logical OR) of PipeAccessRights.TakeOwnership,
/// PipeAccessRights.AccessSystemSecurity, and PipeAccessRights.ChangePermissions</param>
[SecuritySafeCritical]
private NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
HandleInheritability inheritability)
: base(direction, transmissionMode, outBufferSize)
{
if (pipeName == null)
{
throw new ArgumentNullException("pipeName");
}
if (pipeName.Length == 0)
{
throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
}
if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0)
{
throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_OptionsInvalid);
}
if (inBufferSize < 0)
{
throw new ArgumentOutOfRangeException("inBufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
}
ValidateMaxNumberOfServerInstances(maxNumberOfServerInstances);
// inheritability will always be None since this private constructor is only called from other constructors from which
// inheritability is always set to None. Desktop has a public constructor to allow setting it to something else, but Core
// doesnt.
if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
{
throw new ArgumentOutOfRangeException("inheritability", SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
}
Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode,
options, inBufferSize, outBufferSize, inheritability);
}
// Create a NamedPipeServerStream from an existing server pipe handle.
[SecuritySafeCritical]
public NamedPipeServerStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle)
: base(direction, PipeTransmissionMode.Byte, 0)
{
if (safePipeHandle == null)
{
throw new ArgumentNullException("safePipeHandle");
}
if (safePipeHandle.IsInvalid)
{
throw new ArgumentException(SR.Argument_InvalidHandle, "safePipeHandle");
}
ValidateHandleIsPipe(safePipeHandle);
InitializeHandle(safePipeHandle, true, isAsync);
if (isConnected)
{
State = PipeState.Connected;
}
}
~NamedPipeServerStream()
{
Dispose(false);
}
public Task WaitForConnectionAsync()
{
return WaitForConnectionAsync(CancellationToken.None);
}
// Server can only connect from Disconnected state
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Consistent with security model")]
private void CheckConnectOperationsServer()
{
// we're not checking whether already connected; this allows us to throw IOException
// "pipe is being closed" if other side is closing (as does win32) or no-op if
// already connected
if (State == PipeState.Closed)
{
throw Error.GetPipeNotOpen();
}
if (InternalHandle != null && InternalHandle.IsClosed) // only check IsClosed if we have a handle
{
throw Error.GetPipeNotOpen();
}
if (State == PipeState.Broken)
{
throw new IOException(SR.IO_PipeBroken);
}
}
// Server is allowed to disconnect from connected and broken states
[SecurityCritical]
private void CheckDisconnectOperations()
{
if (State == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (State == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyDisconnected);
}
if (InternalHandle == null && CheckOperationsRequiresSetHandle)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if ((State == PipeState.Closed) || (InternalHandle != null && InternalHandle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
}
#if RunAs
// Users will use this delegate to specify a method to call while impersonating the client
// (see NamedPipeServerStream.RunAsClient).
public delegate void PipeStreamImpersonationWorker();
#endif
}
| |
using PlayFab.PfEditor.EditorModels;
using System;
using System.Collections.Generic;
using System.Text;
using UnityEditor;
using UnityEngine;
namespace PlayFab.PfEditor
{
[InitializeOnLoad]
public class PlayFabEditorSettings : UnityEditor.Editor
{
#region panel variables
public enum SubMenuStates
{
StandardSettings,
TitleSettings,
ApiSettings,
}
public enum WebRequestType
{
#if !UNITY_2018_2_OR_NEWER // Unity has deprecated Www
UnityWww, // High compatability Unity api calls
#endif
UnityWebRequest, // Modern unity HTTP component
HttpWebRequest, // High performance multi-threaded api calls
CustomHttp //If this is used, you must set the Http to an IPlayFabHttp object.
}
private static float LABEL_WIDTH = 180;
private static readonly StringBuilder Sb = new StringBuilder();
private static SubMenuComponent _menu = null;
private static readonly Dictionary<string, StudioDisplaySet> StudioFoldOutStates = new Dictionary<string, StudioDisplaySet>();
private static Vector2 _titleScrollPos = Vector2.zero;
#endregion
#region draw calls
private static void DrawApiSubPanel()
{
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1")))
{
var curDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
var changedFlags = false;
var allFlags = new Dictionary<string, PfDefineFlag>(PlayFabEditorHelper.FLAG_LABELS);
var extraDefines = new HashSet<string>(curDefines.Split(' ', ';'));
foreach (var eachFlag in extraDefines)
if (!string.IsNullOrEmpty(eachFlag) && !allFlags.ContainsKey(eachFlag))
allFlags.Add(eachFlag, new PfDefineFlag { Flag = eachFlag, Label = eachFlag, Category = PfDefineFlag.FlagCategory.Other, isInverted = false, isSafe = false });
var allowUnsafe = extraDefines.Contains(PlayFabEditorHelper.ENABLE_BETA_FETURES);
foreach (PfDefineFlag.FlagCategory activeFlagCategory in Enum.GetValues(typeof(PfDefineFlag.FlagCategory)))
{
if (activeFlagCategory == PfDefineFlag.FlagCategory.Other && !allowUnsafe)
continue;
using (var fwl = new FixedWidthLabel(activeFlagCategory.ToString())) { }
foreach (var eachDefinePair in allFlags)
{
PfDefineFlag eachFlag = eachDefinePair.Value;
if (eachFlag.Category == activeFlagCategory && (eachFlag.isSafe || allowUnsafe))
DisplayDefineToggle(eachFlag.Label + ": ", eachFlag.isInverted, eachFlag.Flag, ref curDefines, ref changedFlags);
}
}
if (changedFlags)
{
PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, curDefines);
Debug.Log("Updating Defines: " + curDefines);
AssetDatabase.Refresh();
}
}
}
private static void DisplayDefineToggle(string label, bool invertDisplay, string displayedDefine, ref string curDefines, ref bool changedFlag)
{
bool flagSet, flagGet = curDefines.Contains(displayedDefine);
using (var fwl = new FixedWidthLabel(label))
{
GUILayout.Space(LABEL_WIDTH - fwl.fieldWidth);
flagSet = EditorGUILayout.Toggle(invertDisplay ? !flagGet : flagGet, PlayFabEditorHelper.uiStyle.GetStyle("Toggle"), GUILayout.MinHeight(25));
if (invertDisplay)
flagSet = !flagSet;
}
changedFlag |= flagSet != flagGet;
Sb.Length = 0;
if (flagSet && !flagGet)
{
Sb.Append(curDefines);
if (Sb.Length > 0)
Sb.Append(";");
Sb.Append(displayedDefine);
curDefines = Sb.ToString();
}
else if (!flagSet && flagGet)
{
Sb.Append(curDefines);
Sb.Replace(displayedDefine, "").Replace(";;", ";");
if (Sb.Length > 0 && Sb[0] == ';')
Sb.Remove(0, 1);
if (Sb.Length > 0 && Sb[Sb.Length - 1] == ';')
Sb.Remove(Sb.Length - 1, 1);
curDefines = Sb.ToString();
}
}
public static void DrawSettingsPanel()
{
if (_menu != null)
{
_menu.DrawMenu();
switch ((SubMenuStates)PlayFabEditorPrefsSO.Instance.curSubMenuIdx)
{
case SubMenuStates.StandardSettings:
DrawStandardSettingsSubPanel();
break;
case SubMenuStates.ApiSettings:
DrawApiSubPanel();
break;
case SubMenuStates.TitleSettings:
DrawTitleSettingsSubPanel();
break;
}
}
else
{
RegisterMenu();
}
}
private static void DrawTitleSettingsSubPanel()
{
float labelWidth = 100;
if (PlayFabEditorPrefsSO.Instance.StudioList != null && PlayFabEditorPrefsSO.Instance.StudioList.Count != StudioFoldOutStates.Count + 1)
{
StudioFoldOutStates.Clear();
foreach (var studio in PlayFabEditorPrefsSO.Instance.StudioList)
{
if (string.IsNullOrEmpty(studio.Id))
continue;
if (!StudioFoldOutStates.ContainsKey(studio.Id))
StudioFoldOutStates.Add(studio.Id, new StudioDisplaySet { Studio = studio });
foreach (var title in studio.Titles)
if (!StudioFoldOutStates[studio.Id].titleFoldOutStates.ContainsKey(title.Id))
StudioFoldOutStates[studio.Id].titleFoldOutStates.Add(title.Id, new TitleDisplaySet { Title = title });
}
}
_titleScrollPos = GUILayout.BeginScrollView(_titleScrollPos, PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"));
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
EditorGUILayout.LabelField("STUDIOS:", PlayFabEditorHelper.uiStyle.GetStyle("labelStyle"), GUILayout.Width(labelWidth));
GUILayout.FlexibleSpace();
if (GUILayout.Button("REFRESH", PlayFabEditorHelper.uiStyle.GetStyle("Button")))
PlayFabEditorDataService.RefreshStudiosList();
}
foreach (var studio in StudioFoldOutStates)
{
var style = new GUIStyle(EditorStyles.foldout);
if (studio.Value.isCollapsed)
style.fontStyle = FontStyle.Normal;
studio.Value.isCollapsed = EditorGUI.Foldout(EditorGUILayout.GetControlRect(), studio.Value.isCollapsed, string.Format("{0} ({1})", studio.Value.Studio.Name, studio.Value.Studio.Titles.Length), true, PlayFabEditorHelper.uiStyle.GetStyle("foldOut_std"));
if (studio.Value.isCollapsed)
continue;
EditorGUI.indentLevel = 2;
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
EditorGUILayout.LabelField("TITLES:", PlayFabEditorHelper.uiStyle.GetStyle("labelStyle"), GUILayout.Width(labelWidth));
}
GUILayout.Space(5);
// draw title foldouts
foreach (var title in studio.Value.titleFoldOutStates)
{
title.Value.isCollapsed = EditorGUI.Foldout(EditorGUILayout.GetControlRect(), title.Value.isCollapsed, string.Format("{0} [{1}]", title.Value.Title.Name, title.Value.Title.Id), true, PlayFabEditorHelper.uiStyle.GetStyle("foldOut_std"));
if (title.Value.isCollapsed)
continue;
EditorGUI.indentLevel = 3;
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
EditorGUILayout.LabelField("SECRET KEY:", PlayFabEditorHelper.uiStyle.GetStyle("labelStyle"), GUILayout.Width(labelWidth));
EditorGUILayout.TextField("" + title.Value.Title.SecretKey);
}
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
EditorGUILayout.LabelField("URL:", PlayFabEditorHelper.uiStyle.GetStyle("labelStyle"), GUILayout.Width(labelWidth));
GUILayout.FlexibleSpace();
if (GUILayout.Button("VIEW IN GAME MANAGER", PlayFabEditorHelper.uiStyle.GetStyle("textButton")))
Application.OpenURL(title.Value.Title.GameManagerUrl);
GUILayout.FlexibleSpace();
}
EditorGUI.indentLevel = 2;
}
EditorGUI.indentLevel = 0;
}
GUILayout.EndScrollView();
}
private static Studio GetStudioForTitleId(string titleId)
{
if (PlayFabEditorPrefsSO.Instance.StudioList == null)
return Studio.OVERRIDE;
foreach (var eachStudio in PlayFabEditorPrefsSO.Instance.StudioList)
if (eachStudio.Titles != null)
foreach (var eachTitle in eachStudio.Titles)
if (eachTitle.Id == titleId)
return eachStudio;
return Studio.OVERRIDE;
}
private static void DrawStandardSettingsSubPanel()
{
float labelWidth = 160;
using (new UnityVertical(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleGray1"), GUILayout.ExpandWidth(true)))
{
var studio = GetStudioForTitleId(PlayFabEditorDataService.SharedSettings.TitleId);
if (string.IsNullOrEmpty(studio.Id))
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
EditorGUILayout.LabelField("You are using a TitleId to which you are not a member. A title administrator can approve access for your account.", PlayFabEditorHelper.uiStyle.GetStyle("orTxt"));
PlayFabGuiFieldHelper.SuperFancyDropdown(labelWidth, "STUDIO: ", studio, PlayFabEditorPrefsSO.Instance.StudioList, eachStudio => eachStudio.Name, OnStudioChange, PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"));
studio = GetStudioForTitleId(PlayFabEditorDataService.SharedSettings.TitleId); // This might have changed above, so refresh it
if (string.IsNullOrEmpty(studio.Id))
{
// Override studio lets you set your own titleId
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
EditorGUILayout.LabelField("TITLE ID: ", PlayFabEditorHelper.uiStyle.GetStyle("labelStyle"), GUILayout.Width(labelWidth));
var newTitleId = EditorGUILayout.TextField(PlayFabEditorDataService.SharedSettings.TitleId, PlayFabEditorHelper.uiStyle.GetStyle("TextField"), GUILayout.MinHeight(25));
if (newTitleId != PlayFabEditorDataService.SharedSettings.TitleId)
OnTitleIdChange(newTitleId);
}
}
else
{
PlayFabGuiFieldHelper.SuperFancyDropdown(labelWidth, "TITLE ID: ", studio.GetTitle(PlayFabEditorDataService.SharedSettings.TitleId), studio.Titles, GetTitleDisplayString, OnTitleChange, PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear"));
}
DrawPfSharedSettingsOptions(labelWidth);
}
}
private static string GetTitleDisplayString(Title title)
{
return string.Format("[{0}] {1}", title.Id, title.Name);
}
private static void DrawPfSharedSettingsOptions(float labelWidth)
{
#if ENABLE_PLAYFABADMIN_API || ENABLE_PLAYFABSERVER_API || UNITY_EDITOR
// Set the title secret key, if we're using the dropdown
var studio = GetStudioForTitleId(PlayFabEditorDataService.SharedSettings.TitleId);
var correctKey = studio.GetTitleSecretKey(PlayFabEditorDataService.SharedSettings.TitleId);
var setKey = !string.IsNullOrEmpty(studio.Id) && !string.IsNullOrEmpty(correctKey);
if (setKey)
PlayFabEditorDataService.SharedSettings.DeveloperSecretKey = correctKey;
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
EditorGUILayout.LabelField("DEVELOPER SECRET KEY: ", PlayFabEditorHelper.uiStyle.GetStyle("labelStyle"), GUILayout.Width(labelWidth));
using (new UnityGuiToggler(!setKey))
PlayFabEditorDataService.SharedSettings.DeveloperSecretKey = EditorGUILayout.TextField(PlayFabEditorDataService.SharedSettings.DeveloperSecretKey, PlayFabEditorHelper.uiStyle.GetStyle("TextField"), GUILayout.MinHeight(25));
}
#endif
using (new UnityHorizontal(PlayFabEditorHelper.uiStyle.GetStyle("gpStyleClear")))
{
EditorGUILayout.LabelField("REQUEST TYPE: ", PlayFabEditorHelper.uiStyle.GetStyle("labelStyle"), GUILayout.MaxWidth(labelWidth));
PlayFabEditorDataService.SharedSettings.WebRequestType = (WebRequestType)EditorGUILayout.EnumPopup(PlayFabEditorDataService.SharedSettings.WebRequestType, PlayFabEditorHelper.uiStyle.GetStyle("TextField"), GUILayout.Height(25));
}
if (PlayFabEditorDataService.SharedSettings.WebRequestType == WebRequestType.HttpWebRequest)
{
using (var fwl = new FixedWidthLabel(new GUIContent("REQUEST TIMEOUT: "), PlayFabEditorHelper.uiStyle.GetStyle("labelStyle")))
{
GUILayout.Space(labelWidth - fwl.fieldWidth);
PlayFabEditorDataService.SharedSettings.TimeOut = EditorGUILayout.IntField(PlayFabEditorDataService.SharedSettings.TimeOut, PlayFabEditorHelper.uiStyle.GetStyle("TextField"), GUILayout.MinHeight(25));
}
using (var fwl = new FixedWidthLabel(new GUIContent("KEEP ALIVE: "), PlayFabEditorHelper.uiStyle.GetStyle("labelStyle")))
{
GUILayout.Space(labelWidth - fwl.fieldWidth);
PlayFabEditorDataService.SharedSettings.KeepAlive = EditorGUILayout.Toggle(PlayFabEditorDataService.SharedSettings.KeepAlive, PlayFabEditorHelper.uiStyle.GetStyle("Toggle"), GUILayout.MinHeight(25));
}
}
}
#endregion
#region menu and helper methods
private static void RegisterMenu()
{
if (_menu != null)
return;
_menu = CreateInstance<SubMenuComponent>();
_menu.RegisterMenuItem("PROJECT", OnStandardSetttingsClicked);
_menu.RegisterMenuItem("STUDIOS", OnTitleSettingsClicked);
_menu.RegisterMenuItem("API", OnApiSettingsClicked);
}
private static void OnApiSettingsClicked()
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnSubmenuItemClicked, SubMenuStates.ApiSettings.ToString(), "" + (int)SubMenuStates.ApiSettings);
}
private static void OnStandardSetttingsClicked()
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnSubmenuItemClicked, SubMenuStates.StandardSettings.ToString(), "" + (int)SubMenuStates.StandardSettings);
}
private static void OnTitleSettingsClicked()
{
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnSubmenuItemClicked, SubMenuStates.TitleSettings.ToString(), "" + (int)SubMenuStates.TitleSettings);
}
private static void OnStudioChange(Studio newStudio)
{
var newTitleId = (newStudio.Titles == null || newStudio.Titles.Length == 0) ? "" : newStudio.Titles[0].Id;
OnTitleIdChange(newTitleId);
}
private static void OnTitleChange(Title newTitle)
{
OnTitleIdChange(newTitle.Id);
}
private static void OnTitleIdChange(string newTitleId)
{
var studio = GetStudioForTitleId(newTitleId);
PlayFabEditorPrefsSO.Instance.SelectedStudio = studio.Name;
PlayFabEditorDataService.SharedSettings.TitleId = newTitleId;
#if ENABLE_PLAYFABADMIN_API || ENABLE_PLAYFABSERVER_API || UNITY_EDITOR
PlayFabEditorDataService.SharedSettings.DeveloperSecretKey = studio.GetTitleSecretKey(newTitleId);
#endif
PlayFabEditorPrefsSO.Instance.TitleDataCache.Clear();
if (PlayFabEditorDataMenu.tdViewer != null)
PlayFabEditorDataMenu.tdViewer.items.Clear();
PlayFabEditorDataService.SaveEnvDetails();
PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnSuccess);
}
#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.
namespace System.Reflection.Metadata.Ecma335
{
public struct InstructionEncoder
{
public BlobBuilder Builder { get; }
private readonly BranchBuilder _branchBuilderOpt;
public InstructionEncoder(BlobBuilder builder, BranchBuilder branchBuilder = null)
{
Builder = builder;
_branchBuilderOpt = branchBuilder;
}
public int Offset => Builder.Count;
public void OpCode(ILOpCode code)
{
if (unchecked((byte)code) == (ushort)code)
{
Builder.WriteByte((byte)code);
}
else
{
// IL opcodes that occupy two bytes are written to
// the byte stream with the high-order byte first,
// in contrast to the little-endian format of the
// numeric arguments and tokens.
Builder.WriteUInt16BE((ushort)code);
}
}
public void Token(EntityHandle handle)
{
Token(MetadataTokens.GetToken(handle));
}
public void Token(int token)
{
Builder.WriteInt32(token);
}
public void LongBranchTarget(int ilOffset)
{
Builder.WriteInt32(ilOffset);
}
public void ShortBranchTarget(byte ilOffset)
{
Builder.WriteByte(ilOffset);
}
public void LoadString(UserStringHandle handle)
{
OpCode(ILOpCode.Ldstr);
Token(MetadataTokens.GetToken(handle));
}
public void Call(EntityHandle methodHandle)
{
OpCode(ILOpCode.Call);
Token(methodHandle);
}
public void CallIndirect(StandaloneSignatureHandle signature)
{
OpCode(ILOpCode.Calli);
Token(signature);
}
public void LoadConstantI4(int value)
{
ILOpCode code;
switch (value)
{
case -1: code = ILOpCode.Ldc_i4_m1; break;
case 0: code = ILOpCode.Ldc_i4_0; break;
case 1: code = ILOpCode.Ldc_i4_1; break;
case 2: code = ILOpCode.Ldc_i4_2; break;
case 3: code = ILOpCode.Ldc_i4_3; break;
case 4: code = ILOpCode.Ldc_i4_4; break;
case 5: code = ILOpCode.Ldc_i4_5; break;
case 6: code = ILOpCode.Ldc_i4_6; break;
case 7: code = ILOpCode.Ldc_i4_7; break;
case 8: code = ILOpCode.Ldc_i4_8; break;
default:
if (unchecked((sbyte)value == value))
{
OpCode(ILOpCode.Ldc_i4_s);
Builder.WriteSByte(unchecked((sbyte)value));
}
else
{
OpCode(ILOpCode.Ldc_i4);
Builder.WriteInt32(value);
}
return;
}
OpCode(code);
}
public void LoadConstantI8(long value)
{
OpCode(ILOpCode.Ldc_i8);
Builder.WriteInt64(value);
}
public void LoadConstantR4(float value)
{
OpCode(ILOpCode.Ldc_r4);
Builder.WriteSingle(value);
}
public void LoadConstantR8(double value)
{
OpCode(ILOpCode.Ldc_r8);
Builder.WriteDouble(value);
}
public void LoadLocal(int slotIndex)
{
switch (slotIndex)
{
case 0: OpCode(ILOpCode.Ldloc_0); break;
case 1: OpCode(ILOpCode.Ldloc_1); break;
case 2: OpCode(ILOpCode.Ldloc_2); break;
case 3: OpCode(ILOpCode.Ldloc_3); break;
default:
if (slotIndex < 0xFF)
{
OpCode(ILOpCode.Ldloc_s);
Builder.WriteByte(unchecked((byte)slotIndex));
}
else
{
OpCode(ILOpCode.Ldloc);
Builder.WriteInt32(slotIndex);
}
break;
}
}
public void StoreLocal(int slotIndex)
{
switch (slotIndex)
{
case 0: OpCode(ILOpCode.Stloc_0); break;
case 1: OpCode(ILOpCode.Stloc_1); break;
case 2: OpCode(ILOpCode.Stloc_2); break;
case 3: OpCode(ILOpCode.Stloc_3); break;
default:
if (slotIndex < 0xFF)
{
OpCode(ILOpCode.Stloc_s);
Builder.WriteByte(unchecked((byte)slotIndex));
}
else
{
OpCode(ILOpCode.Stloc);
Builder.WriteInt32(slotIndex);
}
break;
}
}
public void LoadLocalAddress(int slotIndex)
{
if (slotIndex < 0xFF)
{
OpCode(ILOpCode.Ldloca_s);
Builder.WriteByte(unchecked((byte)slotIndex));
}
else
{
OpCode(ILOpCode.Ldloca);
Builder.WriteInt32(slotIndex);
}
}
public void LoadArgument(int argumentIndex)
{
switch (argumentIndex)
{
case 0: OpCode(ILOpCode.Ldarg_0); break;
case 1: OpCode(ILOpCode.Ldarg_1); break;
case 2: OpCode(ILOpCode.Ldarg_2); break;
case 3: OpCode(ILOpCode.Ldarg_3); break;
default:
if (argumentIndex < 0xFF)
{
OpCode(ILOpCode.Ldarg_s);
Builder.WriteByte(unchecked((byte)argumentIndex));
}
else
{
OpCode(ILOpCode.Ldarg);
Builder.WriteInt32(argumentIndex);
}
break;
}
}
public void LoadArgumentAddress(int argumentIndex)
{
if (argumentIndex < 0xFF)
{
OpCode(ILOpCode.Ldarga_s);
Builder.WriteByte(unchecked((byte)argumentIndex));
}
else
{
OpCode(ILOpCode.Ldarga);
Builder.WriteInt32(argumentIndex);
}
}
public void StoreArgument(int argumentIndex)
{
if (argumentIndex < 0xFF)
{
OpCode(ILOpCode.Starg_s);
Builder.WriteByte(unchecked((byte)argumentIndex));
}
else
{
OpCode(ILOpCode.Starg);
Builder.WriteInt32(argumentIndex);
}
}
public LabelHandle DefineLabel()
{
return GetBranchBuilder().AddLabel();
}
public void Branch(ILOpCode code, LabelHandle label)
{
// throws if code is not a branch:
ILOpCode shortCode = code.GetShortBranch();
GetBranchBuilder().AddBranch(Offset, label, (byte)shortCode);
OpCode(shortCode);
// -1 points in the middle of the branch instruction and is thus invalid.
// We want to produce invalid IL so that if the caller doesn't patch the branches
// the branch instructions will be invalid in an obvious way.
Builder.WriteSByte(-1);
}
public void MarkLabel(LabelHandle label)
{
GetBranchBuilder().MarkLabel(Offset, label);
}
private BranchBuilder GetBranchBuilder()
{
if (_branchBuilderOpt == null)
{
Throw.BranchBuilderNotAvailable();
}
return _branchBuilderOpt;
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) 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.
*****************************************************************************/
// Contributed by: Mitch Thompson
#define SPINE_SKELETON_ANIMATOR
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Spine;
namespace Spine.Unity.Editor {
using Event = UnityEngine.Event;
using Icons = SpineEditorUtilities.Icons;
[CustomEditor(typeof(SkeletonDataAsset)), CanEditMultipleObjects]
public class SkeletonDataAssetInspector : UnityEditor.Editor {
static bool showAnimationStateData = true;
static bool showAnimationList = true;
static bool showSlotList = false;
static bool showAttachments = false;
SerializedProperty atlasAssets, skeletonJSON, scale, fromAnimation, toAnimation, duration, defaultMix;
#if SPINE_TK2D
SerializedProperty spriteCollection;
#endif
#if SPINE_SKELETON_ANIMATOR
static bool isMecanimExpanded = false;
SerializedProperty controller;
#endif
bool m_initialized = false;
SkeletonDataAsset m_skeletonDataAsset;
SkeletonData m_skeletonData;
string m_skeletonDataAssetGUID;
bool needToSerialize;
readonly List<string> warnings = new List<string>();
GUIStyle activePlayButtonStyle, idlePlayButtonStyle;
readonly GUIContent DefaultMixLabel = new GUIContent("Default Mix Duration", "Sets 'SkeletonDataAsset.defaultMix' in the asset and 'AnimationState.data.defaultMix' at runtime load time.");
void OnEnable () {
SpineEditorUtilities.ConfirmInitialization();
m_skeletonDataAsset = (SkeletonDataAsset)target;
bool newAtlasAssets = atlasAssets == null;
if (newAtlasAssets) atlasAssets = serializedObject.FindProperty("atlasAssets");
skeletonJSON = serializedObject.FindProperty("skeletonJSON");
scale = serializedObject.FindProperty("scale");
fromAnimation = serializedObject.FindProperty("fromAnimation");
toAnimation = serializedObject.FindProperty("toAnimation");
duration = serializedObject.FindProperty("duration");
defaultMix = serializedObject.FindProperty("defaultMix");
#if SPINE_SKELETON_ANIMATOR
controller = serializedObject.FindProperty("controller");
#endif
#if SPINE_TK2D
if (newAtlasAssets) atlasAssets.isExpanded = false;
spriteCollection = serializedObject.FindProperty("spriteCollection");
#else
if (newAtlasAssets) atlasAssets.isExpanded = true;
#endif
m_skeletonDataAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_skeletonDataAsset));
EditorApplication.update -= EditorUpdate;
EditorApplication.update += EditorUpdate;
RepopulateWarnings();
if (m_skeletonDataAsset.skeletonJSON == null) {
m_skeletonData = null;
return;
}
m_skeletonData = warnings.Count == 0 ? m_skeletonDataAsset.GetSkeletonData(false) : null;
}
void OnDestroy () {
m_initialized = false;
EditorApplication.update -= EditorUpdate;
this.DestroyPreviewInstances();
if (this.m_previewUtility != null) {
this.m_previewUtility.Cleanup();
this.m_previewUtility = null;
}
}
override public void OnInspectorGUI () {
if (serializedObject.isEditingMultipleObjects) {
using (new SpineInspectorUtility.BoxScope()) {
EditorGUILayout.LabelField("SkeletonData", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(skeletonJSON, SpineInspectorUtility.TempContent(skeletonJSON.displayName, Icons.spine));
EditorGUILayout.PropertyField(scale);
}
using (new SpineInspectorUtility.BoxScope()) {
EditorGUILayout.LabelField("Atlas", EditorStyles.boldLabel);
#if !SPINE_TK2D
EditorGUILayout.PropertyField(atlasAssets, true);
#else
using (new EditorGUI.DisabledGroupScope(spriteCollection.objectReferenceValue != null)) {
EditorGUILayout.PropertyField(atlasAssets, true);
}
EditorGUILayout.LabelField("spine-tk2d", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(spriteCollection, true);
#endif
}
using (new SpineInspectorUtility.BoxScope()) {
EditorGUILayout.LabelField("Mix Settings", EditorStyles.boldLabel);
SpineInspectorUtility.PropertyFieldWideLabel(defaultMix, DefaultMixLabel, 160);
EditorGUILayout.Space();
}
return;
}
{
// Lazy initialization because accessing EditorStyles values in OnEnable during a recompile causes UnityEditor to throw null exceptions. (Unity 5.3.5)
idlePlayButtonStyle = idlePlayButtonStyle ?? new GUIStyle(EditorStyles.miniButton);
if (activePlayButtonStyle == null) {
activePlayButtonStyle = new GUIStyle(idlePlayButtonStyle);
activePlayButtonStyle.normal.textColor = Color.red;
}
}
serializedObject.Update();
EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(target.name + " (SkeletonDataAsset)", Icons.spine), EditorStyles.whiteLargeLabel);
if (m_skeletonData != null) {
EditorGUILayout.LabelField("(Drag and Drop to instantiate.)", EditorStyles.miniLabel);
}
EditorGUI.BeginChangeCheck();
// SkeletonData
using (new SpineInspectorUtility.BoxScope()) {
using (new EditorGUILayout.HorizontalScope()) {
EditorGUILayout.LabelField("SkeletonData", EditorStyles.boldLabel);
if (m_skeletonData != null) {
var sd = m_skeletonData;
string m = string.Format("{8} - {0} {1}\nBones: {2}\nConstraints: \n {5} IK \n {6} Path \n {7} Transform\n\nSlots: {3}\nSkins: {4}\n\nAnimations: {9}",
sd.Version, string.IsNullOrEmpty(sd.Version) ? "" : "export ", sd.Bones.Count, sd.Slots.Count, sd.Skins.Count, sd.IkConstraints.Count, sd.PathConstraints.Count, sd.TransformConstraints.Count, skeletonJSON.objectReferenceValue.name, sd.Animations.Count);
EditorGUILayout.LabelField(GUIContent.none, new GUIContent(Icons.info, m), GUILayout.Width(30f));
}
}
EditorGUILayout.PropertyField(skeletonJSON, SpineInspectorUtility.TempContent(skeletonJSON.displayName, Icons.spine));
EditorGUILayout.PropertyField(scale);
}
// if (m_skeletonData != null) {
// if (SpineInspectorUtility.CenteredButton(new GUIContent("Instantiate", Icons.spine, "Creates a new Spine GameObject in the active scene using this Skeleton Data.\nYou can also instantiate by dragging the SkeletonData asset from Project view into Scene View.")))
// SpineEditorUtilities.ShowInstantiateContextMenu(this.m_skeletonDataAsset, Vector3.zero);
// }
// Atlas
using (new SpineInspectorUtility.BoxScope()) {
EditorGUILayout.LabelField("Atlas", EditorStyles.boldLabel);
#if !SPINE_TK2D
EditorGUILayout.PropertyField(atlasAssets, true);
#else
using (new EditorGUI.DisabledGroupScope(spriteCollection.objectReferenceValue != null)) {
EditorGUILayout.PropertyField(atlasAssets, true);
}
EditorGUILayout.LabelField("spine-tk2d", EditorStyles.boldLabel);
EditorGUILayout.PropertyField(spriteCollection, true);
#endif
{
bool hasNulls = false;
foreach (var a in m_skeletonDataAsset.atlasAssets) {
if (a == null) {
hasNulls = true;
break;
}
}
if (hasNulls) {
if (m_skeletonDataAsset.atlasAssets.Length == 1) {
EditorGUILayout.HelpBox("Atlas array cannot have null entries!", MessageType.None);
} else {
EditorGUILayout.HelpBox("Atlas array should not have null entries!", MessageType.Error);
if (SpineInspectorUtility.CenteredButton(SpineInspectorUtility.TempContent("Remove null entries"))) {
var trimmedAtlasAssets = new List<AtlasAsset>();
foreach (var a in m_skeletonDataAsset.atlasAssets) {
if (a != null) trimmedAtlasAssets.Add(a);
}
m_skeletonDataAsset.atlasAssets = trimmedAtlasAssets.ToArray();
serializedObject.Update();
}
}
}
}
}
if (EditorGUI.EndChangeCheck()) {
if (serializedObject.ApplyModifiedProperties()) {
if (m_previewUtility != null) {
m_previewUtility.Cleanup();
m_previewUtility = null;
}
m_skeletonDataAsset.Clear();
m_skeletonData = null;
OnEnable(); // Should call RepopulateWarnings.
return;
}
}
// Some code depends on the existence of m_skeletonAnimation instance.
// If m_skeletonAnimation is lazy-instantiated elsewhere, this can cause contents to change between Layout and Repaint events, causing GUILayout control count errors.
InitPreview();
if (m_skeletonData != null) {
GUILayout.Space(20f);
using (new SpineInspectorUtility.BoxScope(false)) {
EditorGUILayout.LabelField(SpineInspectorUtility.TempContent("Mix Settings", Icons.animationRoot), EditorStyles.boldLabel);
DrawAnimationStateInfo();
EditorGUILayout.Space();
}
EditorGUILayout.LabelField("Preview", EditorStyles.boldLabel);
DrawAnimationList();
EditorGUILayout.Space();
DrawSlotList();
EditorGUILayout.Space();
DrawUnityTools();
} else {
#if !SPINE_TK2D
// Reimport Button
using (new EditorGUI.DisabledGroupScope(skeletonJSON.objectReferenceValue == null)) {
if (GUILayout.Button(SpineInspectorUtility.TempContent("Attempt Reimport", Icons.warning))) {
DoReimport();
}
}
#else
EditorGUILayout.HelpBox("Couldn't load SkeletonData.", MessageType.Error);
#endif
// List warnings.
foreach (var line in warnings)
EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(line, Icons.warning));
}
if (!Application.isPlaying)
serializedObject.ApplyModifiedProperties();
}
void DrawUnityTools () {
#if SPINE_SKELETON_ANIMATOR
using (new SpineInspectorUtility.BoxScope()) {
isMecanimExpanded = EditorGUILayout.Foldout(isMecanimExpanded, SpineInspectorUtility.TempContent("SkeletonAnimator", SpineInspectorUtility.UnityIcon<SceneAsset>()));
if (isMecanimExpanded) {
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(controller, SpineInspectorUtility.TempContent("Controller", SpineInspectorUtility.UnityIcon<Animator>()));
if (controller.objectReferenceValue == null) {
// Generate Mecanim Controller Button
using (new GUILayout.HorizontalScope()) {
GUILayout.Space(EditorGUIUtility.labelWidth);
if (GUILayout.Button(SpineInspectorUtility.TempContent("Generate Mecanim Controller"), GUILayout.Height(20)))
SkeletonBaker.GenerateMecanimAnimationClips(m_skeletonDataAsset);
}
EditorGUILayout.HelpBox("SkeletonAnimator is the Mecanim alternative to SkeletonAnimation.\nIt is not required.", MessageType.Info);
} else {
// Update AnimationClips button.
using (new GUILayout.HorizontalScope()) {
GUILayout.Space(EditorGUIUtility.labelWidth);
if (GUILayout.Button(SpineInspectorUtility.TempContent("Force Update AnimationClips"), GUILayout.Height(20)))
SkeletonBaker.GenerateMecanimAnimationClips(m_skeletonDataAsset);
}
}
EditorGUI.indentLevel--;
}
}
#endif
}
void DoReimport () {
SpineEditorUtilities.ImportSpineContent(new string[] { AssetDatabase.GetAssetPath(skeletonJSON.objectReferenceValue) }, true);
if (m_previewUtility != null) {
m_previewUtility.Cleanup();
m_previewUtility = null;
}
OnEnable(); // Should call RepopulateWarnings.
EditorUtility.SetDirty(m_skeletonDataAsset);
}
void DrawAnimationStateInfo () {
using (new SpineInspectorUtility.IndentScope())
showAnimationStateData = EditorGUILayout.Foldout(showAnimationStateData, "Animation State Data");
if (!showAnimationStateData)
return;
EditorGUI.BeginChangeCheck();
using (new SpineInspectorUtility.IndentScope())
SpineInspectorUtility.PropertyFieldWideLabel(defaultMix, DefaultMixLabel, 160);
// Do not use EditorGUIUtility.indentLevel. It will add spaces on every field.
for (int i = 0; i < fromAnimation.arraySize; i++) {
SerializedProperty from = fromAnimation.GetArrayElementAtIndex(i);
SerializedProperty to = toAnimation.GetArrayElementAtIndex(i);
SerializedProperty durationProp = duration.GetArrayElementAtIndex(i);
using (new EditorGUILayout.HorizontalScope()) {
GUILayout.Space(16f);
EditorGUILayout.PropertyField(from, GUIContent.none);
EditorGUILayout.PropertyField(to, GUIContent.none);
durationProp.floatValue = EditorGUILayout.FloatField(durationProp.floatValue, GUILayout.MinWidth(25f), GUILayout.MaxWidth(60f));
if (GUILayout.Button("Delete", EditorStyles.miniButton)) {
duration.DeleteArrayElementAtIndex(i);
toAnimation.DeleteArrayElementAtIndex(i);
fromAnimation.DeleteArrayElementAtIndex(i);
}
}
}
using (new EditorGUILayout.HorizontalScope()) {
EditorGUILayout.Space();
if (GUILayout.Button("Add Mix")) {
duration.arraySize++;
toAnimation.arraySize++;
fromAnimation.arraySize++;
}
EditorGUILayout.Space();
}
if (EditorGUI.EndChangeCheck()) {
m_skeletonDataAsset.FillStateData();
EditorUtility.SetDirty(m_skeletonDataAsset);
serializedObject.ApplyModifiedProperties();
needToSerialize = true;
}
}
void DrawAnimationList () {
showAnimationList = EditorGUILayout.Foldout(showAnimationList, SpineInspectorUtility.TempContent(string.Format("Animations [{0}]", m_skeletonData.Animations.Count), Icons.animationRoot));
if (!showAnimationList)
return;
if (m_skeletonAnimation != null && m_skeletonAnimation.state != null) {
if (GUILayout.Button(SpineInspectorUtility.TempContent("Setup Pose", Icons.skeleton), GUILayout.Width(105), GUILayout.Height(18))) {
StopAnimation();
m_skeletonAnimation.skeleton.SetToSetupPose();
m_requireRefresh = true;
}
} else {
EditorGUILayout.HelpBox("Animations can be previewed if you expand the Preview window below.", MessageType.Info);
}
EditorGUILayout.LabelField("Name", " Duration");
foreach (Spine.Animation animation in m_skeletonData.Animations) {
using (new GUILayout.HorizontalScope()) {
if (m_skeletonAnimation != null && m_skeletonAnimation.state != null) {
var activeTrack = m_skeletonAnimation.state.GetCurrent(0);
if (activeTrack != null && activeTrack.Animation == animation) {
if (GUILayout.Button("\u25BA", activePlayButtonStyle, GUILayout.Width(24))) {
StopAnimation();
}
} else {
if (GUILayout.Button("\u25BA", idlePlayButtonStyle, GUILayout.Width(24))) {
PlayAnimation(animation.Name, true);
}
}
} else {
GUILayout.Label("-", GUILayout.Width(24));
}
EditorGUILayout.LabelField(new GUIContent(animation.Name, Icons.animation), SpineInspectorUtility.TempContent(animation.Duration.ToString("f3") + "s" + ("(" + (Mathf.RoundToInt(animation.Duration * 30)) + ")").PadLeft(12, ' ')));
}
}
}
void DrawSlotList () {
showSlotList = EditorGUILayout.Foldout(showSlotList, SpineInspectorUtility.TempContent("Slots", Icons.slotRoot));
if (!showSlotList) return;
if (m_skeletonAnimation == null || m_skeletonAnimation.skeleton == null) return;
EditorGUI.indentLevel++;
showAttachments = EditorGUILayout.ToggleLeft("Show Attachments", showAttachments);
var slotAttachments = new List<Attachment>();
var slotAttachmentNames = new List<string>();
var defaultSkinAttachmentNames = new List<string>();
var defaultSkin = m_skeletonData.Skins.Items[0];
Skin skin = m_skeletonAnimation.skeleton.Skin ?? defaultSkin;
var slotsItems = m_skeletonAnimation.skeleton.Slots.Items;
for (int i = m_skeletonAnimation.skeleton.Slots.Count - 1; i >= 0; i--) {
Slot slot = slotsItems[i];
EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(slot.Data.Name, Icons.slot));
if (showAttachments) {
EditorGUI.indentLevel++;
slotAttachments.Clear();
slotAttachmentNames.Clear();
defaultSkinAttachmentNames.Clear();
skin.FindNamesForSlot(i, slotAttachmentNames);
skin.FindAttachmentsForSlot(i, slotAttachments);
if (skin != defaultSkin) {
defaultSkin.FindNamesForSlot(i, defaultSkinAttachmentNames);
defaultSkin.FindNamesForSlot(i, slotAttachmentNames);
defaultSkin.FindAttachmentsForSlot(i, slotAttachments);
} else {
defaultSkin.FindNamesForSlot(i, defaultSkinAttachmentNames);
}
for (int a = 0; a < slotAttachments.Count; a++) {
Attachment attachment = slotAttachments[a];
string attachmentName = slotAttachmentNames[a];
Texture2D icon = Icons.GetAttachmentIcon(attachment);
bool initialState = slot.Attachment == attachment;
bool toggled = EditorGUILayout.ToggleLeft(SpineInspectorUtility.TempContent(attachmentName, icon), slot.Attachment == attachment);
if (!defaultSkinAttachmentNames.Contains(attachmentName)) {
Rect skinPlaceHolderIconRect = GUILayoutUtility.GetLastRect();
skinPlaceHolderIconRect.width = Icons.skinPlaceholder.width;
skinPlaceHolderIconRect.height = Icons.skinPlaceholder.height;
GUI.DrawTexture(skinPlaceHolderIconRect, Icons.skinPlaceholder);
}
if (toggled != initialState) {
slot.Attachment = toggled ? attachment : null;
m_requireRefresh = true;
}
}
EditorGUI.indentLevel--;
}
}
EditorGUI.indentLevel--;
}
void RepopulateWarnings () {
warnings.Clear();
if (skeletonJSON.objectReferenceValue == null) {
warnings.Add("Missing Skeleton JSON");
} else {
if (SpineEditorUtilities.IsSpineData((TextAsset)skeletonJSON.objectReferenceValue) == false) {
warnings.Add("Skeleton data file is not a valid JSON or binary file.");
} else {
#if SPINE_TK2D
bool searchForSpineAtlasAssets = true;
bool isSpriteCollectionNull = spriteCollection.objectReferenceValue == null;
if (!isSpriteCollectionNull) searchForSpineAtlasAssets = false;
#else
const bool searchForSpineAtlasAssets = true;
#endif
if (searchForSpineAtlasAssets) {
bool detectedNullAtlasEntry = false;
var atlasList = new List<Atlas>();
var actualAtlasAssets = m_skeletonDataAsset.atlasAssets;
for (int i = 0; i < actualAtlasAssets.Length; i++) {
if (m_skeletonDataAsset.atlasAssets[i] == null) {
detectedNullAtlasEntry = true;
break;
} else {
atlasList.Add(actualAtlasAssets[i].GetAtlas());
}
}
if (detectedNullAtlasEntry) {
warnings.Add("AtlasAsset elements should not be null.");
} else {
// Get requirements.
var missingPaths = SpineEditorUtilities.GetRequiredAtlasRegions(AssetDatabase.GetAssetPath((TextAsset)skeletonJSON.objectReferenceValue));
foreach (var atlas in atlasList) {
for (int i = 0; i < missingPaths.Count; i++) {
if (atlas.FindRegion(missingPaths[i]) != null) {
missingPaths.RemoveAt(i);
i--;
}
}
}
#if SPINE_TK2D
if (missingPaths.Count > 0)
warnings.Add("Missing regions. SkeletonDataAsset requires tk2DSpriteCollectionData or Spine AtlasAssets.");
#endif
foreach (var str in missingPaths)
warnings.Add("Missing Region: '" + str + "'");
}
}
}
}
}
#region Preview Window
PreviewRenderUtility m_previewUtility;
GameObject m_previewInstance;
Vector2 previewDir;
SkeletonAnimation m_skeletonAnimation;
static readonly int SliderHash = "Slider".GetHashCode();
float m_lastTime;
bool m_playing;
bool m_requireRefresh;
Color m_originColor = new Color(0.3f, 0.3f, 0.3f, 1);
Camera PreviewUtilityCamera {
get {
#if UNITY_2017_1_OR_NEWER
return m_previewUtility.camera;
#else
return m_previewUtility.m_Camera;
#endif
}
}
void StopAnimation () {
if (m_skeletonAnimation == null) {
Debug.LogWarning("Animation was stopped but preview doesn't exist. It's possible that the Preview Panel is closed.");
}
m_skeletonAnimation.state.ClearTrack(0);
m_playing = false;
}
List<Spine.Event> m_animEvents = new List<Spine.Event>();
List<float> m_animEventFrames = new List<float>();
void PlayAnimation (string animName, bool loop) {
m_animEvents.Clear();
m_animEventFrames.Clear();
m_skeletonAnimation.state.SetAnimation(0, animName, loop);
Spine.Animation a = m_skeletonAnimation.state.GetCurrent(0).Animation;
foreach (Timeline t in a.Timelines) {
if (t.GetType() == typeof(EventTimeline)) {
var et = (EventTimeline)t;
for (int i = 0; i < et.Events.Length; i++) {
m_animEvents.Add(et.Events[i]);
m_animEventFrames.Add(et.Frames[i]);
}
}
}
m_playing = true;
}
void InitPreview () {
if (this.m_previewUtility == null) {
this.m_lastTime = Time.realtimeSinceStartup;
this.m_previewUtility = new PreviewRenderUtility(true);
var c = this.PreviewUtilityCamera;
c.orthographic = true;
c.orthographicSize = 1;
c.cullingMask = -2147483648;
c.nearClipPlane = 0.01f;
c.farClipPlane = 1000f;
this.CreatePreviewInstances();
}
}
void CreatePreviewInstances () {
this.DestroyPreviewInstances();
if (warnings.Count > 0) {
m_skeletonDataAsset.Clear();
return;
}
var skeletonDataAsset = (SkeletonDataAsset)target;
if (skeletonDataAsset.GetSkeletonData(false) == null)
return;
if (this.m_previewInstance == null) {
string skinName = EditorPrefs.GetString(m_skeletonDataAssetGUID + "_lastSkin", "");
try {
m_previewInstance = SpineEditorUtilities.InstantiateSkeletonAnimation(skeletonDataAsset, skinName).gameObject;
if (m_previewInstance != null) {
m_previewInstance.hideFlags = HideFlags.HideAndDontSave;
m_previewInstance.layer = 0x1f;
m_skeletonAnimation = m_previewInstance.GetComponent<SkeletonAnimation>();
m_skeletonAnimation.initialSkinName = skinName;
m_skeletonAnimation.LateUpdate();
m_skeletonData = m_skeletonAnimation.skeletonDataAsset.GetSkeletonData(true);
m_previewInstance.GetComponent<Renderer>().enabled = false;
m_initialized = true;
}
AdjustCameraGoals(true);
} catch {
DestroyPreviewInstances();
}
}
}
void DestroyPreviewInstances () {
if (this.m_previewInstance != null) {
DestroyImmediate(this.m_previewInstance);
m_previewInstance = null;
}
m_initialized = false;
}
public override bool HasPreviewGUI () {
if (serializedObject.isEditingMultipleObjects) {
// JOHN: Implement multi-preview.
return false;
}
for (int i = 0; i < atlasAssets.arraySize; i++) {
var prop = atlasAssets.GetArrayElementAtIndex(i);
if (prop.objectReferenceValue == null)
return false;
}
return skeletonJSON.objectReferenceValue != null;
}
Texture m_previewTex = new Texture();
public override void OnInteractivePreviewGUI (Rect r, GUIStyle background) {
this.InitPreview();
if (Event.current.type == EventType.Repaint) {
if (m_requireRefresh) {
this.m_previewUtility.BeginPreview(r, background);
this.DoRenderPreview(true);
this.m_previewTex = this.m_previewUtility.EndPreview();
m_requireRefresh = false;
}
if (this.m_previewTex != null)
GUI.DrawTexture(r, m_previewTex, ScaleMode.StretchToFill, false);
}
DrawSkinToolbar(r);
NormalizedTimeBar(r);
// MITCH: left a todo: Implement panning
// this.previewDir = Drag2D(this.previewDir, r);
MouseScroll(r);
}
float m_orthoGoal = 1;
Vector3 m_posGoal = new Vector3(0, 0, -10);
double m_adjustFrameEndTime = 0;
void AdjustCameraGoals (bool calculateMixTime) {
if (this.m_previewInstance == null)
return;
if (calculateMixTime) {
if (m_skeletonAnimation.state.GetCurrent(0) != null)
m_adjustFrameEndTime = EditorApplication.timeSinceStartup + m_skeletonAnimation.state.GetCurrent(0).Alpha;
}
GameObject go = this.m_previewInstance;
Bounds bounds = go.GetComponent<Renderer>().bounds;
m_orthoGoal = bounds.size.y;
m_posGoal = bounds.center + new Vector3(0, 0, -10f);
}
void AdjustCameraGoals () {
AdjustCameraGoals(false);
}
void AdjustCamera () {
if (m_previewUtility == null)
return;
if (EditorApplication.timeSinceStartup < m_adjustFrameEndTime)
AdjustCameraGoals();
var c = this.PreviewUtilityCamera;
float orthoSet = Mathf.Lerp(c.orthographicSize, m_orthoGoal, 0.1f);
c.orthographicSize = orthoSet;
float dist = Vector3.Distance(c.transform.position, m_posGoal);
if(dist > 0f) {
Vector3 pos = Vector3.Lerp(c.transform.position, m_posGoal, 0.1f);
pos.x = 0;
c.transform.position = pos;
c.transform.rotation = Quaternion.identity;
m_requireRefresh = true;
}
}
void DoRenderPreview (bool drawHandles) {
GameObject go = this.m_previewInstance;
if (m_requireRefresh && go != null) {
go.GetComponent<Renderer>().enabled = true;
if (!EditorApplication.isPlaying)
m_skeletonAnimation.Update((Time.realtimeSinceStartup - m_lastTime));
m_lastTime = Time.realtimeSinceStartup;
if (!EditorApplication.isPlaying)
m_skeletonAnimation.LateUpdate();
var c = this.PreviewUtilityCamera;
if (drawHandles) {
Handles.SetCamera(c);
Handles.color = m_originColor;
Handles.DrawLine(new Vector3(-1000 * m_skeletonDataAsset.scale, 0, 0), new Vector3(1000 * m_skeletonDataAsset.scale, 0, 0));
Handles.DrawLine(new Vector3(0, 1000 * m_skeletonDataAsset.scale, 0), new Vector3(0, -1000 * m_skeletonDataAsset.scale, 0));
}
c.Render();
if (drawHandles) {
Handles.SetCamera(c);
SpineHandles.DrawBoundingBoxes(m_skeletonAnimation.transform, m_skeletonAnimation.skeleton);
if (showAttachments) SpineHandles.DrawPaths(m_skeletonAnimation.transform, m_skeletonAnimation.skeleton);
}
go.GetComponent<Renderer>().enabled = false;
}
}
void EditorUpdate () {
AdjustCamera();
if (m_playing) {
m_requireRefresh = true;
Repaint();
} else if (m_requireRefresh) {
Repaint();
}
//else {
//only needed if using smooth menus
//}
if (needToSerialize) {
needToSerialize = false;
serializedObject.ApplyModifiedProperties();
}
}
void DrawSkinToolbar (Rect r) {
if (m_skeletonAnimation == null)
return;
if (m_skeletonAnimation.skeleton != null) {
string label = (m_skeletonAnimation.skeleton != null && m_skeletonAnimation.skeleton.Skin != null) ? m_skeletonAnimation.skeleton.Skin.Name : "default";
Rect popRect = new Rect(r);
popRect.y += 32;
popRect.x += 4;
popRect.height = 24;
popRect.width = 40;
EditorGUI.DropShadowLabel(popRect, SpineInspectorUtility.TempContent("Skin"));
popRect.y += 11;
popRect.width = 150;
popRect.x += 44;
if (GUI.Button(popRect, SpineInspectorUtility.TempContent(label, Icons.skin), EditorStyles.popup)) {
DrawSkinDropdown();
}
}
}
void NormalizedTimeBar (Rect r) {
if (m_skeletonAnimation == null)
return;
Rect barRect = new Rect(r);
barRect.height = 32;
barRect.x += 4;
barRect.width -= 4;
GUI.Box(barRect, "");
Rect lineRect = new Rect(barRect);
float width = lineRect.width;
TrackEntry t = m_skeletonAnimation.state.GetCurrent(0);
if (t != null) {
int loopCount = (int)(t.TrackTime / t.TrackEnd);
float currentTime = t.TrackTime - (t.TrackEnd * loopCount);
float normalizedTime = currentTime / t.Animation.Duration;
float wrappedTime = normalizedTime % 1;
lineRect.x = barRect.x + (width * wrappedTime) - 0.5f;
lineRect.width = 2;
GUI.color = Color.red;
GUI.DrawTexture(lineRect, EditorGUIUtility.whiteTexture);
GUI.color = Color.white;
for (int i = 0; i < m_animEvents.Count; i++) {
float fr = m_animEventFrames[i];
var evRect = new Rect(barRect);
evRect.x = Mathf.Clamp(((fr / t.Animation.Duration) * width) - (Icons.userEvent.width / 2), barRect.x, float.MaxValue);
evRect.width = Icons.userEvent.width;
evRect.height = Icons.userEvent.height;
evRect.y += Icons.userEvent.height;
GUI.DrawTexture(evRect, Icons.userEvent);
Event ev = Event.current;
if (ev.type == EventType.Repaint) {
if (evRect.Contains(ev.mousePosition)) {
Rect tooltipRect = new Rect(evRect);
GUIStyle tooltipStyle = EditorStyles.helpBox;
tooltipRect.width = tooltipStyle.CalcSize(new GUIContent(m_animEvents[i].Data.Name)).x;
tooltipRect.y -= 4;
tooltipRect.x += 4;
GUI.Label(tooltipRect, m_animEvents[i].Data.Name, tooltipStyle);
GUI.tooltip = m_animEvents[i].Data.Name;
}
}
}
}
}
void MouseScroll (Rect position) {
Event current = Event.current;
int controlID = GUIUtility.GetControlID(SliderHash, FocusType.Passive);
switch (current.GetTypeForControl(controlID)) {
case EventType.ScrollWheel:
if (position.Contains(current.mousePosition)) {
m_orthoGoal += current.delta.y * 0.06f;
m_orthoGoal = Mathf.Max(0.01f, m_orthoGoal);
GUIUtility.hotControl = controlID;
current.Use();
}
break;
}
}
// MITCH: left todo: Implement preview panning
/*
static Vector2 Drag2D(Vector2 scrollPosition, Rect position)
{
int controlID = GUIUtility.GetControlID(sliderHash, FocusType.Passive);
UnityEngine.Event current = UnityEngine.Event.current;
switch (current.GetTypeForControl(controlID))
{
case EventType.MouseDown:
if (position.Contains(current.mousePosition) && (position.width > 50f))
{
GUIUtility.hotControl = controlID;
current.Use();
EditorGUIUtility.SetWantsMouseJumping(1);
}
return scrollPosition;
case EventType.MouseUp:
if (GUIUtility.hotControl == controlID)
{
GUIUtility.hotControl = 0;
}
EditorGUIUtility.SetWantsMouseJumping(0);
return scrollPosition;
case EventType.MouseMove:
return scrollPosition;
case EventType.MouseDrag:
if (GUIUtility.hotControl == controlID)
{
scrollPosition -= (Vector2) (((current.delta * (!current.shift ? ((float) 1) : ((float) 3))) / Mathf.Min(position.width, position.height)) * 140f);
scrollPosition.y = Mathf.Clamp(scrollPosition.y, -90f, 90f);
current.Use();
GUI.changed = true;
}
return scrollPosition;
}
return scrollPosition;
}
*/
public override GUIContent GetPreviewTitle () {
return SpineInspectorUtility.TempContent("Preview");
}
public override void OnPreviewSettings () {
const float SliderWidth = 100;
if (!m_initialized) {
GUILayout.HorizontalSlider(0, 0, 2, GUILayout.MaxWidth(SliderWidth));
} else {
float speed = GUILayout.HorizontalSlider(m_skeletonAnimation.timeScale, 0, 2, GUILayout.MaxWidth(SliderWidth));
const float SliderSnap = 0.25f;
float y = speed / SliderSnap;
int q = Mathf.RoundToInt(y);
speed = q * SliderSnap;
m_skeletonAnimation.timeScale = speed;
}
}
public override Texture2D RenderStaticPreview (string assetPath, UnityEngine.Object[] subAssets, int width, int height) {
var tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
this.InitPreview();
var c = this.PreviewUtilityCamera;
if (c == null)
return null;
m_requireRefresh = true;
this.DoRenderPreview(false);
AdjustCameraGoals(false);
c.orthographicSize = m_orthoGoal / 2;
c.transform.position = m_posGoal;
this.m_previewUtility.BeginStaticPreview(new Rect(0, 0, width, height));
this.DoRenderPreview(false);
tex = this.m_previewUtility.EndStaticPreview();
return tex;
}
#endregion
#region Skin Dropdown Context Menu
void DrawSkinDropdown () {
var menu = new GenericMenu();
foreach (Skin s in m_skeletonData.Skins)
menu.AddItem(new GUIContent(s.Name, Icons.skin), this.m_skeletonAnimation.skeleton.Skin == s, SetSkin, s);
menu.ShowAsContext();
}
void SetSkin (object o) {
Skin skin = (Skin)o;
m_skeletonAnimation.initialSkinName = skin.Name;
m_skeletonAnimation.Initialize(true);
m_requireRefresh = true;
EditorPrefs.SetString(m_skeletonDataAssetGUID + "_lastSkin", skin.Name);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using GalaSoft.MvvmLight.Messaging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Rebus.Messages;
using Rebus.Shared;
using Rebus.Snoop.Compression;
using Rebus.Snoop.Events;
using Rebus.Snoop.ViewModel.Models;
using Message = Rebus.Snoop.ViewModel.Models.Message;
namespace Rebus.Snoop.Listeners
{
public class MsmqInteraction
{
public MsmqInteraction()
{
Messenger.Default.Register(this, (MachineAdded newMachineCreated) => LoadQueues(newMachineCreated.Machine));
Messenger.Default.Register(this, (ReloadQueuesRequested request) => LoadQueues(request.Machine));
Messenger.Default.Register(this, (ReloadMessagesRequested request) => LoadMessages(request.Queue));
Messenger.Default.Register(this, (MoveMessagesToSourceQueueRequested request) => MoveMessagesToSourceQueues(request.MessagesToMove));
Messenger.Default.Register(this, (MoveMessagesToQueueRequested request) => MoveMessagesToQueue(request.MessagesToMove, true));
Messenger.Default.Register(this, (CopyMessagesToQueueRequested request) => MoveMessagesToQueue(request.MessagesToMove, false));
Messenger.Default.Register(this, (DeleteMessagesRequested request) => DeleteMessages(request.MessagesToMove));
Messenger.Default.Register(this, (DownloadMessagesRequested request) => DownloadMessages(request.MessagesToDownload));
Messenger.Default.Register(this, (UpdateMessageRequested request) => UpdateMessage(request.Message, request.Queue));
Messenger.Default.Register(this, (PurgeMessagesRequested request) => PurgeMessages(request.Queue));
Messenger.Default.Register(this, (DeleteQueueRequested request) => DeleteQueue(request.Queue));
}
void DeleteQueue(Queue queue)
{
var isOk = IsOkWithUser("This will DELETE the queue {0} completely - press OK to continue...",
queue.QueueName);
if (!isOk)
{
return;
}
Task.Factory
.StartNew(() =>
{
try
{
MessageQueue.Delete(queue.QueuePath);
return new
{
Success = true,
Notification = NotificationEvent.Success("Queue {0} was deleted", queue.QueueName)
};
}
catch (Exception e)
{
return new
{
Success = false,
Notification = NotificationEvent.Fail(e.ToString(),
"Something went wrong while attempting to delete queue {0}",
queue.QueueName),
};
}
})
.ContinueWith(r =>
{
var result = r.Result;
Messenger.Default.Send(result.Notification);
if (result.Success)
{
Messenger.Default.Send(new QueueDeleted(queue));
}
}, Context.UiThread);
}
void PurgeMessages(Queue queue)
{
var isOk = IsOkWithUser("This will delete all the messages from the queue {0} - press OK to continue...",
queue.QueueName);
if (!isOk)
{
return;
}
Task.Factory
.StartNew(() =>
{
try
{
using (var msmqQueue = new MessageQueue(queue.QueuePath))
{
msmqQueue.Purge();
}
return new
{
Notification =
NotificationEvent.Success("Queue {0} was purged", queue.QueueName),
Success = true,
};
}
catch (Exception e)
{
return new
{
Notification = NotificationEvent.Fail(e.ToString(),
"Something went wrong while attempting to purge queue {0}",
queue.QueueName),
Success = false,
};
}
})
.ContinueWith(r =>
{
var result = r.Result;
Messenger.Default.Send(result.Notification);
if (result.Success)
{
Messenger.Default.Send(new QueuePurged(queue));
}
}, Context.UiThread);
}
static bool IsOkWithUser(string question, params object[] objs)
{
var text = string.Format(question, objs);
var messageBoxResult = MessageBox.Show(text, "Question", MessageBoxButton.OKCancel);
return messageBoxResult == MessageBoxResult.OK;
}
void UpdateMessage(Message message, Queue queueToReload)
{
Task.Factory
.StartNew(() =>
{
if (!message.CouldDeserializeBody)
{
throw new InvalidOperationException(
string.Format(
"Body of message with ID {0} was not properly deserialized, so it's not safe to try to update it...",
message.Id));
}
using (var queue = new MessageQueue(message.QueuePath))
{
queue.MessageReadPropertyFilter = LosslessFilter();
using (var transaction = new MessageQueueTransaction())
{
transaction.Begin();
try
{
var msmqMessage = queue.ReceiveById(message.Id, transaction);
var newMsmqMessage =
new System.Messaging.Message
{
Label = msmqMessage.Label,
Extension = msmqMessage.Extension,
TimeToBeReceived = msmqMessage.TimeToBeReceived,
UseDeadLetterQueue = msmqMessage.UseDeadLetterQueue,
UseJournalQueue = msmqMessage.UseJournalQueue,
};
EncodeBody(newMsmqMessage, message);
queue.Send(newMsmqMessage, transaction);
transaction.Commit();
}
catch
{
transaction.Abort();
throw;
}
}
}
return new
{
Message = message,
Queue = queueToReload,
Notification =
NotificationEvent.Success("Fetched message with ID {0} and put an updated version back in the queue", message.Id),
};
})
.ContinueWith(a =>
{
if (a.Exception != null)
{
Messenger.Default.Send(NotificationEvent.Fail(a.Exception.ToString(),
"Something went wrong while attempting to update message with ID {0}",
message.Id));
return;
}
var result = a.Result;
Messenger.Default.Send(new ReloadMessagesRequested(result.Queue));
Messenger.Default.Send(result.Notification);
}, Context.UiThread);
}
void DownloadMessages(List<Message> messages)
{
Task.Factory
.StartNew(() =>
{
// for now, just settle with using the desktop
var directory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
Func<int, string> getName = i => Path.Combine("Snoop Message Export", string.Format("export-{0}", i));
var counter = 1;
var directoryName = getName(counter);
while (Directory.Exists(Path.Combine(directory, directoryName)))
{
directoryName = getName(++counter);
}
var directoryToSaveMessagesTo =
new DirectoryInfo(directory).CreateSubdirectory(directoryName);
return new
{
Directory = directoryToSaveMessagesTo,
Messages = messages,
Success = true,
Exception = default(Exception),
};
})
.ContinueWith(a =>
{
var result = a.Result;
foreach (var message in result.Messages)
{
File.WriteAllText(Path.Combine(result.Directory.FullName, GenerateFileName(message)),
FormatMessage(message));
}
return NotificationEvent.Success("Successfully downloaded {0} messages into {1}",
result.Messages.Count,
result.Directory);
})
.ContinueWith(a =>
{
if (a.Exception != null)
{
Messenger.Default.Send(NotificationEvent.Fail(a.Exception.ToString(),
"Something went wrong while attempting to download the messages"));
return;
}
Messenger.Default.Send(a.Result);
}, Context.UiThread);
}
string GenerateFileName(Message message)
{
var fileName = message.Id.Replace("\\", "---");
return string.Format("{0}.txt", fileName);
}
string FormatMessage(Message message)
{
return string.Format(@"ID: {0}
Headers:
{1}
Body:
{2}", message.Id,
string.Join(Environment.NewLine,
message.Headers.Select(h => string.Format(" {0}: {1}", h.Key, h.Value))),
message.Body);
}
void DeleteMessages(List<Message> messages)
{
Task.Factory
.StartNew(() =>
{
var result = new
{
Deleted = new List<Message>(),
Failed = new List<Tuple<Message, string>>(),
};
foreach (var messageToDelete in messages)
{
try
{
DeleteMessage(messageToDelete);
result.Deleted.Add(messageToDelete);
}
catch (Exception e)
{
result.Failed.Add(new Tuple<Message, string>(messageToDelete, e.ToString()));
}
}
return result;
})
.ContinueWith(t =>
{
var result = t.Result;
if (result.Failed.Any())
{
var details = string.Join(Environment.NewLine,
result.Failed.Select(
f => string.Format("Id {0}: {1}", f.Item1.Id, f.Item2)));
return NotificationEvent.Fail(details, "{0} messages deleted - {1} delete operations failed",
result.Deleted.Count, result.Failed.Count);
}
return NotificationEvent.Success("{0} messages moved", result.Deleted.Count);
})
.ContinueWith(t => Messenger.Default.Send(t.Result), Context.UiThread);
}
void MoveMessagesToSourceQueues(IEnumerable<Message> messagesToMove)
{
Task.Factory
.StartNew(() =>
{
var canBeMoved = messagesToMove
.Where(m => m.Headers.ContainsKey(Headers.SourceQueue));
var result = new
{
Moved = new List<Message>(),
Failed = new List<Tuple<Message, string>>(),
};
foreach (var message in canBeMoved)
{
try
{
MoveMessageToSourceQueue(message);
result.Moved.Add(message);
}
catch (Exception e)
{
result.Failed.Add(new Tuple<Message, string>(message, e.ToString()));
}
}
return result;
})
.ContinueWith(t =>
{
var result = t.Result;
if (result.Failed.Any())
{
var details = string.Join(Environment.NewLine, result.Failed.Select(f => string.Format("Id {0}: {1}", f.Item1.Id, f.Item2)));
return NotificationEvent.Fail(details, "{0} messages moved - {1} move operations failed", result.Moved.Count, result.Failed.Count);
}
return NotificationEvent.Success("{0} messages moved", result.Moved.Count);
})
.ContinueWith(t => Messenger.Default.Send(t.Result), Context.UiThread);
}
void MoveMessagesToQueue(List<Message> messagesToMove, bool shouldMoveMessages)
{
Task.Factory
.StartNew(() => messagesToMove)
.ContinueWith(t =>
{
var promptMessage =
string.Format("{0} {1} message(s) - please enter destination queue (e.g. 'someQueue@someMachine'): ",
shouldMoveMessages ? "Moving" : "Copying", messagesToMove.Count);
var destinationQueue = Prompt(promptMessage);
return new
{
DestinationQueue = destinationQueue,
Messages = t.Result
};
}, Context.UiThread)
.ContinueWith(t =>
{
var result = new
{
Moved = new List<Message>(),
Failed = new List<Tuple<Message, string>>(),
DestinationQueue = t.Result.DestinationQueue,
};
if (string.IsNullOrEmpty(t.Result.DestinationQueue))
{
result.Failed.AddRange(t.Result.Messages.Select(m => Tuple.Create(m, "No destination queue entered")));
return result;
}
foreach (var message in t.Result.Messages)
{
try
{
var leaveCopyInSourceQueue = !shouldMoveMessages;
MoveMessage(message, t.Result.DestinationQueue, leaveCopyInSourceQueue);
result.Moved.Add(message);
}
catch (Exception e)
{
result.Failed.Add(new Tuple<Message, string>(message, e.ToString()));
}
}
return result;
})
.ContinueWith(t =>
{
var result = t.Result;
if (result.Failed.Any())
{
var details = string.Join(Environment.NewLine,
result.Failed.Select(
f => string.Format("Id {0}: {1}", f.Item1.Id, f.Item2)));
return NotificationEvent.Fail(details,
"{0} messages moved to {1} - {2} move operations failed",
result.Moved.Count, result.DestinationQueue,
result.Failed.Count);
}
return NotificationEvent.Success("{0} messages moved to {1}", result.Moved.Count,
result.DestinationQueue);
})
.ContinueWith(t => Messenger.Default.Send(t.Result), Context.UiThread);
}
string Prompt(string text)
{
var dialog = new PromptDialog { PromptText = text };
dialog.ShowDialog();
return dialog.ResultText;
}
void DeleteMessage(Message message)
{
using (var queue = new MessageQueue(message.QueuePath))
using (var transaction = new MessageQueueTransaction())
{
transaction.Begin();
try
{
queue.ReceiveById(message.Id, transaction);
transaction.Commit();
}
catch
{
transaction.Abort();
throw;
}
}
Messenger.Default.Send(new MessageDeleted(message));
}
void MoveMessageToSourceQueue(Message message)
{
MoveMessage(message, message.Headers[Headers.SourceQueue], false);
}
static void MoveMessage(Message message, string destinationQueueName, bool leaveCopyInSourceQueue)
{
var sourceQueuePath = message.QueuePath;
var destinationQueuePath = MsmqUtil.GetFullPath(destinationQueueName);
using (var transaction = new MessageQueueTransaction())
{
transaction.Begin();
try
{
var sourceQueue = new MessageQueue(sourceQueuePath) { MessageReadPropertyFilter = DefaultFilter() };
var destinationQueue = new MessageQueue(destinationQueuePath);
var msmqMessage = sourceQueue.ReceiveById(message.Id, transaction);
destinationQueue.Send(msmqMessage, transaction);
if (leaveCopyInSourceQueue)
{
sourceQueue.Send(msmqMessage, transaction);
}
transaction.Commit();
}
catch
{
transaction.Abort();
throw;
}
}
Messenger.Default.Send(new MessageMoved(message, sourceQueuePath, destinationQueuePath, leaveCopyInSourceQueue));
}
void LoadMessages(Queue queue)
{
Task.Factory
.StartNew(() =>
{
var messageQueue = new MessageQueue(queue.QueuePath);
messageQueue.MessageReadPropertyFilter = DefaultFilter();
var list = new List<Message>();
using (var enumerator = messageQueue.GetMessageEnumerator2())
{
while (enumerator.MoveNext())
{
var message = enumerator.Current;
var messageViewModel = GenerateMessage(message, queue.QueuePath);
messageViewModel.ResetDirtyFlags();
list.Add(messageViewModel);
}
}
return new { Messages = list };
})
.ContinueWith(t =>
{
if (t.Exception == null)
{
var result = t.Result;
queue.SetMessages(result.Messages);
return NotificationEvent.Success("{0} messages loaded from {1}",
result.Messages.Count,
queue.QueueName);
}
var details = t.Exception.ToString();
return NotificationEvent.Fail(details, "Could not load messages from {0}: {1}",
queue.QueueName,
t.Exception);
}, Context.UiThread)
.ContinueWith(t => Messenger.Default.Send(t.Result), Context.UiThread);
}
static MessagePropertyFilter DefaultFilter()
{
return new MessagePropertyFilter
{
Label = true,
ArrivedTime = true,
Extension = true,
Body = true,
Id = true,
};
}
static MessagePropertyFilter LosslessFilter()
{
return new MessagePropertyFilter
{
Label = true,
ArrivedTime = true,
Extension = true,
Body = true,
Id = true,
UseDeadLetterQueue = true,
UseJournalQueue = true,
TimeToBeReceived = true,
};
}
Message GenerateMessage(System.Messaging.Message message, string queuePath)
{
try
{
Dictionary<string, string> headers;
var couldDeserializeHeaders = TryDeserializeHeaders(message, out headers);
string body;
int bodySize;
var couldDecodeBody = TryDecodeBody(message, headers, out body, out bodySize);
return new Message
{
Label = message.Label,
Time = message.ArrivedTime,
Headers = couldDeserializeHeaders ? new EditableDictionary<string, string>(headers) : new EditableDictionary<string, string>(),
Bytes = bodySize,
Body = body,
Id = message.Id,
QueuePath = queuePath,
CouldDeserializeBody = couldDecodeBody,
CouldDeserializeHeaders = couldDeserializeHeaders,
};
}
catch (Exception e)
{
return new Message
{
Body = string.Format(@"Message could not be properly decoded:
{0}", e)
};
}
}
void EncodeBody(System.Messaging.Message message, Message messageModel)
{
var headers = messageModel.Headers;
var body = messageModel.Body;
if (headers.ContainsKey(Headers.ContentType))
{
var encoding = headers[Headers.ContentType];
var encoder = GetEncoding(encoding);
message.BodyStream = new MemoryStream(encoder.GetBytes(body));
}
}
static Encoding GetEncoding(string contentType)
{
var contentTypeSettings = contentType
.Split(';')
.Select(token => token.Split('='))
.Where(tokens => tokens.Length == 2)
.ToDictionary(tokens => tokens[0], tokens => tokens[1], StringComparer.InvariantCultureIgnoreCase);
var encoding = contentTypeSettings.ContainsKey("charset")
? Encoding.GetEncoding(contentTypeSettings["charset"])
: Encoding.ASCII;
return encoding;
}
bool TryDecodeBody(System.Messaging.Message message, Dictionary<string, string> headers, out string body, out int bodySize)
{
try
{
if (headers == null)
{
body = "Message has no headers that can be understood by Rebus";
bodySize = GetLengthFromStreamIfPossible(message);
return false;
}
if (!headers.ContainsKey(Headers.ContentType))
{
body = string.Format("Message headers don't contain an element with the '{0}' key", Headers.ContentType);
bodySize = GetLengthFromStreamIfPossible(message);
return false;
}
var destination = new MemoryStream();
message.BodyStream.CopyTo(destination);
var bytes = destination.ToArray();
var bodyIsGzipped = headers.ContainsKey(Headers.ContentEncoding) &&
string.Equals(headers[Headers.ContentEncoding], "gzip", StringComparison.InvariantCultureIgnoreCase);
if (bodyIsGzipped)
{
bytes = new Zipper().Unzip(bytes);
}
var encoding = headers[Headers.ContentType];
var encoder = GetEncoding(encoding);
var str = encoder.GetString(bytes);
body = TryToIndentJson(str);
bodySize = bytes.Length;
return true;
}
catch (Exception e)
{
body = string.Format("An error occurred while decoding the body: {0}", e);
bodySize = GetLengthFromStreamIfPossible(message);
return false;
}
}
string TryToIndentJson(string jsonText)
{
try
{
return JsonConvert.SerializeObject(JsonConvert.DeserializeObject<JObject>(jsonText), Formatting.Indented);
}
catch
{
return jsonText;
}
}
static int GetLengthFromStreamIfPossible(System.Messaging.Message message)
{
try
{
return (int) message.BodyStream.Length;
}
catch
{
return -1;
}
}
bool TryDeserializeHeaders(System.Messaging.Message message, out Dictionary<string, string> dictionary)
{
try
{
var headersAsJsonString = Encoding.UTF7.GetString(message.Extension);
var headers = JsonConvert.DeserializeObject<Dictionary<string, string>>(headersAsJsonString);
dictionary = headers;
return true;
}
catch
{
dictionary = null;
return false;
}
}
void LoadQueues(Machine machine)
{
Task.Factory
.StartNew(() =>
{
var queues = MessageQueue
.GetPrivateQueuesByMachine(machine.MachineName)
.Concat(new[]
{
// don't add non-transactional dead letter queue - wouldn't be safe!
//new MessageQueue(string.Format(@"FormatName:DIRECT=OS:{0}\SYSTEM$;DeadLetter", machine.MachineName)),
new MessageQueue(string.Format(@"FormatName:DIRECT=OS:{0}\SYSTEM$;DeadXact", machine.MachineName)),
})
.ToArray();
return queues;
})
.ContinueWith(t =>
{
if (!t.IsFaulted)
{
try
{
var queues = t.Result
.Select(queue =>
{
try
{
return new Queue(queue);
}
catch (Exception e)
{
throw new ApplicationException(string.Format("An error occurred while loading message queue {0}", queue.Path), e);
}
});
machine.SetQueues(queues);
return NotificationEvent.Success("{0} queues loaded from {1}",
t.Result.Length,
machine.MachineName);
}
catch (Exception e)
{
return NotificationEvent.Fail(e.ToString(), "Could not load queues from {0}: {1}",
machine.MachineName, e.Message);
}
}
return NotificationEvent.Fail(t.Exception.ToString(), "Could not load queues from {0}: {1}",
machine.MachineName, t.Exception.Message);
}, Context.UiThread)
.ContinueWith(t => Messenger.Default.Send(t.Result), Context.UiThread);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.Drawing2D.GraphicsPath.cs
//
// Authors:
//
// Miguel de Icaza ([email protected])
// Duncan Mak ([email protected])
// Jordi Mas i Hernandez ([email protected])
// Ravindra ([email protected])
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2004,2006-2007 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.ComponentModel;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing.Drawing2D
{
public sealed class GraphicsPath : MarshalByRefObject, ICloneable, IDisposable
{
// 1/4 is the FlatnessDefault as defined in GdiPlusEnums.h
private const float FlatnessDefault = 1.0f / 4.0f;
internal IntPtr _nativePath = IntPtr.Zero;
private GraphicsPath(IntPtr ptr)
{
_nativePath = ptr;
}
public GraphicsPath()
{
int status = Gdip.GdipCreatePath(FillMode.Alternate, out _nativePath);
Gdip.CheckStatus(status);
}
public GraphicsPath(FillMode fillMode)
{
int status = Gdip.GdipCreatePath(fillMode, out _nativePath);
Gdip.CheckStatus(status);
}
public GraphicsPath(Point[] pts, byte[] types)
: this(pts, types, FillMode.Alternate)
{
}
public GraphicsPath(PointF[] pts, byte[] types)
: this(pts, types, FillMode.Alternate)
{
}
public GraphicsPath(Point[] pts, byte[] types, FillMode fillMode)
{
if (pts == null)
throw new ArgumentNullException(nameof(pts));
if (pts.Length != types.Length)
throw new ArgumentException("Invalid parameter passed. Number of points and types must be same.");
int status = Gdip.GdipCreatePath2I(pts, types, pts.Length, fillMode, out _nativePath);
Gdip.CheckStatus(status);
}
public GraphicsPath(PointF[] pts, byte[] types, FillMode fillMode)
{
if (pts == null)
throw new ArgumentNullException(nameof(pts));
if (pts.Length != types.Length)
throw new ArgumentException("Invalid parameter passed. Number of points and types must be same.");
int status = Gdip.GdipCreatePath2(pts, types, pts.Length, fillMode, out _nativePath);
Gdip.CheckStatus(status);
}
public object Clone()
{
IntPtr clone;
int status = Gdip.GdipClonePath(_nativePath, out clone);
Gdip.CheckStatus(status);
return new GraphicsPath(clone);
}
public void Dispose()
{
Dispose(true);
System.GC.SuppressFinalize(this);
}
~GraphicsPath()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
int status;
if (_nativePath != IntPtr.Zero)
{
status = Gdip.GdipDeletePath(new HandleRef(this, _nativePath));
Gdip.CheckStatus(status);
_nativePath = IntPtr.Zero;
}
}
public FillMode FillMode
{
get
{
FillMode mode;
int status = Gdip.GdipGetPathFillMode(_nativePath, out mode);
Gdip.CheckStatus(status);
return mode;
}
set
{
if ((value < FillMode.Alternate) || (value > FillMode.Winding))
throw new InvalidEnumArgumentException("FillMode", (int)value, typeof(FillMode));
int status = Gdip.GdipSetPathFillMode(_nativePath, value);
Gdip.CheckStatus(status);
}
}
public PathData PathData
{
get
{
int count;
int status = Gdip.GdipGetPointCount(_nativePath, out count);
Gdip.CheckStatus(status);
PointF[] points = new PointF[count];
byte[] types = new byte[count];
// status would fail if we ask points or types with a 0 count
// anyway that would only mean two unrequired unmanaged calls
if (count > 0)
{
status = Gdip.GdipGetPathPoints(_nativePath, points, count);
Gdip.CheckStatus(status);
status = Gdip.GdipGetPathTypes(_nativePath, types, count);
Gdip.CheckStatus(status);
}
PathData pdata = new PathData();
pdata.Points = points;
pdata.Types = types;
return pdata;
}
}
public PointF[] PathPoints
{
get
{
int count;
int status = Gdip.GdipGetPointCount(_nativePath, out count);
Gdip.CheckStatus(status);
if (count == 0)
throw new ArgumentException("PathPoints");
PointF[] points = new PointF[count];
status = Gdip.GdipGetPathPoints(_nativePath, points, count);
Gdip.CheckStatus(status);
return points;
}
}
public byte[] PathTypes
{
get
{
int count;
int status = Gdip.GdipGetPointCount(_nativePath, out count);
Gdip.CheckStatus(status);
if (count == 0)
throw new ArgumentException("PathTypes");
byte[] types = new byte[count];
status = Gdip.GdipGetPathTypes(_nativePath, types, count);
Gdip.CheckStatus(status);
return types;
}
}
public int PointCount
{
get
{
int count;
int status = Gdip.GdipGetPointCount(_nativePath, out count);
Gdip.CheckStatus(status);
return count;
}
}
internal IntPtr NativeObject
{
get
{
return _nativePath;
}
set
{
_nativePath = value;
}
}
//
// AddArc
//
public void AddArc(Rectangle rect, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathArcI(_nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
public void AddArc(RectangleF rect, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathArc(_nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
public void AddArc(int x, int y, int width, int height, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathArcI(_nativePath, x, y, width, height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
public void AddArc(float x, float y, float width, float height, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathArc(_nativePath, x, y, width, height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
//
// AddBezier
//
public void AddBezier(Point pt1, Point pt2, Point pt3, Point pt4)
{
int status = Gdip.GdipAddPathBezierI(_nativePath, pt1.X, pt1.Y,
pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y);
Gdip.CheckStatus(status);
}
public void AddBezier(PointF pt1, PointF pt2, PointF pt3, PointF pt4)
{
int status = Gdip.GdipAddPathBezier(_nativePath, pt1.X, pt1.Y,
pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y);
Gdip.CheckStatus(status);
}
public void AddBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
{
int status = Gdip.GdipAddPathBezierI(_nativePath, x1, y1, x2, y2, x3, y3, x4, y4);
Gdip.CheckStatus(status);
}
public void AddBezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4)
{
int status = Gdip.GdipAddPathBezier(_nativePath, x1, y1, x2, y2, x3, y3, x4, y4);
Gdip.CheckStatus(status);
}
//
// AddBeziers
//
public void AddBeziers(params Point[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathBeziersI(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddBeziers(PointF[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathBeziers(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
//
// AddEllipse
//
public void AddEllipse(RectangleF rect)
{
int status = Gdip.GdipAddPathEllipse(_nativePath, rect.X, rect.Y, rect.Width, rect.Height);
Gdip.CheckStatus(status);
}
public void AddEllipse(float x, float y, float width, float height)
{
int status = Gdip.GdipAddPathEllipse(_nativePath, x, y, width, height);
Gdip.CheckStatus(status);
}
public void AddEllipse(Rectangle rect)
{
int status = Gdip.GdipAddPathEllipseI(_nativePath, rect.X, rect.Y, rect.Width, rect.Height);
Gdip.CheckStatus(status);
}
public void AddEllipse(int x, int y, int width, int height)
{
int status = Gdip.GdipAddPathEllipseI(_nativePath, x, y, width, height);
Gdip.CheckStatus(status);
}
//
// AddLine
//
public void AddLine(Point pt1, Point pt2)
{
int status = Gdip.GdipAddPathLineI(_nativePath, pt1.X, pt1.Y, pt2.X, pt2.Y);
Gdip.CheckStatus(status);
}
public void AddLine(PointF pt1, PointF pt2)
{
int status = Gdip.GdipAddPathLine(_nativePath, pt1.X, pt1.Y, pt2.X,
pt2.Y);
Gdip.CheckStatus(status);
}
public void AddLine(int x1, int y1, int x2, int y2)
{
int status = Gdip.GdipAddPathLineI(_nativePath, x1, y1, x2, y2);
Gdip.CheckStatus(status);
}
public void AddLine(float x1, float y1, float x2, float y2)
{
int status = Gdip.GdipAddPathLine(_nativePath, x1, y1, x2,
y2);
Gdip.CheckStatus(status);
}
//
// AddLines
//
public void AddLines(Point[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
if (points.Length == 0)
throw new ArgumentException(nameof(points));
int status = Gdip.GdipAddPathLine2I(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddLines(PointF[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
if (points.Length == 0)
throw new ArgumentException(nameof(points));
int status = Gdip.GdipAddPathLine2(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
//
// AddPie
//
public void AddPie(Rectangle rect, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathPie(
_nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
public void AddPie(int x, int y, int width, int height, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathPieI(_nativePath, x, y, width, height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
public void AddPie(float x, float y, float width, float height, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathPie(_nativePath, x, y, width, height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
//
// AddPolygon
//
public void AddPolygon(Point[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathPolygonI(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddPolygon(PointF[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathPolygon(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
//
// AddRectangle
//
public void AddRectangle(Rectangle rect)
{
int status = Gdip.GdipAddPathRectangleI(_nativePath, rect.X, rect.Y, rect.Width, rect.Height);
Gdip.CheckStatus(status);
}
public void AddRectangle(RectangleF rect)
{
int status = Gdip.GdipAddPathRectangle(_nativePath, rect.X, rect.Y, rect.Width, rect.Height);
Gdip.CheckStatus(status);
}
//
// AddRectangles
//
public void AddRectangles(Rectangle[] rects)
{
if (rects == null)
throw new ArgumentNullException(nameof(rects));
if (rects.Length == 0)
throw new ArgumentException(nameof(rects));
int status = Gdip.GdipAddPathRectanglesI(_nativePath, rects, rects.Length);
Gdip.CheckStatus(status);
}
public void AddRectangles(RectangleF[] rects)
{
if (rects == null)
throw new ArgumentNullException(nameof(rects));
if (rects.Length == 0)
throw new ArgumentException(nameof(rects));
int status = Gdip.GdipAddPathRectangles(_nativePath, rects, rects.Length);
Gdip.CheckStatus(status);
}
//
// AddPath
//
public void AddPath(GraphicsPath addingPath, bool connect)
{
if (addingPath == null)
throw new ArgumentNullException(nameof(addingPath));
int status = Gdip.GdipAddPathPath(_nativePath, addingPath._nativePath, connect);
Gdip.CheckStatus(status);
}
public PointF GetLastPoint()
{
PointF pt;
int status = Gdip.GdipGetPathLastPoint(_nativePath, out pt);
Gdip.CheckStatus(status);
return pt;
}
//
// AddClosedCurve
//
public void AddClosedCurve(Point[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathClosedCurveI(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddClosedCurve(PointF[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathClosedCurve(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddClosedCurve(Point[] points, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathClosedCurve2I(_nativePath, points, points.Length, tension);
Gdip.CheckStatus(status);
}
public void AddClosedCurve(PointF[] points, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathClosedCurve2(_nativePath, points, points.Length, tension);
Gdip.CheckStatus(status);
}
//
// AddCurve
//
public void AddCurve(Point[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurveI(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddCurve(PointF[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurve(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddCurve(Point[] points, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurve2I(_nativePath, points, points.Length, tension);
Gdip.CheckStatus(status);
}
public void AddCurve(PointF[] points, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurve2(_nativePath, points, points.Length, tension);
Gdip.CheckStatus(status);
}
public void AddCurve(Point[] points, int offset, int numberOfSegments, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurve3I(_nativePath, points, points.Length,
offset, numberOfSegments, tension);
Gdip.CheckStatus(status);
}
public void AddCurve(PointF[] points, int offset, int numberOfSegments, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurve3(_nativePath, points, points.Length,
offset, numberOfSegments, tension);
Gdip.CheckStatus(status);
}
public void Reset()
{
int status = Gdip.GdipResetPath(_nativePath);
Gdip.CheckStatus(status);
}
public void Reverse()
{
int status = Gdip.GdipReversePath(_nativePath);
Gdip.CheckStatus(status);
}
public void Transform(Matrix matrix)
{
if (matrix == null)
throw new ArgumentNullException(nameof(matrix));
int status = Gdip.GdipTransformPath(_nativePath, matrix.NativeMatrix);
Gdip.CheckStatus(status);
}
public void AddString(string s, FontFamily family, int style, float emSize, Point origin, StringFormat format)
{
Rectangle layout = new Rectangle();
layout.X = origin.X;
layout.Y = origin.Y;
AddString(s, family, style, emSize, layout, format);
}
public void AddString(string s, FontFamily family, int style, float emSize, PointF origin, StringFormat format)
{
RectangleF layout = new RectangleF();
layout.X = origin.X;
layout.Y = origin.Y;
AddString(s, family, style, emSize, layout, format);
}
public void AddString(string s, FontFamily family, int style, float emSize, Rectangle layoutRect, StringFormat format)
{
if (family == null)
throw new ArgumentException(nameof(family));
IntPtr sformat = (format == null) ? IntPtr.Zero : format.nativeFormat;
// note: the NullReferenceException on s.Length is the expected (MS) exception
int status = Gdip.GdipAddPathStringI(_nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat);
Gdip.CheckStatus(status);
}
public void AddString(string s, FontFamily family, int style, float emSize, RectangleF layoutRect, StringFormat format)
{
if (family == null)
throw new ArgumentException(nameof(family));
IntPtr sformat = (format == null) ? IntPtr.Zero : format.nativeFormat;
// note: the NullReferenceException on s.Length is the expected (MS) exception
int status = Gdip.GdipAddPathString(_nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat);
Gdip.CheckStatus(status);
}
public void ClearMarkers()
{
int s = Gdip.GdipClearPathMarkers(_nativePath);
Gdip.CheckStatus(s);
}
public void CloseAllFigures()
{
int s = Gdip.GdipClosePathFigures(_nativePath);
Gdip.CheckStatus(s);
}
public void CloseFigure()
{
int s = Gdip.GdipClosePathFigure(_nativePath);
Gdip.CheckStatus(s);
}
public void Flatten()
{
Flatten(null, FlatnessDefault);
}
public void Flatten(Matrix matrix)
{
Flatten(matrix, FlatnessDefault);
}
public void Flatten(Matrix matrix, float flatness)
{
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.NativeMatrix;
int status = Gdip.GdipFlattenPath(_nativePath, m, flatness);
Gdip.CheckStatus(status);
}
public RectangleF GetBounds()
{
return GetBounds(null, null);
}
public RectangleF GetBounds(Matrix matrix)
{
return GetBounds(matrix, null);
}
public RectangleF GetBounds(Matrix matrix, Pen pen)
{
RectangleF retval;
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.NativeMatrix;
IntPtr p = (pen == null) ? IntPtr.Zero : pen.NativePen;
int s = Gdip.GdipGetPathWorldBounds(_nativePath, out retval, m, p);
Gdip.CheckStatus(s);
return retval;
}
public bool IsOutlineVisible(Point point, Pen pen)
{
return IsOutlineVisible(point.X, point.Y, pen, null);
}
public bool IsOutlineVisible(PointF point, Pen pen)
{
return IsOutlineVisible(point.X, point.Y, pen, null);
}
public bool IsOutlineVisible(int x, int y, Pen pen)
{
return IsOutlineVisible(x, y, pen, null);
}
public bool IsOutlineVisible(float x, float y, Pen pen)
{
return IsOutlineVisible(x, y, pen, null);
}
public bool IsOutlineVisible(Point pt, Pen pen, Graphics graphics)
{
return IsOutlineVisible(pt.X, pt.Y, pen, graphics);
}
public bool IsOutlineVisible(PointF pt, Pen pen, Graphics graphics)
{
return IsOutlineVisible(pt.X, pt.Y, pen, graphics);
}
public bool IsOutlineVisible(int x, int y, Pen pen, Graphics graphics)
{
if (pen == null)
throw new ArgumentNullException(nameof(pen));
bool result;
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.NativeGraphics;
int s = Gdip.GdipIsOutlineVisiblePathPointI(_nativePath, x, y, pen.NativePen, g, out result);
Gdip.CheckStatus(s);
return result;
}
public bool IsOutlineVisible(float x, float y, Pen pen, Graphics graphics)
{
if (pen == null)
throw new ArgumentNullException(nameof(pen));
bool result;
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.NativeGraphics;
int s = Gdip.GdipIsOutlineVisiblePathPoint(_nativePath, x, y, pen.NativePen, g, out result);
Gdip.CheckStatus(s);
return result;
}
public bool IsVisible(Point point)
{
return IsVisible(point.X, point.Y, null);
}
public bool IsVisible(PointF point)
{
return IsVisible(point.X, point.Y, null);
}
public bool IsVisible(int x, int y)
{
return IsVisible(x, y, null);
}
public bool IsVisible(float x, float y)
{
return IsVisible(x, y, null);
}
public bool IsVisible(Point pt, Graphics graphics)
{
return IsVisible(pt.X, pt.Y, graphics);
}
public bool IsVisible(PointF pt, Graphics graphics)
{
return IsVisible(pt.X, pt.Y, graphics);
}
public bool IsVisible(int x, int y, Graphics graphics)
{
bool retval;
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.NativeGraphics;
int s = Gdip.GdipIsVisiblePathPointI(_nativePath, x, y, g, out retval);
Gdip.CheckStatus(s);
return retval;
}
public bool IsVisible(float x, float y, Graphics graphics)
{
bool retval;
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.NativeGraphics;
int s = Gdip.GdipIsVisiblePathPoint(_nativePath, x, y, g, out retval);
Gdip.CheckStatus(s);
return retval;
}
public void SetMarkers()
{
int s = Gdip.GdipSetPathMarker(_nativePath);
Gdip.CheckStatus(s);
}
public void StartFigure()
{
int s = Gdip.GdipStartPathFigure(_nativePath);
Gdip.CheckStatus(s);
}
public void Warp(PointF[] destPoints, RectangleF srcRect)
{
Warp(destPoints, srcRect, null, WarpMode.Perspective, FlatnessDefault);
}
public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix)
{
Warp(destPoints, srcRect, matrix, WarpMode.Perspective, FlatnessDefault);
}
public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix, WarpMode warpMode)
{
Warp(destPoints, srcRect, matrix, warpMode, FlatnessDefault);
}
public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix, WarpMode warpMode, float flatness)
{
if (destPoints == null)
throw new ArgumentNullException(nameof(destPoints));
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.NativeMatrix;
int s = Gdip.GdipWarpPath(_nativePath, m, destPoints, destPoints.Length,
srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, warpMode, flatness);
Gdip.CheckStatus(s);
}
public void Widen(Pen pen)
{
Widen(pen, null, FlatnessDefault);
}
public void Widen(Pen pen, Matrix matrix)
{
Widen(pen, matrix, FlatnessDefault);
}
public void Widen(Pen pen, Matrix matrix, float flatness)
{
if (pen == null)
throw new ArgumentNullException(nameof(pen));
if (PointCount == 0)
return;
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.NativeMatrix;
int s = Gdip.GdipWidenPath(_nativePath, pen.NativePen, m, flatness);
Gdip.CheckStatus(s);
}
}
}
| |
/*
* 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.Common
{
using System;
using System.Globalization;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Event;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Datastream;
using Apache.Ignite.Core.Messaging;
/// <summary>
/// Type descriptor with precompiled delegates for known methods.
/// </summary>
internal class DelegateTypeDescriptor
{
/** Cached descriptors. */
private static readonly CopyOnWriteConcurrentDictionary<Type, DelegateTypeDescriptor> Descriptors
= new CopyOnWriteConcurrentDictionary<Type, DelegateTypeDescriptor>();
/** */
private readonly Func<object, object> _computeOutFunc;
/** */
private readonly Func<object, object, object> _computeFunc;
/** */
private readonly Func<object, object, bool> _eventFilter;
/** */
private readonly Func<object, object, object, bool> _cacheEntryFilter;
/** */
private readonly Tuple<Func<object, IMutableCacheEntryInternal, object, object>, Tuple<Type, Type>>
_cacheEntryProcessor;
/** */
private readonly Func<object, Guid, object, bool> _messageLsnr;
/** */
private readonly Func<object, object> _computeJobExecute;
/** */
private readonly Action<object> _computeJobCancel;
/** */
private readonly Action<object, Ignite, IPlatformTargetInternal, IBinaryStream, bool> _streamReceiver;
/** */
private readonly Func<object, object> _streamTransformerCtor;
/** */
private readonly Func<object, object, object> _continuousQueryFilterCtor;
/// <summary>
/// Gets the <see cref="IComputeFunc{T}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object> GetComputeOutFunc(Type type)
{
return Get(type)._computeOutFunc;
}
/// <summary>
/// Gets the <see cref="IComputeFunc{T, R}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object, object> GetComputeFunc(Type type)
{
return Get(type)._computeFunc;
}
/// <summary>
/// Gets the <see cref="IEventFilter{T}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object, bool> GetEventFilter(Type type)
{
return Get(type)._eventFilter;
}
/// <summary>
/// Gets the <see cref="ICacheEntryFilter{TK,TV}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object, object, bool> GetCacheEntryFilter(Type type)
{
return Get(type)._cacheEntryFilter;
}
/// <summary>
/// Gets the <see cref="ICacheEntryProcessor{K, V, A, R}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, IMutableCacheEntryInternal, object, object> GetCacheEntryProcessor(Type type)
{
return Get(type)._cacheEntryProcessor.Item1;
}
/// <summary>
/// Gets key and value types for the <see cref="ICacheEntryProcessor{K, V, A, R}" />.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Key and value types.</returns>
public static Tuple<Type, Type> GetCacheEntryProcessorTypes(Type type)
{
return Get(type)._cacheEntryProcessor.Item2;
}
/// <summary>
/// Gets the <see cref="IMessageListener{T}" /> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, Guid, object, bool> GetMessageListener(Type type)
{
return Get(type)._messageLsnr;
}
/// <summary>
/// Gets the <see cref="IComputeJob{T}.Execute" /> and <see cref="IComputeJob{T}.Cancel" /> invocators.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="execute">Execute invocator.</param>
/// <param name="cancel">Cancel invocator.</param>
public static void GetComputeJob(Type type, out Func<object, object> execute, out Action<object> cancel)
{
var desc = Get(type);
execute = desc._computeJobExecute;
cancel = desc._computeJobCancel;
}
/// <summary>
/// Gets the <see cref="IStreamReceiver{TK,TV}"/> invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Action<object, Ignite, IPlatformTargetInternal, IBinaryStream, bool> GetStreamReceiver(Type type)
{
return Get(type)._streamReceiver;
}
/// <summary>
/// Gets the <see cref="StreamTransformer{K, V, A, R}"/>> ctor invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object> GetStreamTransformerCtor(Type type)
{
return Get(type)._streamTransformerCtor;
}
/// <summary>
/// Gets the <see cref="ContinuousQueryFilter{TK,TV}"/>> ctor invocator.
/// </summary>
/// <param name="type">Type.</param>
/// <returns>Precompiled invocator delegate.</returns>
public static Func<object, object, object> GetContinuousQueryFilterCtor(Type type)
{
return Get(type)._continuousQueryFilterCtor;
}
/// <summary>
/// Gets the <see cref="DelegateTypeDescriptor" /> by type.
/// </summary>
private static DelegateTypeDescriptor Get(Type type)
{
DelegateTypeDescriptor result;
return Descriptors.TryGetValue(type, out result)
? result
: Descriptors.GetOrAdd(type, t => new DelegateTypeDescriptor(t));
}
/// <summary>
/// Throws an exception if first argument is not null.
/// </summary>
// ReSharper disable once UnusedParameter.Local
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
private static void ThrowIfMultipleInterfaces(object check, Type userType, Type interfaceType)
{
if (check != null)
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"Not Supported: Type {0} implements interface {1} multiple times.", userType, interfaceType));
}
/// <summary>
/// Initializes a new instance of the <see cref="DelegateTypeDescriptor"/> class.
/// </summary>
/// <param name="type">The type.</param>
private DelegateTypeDescriptor(Type type)
{
foreach (var iface in type.GetInterfaces())
{
if (!iface.IsGenericType)
continue;
var genericTypeDefinition = iface.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof (IComputeFunc<>))
{
ThrowIfMultipleInterfaces(_computeOutFunc, type, typeof(IComputeFunc<>));
_computeOutFunc = DelegateConverter.CompileFunc(iface);
}
else if (genericTypeDefinition == typeof (IComputeFunc<,>))
{
ThrowIfMultipleInterfaces(_computeFunc, type, typeof(IComputeFunc<,>));
var args = iface.GetGenericArguments();
_computeFunc = DelegateConverter.CompileFunc<Func<object, object, object>>(iface, new[] {args[0]});
}
else if (genericTypeDefinition == typeof (IEventFilter<>))
{
ThrowIfMultipleInterfaces(_eventFilter, type, typeof(IEventFilter<>));
var args = iface.GetGenericArguments();
_eventFilter = DelegateConverter.CompileFunc<Func<object, object, bool>>(iface,
new[] {args[0]}, new[] {true, false});
}
else if (genericTypeDefinition == typeof (ICacheEntryFilter<,>))
{
ThrowIfMultipleInterfaces(_cacheEntryFilter, type, typeof(ICacheEntryFilter<,>));
var args = iface.GetGenericArguments();
var entryType = typeof (ICacheEntry<,>).MakeGenericType(args);
var invokeFunc = DelegateConverter.CompileFunc<Func<object, object, bool>>(iface,
new[] { entryType }, new[] { true, false });
var ctor = DelegateConverter.CompileCtor<Func<object, object, object>>(
typeof (CacheEntry<,>).MakeGenericType(args), args);
// Resulting func constructs CacheEntry and passes it to user implementation
_cacheEntryFilter = (obj, k, v) => invokeFunc(obj, ctor(k, v));
}
else if (genericTypeDefinition == typeof (ICacheEntryProcessor<,,,>))
{
ThrowIfMultipleInterfaces(_cacheEntryProcessor, type, typeof(ICacheEntryProcessor<,,,>));
var args = iface.GetGenericArguments();
var entryType = typeof (IMutableCacheEntry<,>).MakeGenericType(args[0], args[1]);
var func = DelegateConverter.CompileFunc<Func<object, object, object, object>>(iface,
new[] { entryType, args[2] }, null, "Process");
var types = new Tuple<Type, Type>(args[0], args[1]);
_cacheEntryProcessor = new Tuple<Func<object, IMutableCacheEntryInternal, object, object>, Tuple<Type, Type>>
(func, types);
var transformerType = typeof (StreamTransformer<,,,>).MakeGenericType(args);
_streamTransformerCtor = DelegateConverter.CompileCtor<Func<object, object>>(transformerType,
new[] {iface});
}
else if (genericTypeDefinition == typeof (IMessageListener<>))
{
ThrowIfMultipleInterfaces(_messageLsnr, type, typeof(IMessageListener<>));
var arg = iface.GetGenericArguments()[0];
_messageLsnr = DelegateConverter.CompileFunc<Func<object, Guid, object, bool>>(iface,
new[] { typeof(Guid), arg }, new[] { false, true, false });
}
else if (genericTypeDefinition == typeof (IComputeJob<>))
{
ThrowIfMultipleInterfaces(_messageLsnr, type, typeof(IComputeJob<>));
_computeJobExecute = DelegateConverter.CompileFunc<Func<object, object>>(iface, new Type[0],
methodName: "Execute");
_computeJobCancel = DelegateConverter.CompileFunc<Action<object>>(iface, new Type[0],
new[] {false}, "Cancel");
}
else if (genericTypeDefinition == typeof (IStreamReceiver<,>))
{
ThrowIfMultipleInterfaces(_streamReceiver, type, typeof (IStreamReceiver<,>));
var method =
typeof (StreamReceiverHolder).GetMethod("InvokeReceiver")
.MakeGenericMethod(iface.GetGenericArguments());
_streamReceiver = DelegateConverter
.CompileFunc<Action<object, Ignite, IPlatformTargetInternal, IBinaryStream, bool>>(
typeof (StreamReceiverHolder),
method,
new[]
{
iface, typeof (Ignite), typeof (IPlatformTargetInternal), typeof (IBinaryStream),
typeof (bool)
},
new[] {true, false, false, false, false, false});
}
else if (genericTypeDefinition == typeof (ICacheEntryEventFilter<,>))
{
ThrowIfMultipleInterfaces(_streamReceiver, type, typeof(ICacheEntryEventFilter<,>));
var args = iface.GetGenericArguments();
_continuousQueryFilterCtor =
DelegateConverter.CompileCtor<Func<object, object, object>>(
typeof(ContinuousQueryFilter<,>).MakeGenericType(args), new[] { iface, typeof(bool) });
}
}
}
}
}
| |
namespace Wikipedia
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.renderWindowControl1 = new Kitware.VTK.RenderWindowControl();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
this.toolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox();
this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel();
this.toolStripTextBox2 = new System.Windows.Forms.ToolStripTextBox();
this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel();
this.toolStripTextBox3 = new System.Windows.Forms.ToolStripTextBox();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.webBrowser1 = new System.Windows.Forms.WebBrowser();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.toolStrip1.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// renderWindowControl1
//
this.renderWindowControl1.AddTestActors = false;
this.renderWindowControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.renderWindowControl1.Location = new System.Drawing.Point(0, 0);
this.renderWindowControl1.Name = "renderWindowControl1";
this.renderWindowControl1.Size = new System.Drawing.Size(512, 743);
this.renderWindowControl1.TabIndex = 0;
this.renderWindowControl1.TestText = null;
this.renderWindowControl1.Load += new System.EventHandler(this.renderWindowControl1_Load);
//
// toolStrip1
//
this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripLabel1,
this.toolStripTextBox1,
this.toolStripLabel2,
this.toolStripTextBox2,
this.toolStripLabel3,
this.toolStripTextBox3,
this.toolStripButton1});
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(1024, 25);
this.toolStrip1.TabIndex = 1;
this.toolStrip1.Text = "toolStrip1";
//
// toolStripLabel1
//
this.toolStripLabel1.Name = "toolStripLabel1";
this.toolStripLabel1.Size = new System.Drawing.Size(77, 22);
this.toolStripLabel1.Text = "Origin Article";
//
// toolStripTextBox1
//
this.toolStripTextBox1.Name = "toolStripTextBox1";
this.toolStripTextBox1.Size = new System.Drawing.Size(200, 25);
this.toolStripTextBox1.Text = "Kevin Bacon";
this.toolStripTextBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.toolStripTextBox1_KeyPress);
//
// toolStripLabel2
//
this.toolStripLabel2.Name = "toolStripLabel2";
this.toolStripLabel2.Size = new System.Drawing.Size(91, 22);
this.toolStripLabel2.Text = "Links Per Article";
//
// toolStripTextBox2
//
this.toolStripTextBox2.Name = "toolStripTextBox2";
this.toolStripTextBox2.Size = new System.Drawing.Size(36, 25);
this.toolStripTextBox2.Text = "7";
this.toolStripTextBox2.TextBoxTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.toolStripTextBox2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.toolStripTextBox2_KeyPress);
//
// toolStripLabel3
//
this.toolStripLabel3.Name = "toolStripLabel3";
this.toolStripLabel3.Size = new System.Drawing.Size(98, 22);
this.toolStripLabel3.Text = "Number Of Hops";
//
// toolStripTextBox3
//
this.toolStripTextBox3.Name = "toolStripTextBox3";
this.toolStripTextBox3.Size = new System.Drawing.Size(36, 25);
this.toolStripTextBox3.Text = "2";
this.toolStripTextBox3.TextBoxTextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.toolStripTextBox3.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.toolStripTextBox3_KeyPress);
//
// toolStripButton1
//
this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Size = new System.Drawing.Size(42, 22);
this.toolStripButton1.Text = "Go";
this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click);
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.Location = new System.Drawing.Point(0, 25);
this.splitContainer1.Margin = new System.Windows.Forms.Padding(0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.renderWindowControl1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.webBrowser1);
this.splitContainer1.Size = new System.Drawing.Size(1024, 743);
this.splitContainer1.SplitterDistance = 512;
this.splitContainer1.TabIndex = 2;
//
// webBrowser1
//
this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
this.webBrowser1.Location = new System.Drawing.Point(0, 0);
this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
this.webBrowser1.Name = "webBrowser1";
this.webBrowser1.Size = new System.Drawing.Size(508, 743);
this.webBrowser1.TabIndex = 0;
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Interval = 500;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1024, 768);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.toolStrip1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Wikipedia Browser";
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
this.Activated += new System.EventHandler(this.Form1_Activated);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed);
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Kitware.VTK.RenderWindowControl renderWindowControl1;
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripLabel toolStripLabel1;
private System.Windows.Forms.ToolStripTextBox toolStripTextBox1;
private System.Windows.Forms.ToolStripLabel toolStripLabel2;
private System.Windows.Forms.ToolStripTextBox toolStripTextBox2;
private System.Windows.Forms.ToolStripLabel toolStripLabel3;
private System.Windows.Forms.ToolStripTextBox toolStripTextBox3;
private System.Windows.Forms.ToolStripButton toolStripButton1;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.WebBrowser webBrowser1;
private System.Windows.Forms.Timer timer1;
}
}
| |
/*
* 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.Reflection;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.IO;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.ServiceAuth;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using log4net;
using OpenMetaverse;
using System.Threading;
namespace OpenSim.Server.Handlers.Inventory
{
public class XInventoryInConnector : ServiceConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IInventoryService m_InventoryService;
private string m_ConfigName = "InventoryService";
public XInventoryInConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server, configName)
{
if (configName != String.Empty)
m_ConfigName = configName;
m_log.DebugFormat("[XInventoryInConnector]: Starting with config name {0}", m_ConfigName);
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null)
throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string inventoryService = serverConfig.GetString("LocalServiceModule",
String.Empty);
if (inventoryService == String.Empty)
throw new Exception("No InventoryService in config file");
Object[] args = new Object[] { config, m_ConfigName };
m_InventoryService =
ServerUtils.LoadPlugin<IInventoryService>(inventoryService, args);
IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName);
server.AddStreamHandler(new XInventoryConnectorPostHandler(m_InventoryService, auth));
}
}
public class XInventoryConnectorPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IInventoryService m_InventoryService;
public XInventoryConnectorPostHandler(IInventoryService service, IServiceAuth auth) :
base("POST", "/xinventory", auth)
{
m_InventoryService = service;
}
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
string body;
using(StreamReader sr = new StreamReader(requestData))
body = sr.ReadToEnd();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
request.Remove("METHOD");
switch (method)
{
case "CREATEUSERINVENTORY":
return HandleCreateUserInventory(request);
case "GETINVENTORYSKELETON":
return HandleGetInventorySkeleton(request);
case "GETROOTFOLDER":
return HandleGetRootFolder(request);
case "GETFOLDERFORTYPE":
return HandleGetFolderForType(request);
case "GETFOLDERCONTENT":
return HandleGetFolderContent(request);
case "GETMULTIPLEFOLDERSCONTENT":
return HandleGetMultipleFoldersContent(request);
case "GETFOLDERITEMS":
return HandleGetFolderItems(request);
case "ADDFOLDER":
return HandleAddFolder(request);
case "UPDATEFOLDER":
return HandleUpdateFolder(request);
case "MOVEFOLDER":
return HandleMoveFolder(request);
case "DELETEFOLDERS":
return HandleDeleteFolders(request);
case "PURGEFOLDER":
return HandlePurgeFolder(request);
case "ADDITEM":
return HandleAddItem(request);
case "UPDATEITEM":
return HandleUpdateItem(request);
case "MOVEITEMS":
return HandleMoveItems(request);
case "DELETEITEMS":
return HandleDeleteItems(request);
case "GETITEM":
return HandleGetItem(request);
case "GETMULTIPLEITEMS":
return HandleGetMultipleItems(request);
case "GETFOLDER":
return HandleGetFolder(request);
case "GETACTIVEGESTURES":
return HandleGetActiveGestures(request);
case "GETASSETPERMISSIONS":
return HandleGetAssetPermissions(request);
}
m_log.DebugFormat("[XINVENTORY HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.Error(string.Format("[XINVENTORY HANDLER]: Exception {0} ", e.Message), e);
}
return FailureResult();
}
private byte[] FailureResult()
{
return BoolResult(false);
}
private byte[] SuccessResult()
{
return BoolResult(true);
}
private byte[] BoolResult(bool value)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "RESULT", "");
result.AppendChild(doc.CreateTextNode(value.ToString()));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
byte[] HandleCreateUserInventory(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
if (!request.ContainsKey("PRINCIPAL"))
return FailureResult();
if (m_InventoryService.CreateUserInventory(new UUID(request["PRINCIPAL"].ToString())))
result["RESULT"] = "True";
else
result["RESULT"] = "False";
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetInventorySkeleton(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
if (!request.ContainsKey("PRINCIPAL"))
return FailureResult();
List<InventoryFolderBase> folders = m_InventoryService.GetInventorySkeleton(new UUID(request["PRINCIPAL"].ToString()));
Dictionary<string, object> sfolders = new Dictionary<string, object>();
if (folders != null)
{
int i = 0;
foreach (InventoryFolderBase f in folders)
{
sfolders["folder_" + i.ToString()] = EncodeFolder(f);
i++;
}
}
result["FOLDERS"] = sfolders;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetRootFolder(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
InventoryFolderBase rfolder = m_InventoryService.GetRootFolder(principal);
if (rfolder != null)
result["folder"] = EncodeFolder(rfolder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetFolderForType(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
int type = 0;
Int32.TryParse(request["TYPE"].ToString(), out type);
InventoryFolderBase folder = m_InventoryService.GetFolderForType(principal, (FolderType)type);
if (folder != null)
result["folder"] = EncodeFolder(folder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetFolderContent(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID folderID = UUID.Zero;
UUID.TryParse(request["FOLDER"].ToString(), out folderID);
InventoryCollection icoll = m_InventoryService.GetFolderContent(principal, folderID);
if (icoll != null)
{
result["FID"] = icoll.FolderID.ToString();
result["VERSION"] = icoll.Version.ToString();
Dictionary<string, object> folders = new Dictionary<string, object>();
int i = 0;
if (icoll.Folders != null)
{
foreach (InventoryFolderBase f in icoll.Folders)
{
folders["folder_" + i.ToString()] = EncodeFolder(f);
i++;
}
result["FOLDERS"] = folders;
}
if (icoll.Items != null)
{
i = 0;
Dictionary<string, object> items = new Dictionary<string, object>();
foreach (InventoryItemBase it in icoll.Items)
{
items["item_" + i.ToString()] = EncodeItem(it);
i++;
}
result["ITEMS"] = items;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetMultipleFoldersContent(Dictionary<string, object> request)
{
Dictionary<string, object> resultSet = new Dictionary<string, object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
string folderIDstr = request["FOLDERS"].ToString();
int count = 0;
Int32.TryParse(request["COUNT"].ToString(), out count);
UUID[] fids = new UUID[count];
string[] uuids = folderIDstr.Split(',');
int i = 0;
foreach (string id in uuids)
{
UUID fid = UUID.Zero;
if (UUID.TryParse(id, out fid))
fids[i] = fid;
i += 1;
}
count = 0;
InventoryCollection[] icollList = m_InventoryService.GetMultipleFoldersContent(principal, fids);
if (icollList != null && icollList.Length > 0)
{
foreach (InventoryCollection icoll in icollList)
{
Dictionary<string, object> result = new Dictionary<string, object>();
result["FID"] = icoll.FolderID.ToString();
result["VERSION"] = icoll.Version.ToString();
result["OWNER"] = icoll.OwnerID.ToString();
Dictionary<string, object> folders = new Dictionary<string, object>();
i = 0;
if (icoll.Folders != null)
{
foreach (InventoryFolderBase f in icoll.Folders)
{
folders["folder_" + i.ToString()] = EncodeFolder(f);
i++;
}
result["FOLDERS"] = folders;
}
i = 0;
if (icoll.Items != null)
{
Dictionary<string, object> items = new Dictionary<string, object>();
foreach (InventoryItemBase it in icoll.Items)
{
items["item_" + i.ToString()] = EncodeItem(it);
i++;
}
result["ITEMS"] = items;
}
resultSet["F_" + fids[count++]] = result;
//m_log.DebugFormat("[XXX]: Sending {0} {1}", fids[count-1], icoll.FolderID);
}
}
string xmlString = ServerUtils.BuildXmlResponse(resultSet);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetFolderItems(Dictionary<string, object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID folderID = UUID.Zero;
UUID.TryParse(request["FOLDER"].ToString(), out folderID);
List<InventoryItemBase> items = m_InventoryService.GetFolderItems(principal, folderID);
Dictionary<string, object> sitems = new Dictionary<string, object>();
if (items != null)
{
int i = 0;
foreach (InventoryItemBase item in items)
{
sitems["item_" + i.ToString()] = EncodeItem(item);
i++;
}
}
result["ITEMS"] = sitems;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleAddFolder(Dictionary<string,object> request)
{
InventoryFolderBase folder = BuildFolder(request);
if (m_InventoryService.AddFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleUpdateFolder(Dictionary<string,object> request)
{
InventoryFolderBase folder = BuildFolder(request);
if (m_InventoryService.UpdateFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleMoveFolder(Dictionary<string,object> request)
{
UUID parentID = UUID.Zero;
UUID.TryParse(request["ParentID"].ToString(), out parentID);
UUID folderID = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out folderID);
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
InventoryFolderBase folder = new InventoryFolderBase(folderID, "", principal, parentID);
if (m_InventoryService.MoveFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleDeleteFolders(Dictionary<string,object> request)
{
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<string> slist = (List<string>)request["FOLDERS"];
List<UUID> uuids = new List<UUID>();
foreach (string s in slist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
uuids.Add(u);
}
if (m_InventoryService.DeleteFolders(principal, uuids))
return SuccessResult();
else
return
FailureResult();
}
byte[] HandlePurgeFolder(Dictionary<string,object> request)
{
UUID folderID = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out folderID);
InventoryFolderBase folder = new InventoryFolderBase(folderID);
if (m_InventoryService.PurgeFolder(folder))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleAddItem(Dictionary<string,object> request)
{
InventoryItemBase item = BuildItem(request);
if (m_InventoryService.AddItem(item))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleUpdateItem(Dictionary<string,object> request)
{
InventoryItemBase item = BuildItem(request);
if (m_InventoryService.UpdateItem(item))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleMoveItems(Dictionary<string,object> request)
{
List<string> idlist = (List<string>)request["IDLIST"];
List<string> destlist = (List<string>)request["DESTLIST"];
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<InventoryItemBase> items = new List<InventoryItemBase>();
int n = 0;
try
{
foreach (string s in idlist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
{
UUID fid = UUID.Zero;
if (UUID.TryParse(destlist[n++], out fid))
{
InventoryItemBase item = new InventoryItemBase(u, principal);
item.Folder = fid;
items.Add(item);
}
}
}
}
catch (Exception e)
{
m_log.DebugFormat("[XINVENTORY IN CONNECTOR]: Exception in HandleMoveItems: {0}", e.Message);
return FailureResult();
}
if (m_InventoryService.MoveItems(principal, items))
return SuccessResult();
else
return FailureResult();
}
byte[] HandleDeleteItems(Dictionary<string,object> request)
{
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<string> slist = (List<string>)request["ITEMS"];
List<UUID> uuids = new List<UUID>();
foreach (string s in slist)
{
UUID u = UUID.Zero;
if (UUID.TryParse(s, out u))
uuids.Add(u);
}
if (m_InventoryService.DeleteItems(principal, uuids))
return SuccessResult();
else
return
FailureResult();
}
byte[] HandleGetItem(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID id = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out id);
UUID user = UUID.Zero;
if (request.ContainsKey("PRINCIPAL"))
UUID.TryParse(request["PRINCIPAL"].ToString(), out user);
InventoryItemBase item = m_InventoryService.GetItem(user, id);
if (item != null)
result["item"] = EncodeItem(item);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetMultipleItems(Dictionary<string, object> request)
{
Dictionary<string, object> resultSet = new Dictionary<string, object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
string itemIDstr = request["ITEMS"].ToString();
int count = 0;
Int32.TryParse(request["COUNT"].ToString(), out count);
UUID[] fids = new UUID[count];
string[] uuids = itemIDstr.Split(',');
int i = 0;
foreach (string id in uuids)
{
UUID fid = UUID.Zero;
if (UUID.TryParse(id, out fid))
fids[i] = fid;
i += 1;
}
InventoryItemBase[] itemsList = m_InventoryService.GetMultipleItems(principal, fids);
if (itemsList != null && itemsList.Length > 0)
{
count = 0;
foreach (InventoryItemBase item in itemsList)
resultSet["item_" + count++] = (item == null) ? (object)"NULL" : EncodeItem(item);
}
string xmlString = ServerUtils.BuildXmlResponse(resultSet);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetFolder(Dictionary<string,object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
UUID id = UUID.Zero;
UUID.TryParse(request["ID"].ToString(), out id);
UUID user = UUID.Zero;
if (request.ContainsKey("PRINCIPAL"))
UUID.TryParse(request["PRINCIPAL"].ToString(), out user);
InventoryFolderBase folder = m_InventoryService.GetFolder(user, id);
if (folder != null)
result["folder"] = EncodeFolder(folder);
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetActiveGestures(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(principal);
Dictionary<string, object> items = new Dictionary<string, object>();
if (gestures != null)
{
int i = 0;
foreach (InventoryItemBase item in gestures)
{
items["item_" + i.ToString()] = EncodeItem(item);
i++;
}
}
result["ITEMS"] = items;
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetAssetPermissions(Dictionary<string,object> request)
{
Dictionary<string,object> result = new Dictionary<string,object>();
UUID principal = UUID.Zero;
UUID.TryParse(request["PRINCIPAL"].ToString(), out principal);
UUID assetID = UUID.Zero;
UUID.TryParse(request["ASSET"].ToString(), out assetID);
int perms = m_InventoryService.GetAssetPermissions(principal, assetID);
result["RESULT"] = perms.ToString();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
private Dictionary<string, object> EncodeFolder(InventoryFolderBase f)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
ret["ParentID"] = f.ParentID.ToString();
ret["Type"] = f.Type.ToString();
ret["Version"] = f.Version.ToString();
ret["Name"] = f.Name;
ret["Owner"] = f.Owner.ToString();
ret["ID"] = f.ID.ToString();
return ret;
}
private Dictionary<string, object> EncodeItem(InventoryItemBase item)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
ret["AssetID"] = item.AssetID.ToString();
ret["AssetType"] = item.AssetType.ToString();
ret["BasePermissions"] = item.BasePermissions.ToString();
ret["CreationDate"] = item.CreationDate.ToString();
if (item.CreatorId != null)
ret["CreatorId"] = item.CreatorId.ToString();
else
ret["CreatorId"] = String.Empty;
if (item.CreatorData != null)
ret["CreatorData"] = item.CreatorData;
else
ret["CreatorData"] = String.Empty;
ret["CurrentPermissions"] = item.CurrentPermissions.ToString();
ret["Description"] = item.Description.ToString();
ret["EveryOnePermissions"] = item.EveryOnePermissions.ToString();
ret["Flags"] = item.Flags.ToString();
ret["Folder"] = item.Folder.ToString();
ret["GroupID"] = item.GroupID.ToString();
ret["GroupOwned"] = item.GroupOwned.ToString();
ret["GroupPermissions"] = item.GroupPermissions.ToString();
ret["ID"] = item.ID.ToString();
ret["InvType"] = item.InvType.ToString();
ret["Name"] = item.Name.ToString();
ret["NextPermissions"] = item.NextPermissions.ToString();
ret["Owner"] = item.Owner.ToString();
ret["SalePrice"] = item.SalePrice.ToString();
ret["SaleType"] = item.SaleType.ToString();
return ret;
}
private InventoryFolderBase BuildFolder(Dictionary<string,object> data)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ParentID = new UUID(data["ParentID"].ToString());
folder.Type = short.Parse(data["Type"].ToString());
folder.Version = ushort.Parse(data["Version"].ToString());
folder.Name = data["Name"].ToString();
folder.Owner = new UUID(data["Owner"].ToString());
folder.ID = new UUID(data["ID"].ToString());
return folder;
}
private InventoryItemBase BuildItem(Dictionary<string,object> data)
{
InventoryItemBase item = new InventoryItemBase();
item.AssetID = new UUID(data["AssetID"].ToString());
item.AssetType = int.Parse(data["AssetType"].ToString());
item.Name = data["Name"].ToString();
item.Owner = new UUID(data["Owner"].ToString());
item.ID = new UUID(data["ID"].ToString());
item.InvType = int.Parse(data["InvType"].ToString());
item.Folder = new UUID(data["Folder"].ToString());
item.CreatorId = data["CreatorId"].ToString();
item.CreatorData = data["CreatorData"].ToString();
item.Description = data["Description"].ToString();
item.NextPermissions = uint.Parse(data["NextPermissions"].ToString());
item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString());
item.BasePermissions = uint.Parse(data["BasePermissions"].ToString());
item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString());
item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString());
item.GroupID = new UUID(data["GroupID"].ToString());
item.GroupOwned = bool.Parse(data["GroupOwned"].ToString());
item.SalePrice = int.Parse(data["SalePrice"].ToString());
item.SaleType = byte.Parse(data["SaleType"].ToString());
item.Flags = uint.Parse(data["Flags"].ToString());
item.CreationDate = int.Parse(data["CreationDate"].ToString());
return item;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace Fluid.Drawing.GdiPlus
{
public class GraphicsPath : IDisposable
{
public GraphicsPath() : this(FillMode.Alternate) { }
public GraphicsPath(FillMode fillMode)
{
nativePath = null;
lastResult = GdiPlus.GdipCreatePath(fillMode, out nativePath);
}
~GraphicsPath()
{
Dispose(true);
}
public void Clear()
{
GdiPlus.GdipDeletePath(nativePath);
GdiPlus.GdipCreatePath(FillMode.Alternate, out nativePath);
}
private void SetStatus(GpStatus gpStatus)
{
if (gpStatus != GpStatus.Ok) throw GdiPlusStatusException.Exception(gpStatus);
}
public GraphicsPath Clone()
{
GpPath clonepath = null;
SetStatus(GdiPlus.GdipClonePath(nativePath, out clonepath));
return new GraphicsPath(clonepath);
}
// Reset the path object to empty (and fill mode to FillModeAlternate)
public void Reset()
{
SetStatus(GdiPlus.GdipResetPath(nativePath));
}
private FillMode GetFillMode()
{
FillMode fillmode = FillMode.Alternate;
SetStatus(GdiPlus.GdipGetPathFillMode(nativePath, out fillmode));
return fillmode;
}
private void SetFillMode(FillMode fillmode)
{
SetStatus(GdiPlus.GdipSetPathFillMode(nativePath, fillmode));
}
public FillMode FillMode
{
get
{
return GetFillMode();
}
set
{
SetFillMode(value);
}
}
public void StartFigure()
{
SetStatus(GdiPlus.GdipStartPathFigure(nativePath));
}
public void CloseFigure()
{
SetStatus(GdiPlus.GdipClosePathFigure(nativePath));
}
public void CloseAllFigures()
{
SetStatus(GdiPlus.GdipClosePathFigures(nativePath));
}
public void GetLastPoint(out PointF lastPoint)
{
SetStatus(GdiPlus.GdipGetPathLastPoint(nativePath,
out lastPoint));
}
public void AddLine(PointF pt1, PointF pt2)
{
AddLine(pt1.X, pt1.Y, pt2.X, pt2.Y);
}
public void AddLine(float x1, float y1, float x2, float y2)
{
SetStatus(GdiPlus.GdipAddPathLine(nativePath, x1, y1, x2, y2));
}
public void AddLines(PointF[] points)
{
SetStatus(GdiPlus.GdipAddPathLine2(nativePath, points, points.Length));
}
public void AddLine(Point p1, Point p2)
{
AddLines(new Point[] { p1, p2 });
}
public void AddLine(int x1, int y1, int x2, int y2)
{
Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y1);
AddLine(p1, p2);
}
public void AddLinesArray(Point[] points)
{
SetStatus(GdiPlus.GdipAddPathLine2I(nativePath, points, points.Length));
}
public void AddLines(params Point[] points)
{
SetStatus(GdiPlus.GdipAddPathLine2I(nativePath, points, points.Length));
}
public void AddArc(RectangleF rect, float startAngle, float sweepAngle)
{
AddArc(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
}
public void AddArc(
float x,
float y,
float width,
float height,
float startAngle,
float sweepAngle)
{
SetStatus(GdiPlus.GdipAddPathArc(nativePath, x, y, width, height, startAngle, sweepAngle));
}
public void AddArc(Rectangle rect, float startAngle, float sweepAngle)
{
AddArc(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
}
public void AddArc(int x,
int y,
int width,
int height,
float startAngle,
float sweepAngle)
{
SetStatus(GdiPlus.GdipAddPathArcI(nativePath, x,y,width,height,startAngle,sweepAngle));
}
public void AddBeziers(PointF[] points)
{
int count = points.Length;
count -= (count - 4) % 3;
SetStatus(GdiPlus.GdipAddPathBeziers(nativePath, points, count));
}
public void AddBeziers(Point[] points)
{
SetStatus(GdiPlus.GdipAddPathBeziersI(nativePath, points, points.Length));
}
public void AddRectangle(RectangleF rect)
{
SetStatus(GdiPlus.GdipAddPathPolygon(nativePath,
new PointF[]
{
new PointF(rect.X, rect.Y),
new PointF(rect.X, rect.Y + rect.Height),
new PointF(rect.X + rect.Width, rect.Y + rect.Height),
new PointF(rect.X + rect.Width, rect.Y),
},
4));
}
public void AddRectangles(RectangleF[] rects)
{
SetStatus(GdiPlus.GdipAddPathRectangles(nativePath, rects, rects.Length));
}
public void AddRectangles(Rectangle[] rects)
{
SetStatus(GdiPlus.GdipAddPathRectanglesI(nativePath, rects, rects.Length));
}
public void AddEllipse(RectangleF rect)
{
AddEllipse(rect.X, rect.Y, rect.Width, rect.Height);
}
public void AddEllipse(float x, float y, float width, float height)
{
SetStatus(GdiPlus.GdipAddPathEllipse(nativePath, x, y, width, height));
}
public void AddEllipse(Rectangle rect)
{
AddEllipse(rect.X, rect.Y, rect.Width, rect.Height);
}
public void AddEllipse(int x, int y, int width, int height)
{
SetStatus(GdiPlus.GdipAddPathEllipseI(nativePath, x, y, width, height));
}
public void AddPie(RectangleF rect, float startAngle, float sweepAngle)
{
AddPie(rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
}
public void AddPie(float x,
float y,
float width,
float height,
float startAngle,
float sweepAngle)
{
SetStatus(GdiPlus.GdipAddPathPie(nativePath, x, y, width,
height, startAngle,
sweepAngle));
}
public void AddPie(Rectangle rect,
float startAngle,
float sweepAngle)
{
AddPie(rect.X,
rect.Y,
rect.Width,
rect.Height,
startAngle,
sweepAngle);
}
public void AddPie(int x,
int y,
int width,
int height,
float startAngle,
float sweepAngle)
{
SetStatus(GdiPlus.GdipAddPathPieI(nativePath, x, y, width, height, startAngle, sweepAngle));
}
public void AddPath(GraphicsPath addingPath, bool connect)
{
GpPath nativePath2 = null;
if (addingPath != null) nativePath2 = addingPath.nativePath;
SetStatus(GdiPlus.GdipAddPathPath(nativePath, nativePath2, connect));
}
public int GetPointCount()
{
int count = 0;
SetStatus(GdiPlus.GdipGetPointCount(nativePath, out count));
return count;
}
public void GetPathTypes(byte[] types)
{
SetStatus(GdiPlus.GdipGetPathTypes(nativePath, types, types.Length));
}
public void GetPathPoints(PointF[] points)
{
SetStatus(GdiPlus.GdipGetPathPoints(nativePath, points, points.Length));
}
public void GetPathPoints(Point[] points)
{
SetStatus(GdiPlus.GdipGetPathPointsI(nativePath, points, points.Length));
}
public GpStatus GetLastStatus()
{
GpStatus lastStatus = lastResult;
lastResult = GpStatus.Ok;
return lastStatus;
}
public bool IsVisible(GraphicsPlus g, PointF point)
{
return IsVisible(g, point.X, point.Y);
}
public bool IsVisible(GraphicsPlus g, float x, float y)
{
bool ret;
SetStatus(GdiPlus.GdipIsVisiblePathPoint(nativePath, x, y, g.nativeGraphics, out ret));
return ret;
}
public bool IsVisible(GraphicsPlus g, Point point)
{
return IsVisible(g, point.X, point.Y);
}
public bool IsVisible(GraphicsPlus g, int x, int y)
{
bool ret;
GdiPlus.GdipIsVisiblePathPoint(nativePath, x, y, g.nativeGraphics, out ret);
return ret;
}
public bool IsOutlineVisible(GraphicsPlus g, PointF point, PenPlus pen)
{
return IsOutlineVisible(g, point.X, point.Y, pen);
}
public bool IsOutlineVisible(GraphicsPlus g, float x, float y, PenPlus pen)
{
bool ret;
SetStatus(GdiPlus.GdipIsOutlineVisiblePathPoint(nativePath, x, y, pen.nativePen, g.nativeGraphics, out ret));
return ret;
}
public bool IsOutlineVisible(GraphicsPlus g, Point point, PenPlus pen)
{
return IsOutlineVisible(g, point.X, point.Y, pen);
}
public GraphicsPath(GraphicsPath path)
{
GpPath clonepath = null;
SetStatus(GdiPlus.GdipClonePath(path.nativePath, out clonepath));
SetNativePath(clonepath);
}
protected GraphicsPath(GpPath nativePath)
{
lastResult = GpStatus.Ok;
SetNativePath(nativePath);
}
void SetNativePath(GpPath nativePath)
{
this.nativePath = nativePath;
}
internal GpPath nativePath;
protected GpStatus lastResult;
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
}
if ((IntPtr)nativePath != IntPtr.Zero)
{
GdiPlus.GdipDeletePath(nativePath);
nativePath = new GpPath();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Reflection;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Tests.Integration.Migrations;
using Moq;
using NUnit.Framework;
using NUnit.Should;
using System.Linq;
namespace FluentMigrator.Tests.Unit
{
[TestFixture]
public class MigrationRunnerTests
{
private MigrationRunner _runner;
private Mock<IAnnouncer> _announcer;
private Mock<IStopWatch> _stopWatch;
private Mock<IMigrationProcessor> _processorMock;
private Mock<IMigrationInformationLoader> _migrationLoaderMock;
private Mock<IProfileLoader> _profileLoaderMock;
private Mock<IRunnerContext> _runnerContextMock;
private SortedList<long, IMigrationInfo> _migrationList;
private TestVersionLoader _fakeVersionLoader;
private int _applicationContext;
[SetUp]
public void SetUp()
{
_applicationContext = new Random().Next();
_migrationList = new SortedList<long, IMigrationInfo>();
_runnerContextMock = new Mock<IRunnerContext>(MockBehavior.Loose);
_processorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose);
_migrationLoaderMock = new Mock<IMigrationInformationLoader>(MockBehavior.Loose);
_profileLoaderMock = new Mock<IProfileLoader>(MockBehavior.Loose);
_announcer = new Mock<IAnnouncer>();
_stopWatch = new Mock<IStopWatch>();
_stopWatch.Setup(x => x.Time(It.IsAny<Action>())).Returns(new TimeSpan(1)).Callback((Action a) => a.Invoke());
var options = new ProcessorOptions
{
PreviewOnly = false
};
_processorMock.SetupGet(x => x.Options).Returns(options);
_processorMock.SetupGet(x => x.ConnectionString).Returns(IntegrationTestOptions.SqlServer2008.ConnectionString);
_runnerContextMock.SetupGet(x => x.Namespace).Returns("FluentMigrator.Tests.Integration.Migrations");
_runnerContextMock.SetupGet(x => x.Announcer).Returns(_announcer.Object);
_runnerContextMock.SetupGet(x => x.StopWatch).Returns(_stopWatch.Object);
_runnerContextMock.SetupGet(x => x.Targets).Returns(new string[] { Assembly.GetExecutingAssembly().ToString()});
_runnerContextMock.SetupGet(x => x.Connection).Returns(IntegrationTestOptions.SqlServer2008.ConnectionString);
_runnerContextMock.SetupGet(x => x.Database).Returns("sqlserver");
_runnerContextMock.SetupGet(x => x.ApplicationContext).Returns(_applicationContext);
_migrationLoaderMock.Setup(x => x.LoadMigrations()).Returns(()=> _migrationList);
_runner = new MigrationRunner(Assembly.GetAssembly(typeof(MigrationRunnerTests)), _runnerContextMock.Object, _processorMock.Object)
{
MigrationLoader = _migrationLoaderMock.Object,
ProfileLoader = _profileLoaderMock.Object,
};
_fakeVersionLoader = new TestVersionLoader(_runner, _runner.VersionLoader.VersionTableMetaData);
_runner.VersionLoader = _fakeVersionLoader;
_processorMock.Setup(x => x.SchemaExists(It.Is<string>(s => s == _runner.VersionLoader.VersionTableMetaData.SchemaName)))
.Returns(true);
_processorMock.Setup(x => x.TableExists(It.Is<string>(s => s == _runner.VersionLoader.VersionTableMetaData.SchemaName),
It.Is<string>(t => t == _runner.VersionLoader.VersionTableMetaData.TableName)))
.Returns(true);
}
private void LoadVersionData(params long[] fakeVersions)
{
_fakeVersionLoader.Versions.Clear();
_migrationList.Clear();
foreach (var version in fakeVersions)
{
_fakeVersionLoader.Versions.Add(version);
_migrationList.Add(version,new MigrationInfo(version, TransactionBehavior.Default, new TestMigration()));
}
_fakeVersionLoader.LoadVersionInfo();
}
[Test]
public void ProfilesAreAppliedWhenMigrateUpIsCalledWithNoVersion()
{
_runner.MigrateUp();
_profileLoaderMock.Verify(x => x.ApplyProfiles(), Times.Once());
}
[Test]
public void ProfilesAreAppliedWhenMigrateUpIsCalledWithVersionParameter()
{
_runner.MigrateUp(2009010101);
_profileLoaderMock.Verify(x => x.ApplyProfiles(), Times.Once());
}
[Test]
public void ProfilesAreAppliedWhenMigrateDownIsCalled()
{
_runner.MigrateDown(2009010101);
_profileLoaderMock.Verify(x => x.ApplyProfiles(), Times.Once());
}
/// <summary>Unit test which ensures that the application context is correctly propagated down to each migration class.</summary>
[Test(Description = "Ensure that the application context is correctly propagated down to each migration class.")]
public void CanPassApplicationContext()
{
IMigration migration = new TestEmptyMigration();
_runner.Up(migration);
Assert.AreEqual(_applicationContext, _runnerContextMock.Object.ApplicationContext, "The runner context does not have the expected application context.");
Assert.AreEqual(_applicationContext, _runner.ApplicationContext, "The MigrationRunner does not have the expected application context.");
Assert.AreEqual(_applicationContext, migration.ApplicationContext, "The migration does not have the expected application context.");
_announcer.VerifyAll();
}
[Test]
public void CanPassConnectionString()
{
IMigration migration = new TestEmptyMigration();
_runner.Up(migration);
Assert.AreEqual(IntegrationTestOptions.SqlServer2008.ConnectionString, migration.ConnectionString, "The migration does not have the expected connection string.");
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUp()
{
_announcer.Setup(x => x.Heading(It.IsRegex(containsAll("Test", "migrating"))));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUpFinish()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("Test", "migrated"))));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDown()
{
_announcer.Setup(x => x.Heading(It.IsRegex(containsAll("Test", "reverting"))));
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDownFinish()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("Test", "reverted"))));
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceUpElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanAnnounceDownElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Down(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanReportExceptions()
{
_processorMock.Setup(x => x.Process(It.IsAny<CreateTableExpression>())).Throws(new Exception("Oops"));
var exception = Assert.Throws<Exception>(() => _runner.Up(new TestMigration()));
Assert.That(exception.Message, Is.StringContaining("Oops"));
}
[Test]
public void CanSayExpression()
{
_announcer.Setup(x => x.Say(It.IsRegex(containsAll("CreateTable"))));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(new TimeSpan(0, 0, 0, 1, 3));
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
[Test]
public void CanTimeExpression()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_announcer.Setup(x => x.ElapsedTime(It.Is<TimeSpan>(y => y == ts)));
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
_runner.Up(new TestMigration());
_announcer.VerifyAll();
}
private string containsAll(params string[] words)
{
return ".*?" + string.Join(".*?", words) + ".*?";
}
[Test]
public void LoadsCorrectCallingAssembly()
{
var asm = _runner.MigrationAssemblies.Assemblies.Single();
asm.ShouldBe(Assembly.GetAssembly(typeof(MigrationRunnerTests)));
}
[Test]
public void RollbackOnlyOneStepsOfTwoShouldNotDeleteVersionInfoTable()
{
long fakeMigrationVersion = 2009010101;
long fakeMigrationVersion2 = 2009010102;
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
LoadVersionData(fakeMigrationVersion, fakeMigrationVersion2);
_runner.VersionLoader.LoadVersionInfo();
_runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackLastVersionShouldDeleteVersionInfoTable()
{
long fakeMigrationVersion = 2009010101;
LoadVersionData(fakeMigrationVersion);
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldDeleteVersionInfoTable()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(0);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldNotCreateVersionInfoTableAfterRemoval()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(0);
//Should only be called once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Once()
);
}
[Test]
public void RollbackToVersionShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1,fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.RollbackToVersion(2011010101);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackToVersionZeroShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1, fakeMigration2, fakeMigration3);
_migrationList.Remove(fakeMigration1);
_migrationList.Remove(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.RollbackToVersion(0);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1, fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
_runner.Rollback(2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackToVersionShouldLoadVersionInfoIfVersionGreaterThanZero()
{
var versionInfoTableName = _runner.VersionLoader.VersionTableMetaData.TableName;
_runner.RollbackToVersion(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
//Once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Exactly(1)
);
//After setup is done, fake version loader owns the proccess
_fakeVersionLoader.DidLoadVersionInfoGetCalled.ShouldBe(true);
}
[Test]
public void ValidateVersionOrderingShouldReturnNothingIfNoUnappliedMigrations()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
LoadVersionData(version1, version2);
_migrationList.Clear();
_migrationList.Add(version1,new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
Assert.DoesNotThrow(() => _runner.ValidateVersionOrder());
_announcer.Verify(a => a.Say("Version ordering valid."));
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void ValidateVersionOrderingShouldReturnNothingIfUnappliedMigrationVersionIsGreaterThanLatestAppliedMigration()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
LoadVersionData(version1);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
Assert.DoesNotThrow(() => _runner.ValidateVersionOrder());
_announcer.Verify(a => a.Say("Version ordering valid."));
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void ValidateVersionOrderingShouldThrowExceptionIfUnappliedMigrationVersionIsLessThanGreatestAppliedMigrationVersion()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
const long version3 = 2011010103;
const long version4 = 2011010104;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
var mockMigration3 = new Mock<IMigration>();
var mockMigration4 = new Mock<IMigration>();
LoadVersionData(version1, version4);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
_migrationList.Add(version3, new MigrationInfo(version3, TransactionBehavior.Default, mockMigration3.Object));
_migrationList.Add(version4, new MigrationInfo(version4, TransactionBehavior.Default, mockMigration4.Object));
var exception = Assert.Throws<VersionOrderInvalidException>(() => _runner.ValidateVersionOrder());
exception.InvalidMigrations.Count().ShouldBe(2);
exception.InvalidMigrations.Any(p => p.Key == version2);
exception.InvalidMigrations.Any(p => p.Key == version3);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void CanListVersions()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
LoadVersionData(version1, version2);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
_runner.ListMigrations();
_announcer.Verify(a => a.Say("2011010101: IMigrationProxy"));
_announcer.Verify(a => a.Emphasize("2011010102: IMigrationProxy (current)"));
}
[Test]
public void IfMigrationHasAnInvalidExpressionDuringUpActionShouldThrowAnExceptionAndAnnounceTheError()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression {TableName = "Test"};
invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression));
Assert.Throws<InvalidMigrationException>(() => _runner.Up(invalidMigration.Object));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("UpdateDataExpression: Update statement is missing a condition. Specify one by calling .Where() or target all rows by calling .AllRows()."))));
}
[Test]
public void IfMigrationHasAnInvalidExpressionDuringDownActionShouldThrowAnExceptionAndAnnounceTheError()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression { TableName = "Test" };
invalidMigration.Setup(m => m.GetDownExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression));
Assert.Throws<InvalidMigrationException>(() => _runner.Down(invalidMigration.Object));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("UpdateDataExpression: Update statement is missing a condition. Specify one by calling .Where() or target all rows by calling .AllRows()."))));
}
[Test]
public void IfMigrationHasTwoInvalidExpressionsShouldAnnounceBothErrors()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression { TableName = "Test" };
var secondInvalidExpression = new CreateColumnExpression();
invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>()))
.Callback((IMigrationContext mc) => { mc.Expressions.Add(invalidExpression); mc.Expressions.Add(secondInvalidExpression); });
Assert.Throws<InvalidMigrationException>(() => _runner.Up(invalidMigration.Object));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("UpdateDataExpression: Update statement is missing a condition. Specify one by calling .Where() or target all rows by calling .AllRows()."))));
_announcer.Verify(a => a.Error(It.Is<string>(s => s.Contains("CreateColumnExpression: The table's name cannot be null or an empty string. The column's name cannot be null or an empty string. The column does not have a type defined."))));
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
using static MicrosoftCodeQualityAnalyzersResources;
/// <summary>
/// CA1065: Do not raise exceptions in unexpected locations
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1065";
private static readonly LocalizableString s_localizableTitle = CreateLocalizableResourceString(nameof(DoNotRaiseExceptionsInUnexpectedLocationsTitle));
private static readonly LocalizableString s_localizableDescription = CreateLocalizableResourceString(nameof(DoNotRaiseExceptionsInUnexpectedLocationsDescription));
internal static readonly DiagnosticDescriptor PropertyGetterRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(DoNotRaiseExceptionsInUnexpectedLocationsMessagePropertyGetter)),
DiagnosticCategory.Design,
RuleLevel.Disabled, // Could consider Suggestion level if we could exclude test code by default.
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static readonly DiagnosticDescriptor HasAllowedExceptionsRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(DoNotRaiseExceptionsInUnexpectedLocationsMessageHasAllowedExceptions)),
DiagnosticCategory.Design,
RuleLevel.Disabled, // Could consider Suggestion level if we could exclude test code by default.
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static readonly DiagnosticDescriptor NoAllowedExceptionsRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(DoNotRaiseExceptionsInUnexpectedLocationsMessageNoAllowedExceptions)),
DiagnosticCategory.Design,
RuleLevel.Disabled, // Could consider Suggestion level if we could exclude test code by default.
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(PropertyGetterRule, HasAllowedExceptionsRule, NoAllowedExceptionsRule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(compilationStartContext =>
{
Compilation compilation = compilationStartContext.Compilation;
INamedTypeSymbol? exceptionType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemException);
if (exceptionType == null)
{
return;
}
// Get a list of interesting categories of methods to analyze.
List<MethodCategory> methodCategories = GetMethodCategories(compilation);
compilationStartContext.RegisterOperationBlockStartAction(operationBlockContext =>
{
if (operationBlockContext.OwningSymbol is not IMethodSymbol methodSymbol)
{
return;
}
// Find out if this given method is one of the interesting categories of methods.
// For example, certain Equals methods or certain accessors etc.
MethodCategory methodCategory = methodCategories.FirstOrDefault(l => l.IsMatch(methodSymbol, compilation));
if (methodCategory == null)
{
return;
}
// For the interesting methods, register an operation action to catch all
// Throw statements.
operationBlockContext.RegisterOperationAction(operationContext =>
{
// Get ThrowOperation's ExceptionType
if (((IThrowOperation)operationContext.Operation).GetThrownExceptionType() is INamedTypeSymbol thrownExceptionType && thrownExceptionType.DerivesFrom(exceptionType))
{
// If no exceptions are allowed or if the thrown exceptions is not an allowed one..
if (methodCategory.AllowedExceptions.IsEmpty || !methodCategory.AllowedExceptions.Any(n => thrownExceptionType.IsAssignableTo(n, compilation)))
{
operationContext.ReportDiagnostic(
operationContext.Operation.Syntax.CreateDiagnostic(methodCategory.Rule, methodSymbol.Name, thrownExceptionType.Name));
}
}
}, OperationKind.Throw);
});
});
}
/// <summary>
/// This object describes a class of methods where exception throwing statements should be analyzed.
/// </summary>
private class MethodCategory
{
/// <summary>
/// Function used to determine whether a given method symbol falls into this category.
/// </summary>
private readonly Func<IMethodSymbol, Compilation, bool> _matchFunction;
/// <summary>
/// Determines if we should analyze non-public methods of a given type.
/// </summary>
private readonly bool _analyzeOnlyPublicMethods;
/// <summary>
/// The rule that should be fired if there is an exception in this kind of method.
/// </summary>
public DiagnosticDescriptor Rule { get; }
/// <summary>
/// List of exception types which are allowed to be thrown inside this category of method.
/// This list will be empty if no exceptions are allowed.
/// </summary>
public ImmutableHashSet<ITypeSymbol> AllowedExceptions { get; }
public MethodCategory(Func<IMethodSymbol, Compilation, bool> matchFunction, bool analyzeOnlyPublicMethods, DiagnosticDescriptor rule, params ITypeSymbol?[] allowedExceptionTypes)
{
_matchFunction = matchFunction;
_analyzeOnlyPublicMethods = analyzeOnlyPublicMethods;
this.Rule = rule;
AllowedExceptions = allowedExceptionTypes.WhereNotNull().ToImmutableHashSet();
}
/// <summary>
/// Checks if the given method belong this category
/// </summary>
public bool IsMatch(IMethodSymbol method, Compilation compilation)
{
// If we are supposed to analyze only public methods get the resultant visibility
// i.e public method inside an internal class is not considered public.
if (_analyzeOnlyPublicMethods && !method.IsExternallyVisible())
{
return false;
}
return _matchFunction(method, compilation);
}
}
private static List<MethodCategory> GetMethodCategories(Compilation compilation)
{
var methodCategories = new List<MethodCategory> {
new MethodCategory(IsPropertyGetter, true,
PropertyGetterRule,
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemInvalidOperationException),
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotSupportedException)),
new MethodCategory(IsIndexerGetter, true,
PropertyGetterRule,
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemInvalidOperationException),
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotSupportedException),
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentException),
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericKeyNotFoundException)),
new MethodCategory(IsEventAccessor, true,
HasAllowedExceptionsRule,
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemInvalidOperationException),
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotSupportedException),
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentException)),
new MethodCategory(IsGetHashCodeInterfaceImplementation, true,
HasAllowedExceptionsRule,
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentException)),
new MethodCategory(IsEqualsOverrideOrInterfaceImplementation, true,
NoAllowedExceptionsRule),
new MethodCategory(IsComparisonOperator, true,
NoAllowedExceptionsRule),
new MethodCategory(IsGetHashCodeOverride, true,
NoAllowedExceptionsRule),
new MethodCategory(IsToString, true,
NoAllowedExceptionsRule),
new MethodCategory(IsImplicitCastOperator, true,
NoAllowedExceptionsRule),
new MethodCategory(IsStaticConstructor, false,
NoAllowedExceptionsRule),
new MethodCategory(IsFinalizer, false,
NoAllowedExceptionsRule),
new MethodCategory(IMethodSymbolExtensions.IsDisposeImplementation, true,
NoAllowedExceptionsRule),
};
return methodCategories;
}
private static bool IsPropertyGetter(IMethodSymbol method, Compilation compilation)
{
return method.IsPropertyGetter();
}
private static bool IsIndexerGetter(IMethodSymbol method, Compilation compilation)
{
return method.IsIndexerGetter();
}
private static bool IsEventAccessor(IMethodSymbol method, Compilation compilation)
{
return method.IsEventAccessor();
}
private static bool IsEqualsOverrideOrInterfaceImplementation(IMethodSymbol method, Compilation compilation)
{
return method.IsObjectEqualsOverride() || IsEqualsInterfaceImplementation(method, compilation);
}
/// <summary>
/// Checks if a given method implements IEqualityComparer.Equals or IEquatable.Equals.
/// </summary>
private static bool IsEqualsInterfaceImplementation(IMethodSymbol method, Compilation compilation)
{
if (method.Name != WellKnownMemberNames.ObjectEquals)
{
return false;
}
int paramCount = method.Parameters.Length;
if (method.ReturnType.SpecialType == SpecialType.System_Boolean &&
(paramCount == 1 || paramCount == 2))
{
// Substitute the type of the first parameter of Equals in the generic interface and then check if that
// interface method is implemented by the given method.
INamedTypeSymbol? iEqualityComparer = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEqualityComparer1);
if (method.IsImplementationOfInterfaceMethod(method.Parameters.First().Type, iEqualityComparer, WellKnownMemberNames.ObjectEquals))
{
return true;
}
// Substitute the type of the first parameter of Equals in the generic interface and then check if that
// interface method is implemented by the given method.
INamedTypeSymbol? iEquatable = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIEquatable1);
if (method.IsImplementationOfInterfaceMethod(method.Parameters.First().Type, iEquatable, WellKnownMemberNames.ObjectEquals))
{
return true;
}
}
return false;
}
/// <summary>
/// Checks if a given method implements IEqualityComparer.GetHashCode or IHashCodeProvider.GetHashCode.
/// </summary>
/// <param name="method"></param>
/// <param name="compilation"></param>
/// <returns></returns>
private static bool IsGetHashCodeInterfaceImplementation(IMethodSymbol method, Compilation compilation)
{
if (method.Name != WellKnownMemberNames.ObjectGetHashCode)
{
return false;
}
if (method.ReturnType.SpecialType == SpecialType.System_Int32 && method.Parameters.Length == 1)
{
// Substitute the type of the first parameter of Equals in the generic interface and then check if that
// interface method is implemented by the given method.
INamedTypeSymbol? iEqualityComparer = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEqualityComparer1);
if (method.IsImplementationOfInterfaceMethod(method.Parameters.First().Type, iEqualityComparer, WellKnownMemberNames.ObjectGetHashCode))
{
return true;
}
INamedTypeSymbol? iHashCodeProvider = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIHashCodeProvider);
if (method.IsImplementationOfInterfaceMethod(null, iHashCodeProvider, WellKnownMemberNames.ObjectGetHashCode))
{
return true;
}
}
return false;
}
private static bool IsGetHashCodeOverride(IMethodSymbol method, Compilation compilation)
{
return method.IsGetHashCodeOverride();
}
private static bool IsToString(IMethodSymbol method, Compilation compilation)
{
return method.IsToStringOverride();
}
private static bool IsStaticConstructor(IMethodSymbol method, Compilation compilation)
{
return method.MethodKind == MethodKind.StaticConstructor;
}
private static bool IsFinalizer(IMethodSymbol method, Compilation compilation)
{
return method.IsFinalizer();
}
private static bool IsComparisonOperator(IMethodSymbol method, Compilation compilation)
{
if (!method.IsStatic || !method.IsPublic())
return false;
return method.Name switch
{
WellKnownMemberNames.EqualityOperatorName
or WellKnownMemberNames.InequalityOperatorName
or WellKnownMemberNames.LessThanOperatorName
or WellKnownMemberNames.GreaterThanOperatorName
or WellKnownMemberNames.LessThanOrEqualOperatorName
or WellKnownMemberNames.GreaterThanOrEqualOperatorName => true,
_ => false,
};
}
private static bool IsImplicitCastOperator(IMethodSymbol method, Compilation compilation)
{
if (!method.IsStatic || !method.IsPublic())
return false;
return method.Name == WellKnownMemberNames.ImplicitConversionName;
}
}
}
| |
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 Provisioning.Hybrid.Simple.OnPrem
{
/// <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
}
| |
/*
* 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;
using System.Collections.Generic;
using System.Data;
using OpenMetaverse;
using OpenSim.Framework;
using MySql.Data.MySqlClient;
namespace OpenSim.Data.MySQL
{
public class MySqlAuthenticationData : MySqlFramework, IAuthenticationData
{
private string m_Realm;
private List<string> m_ColumnNames;
private int m_LastExpire;
// private string m_connectionString;
public MySqlAuthenticationData(string connectionString, string realm)
: base(connectionString)
{
m_Realm = realm;
m_connectionString = connectionString;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, GetType().Assembly, "AuthStore");
m.Update();
}
}
public AuthenticationData Get(UUID principalID)
{
AuthenticationData ret = new AuthenticationData();
ret.Data = new Dictionary<string, object>();
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
MySqlCommand cmd = new MySqlCommand("select * from `" + m_Realm + "` where UUID = ?principalID", dbcon);
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
IDataReader result = cmd.ExecuteReader();
if (result.Read())
{
ret.PrincipalID = principalID;
if (m_ColumnNames == null)
{
m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
foreach (string s in m_ColumnNames)
{
if (s == "UUID")
continue;
ret.Data[s] = result[s].ToString();
}
return ret;
}
else
{
return null;
}
}
}
public bool Store(AuthenticationData data)
{
if (data.Data.ContainsKey("UUID"))
data.Data.Remove("UUID");
string[] fields = new List<string>(data.Data.Keys).ToArray();
MySqlCommand cmd = new MySqlCommand();
string update = "update `"+m_Realm+"` set ";
bool first = true;
foreach (string field in fields)
{
if (!first)
update += ", ";
update += "`" + field + "` = ?"+field;
first = false;
cmd.Parameters.AddWithValue("?"+field, data.Data[field]);
}
update += " where UUID = ?principalID";
cmd.CommandText = update;
cmd.Parameters.AddWithValue("?principalID", data.PrincipalID.ToString());
if (ExecuteNonQuery(cmd) < 1)
{
string insert = "insert into `" + m_Realm + "` (`UUID`, `" +
String.Join("`, `", fields) +
"`) values (?principalID, ?" + String.Join(", ?", fields) + ")";
cmd.CommandText = insert;
if (ExecuteNonQuery(cmd) < 1)
{
cmd.Dispose();
return false;
}
}
cmd.Dispose();
return true;
}
public bool SetDataItem(UUID principalID, string item, string value)
{
MySqlCommand cmd = new MySqlCommand("update `" + m_Realm +
"` set `" + item + "` = ?" + item + " where UUID = ?UUID");
cmd.Parameters.AddWithValue("?"+item, value);
cmd.Parameters.AddWithValue("?UUID", principalID.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
return false;
}
public bool SetToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
MySqlCommand cmd = new MySqlCommand("insert into tokens (UUID, token, validity) values (?principalID, ?token, date_add(now(), interval ?lifetime minute))");
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
cmd.Parameters.AddWithValue("?token", token);
cmd.Parameters.AddWithValue("?lifetime", lifetime.ToString());
if (ExecuteNonQuery(cmd) > 0)
{
cmd.Dispose();
return true;
}
cmd.Dispose();
return false;
}
public bool CheckToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
MySqlCommand cmd = new MySqlCommand("update tokens set validity = date_add(now(), interval ?lifetime minute) where UUID = ?principalID and token = ?token and validity > now()");
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
cmd.Parameters.AddWithValue("?token", token);
cmd.Parameters.AddWithValue("?lifetime", lifetime.ToString());
if (ExecuteNonQuery(cmd) > 0)
{
cmd.Dispose();
return true;
}
cmd.Dispose();
return false;
}
private void DoExpire()
{
MySqlCommand cmd = new MySqlCommand("delete from tokens where validity < now()");
ExecuteNonQuery(cmd);
cmd.Dispose();
m_LastExpire = System.Environment.TickCount;
}
}
}
| |
// This source code is dual-licensed under the Apache License, version
// 2.0, and the Mozilla Public License, version 1.1.
//
// The APL v2.0:
//
//---------------------------------------------------------------------------
// Copyright (C) 2007-2014 GoPivotal, 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.
//---------------------------------------------------------------------------
//
// The MPL v1.1:
//
//---------------------------------------------------------------------------
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
// the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is RabbitMQ.
//
// The Initial Developer of the Original Code is GoPivotal, Inc.
// Copyright (c) 2007-2014 GoPivotal, Inc. All rights reserved.
//---------------------------------------------------------------------------
using NUnit.Framework;
using System;
using System.IO;
using System.Collections;
using System.Threading;
using RabbitMQ.Util;
namespace RabbitMQ.Client.Unit
{
[TestFixture]
public class TestSharedQueue : TimingFixture
{
public delegate void Thunk();
//wrapper to work around C#'s lack of local volatiles
public class VolatileInt {
public volatile int v = 0;
}
public class DelayedEnqueuer
{
public SharedQueue m_q;
public int m_delayMs;
public object m_v;
public DelayedEnqueuer(SharedQueue q, int delayMs, object v)
{
m_q = q;
m_delayMs = delayMs;
m_v = v;
}
public void EnqueueValue()
{
Thread.Sleep(m_delayMs);
m_q.Enqueue(m_v);
}
public void Dequeue()
{
m_q.Dequeue();
}
public void DequeueNoWaitZero()
{
m_q.DequeueNoWait(0);
}
public void DequeueAfterOneIntoV()
{
m_q.Dequeue(1, out m_v);
}
public void BackgroundEofExpectingDequeue()
{
ExpectEof(new Thunk(this.Dequeue));
}
}
public static void EnqueueAfter(int delayMs, SharedQueue q, object v)
{
DelayedEnqueuer de = new DelayedEnqueuer(q, delayMs, v);
new Thread(new ThreadStart(de.EnqueueValue)).Start();
}
public static void ExpectEof(Thunk thunk)
{
try
{
thunk();
Assert.Fail("expected System.IO.EndOfStreamException");
}
catch (System.IO.EndOfStreamException) { }
}
public DateTime m_startTime;
public void ResetTimer()
{
m_startTime = DateTime.Now;
}
public int ElapsedMs()
{
return (int)((DateTime.Now - m_startTime).TotalMilliseconds);
}
[Test]
public void TestDequeueNoWait1()
{
SharedQueue q = new SharedQueue();
q.Enqueue(1);
Assert.AreEqual(1, q.DequeueNoWait(0));
Assert.AreEqual(0, q.DequeueNoWait(0));
}
[Test]
public void TestDequeueNoWait2()
{
SharedQueue q = new SharedQueue();
q.Enqueue(1);
Assert.AreEqual(1, q.Dequeue());
Assert.AreEqual(0, q.DequeueNoWait(0));
}
[Test]
public void TestDequeueNoWait3()
{
SharedQueue q = new SharedQueue();
Assert.AreEqual(null, q.DequeueNoWait(null));
}
[Test]
public void TestDelayedEnqueue()
{
SharedQueue q = new SharedQueue();
ResetTimer();
EnqueueAfter(TimingInterval, q, 1);
Assert.AreEqual(0, q.DequeueNoWait(0));
Assert.Greater(TimingInterval - SafetyMargin, ElapsedMs());
Assert.AreEqual(1, q.Dequeue());
Assert.Less(TimingInterval - SafetyMargin, ElapsedMs());
}
[Test]
public void TestTimeoutShort()
{
SharedQueue q = new SharedQueue();
q.Enqueue(123);
ResetTimer();
object v;
bool r = q.Dequeue(TimingInterval, out v);
Assert.Greater(SafetyMargin, ElapsedMs());
Assert.IsTrue(r);
Assert.AreEqual(123, v);
}
[Test]
public void TestTimeoutLong()
{
SharedQueue q = new SharedQueue();
ResetTimer();
object v;
bool r = q.Dequeue(TimingInterval, out v);
Assert.Less(TimingInterval - SafetyMargin, ElapsedMs());
Assert.IsTrue(!r);
Assert.AreEqual(null, v);
}
[Test]
public void TestTimeoutNegative()
{
SharedQueue q = new SharedQueue();
ResetTimer();
object v;
bool r = q.Dequeue(-10000, out v);
Assert.Greater(SafetyMargin, ElapsedMs());
Assert.IsTrue(!r);
Assert.AreEqual(null, v);
}
[Test]
public void TestTimeoutInfinite()
{
SharedQueue q = new SharedQueue();
EnqueueAfter(TimingInterval, q, 123);
ResetTimer();
object v;
bool r = q.Dequeue(Timeout.Infinite, out v);
Assert.Less(TimingInterval - SafetyMargin, ElapsedMs());
Assert.IsTrue(r);
Assert.AreEqual(123, v);
}
[Test]
public void TestBgShort()
{
SharedQueue q = new SharedQueue();
EnqueueAfter(TimingInterval, q, 123);
ResetTimer();
object v;
bool r = q.Dequeue(TimingInterval * 2, out v);
Assert.Less(TimingInterval - SafetyMargin, ElapsedMs());
Assert.IsTrue(r);
Assert.AreEqual(123, v);
}
[Test]
public void TestBgLong()
{
SharedQueue q = new SharedQueue();
EnqueueAfter(TimingInterval * 2, q, 123);
ResetTimer();
object v;
bool r = q.Dequeue(TimingInterval, out v);
Assert.Greater(TimingInterval + SafetyMargin, ElapsedMs());
Assert.IsTrue(!r);
Assert.AreEqual(null, v);
}
[Test]
public void TestDoubleBg()
{
SharedQueue q = new SharedQueue();
EnqueueAfter(TimingInterval, q, 123);
EnqueueAfter(TimingInterval * 2, q, 234);
ResetTimer();
object v;
bool r;
r = q.Dequeue(TimingInterval * 2, out v);
Assert.Less(TimingInterval - SafetyMargin, ElapsedMs());
Assert.Greater(TimingInterval + SafetyMargin, ElapsedMs());
Assert.IsTrue(r);
Assert.AreEqual(123, v);
r = q.Dequeue(TimingInterval * 2, out v);
Assert.Less(TimingInterval * 2 - SafetyMargin, ElapsedMs());
Assert.Greater(TimingInterval * 2 + SafetyMargin, ElapsedMs());
Assert.IsTrue(r);
Assert.AreEqual(234, v);
}
[Test]
public void TestDoublePoll()
{
SharedQueue q = new SharedQueue();
EnqueueAfter(TimingInterval * 2, q, 123);
ResetTimer();
object v;
bool r;
r = q.Dequeue(TimingInterval, out v);
Assert.Less(TimingInterval - SafetyMargin, ElapsedMs());
Assert.Greater(TimingInterval + SafetyMargin, ElapsedMs());
Assert.IsTrue(!r);
Assert.AreEqual(null, v);
r = q.Dequeue(TimingInterval * 2, out v);
Assert.Less(TimingInterval * 2 - SafetyMargin, ElapsedMs());
Assert.Greater(TimingInterval * 2 + SafetyMargin, ElapsedMs());
Assert.IsTrue(r);
Assert.AreEqual(123, v);
}
[Test]
public void TestCloseWhenEmpty()
{
DelayedEnqueuer de = new DelayedEnqueuer(new SharedQueue(), 0, 1);
de.m_q.Close();
ExpectEof(new Thunk(de.EnqueueValue));
ExpectEof(new Thunk(de.Dequeue));
ExpectEof(new Thunk(de.DequeueNoWaitZero));
ExpectEof(new Thunk(de.DequeueAfterOneIntoV));
}
[Test]
public void TestCloseWhenFull()
{
SharedQueue q = new SharedQueue();
object v;
q.Enqueue(1);
q.Enqueue(2);
q.Enqueue(3);
q.Close();
DelayedEnqueuer de = new DelayedEnqueuer(q, 0, 4);
ExpectEof(new Thunk(de.EnqueueValue));
Assert.AreEqual(1, q.Dequeue());
Assert.AreEqual(2, q.DequeueNoWait(0));
bool r = q.Dequeue(1, out v);
Assert.IsTrue(r);
Assert.AreEqual(3, v);
ExpectEof(new Thunk(de.Dequeue));
}
[Test]
public void TestCloseWhenWaiting()
{
SharedQueue q = new SharedQueue();
DelayedEnqueuer de = new DelayedEnqueuer(q, 0, null);
Thread t =
new Thread(new ThreadStart(de.BackgroundEofExpectingDequeue));
t.Start();
Thread.Sleep(SafetyMargin);
q.Close();
t.Join();
}
[Test]
public void TestEnumerator()
{
SharedQueue q = new SharedQueue();
VolatileInt c1 = new VolatileInt();
VolatileInt c2 = new VolatileInt();
Thread t1 = new Thread(delegate() {
foreach (int v in q) c1.v+=v;
});
Thread t2 = new Thread(delegate() {
foreach (int v in q) c2.v+=v;
});
t1.Start();
t2.Start();
q.Enqueue(1);
q.Enqueue(2);
q.Enqueue(3);
q.Close();
t1.Join();
t2.Join();
Assert.AreEqual(6, c1.v + c2.v);
}
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using PlayFab.ProfilesModels;
using PlayFab.Internal;
#pragma warning disable 0649
using System;
// This is required for the Obsolete Attribute flag
// which is not always present in all API's
#pragma warning restore 0649
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PlayFab
{
/// <summary>
/// All PlayFab entities have profiles, which hold top-level properties about the entity. These APIs give you the tools
/// needed to manage entity profiles.
/// </summary>
public class PlayFabProfilesInstanceAPI
{
public readonly PlayFabApiSettings apiSettings = null;
public readonly PlayFabAuthenticationContext authenticationContext = null;
public PlayFabProfilesInstanceAPI(PlayFabAuthenticationContext context)
{
if (context == null)
throw new PlayFabException(PlayFabExceptionCode.AuthContextRequired, "Context cannot be null, create a PlayFabAuthenticationContext for each player in advance, or get <PlayFabClientInstanceAPI>.authenticationContext");
authenticationContext = context;
}
public PlayFabProfilesInstanceAPI(PlayFabApiSettings settings, PlayFabAuthenticationContext context)
{
if (context == null)
throw new PlayFabException(PlayFabExceptionCode.AuthContextRequired, "Context cannot be null, create a PlayFabAuthenticationContext for each player in advance, or get <PlayFabClientInstanceAPI>.authenticationContext");
apiSettings = settings;
authenticationContext = context;
}
/// <summary>
/// Verify entity login.
/// </summary>
public bool IsEntityLoggedIn()
{
return authenticationContext == null ? false : authenticationContext.IsEntityLoggedIn();
}
/// <summary>
/// Clear the Client SessionToken which allows this Client to call API calls requiring login.
/// A new/fresh login will be required after calling this.
/// </summary>
public void ForgetAllCredentials()
{
authenticationContext?.ForgetAllCredentials();
}
/// <summary>
/// Gets the global title access policy
/// </summary>
public async Task<PlayFabResult<GetGlobalPolicyResponse>> GetGlobalPolicyAsync(GetGlobalPolicyRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Profile/GetGlobalPolicy", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<GetGlobalPolicyResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetGlobalPolicyResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<GetGlobalPolicyResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Retrieves the entity's profile.
/// </summary>
public async Task<PlayFabResult<GetEntityProfileResponse>> GetProfileAsync(GetEntityProfileRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Profile/GetProfile", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<GetEntityProfileResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetEntityProfileResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<GetEntityProfileResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Retrieves the entity's profile.
/// </summary>
public async Task<PlayFabResult<GetEntityProfilesResponse>> GetProfilesAsync(GetEntityProfilesRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Profile/GetProfiles", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<GetEntityProfilesResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetEntityProfilesResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<GetEntityProfilesResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Retrieves the title player accounts associated with the given master player account.
/// </summary>
public async Task<PlayFabResult<GetTitlePlayersFromMasterPlayerAccountIdsResponse>> GetTitlePlayersFromMasterPlayerAccountIdsAsync(GetTitlePlayersFromMasterPlayerAccountIdsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Profile/GetTitlePlayersFromMasterPlayerAccountIds", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<GetTitlePlayersFromMasterPlayerAccountIdsResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetTitlePlayersFromMasterPlayerAccountIdsResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<GetTitlePlayersFromMasterPlayerAccountIdsResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Sets the global title access policy
/// </summary>
public async Task<PlayFabResult<SetGlobalPolicyResponse>> SetGlobalPolicyAsync(SetGlobalPolicyRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Profile/SetGlobalPolicy", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<SetGlobalPolicyResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<SetGlobalPolicyResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<SetGlobalPolicyResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Updates the entity's language. The precedence hierarchy for communication to the player is Title Player Account
/// language, Master Player Account language, and then title default language if the first two aren't set or supported.
/// </summary>
public async Task<PlayFabResult<SetProfileLanguageResponse>> SetProfileLanguageAsync(SetProfileLanguageRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Profile/SetProfileLanguage", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<SetProfileLanguageResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<SetProfileLanguageResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<SetProfileLanguageResponse> { Result = result, CustomData = customData };
}
/// <summary>
/// Sets the profiles access policy
/// </summary>
public async Task<PlayFabResult<SetEntityProfilePolicyResponse>> SetProfilePolicyAsync(SetEntityProfilePolicyRequest request, object customData = null, Dictionary<string, string> extraHeaders = null)
{
await new PlayFabUtil.SynchronizationContextRemover();
var requestContext = request?.AuthenticationContext ?? authenticationContext;
var requestSettings = apiSettings ?? PlayFabSettings.staticSettings;
if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method");
var httpResult = await PlayFabHttp.DoPost("/Profile/SetProfilePolicy", request, "X-EntityToken", requestContext.EntityToken, extraHeaders, requestSettings);
if (httpResult is PlayFabError)
{
var error = (PlayFabError)httpResult;
PlayFabSettings.GlobalErrorHandler?.Invoke(error);
return new PlayFabResult<SetEntityProfilePolicyResponse> { Error = error, CustomData = customData };
}
var resultRawJson = (string)httpResult;
var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<SetEntityProfilePolicyResponse>>(resultRawJson);
var result = resultData.data;
return new PlayFabResult<SetEntityProfilePolicyResponse> { Result = result, CustomData = customData };
}
}
}
#endif
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Gallio.Icarus.Events;
using Gallio.Icarus.Models;
using Gallio.Icarus.Models.TestTreeNodes;
using Gallio.Icarus.TestResults;
using Gallio.Model;
using Gallio.Model.Schema;
using Gallio.Runner.Reports.Schema;
using MbUnit.Framework;
using Rhino.Mocks;
namespace Gallio.Icarus.Tests.TestResults
{
[Category("Controllers"), Author("Graham Hay"), TestsOn(typeof(TestResultsController))]
public class TestResultsControllerTest
{
private TestResultsController testResultsController;
private ITestTreeModel testTreeModel;
[SetUp]
public void EstablishContext()
{
testTreeModel = MockRepository.GenerateStub<ITestTreeModel>();
testTreeModel.Stub(ttm => ttm.Root).Return(Root);
testResultsController = new TestResultsController(testTreeModel);
}
[Test]
public void ElapsedTime_should_be_zero_before_test_run_starts()
{
Assert.AreEqual(new TimeSpan(), testResultsController.ElapsedTime);
}
[Test]
public void ElapsedTime_should_be_greater_than_zero_once_test_run_has_started()
{
testResultsController.Handle(new RunStarted());
testResultsController.Handle(new TestSelectionChanged(new TestTreeNode[0]));
Assert.GreaterThan(testResultsController.ElapsedTime, new TimeSpan());
}
[Test, Ignore]
public void ElapsedTime_should_stop_increasing_once_test_run_has_finished()
{
testResultsController.Handle(new RunStarted());
testResultsController.Handle(new TestSelectionChanged(new TestTreeNode[0]));
Assert.GreaterThan(testResultsController.ElapsedTime, new TimeSpan());
testResultsController.Handle(new RunFinished());
var elapsed = testResultsController.ElapsedTime;
Assert.AreEqual(elapsed, testResultsController.ElapsedTime);
}
[Test]
public void Cache_and_then_retrieve_item()
{
EstablishContext();
testResultsController.CacheVirtualItems(0, 3);
var listViewItem = testResultsController.RetrieveVirtualItem(0);
Assert.AreEqual("test1", listViewItem.Text);
Assert.AreEqual(0, listViewItem.ImageIndex); // passed
Assert.AreEqual(TestKinds.Test, listViewItem.SubItems[1].Text); // testkind
Assert.AreEqual("0.500", listViewItem.SubItems[2].Text); // duration
Assert.AreEqual("5", listViewItem.SubItems[3].Text); // assert count
Assert.AreEqual("", listViewItem.SubItems[4].Text); // code ref
Assert.AreEqual("", listViewItem.SubItems[5].Text); // file name
Assert.AreEqual(2, listViewItem.IndentCount);
}
[Test]
public void Smaller_cache_than_number_of_test_runs()
{
EstablishContext();
testResultsController.CacheVirtualItems(1, 3);
}
private static TestTreeNode Root
{
get
{
var root = new TestDataNode(new TestData("root", "root", "root")
{
Metadata = { { MetadataKeys.TestKind, TestKinds.Root } }
});
var fixture = new TestDataNode(new TestData("fixture", "fixture", "fixture")
{
Metadata = { { MetadataKeys.TestKind, TestKinds.Fixture } }
});
root.Nodes.Add(fixture);
var test1 = new TestDataNode(new TestData("test1", "test1", "test1")
{
Metadata = { { MetadataKeys.TestKind, TestKinds.Test } }
});
fixture.Nodes.Add(test1);
var testStepRun1 = new TestStepRun(new TestStepData("test1", "test1", "test1", "test1")
{
Metadata = { { MetadataKeys.TestKind, TestKinds.Test } }
})
{
Result = new TestResult
{
AssertCount = 5,
DurationInSeconds = 0.5,
Outcome = TestOutcome.Passed
}
};
test1.AddTestStepRun(testStepRun1);
var test2 = new TestDataNode(new TestData("test2", "test2", "test2")
{
Metadata = { { MetadataKeys.TestKind, TestKinds.Test } }
});
fixture.Nodes.Add(test2);
var testStepRun2 = new TestStepRun(new TestStepData("test2", "test2", "test2", "test2")
{
Metadata = { { MetadataKeys.TestKind, TestKinds.Test } }
})
{
Result = new TestResult
{
AssertCount = 1,
DurationInSeconds = 0.1,
Outcome = TestOutcome.Failed
}
};
test2.AddTestStepRun(testStepRun2);
var test3 = new TestDataNode(new TestData("test3", "test3", "test3")
{
Metadata = { { MetadataKeys.TestKind, TestKinds.Test } }
});
fixture.Nodes.Add(test3);
var testStepRun3 = new TestStepRun(new TestStepData("test3", "test3", "test3", "test3")
{
Metadata = { { MetadataKeys.TestKind, TestKinds.Test } }
})
{
Result = new TestResult
{
AssertCount = 2,
DurationInSeconds = 0.2,
Outcome = TestOutcome.Inconclusive
}
};
test3.AddTestStepRun(testStepRun3);
return root;
}
}
[Test]
public void Sort_list_by_int()
{
EstablishContext();
testResultsController.CacheVirtualItems(0, 3);
testResultsController.SetSortColumn(3);
Assert.AreEqual("test2", testResultsController.RetrieveVirtualItem(0).Text);
Assert.AreEqual("test3", testResultsController.RetrieveVirtualItem(1).Text);
Assert.AreEqual("test1", testResultsController.RetrieveVirtualItem(2).Text);
}
[Test]
public void Sort_list_by_string_desc()
{
EstablishContext();
testResultsController.CacheVirtualItems(0, 3);
testResultsController.SetSortColumn(0);
testResultsController.SetSortColumn(0);
Assert.AreEqual("test3", testResultsController.RetrieveVirtualItem(0).Text);
Assert.AreEqual("test2", testResultsController.RetrieveVirtualItem(1).Text);
Assert.AreEqual("test1", testResultsController.RetrieveVirtualItem(2).Text);
}
[Test]
public void Sort_list_by_double()
{
EstablishContext();
testResultsController.CacheVirtualItems(0, 3);
testResultsController.SetSortColumn(2);
Assert.AreEqual("test2", testResultsController.RetrieveVirtualItem(0).Text);
Assert.AreEqual("test3", testResultsController.RetrieveVirtualItem(1).Text);
Assert.AreEqual("test1", testResultsController.RetrieveVirtualItem(2).Text);
}
[Test]
public void Cache_miss_low()
{
EstablishContext();
testResultsController.CacheVirtualItems(1, 2);
var listViewItem = testResultsController.RetrieveVirtualItem(0);
Assert.AreEqual("test1", listViewItem.Text);
}
[Test]
public void Cache_miss_high()
{
EstablishContext();
testResultsController.CacheVirtualItems(0, 1);
var listViewItem = testResultsController.RetrieveVirtualItem(2);
Assert.AreEqual("test3", listViewItem.Text);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using ServiceStack.Text.Common;
using ServiceStack.Text.Json;
using ServiceStack.Text.Jsv;
#if WINDOWS_PHONE && !WP8
using ServiceStack.Text.WP;
#endif
namespace ServiceStack.Text
{
public static class
JsConfig
{
static JsConfig()
{
//In-built default serialization, to Deserialize Color struct do:
//JsConfig<System.Drawing.Color>.SerializeFn = c => c.ToString().Replace("Color ", "").Replace("[", "").Replace("]", "");
//JsConfig<System.Drawing.Color>.DeSerializeFn = System.Drawing.Color.FromName;
Reset();
}
public static JsConfigScope BeginScope()
{
return new JsConfigScope();
}
public static JsConfigScope With(
bool? convertObjectTypesIntoStringDictionary = null,
bool? tryToParsePrimitiveTypeValues = null,
bool? includeNullValues = null,
bool? excludeTypeInfo = null,
bool? includeTypeInfo = null,
bool? emitCamelCaseNames = null,
bool? emitLowercaseUnderscoreNames = null,
JsonDateHandler? dateHandler = null,
JsonTimeSpanHandler? timeSpanHandler = null,
bool? preferInterfaces = null,
bool? throwOnDeserializationError = null,
string typeAttr = null,
Func<Type, string> typeWriter = null,
Func<string, Type> typeFinder = null,
bool? treatEnumAsInteger = null,
bool? alwaysUseUtc = null,
bool? includePublicFields = null,
EmptyCtorFactoryDelegate modelFactory = null)
{
return new JsConfigScope {
ConvertObjectTypesIntoStringDictionary = convertObjectTypesIntoStringDictionary ?? sConvertObjectTypesIntoStringDictionary,
TryToParsePrimitiveTypeValues = tryToParsePrimitiveTypeValues ?? sTryToParsePrimitiveTypeValues,
IncludeNullValues = includeNullValues ?? sIncludeNullValues,
ExcludeTypeInfo = excludeTypeInfo ?? sExcludeTypeInfo,
IncludeTypeInfo = includeTypeInfo ?? sIncludeTypeInfo,
EmitCamelCaseNames = emitCamelCaseNames ?? sEmitCamelCaseNames,
EmitLowercaseUnderscoreNames = emitLowercaseUnderscoreNames ?? sEmitLowercaseUnderscoreNames,
DateHandler = dateHandler ?? sDateHandler,
TimeSpanHandler = timeSpanHandler ?? sTimeSpanHandler,
PreferInterfaces = preferInterfaces ?? sPreferInterfaces,
ThrowOnDeserializationError = throwOnDeserializationError ?? sThrowOnDeserializationError,
TypeAttr = typeAttr ?? sTypeAttr,
TypeWriter = typeWriter ?? sTypeWriter,
TypeFinder = typeFinder ?? sTypeFinder,
TreatEnumAsInteger = treatEnumAsInteger ?? sTreatEnumAsInteger,
AlwaysUseUtc = alwaysUseUtc ?? sAlwaysUseUtc,
IncludePublicFields = includePublicFields ?? sIncludePublicFields,
ModelFactory = modelFactory ?? ModelFactory,
};
}
private static bool? sConvertObjectTypesIntoStringDictionary;
public static bool ConvertObjectTypesIntoStringDictionary
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.ConvertObjectTypesIntoStringDictionary: null)
?? sConvertObjectTypesIntoStringDictionary
?? false;
}
set
{
if (!sConvertObjectTypesIntoStringDictionary.HasValue) sConvertObjectTypesIntoStringDictionary = value;
}
}
private static bool? sTryToParsePrimitiveTypeValues;
public static bool TryToParsePrimitiveTypeValues
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TryToParsePrimitiveTypeValues: null)
?? sTryToParsePrimitiveTypeValues
?? false;
}
set
{
if (!sTryToParsePrimitiveTypeValues.HasValue) sTryToParsePrimitiveTypeValues = value;
}
}
private static bool? sIncludeNullValues;
public static bool IncludeNullValues
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.IncludeNullValues: null)
?? sIncludeNullValues
?? false;
}
set
{
if (!sIncludeNullValues.HasValue) sIncludeNullValues = value;
}
}
private static bool? sTreatEnumAsInteger;
public static bool TreatEnumAsInteger
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TreatEnumAsInteger: null)
?? sTreatEnumAsInteger
?? false;
}
set
{
if (!sTreatEnumAsInteger.HasValue) sTreatEnumAsInteger = value;
}
}
private static bool? sExcludeTypeInfo;
public static bool ExcludeTypeInfo
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.ExcludeTypeInfo: null)
?? sExcludeTypeInfo
?? false;
}
set
{
if (!sExcludeTypeInfo.HasValue) sExcludeTypeInfo = value;
}
}
private static bool? sIncludeTypeInfo;
public static bool IncludeTypeInfo
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.IncludeTypeInfo: null)
?? sIncludeTypeInfo
?? false;
}
set
{
if (!sIncludeTypeInfo.HasValue) sIncludeTypeInfo = value;
}
}
private static string sTypeAttr;
public static string TypeAttr
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TypeAttr: null)
?? sTypeAttr
?? JsWriter.TypeAttr;
}
set
{
if (sTypeAttr == null) sTypeAttr = value;
JsonTypeAttrInObject = JsonTypeSerializer.GetTypeAttrInObject(value);
JsvTypeAttrInObject = JsvTypeSerializer.GetTypeAttrInObject(value);
}
}
private static string sJsonTypeAttrInObject;
private static readonly string defaultJsonTypeAttrInObject = JsonTypeSerializer.GetTypeAttrInObject(TypeAttr);
internal static string JsonTypeAttrInObject
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.JsonTypeAttrInObject: null)
?? sJsonTypeAttrInObject
?? defaultJsonTypeAttrInObject;
}
set
{
if (sJsonTypeAttrInObject == null) sJsonTypeAttrInObject = value;
}
}
private static string sJsvTypeAttrInObject;
private static readonly string defaultJsvTypeAttrInObject = JsvTypeSerializer.GetTypeAttrInObject(TypeAttr);
internal static string JsvTypeAttrInObject
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.JsvTypeAttrInObject: null)
?? sJsvTypeAttrInObject
?? defaultJsvTypeAttrInObject;
}
set
{
if (sJsvTypeAttrInObject == null) sJsvTypeAttrInObject = value;
}
}
private static Func<Type, string> sTypeWriter;
public static Func<Type, string> TypeWriter
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TypeWriter: null)
?? sTypeWriter
?? AssemblyUtils.WriteType;
}
set
{
if (sTypeWriter == null) sTypeWriter = value;
}
}
private static Func<string, Type> sTypeFinder;
public static Func<string, Type> TypeFinder
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TypeFinder: null)
?? sTypeFinder
?? AssemblyUtils.FindType;
}
set
{
if (sTypeFinder == null) sTypeFinder = value;
}
}
private static JsonDateHandler? sDateHandler;
public static JsonDateHandler DateHandler
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.DateHandler: null)
?? sDateHandler
?? JsonDateHandler.TimestampOffset;
}
set
{
if (!sDateHandler.HasValue) sDateHandler = value;
}
}
/// <summary>
/// Sets which format to use when serializing TimeSpans
/// </summary>
private static JsonTimeSpanHandler? sTimeSpanHandler;
public static JsonTimeSpanHandler TimeSpanHandler
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.TimeSpanHandler : null)
?? sTimeSpanHandler
?? JsonTimeSpanHandler.DurationFormat;
}
set
{
if (!sTimeSpanHandler.HasValue) sTimeSpanHandler = value;
}
}
/// <summary>
/// <see langword="true"/> if the <see cref="ITypeSerializer"/> is configured
/// to take advantage of <see cref="CLSCompliantAttribute"/> specification,
/// to support user-friendly serialized formats, ie emitting camelCasing for JSON
/// and parsing member names and enum values in a case-insensitive manner.
/// </summary>
private static bool? sEmitCamelCaseNames;
public static bool EmitCamelCaseNames
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.EmitCamelCaseNames: null)
?? sEmitCamelCaseNames
?? false;
}
set
{
if (!sEmitCamelCaseNames.HasValue) sEmitCamelCaseNames = value;
}
}
/// <summary>
/// <see langword="true"/> if the <see cref="ITypeSerializer"/> is configured
/// to support web-friendly serialized formats, ie emitting lowercase_underscore_casing for JSON
/// </summary>
private static bool? sEmitLowercaseUnderscoreNames;
public static bool EmitLowercaseUnderscoreNames
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.EmitLowercaseUnderscoreNames: null)
?? sEmitLowercaseUnderscoreNames
?? false;
}
set
{
if (!sEmitLowercaseUnderscoreNames.HasValue) sEmitLowercaseUnderscoreNames = value;
}
}
/// <summary>
/// Define how property names are mapped during deserialization
/// </summary>
private static JsonPropertyConvention propertyConvention;
public static JsonPropertyConvention PropertyConvention
{
get { return propertyConvention; }
set
{
propertyConvention = value;
switch (propertyConvention)
{
case JsonPropertyConvention.ExactMatch:
DeserializeTypeRefJson.PropertyNameResolver = DeserializeTypeRefJson.DefaultPropertyNameResolver;
break;
case JsonPropertyConvention.Lenient:
DeserializeTypeRefJson.PropertyNameResolver = DeserializeTypeRefJson.LenientPropertyNameResolver;
break;
}
}
}
/// <summary>
/// Gets or sets a value indicating if the framework should throw serialization exceptions
/// or continue regardless of deserialization errors. If <see langword="true"/> the framework
/// will throw; otherwise, it will parse as many fields as possible. The default is <see langword="false"/>.
/// </summary>
private static bool? sThrowOnDeserializationError;
public static bool ThrowOnDeserializationError
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.ThrowOnDeserializationError: null)
?? sThrowOnDeserializationError
?? false;
}
set
{
if (!sThrowOnDeserializationError.HasValue) sThrowOnDeserializationError = value;
}
}
/// <summary>
/// Gets or sets a value indicating if the framework should always convert <see cref="DateTime"/> to UTC format instead of local time.
/// </summary>
private static bool? sAlwaysUseUtc;
public static bool AlwaysUseUtc
{
// obeying the use of ThreadStatic, but allowing for setting JsConfig once as is the normal case
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.AlwaysUseUtc: null)
?? sAlwaysUseUtc
?? false;
}
set
{
if (!sAlwaysUseUtc.HasValue) sAlwaysUseUtc = value;
}
}
internal static HashSet<Type> HasSerializeFn = new HashSet<Type>();
public static HashSet<Type> TreatValueAsRefTypes = new HashSet<Type>();
private static bool? sPreferInterfaces;
/// <summary>
/// If set to true, Interface types will be prefered over concrete types when serializing.
/// </summary>
public static bool PreferInterfaces
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.PreferInterfaces: null)
?? sPreferInterfaces
?? false;
}
set
{
if (!sPreferInterfaces.HasValue) sPreferInterfaces = value;
}
}
internal static bool TreatAsRefType(Type valueType)
{
#if NETFX_CORE
return TreatValueAsRefTypes.Contains(valueType.GetTypeInfo().IsGenericType ? valueType.GetGenericTypeDefinition() : valueType);
#else
return TreatValueAsRefTypes.Contains(valueType.IsGenericType ? valueType.GetGenericTypeDefinition() : valueType);
#endif
}
/// <summary>
/// If set to true, Interface types will be prefered over concrete types when serializing.
/// </summary>
private static bool? sIncludePublicFields;
public static bool IncludePublicFields
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.IncludePublicFields : null)
?? sIncludePublicFields
?? false;
}
set
{
if (!sIncludePublicFields.HasValue) sIncludePublicFields = value;
}
}
/// <summary>
/// Set this to enable your own type construction provider.
/// This is helpful for integration with IoC containers where you need to call the container constructor.
/// Return null if you don't know how to construct the type and the parameterless constructor will be used.
/// </summary>
private static EmptyCtorFactoryDelegate sModelFactory;
public static EmptyCtorFactoryDelegate ModelFactory
{
get
{
return (JsConfigScope.Current != null ? JsConfigScope.Current.ModelFactory : null)
?? sModelFactory
?? null;
}
set
{
if (sModelFactory != null) sModelFactory = value;
}
}
public static void Reset()
{
sModelFactory = ReflectionExtensions.GetConstructorMethodToCache;
sTryToParsePrimitiveTypeValues = null;
sConvertObjectTypesIntoStringDictionary = null;
sIncludeNullValues = null;
sExcludeTypeInfo = null;
sEmitCamelCaseNames = null;
sEmitLowercaseUnderscoreNames = null;
sDateHandler = null;
sTimeSpanHandler = null;
sPreferInterfaces = null;
sThrowOnDeserializationError = null;
sTypeAttr = null;
sJsonTypeAttrInObject = null;
sJsvTypeAttrInObject = null;
sTypeWriter = null;
sTypeFinder = null;
sTreatEnumAsInteger = null;
sAlwaysUseUtc = null;
sIncludePublicFields = null;
HasSerializeFn = new HashSet<Type>();
TreatValueAsRefTypes = new HashSet<Type> { typeof(KeyValuePair<,>) };
PropertyConvention = JsonPropertyConvention.ExactMatch;
}
#if MONOTOUCH
/// <summary>
/// Provide hint to MonoTouch AOT compiler to pre-compile generic classes for all your DTOs.
/// Just needs to be called once in a static constructor.
/// </summary>
[MonoTouch.Foundation.Preserve]
public static void InitForAot() {
}
[MonoTouch.Foundation.Preserve]
public static void RegisterForAot()
{
RegisterTypeForAot<Poco>();
RegisterElement<Poco, string>();
RegisterElement<Poco, bool>();
RegisterElement<Poco, char>();
RegisterElement<Poco, byte>();
RegisterElement<Poco, sbyte>();
RegisterElement<Poco, short>();
RegisterElement<Poco, ushort>();
RegisterElement<Poco, int>();
RegisterElement<Poco, uint>();
RegisterElement<Poco, long>();
RegisterElement<Poco, ulong>();
RegisterElement<Poco, float>();
RegisterElement<Poco, double>();
RegisterElement<Poco, decimal>();
RegisterElement<Poco, bool?>();
RegisterElement<Poco, char?>();
RegisterElement<Poco, byte?>();
RegisterElement<Poco, sbyte?>();
RegisterElement<Poco, short?>();
RegisterElement<Poco, ushort?>();
RegisterElement<Poco, int?>();
RegisterElement<Poco, uint?>();
RegisterElement<Poco, long?>();
RegisterElement<Poco, ulong?>();
RegisterElement<Poco, float?>();
RegisterElement<Poco, double?>();
RegisterElement<Poco, decimal?>();
//RegisterElement<Poco, JsonValue>();
RegisterTypeForAot<DayOfWeek>(); // used by DateTime
// register built in structs
RegisterTypeForAot<Guid>();
RegisterTypeForAot<TimeSpan>();
RegisterTypeForAot<DateTime>();
RegisterTypeForAot<DateTime?>();
RegisterTypeForAot<TimeSpan?>();
RegisterTypeForAot<Guid?>();
}
[MonoTouch.Foundation.Preserve]
public static void RegisterTypeForAot<T>()
{
AotConfig.RegisterSerializers<T>();
}
[MonoTouch.Foundation.Preserve]
static void RegisterQueryStringWriter()
{
var i = 0;
if (QueryStringWriter<Poco>.WriteFn() != null) i++;
}
[MonoTouch.Foundation.Preserve]
internal static int RegisterElement<T, TElement>()
{
var i = 0;
i += AotConfig.RegisterSerializers<TElement>();
AotConfig.RegisterElement<T, TElement, JsonTypeSerializer>();
AotConfig.RegisterElement<T, TElement, JsvTypeSerializer>();
return i;
}
///<summary>
/// Class contains Ahead-of-Time (AOT) explicit class declarations which is used only to workaround "-aot-only" exceptions occured on device only.
/// </summary>
[MonoTouch.Foundation.Preserve(AllMembers=true)]
internal class AotConfig
{
internal static JsReader<JsonTypeSerializer> jsonReader;
internal static JsWriter<JsonTypeSerializer> jsonWriter;
internal static JsReader<JsvTypeSerializer> jsvReader;
internal static JsWriter<JsvTypeSerializer> jsvWriter;
internal static JsonTypeSerializer jsonSerializer;
internal static JsvTypeSerializer jsvSerializer;
static AotConfig()
{
jsonSerializer = new JsonTypeSerializer();
jsvSerializer = new JsvTypeSerializer();
jsonReader = new JsReader<JsonTypeSerializer>();
jsonWriter = new JsWriter<JsonTypeSerializer>();
jsvReader = new JsReader<JsvTypeSerializer>();
jsvWriter = new JsWriter<JsvTypeSerializer>();
}
internal static int RegisterSerializers<T>()
{
var i = 0;
i += Register<T, JsonTypeSerializer>();
if (jsonSerializer.GetParseFn<T>() != null) i++;
if (jsonSerializer.GetWriteFn<T>() != null) i++;
if (jsonReader.GetParseFn<T>() != null) i++;
if (jsonWriter.GetWriteFn<T>() != null) i++;
i += Register<T, JsvTypeSerializer>();
if (jsvSerializer.GetParseFn<T>() != null) i++;
if (jsvSerializer.GetWriteFn<T>() != null) i++;
if (jsvReader.GetParseFn<T>() != null) i++;
if (jsvWriter.GetWriteFn<T>() != null) i++;
//RegisterCsvSerializer<T>();
RegisterQueryStringWriter();
return i;
}
internal static void RegisterCsvSerializer<T>()
{
CsvSerializer<T>.WriteFn();
CsvSerializer<T>.WriteObject(null, null);
CsvWriter<T>.Write(null, default(IEnumerable<T>));
CsvWriter<T>.WriteRow(null, default(T));
}
public static ParseStringDelegate GetParseFn(Type type)
{
var parseFn = JsonTypeSerializer.Instance.GetParseFn(type);
return parseFn;
}
internal static int Register<T, TSerializer>() where TSerializer : ITypeSerializer
{
var i = 0;
if (JsonWriter<T>.WriteFn() != null) i++;
if (JsonWriter.Instance.GetWriteFn<T>() != null) i++;
if (JsonReader.Instance.GetParseFn<T>() != null) i++;
if (JsonReader<T>.Parse(null) != null) i++;
if (JsonReader<T>.GetParseFn() != null) i++;
//if (JsWriter.GetTypeSerializer<JsonTypeSerializer>().GetWriteFn<T>() != null) i++;
if (new List<T>() != null) i++;
if (new T[0] != null) i++;
JsConfig<T>.ExcludeTypeInfo = false;
if (JsConfig<T>.OnDeserializedFn != null) i++;
if (JsConfig<T>.HasDeserializeFn) i++;
if (JsConfig<T>.SerializeFn != null) i++;
if (JsConfig<T>.DeSerializeFn != null) i++;
//JsConfig<T>.SerializeFn = arg => "";
//JsConfig<T>.DeSerializeFn = arg => default(T);
if (TypeConfig<T>.Properties != null) i++;
/*
if (WriteType<T, TSerializer>.Write != null) i++;
if (WriteType<object, TSerializer>.Write != null) i++;
if (DeserializeBuiltin<T>.Parse != null) i++;
if (DeserializeArray<T[], TSerializer>.Parse != null) i++;
DeserializeType<TSerializer>.ExtractType(null);
DeserializeArrayWithElements<T, TSerializer>.ParseGenericArray(null, null);
DeserializeCollection<TSerializer>.ParseCollection<T>(null, null, null);
DeserializeListWithElements<T, TSerializer>.ParseGenericList(null, null, null);
SpecializedQueueElements<T>.ConvertToQueue(null);
SpecializedQueueElements<T>.ConvertToStack(null);
*/
WriteListsOfElements<T, TSerializer>.WriteList(null, null);
WriteListsOfElements<T, TSerializer>.WriteIList(null, null);
WriteListsOfElements<T, TSerializer>.WriteEnumerable(null, null);
WriteListsOfElements<T, TSerializer>.WriteListValueType(null, null);
WriteListsOfElements<T, TSerializer>.WriteIListValueType(null, null);
WriteListsOfElements<T, TSerializer>.WriteGenericArrayValueType(null, null);
WriteListsOfElements<T, TSerializer>.WriteArray(null, null);
TranslateListWithElements<T>.LateBoundTranslateToGenericICollection(null, null);
TranslateListWithConvertibleElements<T, T>.LateBoundTranslateToGenericICollection(null, null);
QueryStringWriter<T>.WriteObject(null, null);
return i;
}
internal static void RegisterElement<T, TElement, TSerializer>() where TSerializer : ITypeSerializer
{
DeserializeDictionary<TSerializer>.ParseDictionary<T, TElement>(null, null, null, null);
DeserializeDictionary<TSerializer>.ParseDictionary<TElement, T>(null, null, null, null);
ToStringDictionaryMethods<T, TElement, TSerializer>.WriteIDictionary(null, null, null, null);
ToStringDictionaryMethods<TElement, T, TSerializer>.WriteIDictionary(null, null, null, null);
// Include List deserialisations from the Register<> method above. This solves issue where List<Guid> properties on responses deserialise to null.
// No idea why this is happening because there is no visible exception raised. Suspect MonoTouch is swallowing an AOT exception somewhere.
DeserializeArrayWithElements<TElement, TSerializer>.ParseGenericArray(null, null);
DeserializeListWithElements<TElement, TSerializer>.ParseGenericList(null, null, null);
// Cannot use the line below for some unknown reason - when trying to compile to run on device, mtouch bombs during native code compile.
// Something about this line or its inner workings is offensive to mtouch. Luckily this was not needed for my List<Guide> issue.
// DeserializeCollection<JsonTypeSerializer>.ParseCollection<TElement>(null, null, null);
TranslateListWithElements<TElement>.LateBoundTranslateToGenericICollection(null, typeof(List<TElement>));
TranslateListWithConvertibleElements<TElement, TElement>.LateBoundTranslateToGenericICollection(null, typeof(List<TElement>));
}
}
#endif
}
#if MONOTOUCH
[MonoTouch.Foundation.Preserve(AllMembers=true)]
internal class Poco
{
public string Dummy { get; set; }
}
#endif
public class JsConfig<T>
{
/// <summary>
/// Always emit type info for this type. Takes precedence over ExcludeTypeInfo
/// </summary>
public static bool IncludeTypeInfo = false;
/// <summary>
/// Never emit type info for this type
/// </summary>
public static bool ExcludeTypeInfo = false;
/// <summary>
/// <see langword="true"/> if the <see cref="ITypeSerializer"/> is configured
/// to take advantage of <see cref="CLSCompliantAttribute"/> specification,
/// to support user-friendly serialized formats, ie emitting camelCasing for JSON
/// and parsing member names and enum values in a case-insensitive manner.
/// </summary>
public static bool EmitCamelCaseNames = false;
public static bool EmitLowercaseUnderscoreNames = false;
/// <summary>
/// Define custom serialization fn for BCL Structs
/// </summary>
private static Func<T, string> serializeFn;
public static Func<T, string> SerializeFn
{
get { return serializeFn; }
set
{
serializeFn = value;
if (value != null)
JsConfig.HasSerializeFn.Add(typeof(T));
else
JsConfig.HasSerializeFn.Remove(typeof(T));
}
}
/// <summary>
/// Opt-in flag to set some Value Types to be treated as a Ref Type
/// </summary>
public static bool TreatValueAsRefType
{
get { return JsConfig.TreatValueAsRefTypes.Contains(typeof(T)); }
set
{
if (value)
JsConfig.TreatValueAsRefTypes.Add(typeof(T));
else
JsConfig.TreatValueAsRefTypes.Remove(typeof(T));
}
}
/// <summary>
/// Whether there is a fn (raw or otherwise)
/// </summary>
public static bool HasSerializeFn
{
get { return serializeFn != null || rawSerializeFn != null; }
}
/// <summary>
/// Define custom raw serialization fn
/// </summary>
private static Func<T, string> rawSerializeFn;
public static Func<T, string> RawSerializeFn
{
get { return rawSerializeFn; }
set
{
rawSerializeFn = value;
if (value != null)
JsConfig.HasSerializeFn.Add(typeof(T));
else
JsConfig.HasSerializeFn.Remove(typeof(T));
}
}
/// <summary>
/// Define custom serialization hook
/// </summary>
private static Func<T, T> onSerializingFn;
public static Func<T, T> OnSerializingFn
{
get { return onSerializingFn; }
set { onSerializingFn = value; }
}
/// <summary>
/// Define custom deserialization fn for BCL Structs
/// </summary>
public static Func<string, T> DeSerializeFn;
/// <summary>
/// Define custom raw deserialization fn for objects
/// </summary>
public static Func<string, T> RawDeserializeFn;
public static bool HasDeserializeFn
{
get { return DeSerializeFn != null || RawDeserializeFn != null; }
}
private static Func<T, T> onDeserializedFn;
public static Func<T, T> OnDeserializedFn
{
get { return onDeserializedFn; }
set { onDeserializedFn = value; }
}
/// <summary>
/// Exclude specific properties of this type from being serialized
/// </summary>
public static string[] ExcludePropertyNames;
public static void WriteFn<TSerializer>(TextWriter writer, object obj)
{
if (RawSerializeFn != null)
{
writer.Write(RawSerializeFn((T)obj));
}
else
{
var serializer = JsWriter.GetTypeSerializer<TSerializer>();
serializer.WriteString(writer, SerializeFn((T)obj));
}
}
public static object ParseFn(string str)
{
return DeSerializeFn(str);
}
internal static object ParseFn(ITypeSerializer serializer, string str)
{
if (RawDeserializeFn != null)
{
return RawDeserializeFn(str);
}
else
{
return DeSerializeFn(serializer.UnescapeString(str));
}
}
}
public enum JsonPropertyConvention
{
/// <summary>
/// The property names on target types must match property names in the JSON source
/// </summary>
ExactMatch,
/// <summary>
/// The property names on target types may not match the property names in the JSON source
/// </summary>
Lenient
}
public enum JsonDateHandler
{
TimestampOffset,
DCJSCompatible,
ISO8601
}
public enum JsonTimeSpanHandler
{
/// <summary>
/// Uses the xsd format like PT15H10M20S
/// </summary>
DurationFormat,
/// <summary>
/// Uses the standard .net ToString method of the TimeSpan class
/// </summary>
StandardFormat
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityStandardAssets.Water
{
[ExecuteInEditMode]
[RequireComponent(typeof(WaterBase))]
public class PlanarReflection : MonoBehaviour
{
public LayerMask reflectionMask;
public bool reflectSkybox = false;
public Color clearColor = Color.grey;
public String reflectionSampler = "_ReflectionTex";
public float clipPlaneOffset = 0.07F;
Vector3 m_Oldpos;
Camera m_ReflectionCamera;
Material m_SharedMaterial;
Dictionary<Camera, bool> m_HelperCameras;
public void Start()
{
m_SharedMaterial = ((WaterBase)gameObject.GetComponent(typeof(WaterBase))).sharedMaterial;
}
Camera CreateReflectionCameraFor(Camera cam)
{
// Reflection name with removed "+ cam.name" hoping it won't cause collisions, because it was often random
String reflName = gameObject.name + "Reflection";
GameObject go = GameObject.Find(reflName);
if (!go)
{
go = new GameObject(reflName, typeof(Camera));
}
if (!go.GetComponent(typeof(Camera)))
{
go.AddComponent(typeof(Camera));
}
Camera reflectCamera = go.GetComponent<Camera>();
reflectCamera.backgroundColor = clearColor;
reflectCamera.clearFlags = reflectSkybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor;
SetStandardCameraParameter(reflectCamera, reflectionMask);
if (!reflectCamera.targetTexture)
{
reflectCamera.targetTexture = CreateTextureFor(cam);
}
return reflectCamera;
}
void SetStandardCameraParameter(Camera cam, LayerMask mask)
{
cam.cullingMask = mask & ~(1 << LayerMask.NameToLayer("Water"));
cam.backgroundColor = Color.black;
cam.enabled = false;
}
RenderTexture CreateTextureFor(Camera cam)
{
RenderTexture rt = new RenderTexture(Mathf.FloorToInt(cam.pixelWidth * 0.5F),
Mathf.FloorToInt(cam.pixelHeight * 0.5F), 24);
rt.hideFlags = HideFlags.DontSave;
return rt;
}
public void RenderHelpCameras(Camera currentCam)
{
if (null == m_HelperCameras)
{
m_HelperCameras = new Dictionary<Camera, bool>();
}
if (!m_HelperCameras.ContainsKey(currentCam))
{
m_HelperCameras.Add(currentCam, false);
}
if (m_HelperCameras[currentCam])
{
return;
}
if (!m_ReflectionCamera)
{
m_ReflectionCamera = CreateReflectionCameraFor(currentCam);
}
RenderReflectionFor(currentCam, m_ReflectionCamera);
m_HelperCameras[currentCam] = true;
}
public void LateUpdate()
{
if (null != m_HelperCameras)
{
m_HelperCameras.Clear();
}
}
public void WaterTileBeingRendered(Transform tr, Camera currentCam)
{
RenderHelpCameras(currentCam);
if (m_ReflectionCamera && m_SharedMaterial)
{
m_SharedMaterial.SetTexture(reflectionSampler, m_ReflectionCamera.targetTexture);
}
}
public void OnEnable()
{
Shader.EnableKeyword("WATER_REFLECTIVE");
Shader.DisableKeyword("WATER_SIMPLE");
}
public void OnDisable()
{
Shader.EnableKeyword("WATER_SIMPLE");
Shader.DisableKeyword("WATER_REFLECTIVE");
}
void RenderReflectionFor(Camera cam, Camera reflectCamera)
{
if (!reflectCamera)
{
return;
}
if (m_SharedMaterial && !m_SharedMaterial.HasProperty(reflectionSampler))
{
return;
}
reflectCamera.cullingMask = reflectionMask & ~(1 << LayerMask.NameToLayer("Water"));
SaneCameraSettings(reflectCamera);
reflectCamera.backgroundColor = clearColor;
reflectCamera.clearFlags = reflectSkybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor;
if (reflectSkybox)
{
if (cam.gameObject.GetComponent(typeof(Skybox)))
{
Skybox sb = (Skybox)reflectCamera.gameObject.GetComponent(typeof(Skybox));
if (!sb)
{
sb = (Skybox)reflectCamera.gameObject.AddComponent(typeof(Skybox));
}
sb.material = ((Skybox)cam.GetComponent(typeof(Skybox))).material;
}
}
GL.invertCulling = true;
Transform reflectiveSurface = transform; //waterHeight;
Vector3 eulerA = cam.transform.eulerAngles;
reflectCamera.transform.eulerAngles = new Vector3(-eulerA.x, eulerA.y, eulerA.z);
reflectCamera.transform.position = cam.transform.position;
Vector3 pos = reflectiveSurface.transform.position;
pos.y = reflectiveSurface.position.y;
Vector3 normal = reflectiveSurface.transform.up;
float d = -Vector3.Dot(normal, pos) - clipPlaneOffset;
Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);
Matrix4x4 reflection = Matrix4x4.zero;
reflection = CalculateReflectionMatrix(reflection, reflectionPlane);
m_Oldpos = cam.transform.position;
Vector3 newpos = reflection.MultiplyPoint(m_Oldpos);
reflectCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
Vector4 clipPlane = CameraSpacePlane(reflectCamera, pos, normal, 1.0f);
Matrix4x4 projection = cam.projectionMatrix;
projection = CalculateObliqueMatrix(projection, clipPlane);
reflectCamera.projectionMatrix = projection;
reflectCamera.transform.position = newpos;
Vector3 euler = cam.transform.eulerAngles;
reflectCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z);
reflectCamera.Render();
GL.invertCulling = false;
}
void SaneCameraSettings(Camera helperCam)
{
helperCam.depthTextureMode = DepthTextureMode.None;
helperCam.backgroundColor = Color.black;
helperCam.clearFlags = CameraClearFlags.SolidColor;
helperCam.renderingPath = RenderingPath.Forward;
}
static Matrix4x4 CalculateObliqueMatrix(Matrix4x4 projection, Vector4 clipPlane)
{
Vector4 q = projection.inverse * new Vector4(
Sgn(clipPlane.x),
Sgn(clipPlane.y),
1.0F,
1.0F
);
Vector4 c = clipPlane * (2.0F / (Vector4.Dot(clipPlane, q)));
// third row = clip plane - fourth row
projection[2] = c.x - projection[3];
projection[6] = c.y - projection[7];
projection[10] = c.z - projection[11];
projection[14] = c.w - projection[15];
return projection;
}
static Matrix4x4 CalculateReflectionMatrix(Matrix4x4 reflectionMat, Vector4 plane)
{
reflectionMat.m00 = (1.0F - 2.0F * plane[0] * plane[0]);
reflectionMat.m01 = (- 2.0F * plane[0] * plane[1]);
reflectionMat.m02 = (- 2.0F * plane[0] * plane[2]);
reflectionMat.m03 = (- 2.0F * plane[3] * plane[0]);
reflectionMat.m10 = (- 2.0F * plane[1] * plane[0]);
reflectionMat.m11 = (1.0F - 2.0F * plane[1] * plane[1]);
reflectionMat.m12 = (- 2.0F * plane[1] * plane[2]);
reflectionMat.m13 = (- 2.0F * plane[3] * plane[1]);
reflectionMat.m20 = (- 2.0F * plane[2] * plane[0]);
reflectionMat.m21 = (- 2.0F * plane[2] * plane[1]);
reflectionMat.m22 = (1.0F - 2.0F * plane[2] * plane[2]);
reflectionMat.m23 = (- 2.0F * plane[3] * plane[2]);
reflectionMat.m30 = 0.0F;
reflectionMat.m31 = 0.0F;
reflectionMat.m32 = 0.0F;
reflectionMat.m33 = 1.0F;
return reflectionMat;
}
static float Sgn(float a)
{
if (a > 0.0F)
{
return 1.0F;
}
if (a < 0.0F)
{
return -1.0F;
}
return 0.0F;
}
Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
Vector3 offsetPos = pos + normal * clipPlaneOffset;
Matrix4x4 m = cam.worldToCameraMatrix;
Vector3 cpos = m.MultiplyPoint(offsetPos);
Vector3 cnormal = m.MultiplyVector(normal).normalized * sideSign;
return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos, cnormal));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void Permute2x128UInt322()
{
var test = new ImmBinaryOpTest__Permute2x128UInt322();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__Permute2x128UInt322
{
private struct TestStruct
{
public Vector256<UInt32> _fld1;
public Vector256<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__Permute2x128UInt322 testClass)
{
var result = Avx2.Permute2x128(_fld1, _fld2, 2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector256<UInt32> _clsVar1;
private static Vector256<UInt32> _clsVar2;
private Vector256<UInt32> _fld1;
private Vector256<UInt32> _fld2;
private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable;
static ImmBinaryOpTest__Permute2x128UInt322()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
}
public ImmBinaryOpTest__Permute2x128UInt322()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Permute2x128(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Permute2x128(
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Permute2x128(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Permute2x128), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Permute2x128), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Permute2x128), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Permute2x128(
_clsVar1,
_clsVar2,
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr);
var result = Avx2.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.Permute2x128(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__Permute2x128UInt322();
var result = Avx2.Permute2x128(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Permute2x128(_fld1, _fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Permute2x128(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt32> left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != right[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (i > 3 ? (result[i] != left[i - 4]) : (result[i] != right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Permute2x128)}<UInt32>(Vector256<UInt32>.2, Vector256<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Text;
using System.Xml;
using System.IO;
using fyiReporting.RDL;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// Summary description for DialogDataSourceRef.
/// </summary>
internal class DialogDataSources : System.Windows.Forms.Form
{
DesignXmlDraw _Draw;
string _FileName; // file name of open file; used to obtain directory
private System.Windows.Forms.TextBox tbFilename;
private System.Windows.Forms.Button bGetFilename;
private System.Windows.Forms.ComboBox cbDataProvider;
private System.Windows.Forms.TextBox tbConnection;
private System.Windows.Forms.CheckBox ckbIntSecurity;
private System.Windows.Forms.TextBox tbPrompt;
private System.Windows.Forms.Button bOK;
private System.Windows.Forms.Button bCancel;
private System.Windows.Forms.Button bTestConnection;
private System.Windows.Forms.ListBox lbDataSources;
private System.Windows.Forms.Button bRemove;
private System.Windows.Forms.Button bAdd;
private System.Windows.Forms.CheckBox chkSharedDataSource;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lDataProvider;
private System.Windows.Forms.Label lConnectionString;
private System.Windows.Forms.Label lPrompt;
private System.Windows.Forms.TextBox tbDSName;
private System.Windows.Forms.Button bExprConnect;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal DialogDataSources(string filename, DesignXmlDraw draw)
{
_Draw = draw;
_FileName = filename;
//
// Required for Windows Form Designer support
//
InitializeComponent();
InitValues();
}
private void InitValues()
{
// Populate the DataProviders
cbDataProvider.Items.Clear();
string[] items = RdlEngineConfig.GetProviders();
cbDataProvider.Items.AddRange(items);
//
// Obtain the existing DataSets info
//
XmlNode rNode = _Draw.GetReportNode();
XmlNode dsNode = _Draw.GetNamedChildNode(rNode, "DataSources");
if (dsNode == null)
return;
foreach (XmlNode dNode in dsNode)
{
if (dNode.Name != "DataSource")
continue;
XmlAttribute nAttr = dNode.Attributes["Name"];
if (nAttr == null) // shouldn't really happen
continue;
DataSourceValues dsv = new DataSourceValues(nAttr.Value);
dsv.Node = dNode;
dsv.DataSourceReference = _Draw.GetElementValue(dNode, "DataSourceReference", null);
if (dsv.DataSourceReference == null)
{ // this is not a data source reference
dsv.bDataSourceReference = false;
dsv.DataSourceReference = "";
XmlNode cpNode = DesignXmlDraw.FindNextInHierarchy(dNode, "ConnectionProperties", "ConnectString");
dsv.ConnectionString = cpNode == null? "": cpNode.InnerText;
XmlNode datap = DesignXmlDraw.FindNextInHierarchy(dNode, "ConnectionProperties", "DataProvider");
dsv.DataProvider = datap == null? "": datap.InnerText;
XmlNode p = DesignXmlDraw.FindNextInHierarchy(dNode, "ConnectionProperties", "Prompt");
dsv.Prompt = p == null? "": p.InnerText;
}
else
{ // we have a data source reference
dsv.bDataSourceReference = true;
dsv.ConnectionString = "";
dsv.DataProvider = "";
dsv.Prompt = "";
}
this.lbDataSources.Items.Add(dsv);
}
if (lbDataSources.Items.Count > 0)
lbDataSources.SelectedIndex = 0;
else
this.bOK.Enabled = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tbFilename = new System.Windows.Forms.TextBox();
this.bGetFilename = new System.Windows.Forms.Button();
this.lDataProvider = new System.Windows.Forms.Label();
this.cbDataProvider = new System.Windows.Forms.ComboBox();
this.lConnectionString = new System.Windows.Forms.Label();
this.tbConnection = new System.Windows.Forms.TextBox();
this.ckbIntSecurity = new System.Windows.Forms.CheckBox();
this.lPrompt = new System.Windows.Forms.Label();
this.tbPrompt = new System.Windows.Forms.TextBox();
this.bOK = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.bTestConnection = new System.Windows.Forms.Button();
this.lbDataSources = new System.Windows.Forms.ListBox();
this.bRemove = new System.Windows.Forms.Button();
this.bAdd = new System.Windows.Forms.Button();
this.chkSharedDataSource = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this.tbDSName = new System.Windows.Forms.TextBox();
this.bExprConnect = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// tbFilename
//
this.tbFilename.Location = new System.Drawing.Point(192, 112);
this.tbFilename.Name = "tbFilename";
this.tbFilename.Size = new System.Drawing.Size(216, 20);
this.tbFilename.TabIndex = 2;
this.tbFilename.Text = "";
this.tbFilename.TextChanged += new System.EventHandler(this.tbFilename_TextChanged);
//
// bGetFilename
//
this.bGetFilename.Location = new System.Drawing.Point(424, 112);
this.bGetFilename.Name = "bGetFilename";
this.bGetFilename.Size = new System.Drawing.Size(24, 23);
this.bGetFilename.TabIndex = 3;
this.bGetFilename.Text = "...";
this.bGetFilename.Click += new System.EventHandler(this.bGetFilename_Click);
//
// lDataProvider
//
this.lDataProvider.Location = new System.Drawing.Point(8, 152);
this.lDataProvider.Name = "lDataProvider";
this.lDataProvider.Size = new System.Drawing.Size(80, 23);
this.lDataProvider.TabIndex = 7;
this.lDataProvider.Text = "Data provider";
//
// cbDataProvider
//
this.cbDataProvider.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbDataProvider.Items.AddRange(new object[] {
"SQL",
"ODBC",
"OLEDB"});
this.cbDataProvider.Location = new System.Drawing.Point(96, 152);
this.cbDataProvider.Name = "cbDataProvider";
this.cbDataProvider.Size = new System.Drawing.Size(144, 21);
this.cbDataProvider.TabIndex = 4;
this.cbDataProvider.SelectedIndexChanged += new System.EventHandler(this.cbDataProvider_SelectedIndexChanged);
//
// lConnectionString
//
this.lConnectionString.Location = new System.Drawing.Point(8, 192);
this.lConnectionString.Name = "lConnectionString";
this.lConnectionString.Size = new System.Drawing.Size(100, 16);
this.lConnectionString.TabIndex = 10;
this.lConnectionString.Text = "Connection string";
//
// tbConnection
//
this.tbConnection.Location = new System.Drawing.Point(16, 216);
this.tbConnection.Multiline = true;
this.tbConnection.Name = "tbConnection";
this.tbConnection.Size = new System.Drawing.Size(424, 40);
this.tbConnection.TabIndex = 6;
this.tbConnection.Text = "";
this.tbConnection.TextChanged += new System.EventHandler(this.tbConnection_TextChanged);
//
// ckbIntSecurity
//
this.ckbIntSecurity.Location = new System.Drawing.Point(280, 152);
this.ckbIntSecurity.Name = "ckbIntSecurity";
this.ckbIntSecurity.Size = new System.Drawing.Size(144, 24);
this.ckbIntSecurity.TabIndex = 5;
this.ckbIntSecurity.Text = "Use integrated security";
this.ckbIntSecurity.CheckedChanged += new System.EventHandler(this.ckbIntSecurity_CheckedChanged);
//
// lPrompt
//
this.lPrompt.Location = new System.Drawing.Point(8, 272);
this.lPrompt.Name = "lPrompt";
this.lPrompt.Size = new System.Drawing.Size(432, 16);
this.lPrompt.TabIndex = 12;
this.lPrompt.Text = "(Optional) Enter the prompt displayed when asking for database credentials ";
//
// tbPrompt
//
this.tbPrompt.Location = new System.Drawing.Point(16, 296);
this.tbPrompt.Name = "tbPrompt";
this.tbPrompt.Size = new System.Drawing.Size(424, 20);
this.tbPrompt.TabIndex = 7;
this.tbPrompt.Text = "";
this.tbPrompt.TextChanged += new System.EventHandler(this.tbPrompt_TextChanged);
//
// bOK
//
this.bOK.Location = new System.Drawing.Point(272, 344);
this.bOK.Name = "bOK";
this.bOK.TabIndex = 9;
this.bOK.Text = "OK";
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.CausesValidation = false;
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(368, 344);
this.bCancel.Name = "bCancel";
this.bCancel.TabIndex = 10;
this.bCancel.Text = "Cancel";
//
// bTestConnection
//
this.bTestConnection.Location = new System.Drawing.Point(16, 344);
this.bTestConnection.Name = "bTestConnection";
this.bTestConnection.Size = new System.Drawing.Size(96, 23);
this.bTestConnection.TabIndex = 8;
this.bTestConnection.Text = "Test Connection";
this.bTestConnection.Click += new System.EventHandler(this.bTestConnection_Click);
//
// lbDataSources
//
this.lbDataSources.Location = new System.Drawing.Point(16, 8);
this.lbDataSources.Name = "lbDataSources";
this.lbDataSources.Size = new System.Drawing.Size(120, 82);
this.lbDataSources.TabIndex = 11;
this.lbDataSources.SelectedIndexChanged += new System.EventHandler(this.lbDataSources_SelectedIndexChanged);
//
// bRemove
//
this.bRemove.Location = new System.Drawing.Point(144, 40);
this.bRemove.Name = "bRemove";
this.bRemove.Size = new System.Drawing.Size(56, 23);
this.bRemove.TabIndex = 20;
this.bRemove.Text = "Remove";
this.bRemove.Click += new System.EventHandler(this.bRemove_Click);
//
// bAdd
//
this.bAdd.Location = new System.Drawing.Point(144, 8);
this.bAdd.Name = "bAdd";
this.bAdd.Size = new System.Drawing.Size(56, 23);
this.bAdd.TabIndex = 19;
this.bAdd.Text = "Add";
this.bAdd.Click += new System.EventHandler(this.bAdd_Click);
//
// chkSharedDataSource
//
this.chkSharedDataSource.Location = new System.Drawing.Point(8, 112);
this.chkSharedDataSource.Name = "chkSharedDataSource";
this.chkSharedDataSource.Size = new System.Drawing.Size(184, 16);
this.chkSharedDataSource.TabIndex = 1;
this.chkSharedDataSource.Text = "Shared Data Source Reference";
this.chkSharedDataSource.CheckedChanged += new System.EventHandler(this.chkSharedDataSource_CheckedChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(216, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(104, 23);
this.label1.TabIndex = 22;
this.label1.Text = "Data Source Name";
//
// tbDSName
//
this.tbDSName.Location = new System.Drawing.Point(216, 24);
this.tbDSName.Name = "tbDSName";
this.tbDSName.Size = new System.Drawing.Size(216, 20);
this.tbDSName.TabIndex = 0;
this.tbDSName.Text = "";
this.tbDSName.Validating += new System.ComponentModel.CancelEventHandler(this.tbDSName_Validating);
this.tbDSName.TextChanged += new System.EventHandler(this.tbDSName_TextChanged);
//
// bExprConnect
//
this.bExprConnect.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.bExprConnect.Location = new System.Drawing.Point(416, 192);
this.bExprConnect.Name = "bExprConnect";
this.bExprConnect.Size = new System.Drawing.Size(22, 16);
this.bExprConnect.TabIndex = 23;
this.bExprConnect.Tag = "pright";
this.bExprConnect.Text = "fx";
this.bExprConnect.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bExprConnect.Click += new System.EventHandler(this.bExprConnect_Click);
//
// DialogDataSources
//
this.AcceptButton = this.bOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(456, 374);
this.Controls.Add(this.bExprConnect);
this.Controls.Add(this.tbDSName);
this.Controls.Add(this.label1);
this.Controls.Add(this.chkSharedDataSource);
this.Controls.Add(this.bRemove);
this.Controls.Add(this.bAdd);
this.Controls.Add(this.lbDataSources);
this.Controls.Add(this.bTestConnection);
this.Controls.Add(this.bCancel);
this.Controls.Add(this.bOK);
this.Controls.Add(this.tbPrompt);
this.Controls.Add(this.lPrompt);
this.Controls.Add(this.ckbIntSecurity);
this.Controls.Add(this.tbConnection);
this.Controls.Add(this.lConnectionString);
this.Controls.Add(this.cbDataProvider);
this.Controls.Add(this.lDataProvider);
this.Controls.Add(this.bGetFilename);
this.Controls.Add(this.tbFilename);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DialogDataSources";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "DataSources in Report";
this.ResumeLayout(false);
}
#endregion
public void Apply()
{
XmlNode rNode = _Draw.GetReportNode();
_Draw.RemoveElement(rNode, "DataSources"); // remove old DataSources
if (this.lbDataSources.Items.Count <= 0)
return; // nothing in list? all done
XmlNode dsNode = _Draw.SetElement(rNode, "DataSources", null);
foreach (DataSourceValues dsv in lbDataSources.Items)
{
if (dsv.Name == null || dsv.Name.Length <= 0)
continue; // shouldn't really happen
XmlNode dNode = _Draw.CreateElement(dsNode, "DataSource", null);
// Create the name attribute
_Draw.SetElementAttribute(dNode, "Name", dsv.Name);
if (dsv.bDataSourceReference)
{
_Draw.SetElement(dNode, "DataSourceReference", dsv.DataSourceReference);
continue;
}
// must fill out the connection properties
XmlNode cNode = _Draw.CreateElement(dNode, "ConnectionProperties", null);
_Draw.SetElement(cNode, "DataProvider", dsv.DataProvider);
_Draw.SetElement(cNode, "ConnectString", dsv.ConnectionString);
_Draw.SetElement(cNode, "IntegratedSecurity", dsv.IntegratedSecurity? "true": "false");
if (dsv.Prompt != null && dsv.Prompt.Length > 0)
_Draw.SetElement(cNode, "Prompt", dsv.Prompt);
}
}
private void bGetFilename_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Data source reference files (*.dsr)|*.dsr" +
"|All files (*.*)|*.*";
ofd.FilterIndex = 1;
if (tbFilename.Text.Length > 0)
ofd.FileName = tbFilename.Text;
else
ofd.FileName = "*.dsr";
ofd.Title = "Specify Data Source Reference File Name";
ofd.DefaultExt = "dsr";
ofd.AddExtension = true;
try
{
if (_FileName != null)
ofd.InitialDirectory = Path.GetDirectoryName(_FileName);
}
catch
{
}
try
{
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
string dsr = DesignerUtility.RelativePathTo(
Path.GetDirectoryName(_FileName), Path.GetDirectoryName(ofd.FileName));
string f = Path.GetFileNameWithoutExtension(ofd.FileName);
tbFilename.Text = dsr == "" ? f : dsr + Path.DirectorySeparatorChar + f;
}
catch
{
tbFilename.Text = Path.GetFileNameWithoutExtension(ofd.FileName);
}
}
}
finally
{
ofd.Dispose();
}
}
private void tbFilename_TextChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.DataSourceReference = tbFilename.Text;
return;
}
private void bOK_Click(object sender, System.EventArgs e)
{
// Verify there are no duplicate names in the data sources
Hashtable ht = new Hashtable(this.lbDataSources.Items.Count+1);
foreach (DataSourceValues dsv in lbDataSources.Items)
{
if (dsv.Name == null || dsv.Name.Length == 0)
{
MessageBox.Show(this, "Name must be specified for all DataSources.", "Data Sources");
return;
}
if (!ReportNames.IsNameValid(dsv.Name))
{
MessageBox.Show(this,
string.Format("Name '{0}' contains invalid characters.", dsv.Name), "Data Sources");
return;
}
string name = (string) ht[dsv.Name];
if (name != null)
{
MessageBox.Show(this,
string.Format("Each DataSource must have a unique name. '{0}' is repeated.", dsv.Name), "Data Sources");
return;
}
ht.Add(dsv.Name, dsv.Name);
}
// apply the result
Apply();
DialogResult = DialogResult.OK;
}
private void bTestConnection_Click(object sender, System.EventArgs e)
{
if (DesignerUtility.TestConnection(this.cbDataProvider.Text, tbConnection.Text))
MessageBox.Show("Connection succeeded!", "Test Connection");
}
private void tbDSName_TextChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
if (dsv.Name == tbDSName.Text)
return;
dsv.Name = tbDSName.Text;
// text doesn't change in listbox; force change by removing and re-adding item
lbDataSources.BeginUpdate();
lbDataSources.Items.RemoveAt(cur);
lbDataSources.Items.Insert(cur, dsv);
lbDataSources.SelectedIndex = cur;
lbDataSources.EndUpdate();
}
private void chkSharedDataSource_CheckedChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.bDataSourceReference = chkSharedDataSource.Checked;
bool bEnableDataSourceRef = chkSharedDataSource.Checked;
// shared data source fields
tbFilename.Enabled = bEnableDataSourceRef;
bGetFilename.Enabled = bEnableDataSourceRef;
// in report data source
cbDataProvider.Enabled = !bEnableDataSourceRef;
tbConnection.Enabled = !bEnableDataSourceRef;
ckbIntSecurity.Enabled = !bEnableDataSourceRef;
tbPrompt.Enabled = !bEnableDataSourceRef;
bTestConnection.Enabled = !bEnableDataSourceRef;
lDataProvider.Enabled = !bEnableDataSourceRef;
lConnectionString.Enabled = !bEnableDataSourceRef;
lPrompt.Enabled = !bEnableDataSourceRef;
}
private void lbDataSources_SelectedIndexChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
tbDSName.Text = dsv.Name;
cbDataProvider.Text = dsv.DataProvider;
tbConnection.Text = dsv.ConnectionString;
ckbIntSecurity.Checked = dsv.IntegratedSecurity;
this.tbFilename.Text = dsv.DataSourceReference;
tbPrompt.Text = dsv.Prompt;
this.chkSharedDataSource.Checked = dsv.bDataSourceReference;
chkSharedDataSource_CheckedChanged(this.chkSharedDataSource, e); // force message
}
private void bAdd_Click(object sender, System.EventArgs e)
{
DataSourceValues dsv = new DataSourceValues("datasource");
int cur = this.lbDataSources.Items.Add(dsv);
lbDataSources.SelectedIndex = cur;
this.tbDSName.Focus();
}
private void bRemove_Click(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
lbDataSources.Items.RemoveAt(cur);
if (lbDataSources.Items.Count <= 0)
return;
cur--;
if (cur < 0)
cur = 0;
lbDataSources.SelectedIndex = cur;
}
private void tbDSName_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
if (!ReportNames.IsNameValid(tbDSName.Text))
{
e.Cancel = true;
MessageBox.Show(this,
string.Format("Name '{0}' contains invalid characters.", tbDSName.Text), "Data Sources");
}
}
private void tbConnection_TextChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.ConnectionString = tbConnection.Text;
}
private void tbPrompt_TextChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.Prompt = tbPrompt.Text;
}
private void cbDataProvider_SelectedIndexChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.DataProvider = cbDataProvider.Text;
}
private void ckbIntSecurity_CheckedChanged(object sender, System.EventArgs e)
{
int cur = lbDataSources.SelectedIndex;
if (cur < 0)
return;
DataSourceValues dsv = lbDataSources.Items[cur] as DataSourceValues;
if (dsv == null)
return;
dsv.IntegratedSecurity = ckbIntSecurity.Checked;
}
private void bExprConnect_Click(object sender, System.EventArgs e)
{
DialogExprEditor ee = new DialogExprEditor(_Draw, this.tbConnection.Text, null, false);
try
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
tbConnection.Text = ee.Expression;
}
finally
{
ee.Dispose();
}
}
}
class DataSourceValues
{
string _Name;
bool _bDataSourceReference;
string _DataSourceReference;
string _DataProvider;
string _ConnectionString;
bool _IntegratedSecurity;
string _Prompt;
XmlNode _Node;
internal DataSourceValues(string name)
{
_Name = name;
}
internal string Name
{
get {return _Name;}
set {_Name = value;}
}
internal bool bDataSourceReference
{
get {return _bDataSourceReference;}
set {_bDataSourceReference = value;}
}
internal string DataSourceReference
{
get {return _DataSourceReference;}
set {_DataSourceReference = value;}
}
internal string DataProvider
{
get {return _DataProvider;}
set {_DataProvider = value;}
}
internal string ConnectionString
{
get {return _ConnectionString;}
set {_ConnectionString = value;}
}
internal bool IntegratedSecurity
{
get {return _IntegratedSecurity;}
set {_IntegratedSecurity = value;}
}
internal string Prompt
{
get {return _Prompt;}
set {_Prompt = value;}
}
internal XmlNode Node
{
get {return _Node;}
set {_Node = value;}
}
override public string ToString()
{
return _Name;
}
}
}
| |
// 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.Reflection;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// Alias ID's are indices into BitSets.
// 0 is reserved for the global namespace alias.
// 1 is reserved for this assembly.
// Start assigning at kaidStartAssigning.
internal enum KAID
{
kaidNil = -1,
kaidGlobal = 0,
kaidThisAssembly,
kaidUnresolved,
kaidStartAssigning,
// Module id's are in their own range.
kaidMinModule = 0x10000000,
}
/*
* Define the different access levels that symbols can have.
*/
internal enum ACCESS
{
ACC_UNKNOWN, // Not yet determined.
ACC_PRIVATE,
ACC_INTERNAL,
ACC_PROTECTED,
ACC_INTERNALPROTECTED, // internal OR protected
ACC_PUBLIC
}
// The kinds of aggregates.
internal enum AggKindEnum
{
Unknown,
Class,
Delegate,
Interface,
Struct,
Enum,
Lim
}
/////////////////////////////////////////////////////////////////////////////////
// Special constraints.
internal enum SpecCons
{
None = 0x00,
New = 0x01,
Ref = 0x02,
Val = 0x04
}
// ----------------------------------------------------------------------------
//
// Symbol - the base symbol.
//
// ----------------------------------------------------------------------------
internal abstract class Symbol
{
private SYMKIND _kind; // the symbol kind
private bool _isBogus; // can't be used in our language -- unsupported type(s)
private bool _checkedBogus; // Have we checked a method args/return for bogus types
private ACCESS _access; // access level
// If this is true, then we had an error the first time so do not give an error the second time.
public Name name; // name of the symbol
public ParentSymbol parent; // parent of the symbol
public Symbol nextChild; // next child of this parent
public Symbol nextSameName; // next child of this parent with same name.
public ACCESS GetAccess()
{
Debug.Assert(_access != ACCESS.ACC_UNKNOWN);
return _access;
}
public void SetAccess(ACCESS access)
{
_access = access;
}
public SYMKIND getKind()
{
return _kind;
}
public void setKind(SYMKIND kind)
{
_kind = kind;
}
public symbmask_t mask()
{
return (symbmask_t)(1 << (int)_kind);
}
public bool checkBogus()
{
Debug.Assert(_checkedBogus);
return _isBogus;
} // if this Debug.Assert fires then call COMPILER_BASE::CheckBogus() instead
public bool getBogus()
{
return _isBogus;
}
public bool hasBogus()
{
return _checkedBogus;
}
public void setBogus(bool isBogus)
{
_isBogus = isBogus;
_checkedBogus = true;
}
public void initBogus()
{
_isBogus = false;
_checkedBogus = false;
}
public bool computeCurrentBogusState()
{
if (hasBogus())
{
return checkBogus();
}
bool fBogus = false;
switch (getKind())
{
case SYMKIND.SK_PropertySymbol:
case SYMKIND.SK_MethodSymbol:
{
MethodOrPropertySymbol meth = this.AsMethodOrPropertySymbol();
if (meth.RetType != null)
{
fBogus = meth.RetType.computeCurrentBogusState();
}
if (meth.Params != null)
{
for (int i = 0; !fBogus && i < meth.Params.Count; i++)
{
fBogus |= meth.Params[i].computeCurrentBogusState();
}
}
}
break;
/*
case SYMKIND.SK_ParameterModifierType:
case SYMKIND.SK_OptionalModifierType:
case SYMKIND.SK_PointerType:
case SYMKIND.SK_ArrayType:
case SYMKIND.SK_NullableType:
case SYMKIND.SK_PinnedType:
if (this.AsType().GetBaseOrParameterOrElementType() != null)
{
fBogus = this.AsType().GetBaseOrParameterOrElementType().computeCurrentBogusState();
}
break;
*/
case SYMKIND.SK_EventSymbol:
if (this.AsEventSymbol().type != null)
{
fBogus = this.AsEventSymbol().type.computeCurrentBogusState();
}
break;
case SYMKIND.SK_FieldSymbol:
if (this.AsFieldSymbol().GetType() != null)
{
fBogus = this.AsFieldSymbol().GetType().computeCurrentBogusState();
}
break;
/*
case SYMKIND.SK_ErrorType:
this.setBogus(false);
break;
case SYMKIND.SK_AggregateType:
fBogus = this.AsAggregateType().getAggregate().computeCurrentBogusState();
for (int i = 0; !fBogus && i < this.AsAggregateType().GetTypeArgsAll().size; i++)
{
fBogus |= this.AsAggregateType().GetTypeArgsAll()[i].computeCurrentBogusState();
}
break;
*/
case SYMKIND.SK_TypeParameterSymbol:
/*
case SYMKIND.SK_TypeParameterType:
case SYMKIND.SK_VoidType:
case SYMKIND.SK_NullType:
case SYMKIND.SK_OpenTypePlaceholderType:
case SYMKIND.SK_ArgumentListType:
case SYMKIND.SK_NaturalIntegerType:
*/
case SYMKIND.SK_LocalVariableSymbol:
setBogus(false);
break;
case SYMKIND.SK_AggregateSymbol:
fBogus = hasBogus() && checkBogus();
break;
case SYMKIND.SK_Scope:
case SYMKIND.SK_LambdaScope:
case SYMKIND.SK_NamespaceSymbol:
default:
Debug.Assert(false, "CheckBogus with invalid Symbol kind");
setBogus(false);
break;
}
if (fBogus)
{
// Only set this if at least 1 declared thing is bogus
setBogus(fBogus);
}
return hasBogus() && checkBogus();
}
public bool IsNamespaceSymbol() { return _kind == SYMKIND.SK_NamespaceSymbol; }
public bool IsAggregateSymbol() { return _kind == SYMKIND.SK_AggregateSymbol; }
public bool IsAggregateDeclaration() { return _kind == SYMKIND.SK_AggregateDeclaration; }
public bool IsFieldSymbol() { return _kind == SYMKIND.SK_FieldSymbol; }
public bool IsLocalVariableSymbol() { return _kind == SYMKIND.SK_LocalVariableSymbol; }
public bool IsMethodSymbol() { return _kind == SYMKIND.SK_MethodSymbol; }
public bool IsPropertySymbol() { return _kind == SYMKIND.SK_PropertySymbol; }
public bool IsTypeParameterSymbol() { return _kind == SYMKIND.SK_TypeParameterSymbol; }
public bool IsEventSymbol() { return _kind == SYMKIND.SK_EventSymbol; }
public bool IsMethodOrPropertySymbol()
{
return IsMethodSymbol() || IsPropertySymbol();
}
public bool IsFMETHSYM()
{
return IsMethodSymbol();
}
public CType getType()
{
CType type = null;
if (IsMethodOrPropertySymbol())
{
type = this.AsMethodOrPropertySymbol().RetType;
}
else if (IsFieldSymbol())
{
type = this.AsFieldSymbol().GetType();
}
else if (IsEventSymbol())
{
type = this.AsEventSymbol().type;
}
return type;
}
public bool isStatic
{
get
{
bool fStatic = false;
if (IsFieldSymbol())
{
fStatic = this.AsFieldSymbol().isStatic;
}
else if (IsEventSymbol())
{
fStatic = this.AsEventSymbol().isStatic;
}
else if (IsMethodOrPropertySymbol())
{
fStatic = this.AsMethodOrPropertySymbol().isStatic;
}
else if (IsAggregateSymbol())
{
fStatic = true;
}
return fStatic;
}
}
private Assembly GetAssembly()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
case SYMKIND.SK_FieldSymbol:
case SYMKIND.SK_EventSymbol:
case SYMKIND.SK_TypeParameterSymbol:
return parent.AsAggregateSymbol().AssociatedAssembly;
case SYMKIND.SK_AggregateDeclaration:
return this.AsAggregateDeclaration().GetAssembly();
case SYMKIND.SK_AggregateSymbol:
return this.AsAggregateSymbol().AssociatedAssembly;
case SYMKIND.SK_NamespaceSymbol:
case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol:
default:
// Should never call this with any other kind.
Debug.Assert(false, "GetAssemblyID called on bad sym kind");
return null;
}
}
/*
* returns the assembly id for the declaration of this symbol
*/
private bool InternalsVisibleTo(Assembly assembly)
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
case SYMKIND.SK_FieldSymbol:
case SYMKIND.SK_EventSymbol:
case SYMKIND.SK_TypeParameterSymbol:
return parent.AsAggregateSymbol().InternalsVisibleTo(assembly);
case SYMKIND.SK_AggregateDeclaration:
return this.AsAggregateDeclaration().Agg().InternalsVisibleTo(assembly);
case SYMKIND.SK_AggregateSymbol:
return this.AsAggregateSymbol().InternalsVisibleTo(assembly);
case SYMKIND.SK_ExternalAliasDefinitionSymbol:
case SYMKIND.SK_NamespaceSymbol:
case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol:
default:
// Should never call this with any other kind.
Debug.Assert(false, "InternalsVisibleTo called on bad sym kind");
return false;
}
}
public bool SameAssemOrFriend(Symbol sym)
{
Assembly assem = GetAssembly();
return assem == sym.GetAssembly() || sym.InternalsVisibleTo(assem);
}
/* Returns if the symbol is virtual. */
public bool IsVirtual()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
return this.AsMethodSymbol().isVirtual;
case SYMKIND.SK_EventSymbol:
return this.AsEventSymbol().methAdd != null && this.AsEventSymbol().methAdd.isVirtual;
case SYMKIND.SK_PropertySymbol:
return (this.AsPropertySymbol().methGet != null && this.AsPropertySymbol().methGet.isVirtual) ||
(this.AsPropertySymbol().methSet != null && this.AsPropertySymbol().methSet.isVirtual);
default:
return false;
}
}
public bool IsOverride()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
return this.AsMethodOrPropertySymbol().isOverride;
case SYMKIND.SK_EventSymbol:
return this.AsEventSymbol().isOverride;
default:
return false;
}
}
public bool IsHideByName()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
return this.AsMethodOrPropertySymbol().isHideByName;
case SYMKIND.SK_EventSymbol:
return this.AsEventSymbol().methAdd != null && this.AsEventSymbol().methAdd.isHideByName;
default:
return true;
}
}
// Returns the virtual that this sym overrides (if IsOverride() is true), null otherwise.
public Symbol SymBaseVirtual()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
case SYMKIND.SK_PropertySymbol:
return this.AsMethodOrPropertySymbol().swtSlot.Sym;
case SYMKIND.SK_EventSymbol:
default:
return null;
}
}
/*
* returns true if this symbol is a normal symbol visible to the user
*/
public bool isUserCallable()
{
switch (_kind)
{
case SYMKIND.SK_MethodSymbol:
return this.AsMethodSymbol().isUserCallable();
default:
break;
}
return true;
}
}
/*
* We have member functions here to do casts that, in DEBUG, check the
* symbol kind to make sure it is right. For example, the casting method
* for METHODSYM is called "asMETHODSYM". In retail builds, these
* methods optimize away to nothing.
*/
internal static class SymbolExtensions
{
public static IEnumerable<Symbol> Children(this ParentSymbol symbol)
{
if (symbol == null)
yield break;
Symbol current = symbol.firstChild;
while (current != null)
{
yield return current;
current = current.nextChild;
}
}
internal static MethodSymbol AsFMETHSYM(this Symbol symbol) { return symbol as MethodSymbol; }
internal static NamespaceOrAggregateSymbol AsNamespaceOrAggregateSymbol(this Symbol symbol) { return symbol as NamespaceOrAggregateSymbol; }
internal static NamespaceSymbol AsNamespaceSymbol(this Symbol symbol) { return symbol as NamespaceSymbol; }
internal static AssemblyQualifiedNamespaceSymbol AsAssemblyQualifiedNamespaceSymbol(this Symbol symbol) { return symbol as AssemblyQualifiedNamespaceSymbol; }
internal static AggregateSymbol AsAggregateSymbol(this Symbol symbol) { return symbol as AggregateSymbol; }
internal static AggregateDeclaration AsAggregateDeclaration(this Symbol symbol) { return symbol as AggregateDeclaration; }
internal static FieldSymbol AsFieldSymbol(this Symbol symbol) { return symbol as FieldSymbol; }
internal static LocalVariableSymbol AsLocalVariableSymbol(this Symbol symbol) { return symbol as LocalVariableSymbol; }
internal static MethodSymbol AsMethodSymbol(this Symbol symbol) { return symbol as MethodSymbol; }
internal static PropertySymbol AsPropertySymbol(this Symbol symbol) { return symbol as PropertySymbol; }
internal static MethodOrPropertySymbol AsMethodOrPropertySymbol(this Symbol symbol) { return symbol as MethodOrPropertySymbol; }
internal static Scope AsScope(this Symbol symbol) { return symbol as Scope; }
internal static TypeParameterSymbol AsTypeParameterSymbol(this Symbol symbol) { return symbol as TypeParameterSymbol; }
internal static EventSymbol AsEventSymbol(this Symbol symbol) { return symbol as EventSymbol; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using log4net;
using Polly;
using Polly.Retry;
using RestSharp;
using Xpressive.Home.Contracts.Gateway;
using Xpressive.Home.Contracts.Messaging;
namespace Xpressive.Home.Plugins.Netatmo
{
internal class NetatmoGateway : GatewayBase, INetatmoGateway
{
private static readonly ILog _log = LogManager.GetLogger(typeof(NetatmoGateway));
private readonly IMessageQueue _messageQueue;
private readonly object _deviceLock = new object();
private readonly string _clientId;
private readonly string _clientSecret;
private readonly string _username;
private readonly string _password;
private readonly bool _isValidConfiguration;
public NetatmoGateway(IMessageQueue messageQueue) : base("Netatmo")
{
_messageQueue = messageQueue;
_clientId = ConfigurationManager.AppSettings["netatmo.clientid"];
_clientSecret = ConfigurationManager.AppSettings["netatmo.clientsecret"];
_username = ConfigurationManager.AppSettings["netatmo.username"];
_password = ConfigurationManager.AppSettings["netatmo.password"];
_isValidConfiguration =
!string.IsNullOrEmpty(_clientId) &&
!string.IsNullOrEmpty(_clientSecret) &&
!string.IsNullOrEmpty(_username) &&
!string.IsNullOrEmpty(_password);
_canCreateDevices = false;
}
public override IDevice CreateEmptyDevice()
{
throw new NotSupportedException();
}
public override IEnumerable<IAction> GetActions(IDevice device)
{
yield break;
}
public IEnumerable<NetatmoDevice> GetDevices()
{
return Devices.Cast<NetatmoDevice>();
}
protected override Task ExecuteInternalAsync(IDevice device, IAction action, IDictionary<string, string> values)
{
throw new NotSupportedException();
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ContinueWith(_ => { });
if (!_isValidConfiguration)
{
_messageQueue.Publish(new NotifyUserMessage("Add netatmo configuration to config file."));
return;
}
var token = await GetTokenAsync();
while (!cancellationToken.IsCancellationRequested)
{
try
{
if (token == null || token.Expiration <= DateTime.UtcNow)
{
token = await GetTokenAsync();
}
else if (token.Expiration - DateTime.UtcNow < TimeSpan.FromMinutes(10))
{
token = await RefreshTokenAsync(token);
}
if (token != null)
{
await GetDeviceData(token);
}
}
catch (Exception e)
{
_log.Error(e.Message, e);
}
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken).ContinueWith(_ => { });
}
}
private async Task GetDeviceData(TokenResponseDto token)
{
var client = new RestClient("https://api.netatmo.com");
var request = new RestRequest("/api/getstationsdata");
request.AddQueryParameter("access_token", token.AccessToken);
var data = await client.GetTaskAsync<StationDataResponseDto>(request);
if (data?.Body?.Devices == null)
{
return;
}
lock (_deviceLock)
{
foreach (var dataDevice in data.Body.Devices)
{
var station = dataDevice.StationName;
dataDevice.BatteryPercent = 100;
UpdateDevice(station, dataDevice);
if (dataDevice.Modules == null)
{
continue;
}
foreach (var module in dataDevice.Modules)
{
UpdateDevice(station, module);
}
}
}
}
private void UpdateDevice(string station, IStationModule module)
{
var id = $"{station}-{module.ModuleName}";
var device = GetDevices().SingleOrDefault(d => d.Id.Equals(id));
if (device == null)
{
device = new NetatmoDevice(id, module.ModuleName);
_devices.Add(device);
}
PublishVariables(device, module);
if (module.BatteryPercent > 85)
{
device.BatteryStatus = DeviceBatteryStatus.Full;
}
else if (module.BatteryPercent > 25)
{
device.BatteryStatus = DeviceBatteryStatus.Good;
}
else
{
device.BatteryStatus = DeviceBatteryStatus.Low;
}
}
private void PublishVariables(NetatmoDevice device, IStationModule module)
{
var properties = module.DashboardData.GetType().GetProperties();
foreach (var property in properties)
{
if (module.DataType.Contains(property.Name))
{
var name = property.Name[0] + property.Name.ToLowerInvariant().Substring(1);
var value = (double) property.GetValue(module.DashboardData);
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, name, value));
switch (name)
{
case "Co2":
device.Co2 = module.DashboardData.CO2;
break;
case "Humidity":
device.Humidity = module.DashboardData.Humidity;
break;
case "Noise":
device.Noise = module.DashboardData.Noise;
break;
case "Pressure":
device.Pressure = module.DashboardData.Pressure;
break;
case "Temperature":
device.Temperature = module.DashboardData.Temperature;
break;
}
}
}
}
private async Task<TokenResponseDto> GetTokenAsync()
{
var policy = GetRetryPolicy();
return await policy.ExecuteAsync(async () =>
{
var client = new RestClient("https://api.netatmo.com");
var request = new RestRequest("/oauth2/token");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
request.AddParameter("grant_type", "password");
request.AddParameter("client_id", _clientId);
request.AddParameter("client_secret", _clientSecret);
request.AddParameter("username", _username);
request.AddParameter("password", _password);
request.AddParameter("scope", "read_station read_thermostat");
var token = await client.PostTaskAsync<TokenResponseDto>(request);
if (token?.AccessToken == null)
{
return null;
}
token.Expiration = DateTime.UtcNow.AddSeconds(token.ExpiresIn);
return token;
});
}
private async Task<TokenResponseDto> RefreshTokenAsync(TokenResponseDto dto)
{
var policy = GetRetryPolicy();
return await policy.ExecuteAsync(async () =>
{
var client = new RestClient("https://api.netatmo.com");
var request = new RestRequest("/oauth2/token");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
request.AddParameter("grant_type", dto.RefreshToken);
request.AddParameter("client_id", _clientId);
request.AddParameter("client_secret", _clientSecret);
var token = await client.PostTaskAsync<TokenResponseDto>(request);
if (token?.AccessToken == null)
{
return null;
}
token.Expiration = DateTime.UtcNow.AddSeconds(token.ExpiresIn);
return token;
});
}
private RetryPolicy<TokenResponseDto> GetRetryPolicy()
{
return Policy
.Handle<Exception>()
.OrResult((TokenResponseDto)null)
.WaitAndRetryAsync(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(15),
TimeSpan.FromSeconds(20)
});
}
public class StationModuleDto : IStationModule
{
public string Type { get; set; }
public StationDashboardData DashboardData { get; set; }
public List<string> DataType { get; set; }
public string ModuleName { get; set; }
public int BatteryPercent { get; set; }
}
public class StationDataResponseDto
{
public StationDataBody Body { get; set; }
}
public class StationDataBody
{
public List<StationDataDevice> Devices { get; set; }
}
public class StationDataDevice : IStationModule
{
public string StationName { get; set; }
public string ModuleName { get; set; }
public StationDashboardData DashboardData { get; set; }
public List<StationModuleDto> Modules { get; set; }
public List<string> DataType { get; set; }
public int BatteryPercent { get; set; }
}
public interface IStationModule
{
string ModuleName { get; set; }
StationDashboardData DashboardData { get; set; }
List<string> DataType { get; set; }
int BatteryPercent { get; set; }
}
public class StationDashboardData
{
public double AbsolutePressure { get; set; }
public double Noise { get; set; }
public double Temperature { get; set; }
public double Humidity { get; set; }
public double Pressure { get; set; }
public double CO2 { get; set; }
}
public class TokenResponseDto
{
public string AccessToken { get; set; }
public int ExpiresIn { get; set; }
public string RefreshToken { get; set; }
public DateTime Expiration { get; set; }
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// ReservationGuest
/// </summary>
[DataContract]
public partial class ReservationGuest : IEquatable<ReservationGuest>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ReservationGuest" /> class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="TimeZone">TimeZone.</param>
/// <param name="Email">Email.</param>
/// <param name="Status">Status.</param>
/// <param name="CustomerName">CustomerName.</param>
/// <param name="Phone">Phone.</param>
/// <param name="Areas">Areas.</param>
/// <param name="SpecialRequests">SpecialRequests.</param>
/// <param name="TableNumber">TableNumber.</param>
/// <param name="DepositStatus">DepositStatus.</param>
/// <param name="Source">Source.</param>
/// <param name="Created">Created.</param>
/// <param name="Closed">Closed.</param>
/// <param name="ReservationTime">ReservationTime.</param>
/// <param name="GroupSize">GroupSize.</param>
/// <param name="RestaurantId">RestaurantId.</param>
/// <param name="Amount">Amount.</param>
/// <param name="Roles">Roles.</param>
/// <param name="Token">Token.</param>
/// <param name="HighChair">HighChair.</param>
/// <param name="Stroller">Stroller.</param>
/// <param name="Booth">Booth.</param>
/// <param name="HighTop">HighTop.</param>
/// <param name="Table">Table.</param>
/// <param name="Party">Party.</param>
/// <param name="PartyTypes">PartyTypes.</param>
/// <param name="CustomerProfile">CustomerProfile.</param>
/// <param name="EstimatedTurnOverTime">EstimatedTurnOverTime.</param>
public ReservationGuest(string Id = null, string TimeZone = null, string Email = null, string Status = null, string CustomerName = null, string Phone = null, string Areas = null, string SpecialRequests = null, string TableNumber = null, string DepositStatus = null, string Source = null, DateTimeOffset? Created = null, DateTimeOffset? Closed = null, DateTimeOffset? ReservationTime = null, int? GroupSize = null, int? RestaurantId = null, int? Amount = null, List<string> Roles = null, string Token = null, bool? HighChair = null, bool? Stroller = null, bool? Booth = null, bool? HighTop = null, bool? Table = null, bool? Party = null, List<string> PartyTypes = null, ProfileData CustomerProfile = null, double? EstimatedTurnOverTime = null)
{
this.Id = Id;
this.TimeZone = TimeZone;
this.Email = Email;
this.Status = Status;
this.CustomerName = CustomerName;
this.Phone = Phone;
this.Areas = Areas;
this.SpecialRequests = SpecialRequests;
this.TableNumber = TableNumber;
this.DepositStatus = DepositStatus;
this.Source = Source;
this.Created = Created;
this.Closed = Closed;
this.ReservationTime = ReservationTime;
this.GroupSize = GroupSize;
this.RestaurantId = RestaurantId;
this.Amount = Amount;
this.Roles = Roles;
this.Token = Token;
this.HighChair = HighChair;
this.Stroller = Stroller;
this.Booth = Booth;
this.HighTop = HighTop;
this.Table = Table;
this.Party = Party;
this.PartyTypes = PartyTypes;
this.CustomerProfile = CustomerProfile;
this.EstimatedTurnOverTime = EstimatedTurnOverTime;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=true)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets TimeZone
/// </summary>
[DataMember(Name="timeZone", EmitDefaultValue=true)]
public string TimeZone { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name="email", EmitDefaultValue=true)]
public string Email { get; set; }
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=true)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets CustomerName
/// </summary>
[DataMember(Name="customerName", EmitDefaultValue=true)]
public string CustomerName { get; set; }
/// <summary>
/// Gets or Sets Phone
/// </summary>
[DataMember(Name="phone", EmitDefaultValue=true)]
public string Phone { get; set; }
/// <summary>
/// Gets or Sets Areas
/// </summary>
[DataMember(Name="areas", EmitDefaultValue=true)]
public string Areas { get; set; }
/// <summary>
/// Gets or Sets SpecialRequests
/// </summary>
[DataMember(Name="specialRequests", EmitDefaultValue=true)]
public string SpecialRequests { get; set; }
/// <summary>
/// Gets or Sets TableNumber
/// </summary>
[DataMember(Name="tableNumber", EmitDefaultValue=true)]
public string TableNumber { get; set; }
/// <summary>
/// Gets or Sets DepositStatus
/// </summary>
[DataMember(Name="depositStatus", EmitDefaultValue=true)]
public string DepositStatus { get; set; }
/// <summary>
/// Gets or Sets Source
/// </summary>
[DataMember(Name="source", EmitDefaultValue=true)]
public string Source { get; set; }
/// <summary>
/// Gets or Sets Created
/// </summary>
[DataMember(Name="created", EmitDefaultValue=true)]
public DateTimeOffset? Created { get; set; }
/// <summary>
/// Gets or Sets Closed
/// </summary>
[DataMember(Name="closed", EmitDefaultValue=true)]
public DateTimeOffset? Closed { get; set; }
/// <summary>
/// Gets or Sets ReservationTime
/// </summary>
[DataMember(Name="reservationTime", EmitDefaultValue=true)]
public DateTimeOffset? ReservationTime { get; set; }
/// <summary>
/// Gets or Sets GroupSize
/// </summary>
[DataMember(Name="groupSize", EmitDefaultValue=true)]
public int? GroupSize { get; set; }
/// <summary>
/// Gets or Sets RestaurantId
/// </summary>
[DataMember(Name="restaurantId", EmitDefaultValue=true)]
public int? RestaurantId { get; set; }
/// <summary>
/// Gets or Sets Amount
/// </summary>
[DataMember(Name="amount", EmitDefaultValue=true)]
public int? Amount { get; set; }
/// <summary>
/// Gets or Sets Roles
/// </summary>
[DataMember(Name="roles", EmitDefaultValue=true)]
public List<string> Roles { get; set; }
/// <summary>
/// Gets or Sets Token
/// </summary>
[DataMember(Name="token", EmitDefaultValue=true)]
public string Token { get; set; }
/// <summary>
/// Gets or Sets HighChair
/// </summary>
[DataMember(Name="highChair", EmitDefaultValue=true)]
public bool? HighChair { get; set; }
/// <summary>
/// Gets or Sets Stroller
/// </summary>
[DataMember(Name="stroller", EmitDefaultValue=true)]
public bool? Stroller { get; set; }
/// <summary>
/// Gets or Sets Booth
/// </summary>
[DataMember(Name="booth", EmitDefaultValue=true)]
public bool? Booth { get; set; }
/// <summary>
/// Gets or Sets HighTop
/// </summary>
[DataMember(Name="highTop", EmitDefaultValue=true)]
public bool? HighTop { get; set; }
/// <summary>
/// Gets or Sets Table
/// </summary>
[DataMember(Name="table", EmitDefaultValue=true)]
public bool? Table { get; set; }
/// <summary>
/// Gets or Sets Party
/// </summary>
[DataMember(Name="party", EmitDefaultValue=true)]
public bool? Party { get; set; }
/// <summary>
/// Gets or Sets PartyTypes
/// </summary>
[DataMember(Name="partyTypes", EmitDefaultValue=true)]
public List<string> PartyTypes { get; set; }
/// <summary>
/// Gets or Sets CustomerProfile
/// </summary>
[DataMember(Name="customerProfile", EmitDefaultValue=true)]
public ProfileData CustomerProfile { get; set; }
/// <summary>
/// Gets or Sets EstimatedTurnOverTime
/// </summary>
[DataMember(Name="estimatedTurnOverTime", EmitDefaultValue=true)]
public double? EstimatedTurnOverTime { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ReservationGuest {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" TimeZone: ").Append(TimeZone).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" CustomerName: ").Append(CustomerName).Append("\n");
sb.Append(" Phone: ").Append(Phone).Append("\n");
sb.Append(" Areas: ").Append(Areas).Append("\n");
sb.Append(" SpecialRequests: ").Append(SpecialRequests).Append("\n");
sb.Append(" TableNumber: ").Append(TableNumber).Append("\n");
sb.Append(" DepositStatus: ").Append(DepositStatus).Append("\n");
sb.Append(" Source: ").Append(Source).Append("\n");
sb.Append(" Created: ").Append(Created).Append("\n");
sb.Append(" Closed: ").Append(Closed).Append("\n");
sb.Append(" ReservationTime: ").Append(ReservationTime).Append("\n");
sb.Append(" GroupSize: ").Append(GroupSize).Append("\n");
sb.Append(" RestaurantId: ").Append(RestaurantId).Append("\n");
sb.Append(" Amount: ").Append(Amount).Append("\n");
sb.Append(" Roles: ").Append(Roles).Append("\n");
sb.Append(" Token: ").Append(Token).Append("\n");
sb.Append(" HighChair: ").Append(HighChair).Append("\n");
sb.Append(" Stroller: ").Append(Stroller).Append("\n");
sb.Append(" Booth: ").Append(Booth).Append("\n");
sb.Append(" HighTop: ").Append(HighTop).Append("\n");
sb.Append(" Table: ").Append(Table).Append("\n");
sb.Append(" Party: ").Append(Party).Append("\n");
sb.Append(" PartyTypes: ").Append(PartyTypes).Append("\n");
sb.Append(" CustomerProfile: ").Append(CustomerProfile).Append("\n");
sb.Append(" EstimatedTurnOverTime: ").Append(EstimatedTurnOverTime).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ReservationGuest);
}
/// <summary>
/// Returns true if ReservationGuest instances are equal
/// </summary>
/// <param name="other">Instance of ReservationGuest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ReservationGuest other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.TimeZone == other.TimeZone ||
this.TimeZone != null &&
this.TimeZone.Equals(other.TimeZone)
) &&
(
this.Email == other.Email ||
this.Email != null &&
this.Email.Equals(other.Email)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.CustomerName == other.CustomerName ||
this.CustomerName != null &&
this.CustomerName.Equals(other.CustomerName)
) &&
(
this.Phone == other.Phone ||
this.Phone != null &&
this.Phone.Equals(other.Phone)
) &&
(
this.Areas == other.Areas ||
this.Areas != null &&
this.Areas.Equals(other.Areas)
) &&
(
this.SpecialRequests == other.SpecialRequests ||
this.SpecialRequests != null &&
this.SpecialRequests.Equals(other.SpecialRequests)
) &&
(
this.TableNumber == other.TableNumber ||
this.TableNumber != null &&
this.TableNumber.Equals(other.TableNumber)
) &&
(
this.DepositStatus == other.DepositStatus ||
this.DepositStatus != null &&
this.DepositStatus.Equals(other.DepositStatus)
) &&
(
this.Source == other.Source ||
this.Source != null &&
this.Source.Equals(other.Source)
) &&
(
this.Created == other.Created ||
this.Created != null &&
this.Created.Equals(other.Created)
) &&
(
this.Closed == other.Closed ||
this.Closed != null &&
this.Closed.Equals(other.Closed)
) &&
(
this.ReservationTime == other.ReservationTime ||
this.ReservationTime != null &&
this.ReservationTime.Equals(other.ReservationTime)
) &&
(
this.GroupSize == other.GroupSize ||
this.GroupSize != null &&
this.GroupSize.Equals(other.GroupSize)
) &&
(
this.RestaurantId == other.RestaurantId ||
this.RestaurantId != null &&
this.RestaurantId.Equals(other.RestaurantId)
) &&
(
this.Amount == other.Amount ||
this.Amount != null &&
this.Amount.Equals(other.Amount)
) &&
(
this.Roles == other.Roles ||
this.Roles != null &&
this.Roles.SequenceEqual(other.Roles)
) &&
(
this.Token == other.Token ||
this.Token != null &&
this.Token.Equals(other.Token)
) &&
(
this.HighChair == other.HighChair ||
this.HighChair != null &&
this.HighChair.Equals(other.HighChair)
) &&
(
this.Stroller == other.Stroller ||
this.Stroller != null &&
this.Stroller.Equals(other.Stroller)
) &&
(
this.Booth == other.Booth ||
this.Booth != null &&
this.Booth.Equals(other.Booth)
) &&
(
this.HighTop == other.HighTop ||
this.HighTop != null &&
this.HighTop.Equals(other.HighTop)
) &&
(
this.Table == other.Table ||
this.Table != null &&
this.Table.Equals(other.Table)
) &&
(
this.Party == other.Party ||
this.Party != null &&
this.Party.Equals(other.Party)
) &&
(
this.PartyTypes == other.PartyTypes ||
this.PartyTypes != null &&
this.PartyTypes.SequenceEqual(other.PartyTypes)
) &&
(
this.CustomerProfile == other.CustomerProfile ||
this.CustomerProfile != null &&
this.CustomerProfile.Equals(other.CustomerProfile)
) &&
(
this.EstimatedTurnOverTime == other.EstimatedTurnOverTime ||
this.EstimatedTurnOverTime != null &&
this.EstimatedTurnOverTime.Equals(other.EstimatedTurnOverTime)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.TimeZone != null)
hash = hash * 59 + this.TimeZone.GetHashCode();
if (this.Email != null)
hash = hash * 59 + this.Email.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.CustomerName != null)
hash = hash * 59 + this.CustomerName.GetHashCode();
if (this.Phone != null)
hash = hash * 59 + this.Phone.GetHashCode();
if (this.Areas != null)
hash = hash * 59 + this.Areas.GetHashCode();
if (this.SpecialRequests != null)
hash = hash * 59 + this.SpecialRequests.GetHashCode();
if (this.TableNumber != null)
hash = hash * 59 + this.TableNumber.GetHashCode();
if (this.DepositStatus != null)
hash = hash * 59 + this.DepositStatus.GetHashCode();
if (this.Source != null)
hash = hash * 59 + this.Source.GetHashCode();
if (this.Created != null)
hash = hash * 59 + this.Created.GetHashCode();
if (this.Closed != null)
hash = hash * 59 + this.Closed.GetHashCode();
if (this.ReservationTime != null)
hash = hash * 59 + this.ReservationTime.GetHashCode();
if (this.GroupSize != null)
hash = hash * 59 + this.GroupSize.GetHashCode();
if (this.RestaurantId != null)
hash = hash * 59 + this.RestaurantId.GetHashCode();
if (this.Amount != null)
hash = hash * 59 + this.Amount.GetHashCode();
if (this.Roles != null)
hash = hash * 59 + this.Roles.GetHashCode();
if (this.Token != null)
hash = hash * 59 + this.Token.GetHashCode();
if (this.HighChair != null)
hash = hash * 59 + this.HighChair.GetHashCode();
if (this.Stroller != null)
hash = hash * 59 + this.Stroller.GetHashCode();
if (this.Booth != null)
hash = hash * 59 + this.Booth.GetHashCode();
if (this.HighTop != null)
hash = hash * 59 + this.HighTop.GetHashCode();
if (this.Table != null)
hash = hash * 59 + this.Table.GetHashCode();
if (this.Party != null)
hash = hash * 59 + this.Party.GetHashCode();
if (this.PartyTypes != null)
hash = hash * 59 + this.PartyTypes.GetHashCode();
if (this.CustomerProfile != null)
hash = hash * 59 + this.CustomerProfile.GetHashCode();
if (this.EstimatedTurnOverTime != null)
hash = hash * 59 + this.EstimatedTurnOverTime.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// -------------------------------------
// Domain : IBT / Realtime.co
// Author : Nicholas Ventimiglia
// Product : Messaging and Storage
// Published : 2014
// -------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Realtime.Ortc.Api;
using Realtime.Ortc.Internal;
using UnityEngine;
#if UNITY_WSA && !UNITY_EDITOR
using System.Collections.Concurrent;
#endif
namespace Realtime.Ortc
{
/// <summary>
/// IBT Real Time SJ type client.
/// </summary>
public class UnityOrtcClient : IOrtcClient
{
#region Constants (11)
// REGEX patterns
private const string OPERATION_PATTERN = @"^a\[""{""op"":""(?<op>[^\""]+)"",(?<args>.*)}""\]$";
private const string CLOSE_PATTERN = @"^c\[?(?<code>[^""]+),?""?(?<message>.*)""?\]?$";
private const string VALIDATED_PATTERN = @"^(""up"":){1}(?<up>.*)?,""set"":(?<set>.*)$";
private const string CHANNEL_PATTERN = @"^""ch"":""(?<channel>.*)""$";
private const string EXCEPTION_PATTERN = @"^""ex"":{(""op"":""(?<op>[^""]+)"",)?(""ch"":""(?<channel>.*)"",)?""ex"":""(?<error>.*)""}$";
private const string RECEIVED_PATTERN = @"^a\[""{""ch"":""(?<channel>.*)"",""m"":""(?<message>[\s\S]*)""}""\]$";
private const string MULTI_PART_MESSAGE_PATTERN = @"^(?<messageId>.[^_]*)_(?<messageCurrentPart>.[^-]*)-(?<messageTotalPart>.[^_]*)_(?<message>[\s\S]*)$";
private const string PERMISSIONS_PATTERN = @"""(?<key>[^""]+)"":{1}""(?<value>[^,""]+)"",?";
// ReSharper disable InconsistentNaming
/// <summary>
/// Message maximum size in bytes
/// </summary>
/// <exclude />
public const int MAX_MESSAGE_SIZE = 700;
/// <summary>
/// Channel maximum size in bytes
/// </summary>
/// <exclude />
public const int MAX_CHANNEL_SIZE = 100;
/// <summary>
/// Connection Metadata maximum size in bytes
/// </summary>
/// <exclude />
public const int MAX_CONNECTION_METADATA_SIZE = 256;
protected const int HEARTBEAT_MAX_TIME = 60;
protected const int HEARTBEAT_MIN_TIME = 10;
protected const int HEARTBEAT_MAX_FAIL = 6;
protected const int HEARTBEAT_MIN_FAIL = 1;
#endregion
#region Attributes (17)
private string _url;
private string _clusterUrl;
private string _applicationKey;
private string _authenticationToken;
private bool _alreadyConnectedFirstTime;
private bool _forcedClosed;
private bool _waitingServerResponse;
// private int _sessionExpirationTime; // minutes
private List<KeyValuePair<string, string>> _permissions;
#if !UNITY_WSA || UNITY_EDITOR
private readonly RealtimeDictionary<string, ChannelSubscription> _subscribedChannels;
private readonly RealtimeDictionary<string, RealtimeDictionary<int, BufferedMessage>> _multiPartMessagesBuffer;
#else
private readonly ConcurrentDictionary<string, ChannelSubscription> _subscribedChannels;
private readonly ConcurrentDictionary<string, ConcurrentDictionary<int, BufferedMessage>> _multiPartMessagesBuffer;
#endif
private IWebSocketConnection _webSocketConnection;
private readonly TaskTimer _reconnectTimer;
private readonly TaskTimer _heartbeatTimer;
#endregion
#region Properties (9)
public string Id { get; set; }
public string SessionId { get; set; }
public string Url
{
get { return _url; }
set
{
IsCluster = false;
_url = string.IsNullOrEmpty(value) ? string.Empty : value.Trim();
}
}
public string ClusterUrl
{
get { return _clusterUrl; }
set
{
IsCluster = true;
_clusterUrl = string.IsNullOrEmpty(value) ? string.Empty : value.Trim();
}
}
public int HeartbeatTime
{
get { return _heartbeatTimer.Interval; }
set
{
_heartbeatTimer.Interval = value > HEARTBEAT_MAX_TIME
? HEARTBEAT_MAX_TIME
: (value < HEARTBEAT_MIN_TIME ? HEARTBEAT_MIN_TIME : value);
}
}
public int HeartbeatFails { get; set; }
public int ConnectionTimeout { get; set; }
public string ConnectionMetadata { get; set; }
public string AnnouncementSubChannel { get; set; }
public bool HeartbeatActive
{
get { return _heartbeatTimer.IsRunning; }
set
{
if (value)
_heartbeatTimer.Start();
else
_heartbeatTimer.Stop();
}
}
public bool EnableReconnect { get; set; }
public bool IsConnected { get; set; }
public bool IsConnecting { get; set; }
public bool IsCluster { get; set; }
#endregion
#region Events (7)
/// <summary>
/// Occurs when a connection attempt was successful.
/// </summary>
public event OnConnectedDelegate OnConnected = delegate { };
/// <summary>
/// Occurs when the client connection terminated.
/// </summary>
public event OnDisconnectedDelegate OnDisconnected = delegate { };
/// <summary>
/// Occurs when the client subscribed to a channel.
/// </summary>
public event OnSubscribedDelegate OnSubscribed = delegate { };
/// <summary>
/// Occurs when the client unsubscribed from a channel.
/// </summary>
public event OnUnsubscribedDelegate OnUnsubscribed = delegate { };
/// <summary>
/// Occurs when there is an error.
/// </summary>
public event OnExceptionDelegate OnException = delegate { };
/// <summary>
/// Occurs when a client attempts to reconnect.
/// </summary>
public event OnReconnectingDelegate OnReconnecting = delegate { };
/// <summary>
/// Occurs when a client reconnected.
/// </summary>
public event OnReconnectedDelegate OnReconnected = delegate { };
#endregion
#region Constructor (1)
static UnityOrtcClient()
{
//WSA Fix
UnityOrtcStartup.ConfigureOrtc();
RealtimeProxy.ConfirmInit();
}
/// <summary>
/// Initializes a new instance of the <see cref="UnityOrtcClient" /> class.
/// </summary>
public UnityOrtcClient()
{
_heartbeatTimer = new TaskTimer { Interval = 2, AutoReset = true };
_heartbeatTimer.Elapsed += _heartbeatTimer_Elapsed;
_heartbeatTimer.Start();
_reconnectTimer = new TaskTimer { Interval = 2, AutoReset = false };
_reconnectTimer.Elapsed += _reconnectTimer_Elapsed;
IsCluster = true;
Url = "http://ortc-developers.realtime.co/server/2.1";
EnableReconnect = true;
_permissions = new List<KeyValuePair<string, string>>();
#if !UNITY_WSA || UNITY_EDITOR
_subscribedChannels = new RealtimeDictionary<string, ChannelSubscription>();
_multiPartMessagesBuffer = new RealtimeDictionary<string, RealtimeDictionary<int, BufferedMessage>>();
#else
_subscribedChannels = new ConcurrentDictionary<string, ChannelSubscription>();
_multiPartMessagesBuffer = new ConcurrentDictionary<string, ConcurrentDictionary<int, BufferedMessage>>();
#endif
}
void CreateConnection(bool isSSL)
{
DisposeConnection();
#if UNITY_EDITOR
_webSocketConnection = new DotNetConnection();
#elif UNITY_ANDROID
_webSocketConnection = new DroidConnection();
#elif UNITY_WEBGL
_webSocketConnection = new WebGLConnection();
#elif UNITY_WSA
_webSocketConnection = new WSAConnection();
#elif UNITY_IOS
//IOS does not support HTTP
_webSocketConnection = isSSL ? (IWebSocketConnection) new IOSConnection() : (IWebSocketConnection) new DotNetConnection();
#else
_webSocketConnection = new DotNetConnection();
#endif
_webSocketConnection.OnOpened += _webSocketConnection_OnOpened;
_webSocketConnection.OnClosed += _webSocketConnection_OnClosed;
_webSocketConnection.OnError += _webSocketConnection_OnError;
_webSocketConnection.OnMessage += WebSocketConnectionOnMessage;
}
void DisposeConnection()
{
if (_webSocketConnection == null) return;
_webSocketConnection.OnOpened -= _webSocketConnection_OnOpened;
_webSocketConnection.OnClosed -= _webSocketConnection_OnClosed;
_webSocketConnection.OnError -= _webSocketConnection_OnError;
_webSocketConnection.OnMessage -= WebSocketConnectionOnMessage;
_webSocketConnection.Dispose();
_webSocketConnection = null;
}
#endregion
#region Public Methods (6)
public void Dispose()
{
if (_webSocketConnection != null)
_webSocketConnection.Dispose();
}
/// <summary>
/// Connects to the gateway with the application key and authentication token. The gateway must be set before using
/// this method.
/// </summary>
/// <param name="appKey">Your application key to use ORTC.</param>
/// <param name="authToken">Authentication token that identifies your permissions.</param>
/// <example>
/// <code>
/// ortcClient.Connect("myApplicationKey", "myAuthenticationToken");
/// </code>
/// </example>
public void Connect(string appKey, string authToken)
{
Debug.Log(string.Format("Ortc.Connect key:{0} token:{1}", appKey, authToken));
#region Sanity Checks
if (IsConnected)
{
DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Already connected"));
}
else if (IsConnecting)
{
DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments,
"Already trying to connect"));
}
else if (string.IsNullOrEmpty(ClusterUrl) && string.IsNullOrEmpty(Url))
{
DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments,
"URL and Cluster URL are null or empty"));
}
else if (string.IsNullOrEmpty(appKey))
{
DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments,
"Application Key is null or empty"));
}
else if (string.IsNullOrEmpty(authToken))
{
DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments,
"Authentication ToKen is null or empty"));
}
else if (!IsCluster && !Url.OrtcIsValidUrl())
{
DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Invalid URL"));
}
else if (IsCluster && !ClusterUrl.OrtcIsValidUrl())
{
DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments, "Invalid Cluster URL"));
}
else if (!appKey.OrtcIsValidInput())
{
DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments,
"Application Key has invalid characters"));
}
else if (!authToken.OrtcIsValidInput())
{
DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments,
"Authentication Token has invalid characters"));
}
else if (AnnouncementSubChannel != null && !AnnouncementSubChannel.OrtcIsValidInput())
{
DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments,
"Announcement Subchannel has invalid characters"));
}
else if (!string.IsNullOrEmpty(ConnectionMetadata) &&
ConnectionMetadata.Length > MAX_CONNECTION_METADATA_SIZE)
{
DelegateExceptionCallback(new OrtcException(OrtcExceptionReason.InvalidArguments,
string.Format("Connection metadata size exceeds the limit of {0} characters",
MAX_CONNECTION_METADATA_SIZE)));
}
else
#endregion
{
_forcedClosed = false;
_authenticationToken = authToken;
_applicationKey = appKey;
DoConnect();
}
}
/// <summary>
/// Sends a message to a channel.
/// </summary>
/// <param name="channel">Channel name.</param>
/// <param name="message">Message to be sent.</param>
/// <example>
/// <code>
/// ortcClient.Send("channelName", "messageToSend");
/// </code>
/// </example>
public void Send(string channel, string message)
{
#region Sanity Checks
if (!IsConnected)
{
DelegateExceptionCallback(new OrtcException("Not connected"));
}
else if (string.IsNullOrEmpty(channel))
{
DelegateExceptionCallback(new OrtcException("Channel is null or empty"));
}
else if (!channel.OrtcIsValidInput())
{
DelegateExceptionCallback(new OrtcException("Channel has invalid characters"));
}
else if (string.IsNullOrEmpty(message))
{
DelegateExceptionCallback(new OrtcException("Message is null or empty"));
}
else
#endregion
{
var channelBytes = Encoding.UTF8.GetBytes(channel);
if (channelBytes.Length > MAX_CHANNEL_SIZE)
{
DelegateExceptionCallback(
new OrtcException(string.Format("Channel size exceeds the limit of {0} characters",
MAX_CHANNEL_SIZE)));
}
else
{
var domainChannelCharacterIndex = channel.IndexOf(':');
var channelToValidate = channel;
if (domainChannelCharacterIndex > 0)
{
channelToValidate = channel.Substring(0, domainChannelCharacterIndex + 1) + "*";
}
var hash = GetChannelHash(channel, channelToValidate);
if (_permissions != null && _permissions.Count > 0 && string.IsNullOrEmpty(hash))
{
DelegateExceptionCallback(
new OrtcException(string.Format("No permission found to send to the channel '{0}'", channel)));
}
else
{
if (channel != string.Empty && message != string.Empty)
{
try
{
message = message.Replace(Environment.NewLine, "\n");
var messageBytes = Encoding.UTF8.GetBytes(message);
var messageParts = new List<string>();
var pos = 0;
int remaining;
var messageId = Strings.GenerateId(8);
// Multi part
while ((remaining = messageBytes.Length - pos) > 0)
{
byte[] messagePart;
if (remaining >= MAX_MESSAGE_SIZE - channelBytes.Length)
{
messagePart = new byte[MAX_MESSAGE_SIZE - channelBytes.Length];
}
else
{
messagePart = new byte[remaining];
}
Array.Copy(messageBytes, pos, messagePart, 0, messagePart.Length);
#if UNITY_WSA
var b = (byte[])messagePart;
messageParts.Add(Encoding.UTF8.GetString(b, 0, b.Length));
#else
messageParts.Add(Encoding.UTF8.GetString(messagePart));
#endif
pos += messagePart.Length;
}
for (var i = 0; i < messageParts.Count; i++)
{
var s = string.Format("send;{0};{1};{2};{3};{4}", _applicationKey,_authenticationToken, channel, hash,string.Format("{0}_{1}-{2}_{3}", messageId, i + 1, messageParts.Count,messageParts[i]));
DoSend(s);
}
}
catch (Exception ex)
{
string exName = null;
if (ex.InnerException != null)
{
exName = ex.InnerException.GetType().Name;
}
switch (exName)
{
case "OrtcNotConnectedException":
// Server went down
if (IsConnected)
{
DoDisconnect();
}
break;
default:
DelegateExceptionCallback(
new OrtcException(string.Format("Unable to send: {0}", ex)));
break;
}
}
}
}
}
}
}
public void SendProxy(string applicationKey, string privateKey, string channel, string message)
{
#region Sanity Checks
if (!IsConnected)
{
DelegateExceptionCallback(new OrtcException("Not connected"));
}
else if (string.IsNullOrEmpty(applicationKey))
{
DelegateExceptionCallback(new OrtcException("Application Key is null or empty"));
}
else if (string.IsNullOrEmpty(privateKey))
{
DelegateExceptionCallback(new OrtcException("Private Key is null or empty"));
}
else if (string.IsNullOrEmpty(channel))
{
DelegateExceptionCallback(new OrtcException("Channel is null or empty"));
}
else if (!channel.OrtcIsValidInput())
{
DelegateExceptionCallback(new OrtcException("Channel has invalid characters"));
}
else if (string.IsNullOrEmpty(message))
{
DelegateExceptionCallback(new OrtcException("Message is null or empty"));
}
else
#endregion
{
var channelBytes = Encoding.UTF8.GetBytes(channel);
if (channelBytes.Length > MAX_CHANNEL_SIZE)
{
DelegateExceptionCallback(
new OrtcException(string.Format("Channel size exceeds the limit of {0} characters",
MAX_CHANNEL_SIZE)));
}
else
{
message = message.Replace(Environment.NewLine, "\n");
if (channel != string.Empty && message != string.Empty)
{
try
{
var messageBytes = Encoding.UTF8.GetBytes(message);
var messageParts = new List<string>();
var pos = 0;
int remaining;
var messageId = Strings.GenerateId(8);
// Multi part
while ((remaining = messageBytes.Length - pos) > 0)
{
byte[] messagePart;
if (remaining >= MAX_MESSAGE_SIZE - channelBytes.Length)
{
messagePart = new byte[MAX_MESSAGE_SIZE - channelBytes.Length];
}
else
{
messagePart = new byte[remaining];
}
Array.Copy(messageBytes, pos, messagePart, 0, messagePart.Length);
#if UNITY_WSA
var b = (byte[])messagePart;
messageParts.Add(Encoding.UTF8.GetString(b, 0, b.Length));
#else
messageParts.Add(Encoding.UTF8.GetString(messagePart));
#endif
pos += messagePart.Length;
}
for (var i = 0; i < messageParts.Count; i++)
{
var s = string.Format("sendproxy;{0};{1};{2};{3}", applicationKey, privateKey, channel,
string.Format("{0}_{1}-{2}_{3}", messageId, i + 1, messageParts.Count,
messageParts[i]));
DoSend(s);
}
}
catch (Exception ex)
{
string exName = null;
if (ex.InnerException != null)
{
exName = ex.InnerException.GetType().Name;
}
switch (exName)
{
case "OrtcNotConnectedException":
// Server went down
if (IsConnected)
{
DoDisconnect();
}
break;
default:
DelegateExceptionCallback(new OrtcException(string.Format("Unable to send: {0}", ex)));
break;
}
}
}
}
}
}
/// <summary>
/// Subscribes to a channel.
/// </summary>
/// <param name="channel">Channel name.</param>
/// <param name="onMessage"><see cref="OnMessageDelegate" /> callback.</param>
/// <example>
/// <code>
/// ortcClient.Subscribe("channelName", true, OnMessageCallback);
/// private void OnMessageCallback(object sender, string channel, string message)
/// {
/// // Do something
/// }
/// </code>
/// </example>
public void Subscribe(string channel, bool subscribeOnReconnected, OnMessageDelegate onMessage)
{
#region Sanity Checks
var sanityChecked = true;
if (!IsConnected)
{
DelegateExceptionCallback(new OrtcException("Not connected"));
sanityChecked = false;
}
else if (string.IsNullOrEmpty(channel))
{
DelegateExceptionCallback(new OrtcException("Channel is null or empty"));
sanityChecked = false;
}
else if (!channel.OrtcIsValidInput())
{
DelegateExceptionCallback(new OrtcException("Channel has invalid characters"));
sanityChecked = false;
}
else if (_subscribedChannels.ContainsKey(channel))
{
ChannelSubscription channelSubscription = null;
_subscribedChannels.TryGetValue(channel, out channelSubscription);
if (channelSubscription != null)
{
if (channelSubscription.IsSubscribing)
{
DelegateExceptionCallback(
new OrtcException(string.Format("Already subscribing to the channel {0}", channel)));
sanityChecked = false;
}
else if (channelSubscription.IsSubscribed)
{
DelegateExceptionCallback(
new OrtcException(string.Format("Already subscribed to the channel {0}", channel)));
sanityChecked = false;
}
}
}
else
{
var channelBytes = Encoding.UTF8.GetBytes(channel);
if (channelBytes.Length > MAX_CHANNEL_SIZE)
{
if (_subscribedChannels.ContainsKey(channel))
{
ChannelSubscription channelSubscription = null;
_subscribedChannels.TryGetValue(channel, out channelSubscription);
if (channelSubscription != null)
{
channelSubscription.IsSubscribing = false;
}
}
DelegateExceptionCallback(
new OrtcException(string.Format("Channel size exceeds the limit of {0} characters",
MAX_CHANNEL_SIZE)));
sanityChecked = false;
}
}
#endregion
if (sanityChecked)
{
var domainChannelCharacterIndex = channel.IndexOf(':');
var channelToValidate = channel;
if (domainChannelCharacterIndex > 0)
{
channelToValidate = channel.Substring(0, domainChannelCharacterIndex + 1) + "*";
}
var hash = GetChannelHash(channel, channelToValidate);
if (_permissions != null && _permissions.Count > 0 && string.IsNullOrEmpty(hash))
{
DelegateExceptionCallback(
new OrtcException(string.Format("No permission found to subscribe to the channel '{0}'", channel)));
}
else
{
if (!_subscribedChannels.ContainsKey(channel))
{
_subscribedChannels.TryAdd(channel,
new ChannelSubscription
{
IsSubscribing = true,
IsSubscribed = false,
SubscribeOnReconnected = subscribeOnReconnected,
OnMessage = onMessage
});
}
try
{
if (_subscribedChannels.ContainsKey(channel))
{
ChannelSubscription channelSubscription = null;
_subscribedChannels.TryGetValue(channel, out channelSubscription);
channelSubscription.IsSubscribing = true;
channelSubscription.IsSubscribed = false;
channelSubscription.SubscribeOnReconnected = subscribeOnReconnected;
channelSubscription.OnMessage = onMessage;
}
var s = string.Format("subscribe;{0};{1};{2};{3}", _applicationKey, _authenticationToken,
channel, hash);
DoSend(s);
}
catch (Exception ex)
{
string exName = null;
if (ex.InnerException != null)
{
exName = ex.InnerException.GetType().Name;
}
switch (exName)
{
case "OrtcNotConnectedException":
// Server went down
if (IsConnected)
{
DoDisconnect();
}
break;
default:
DelegateExceptionCallback(
new OrtcException(string.Format("Unable to subscribe: {0}", ex)));
break;
}
}
}
}
}
/// <summary>
/// Unsubscribes from a channel.
/// </summary>
/// <param name="channel">Channel name.</param>
/// <example>
/// <code>
/// ortcClient.Unsubscribe("channelName");
/// </code>
/// </example>
public void Unsubscribe(string channel)
{
#region Sanity Checks
var sanityChecked = true;
if (!IsConnected)
{
DelegateExceptionCallback(new OrtcException("Not connected"));
sanityChecked = false;
}
else if (string.IsNullOrEmpty(channel))
{
DelegateExceptionCallback(new OrtcException("Channel is null or empty"));
sanityChecked = false;
}
else if (!channel.OrtcIsValidInput())
{
DelegateExceptionCallback(new OrtcException("Channel has invalid characters"));
sanityChecked = false;
}
else if (!_subscribedChannels.ContainsKey(channel))
{
DelegateExceptionCallback(new OrtcException(string.Format("Not subscribed to the channel {0}", channel)));
sanityChecked = false;
}
else if (_subscribedChannels.ContainsKey(channel))
{
ChannelSubscription channelSubscription = null;
_subscribedChannels.TryGetValue(channel, out channelSubscription);
if (channelSubscription != null && !channelSubscription.IsSubscribed)
{
DelegateExceptionCallback(
new OrtcException(string.Format("Not subscribed to the channel {0}", channel)));
sanityChecked = false;
}
}
else
{
var channelBytes = Encoding.UTF8.GetBytes(channel);
if (channelBytes.Length > MAX_CHANNEL_SIZE)
{
DelegateExceptionCallback(
new OrtcException(string.Format("Channel size exceeds the limit of {0} characters",
MAX_CHANNEL_SIZE)));
sanityChecked = false;
}
}
#endregion
if (sanityChecked)
{
try
{
var s = string.Format("unsubscribe;{0};{1}", _applicationKey, channel);
DoSend(s);
}
catch (Exception ex)
{
string exName = null;
if (ex.InnerException != null)
{
exName = ex.InnerException.GetType().Name;
}
switch (exName)
{
case "OrtcNotConnectedException":
// Server went down
if (IsConnected)
{
DoDisconnect();
}
break;
default:
DelegateExceptionCallback(new OrtcException(string.Format("Unable to unsubscribe: {0}", ex)));
break;
}
}
}
}
/// <summary>
/// Disconnects from the gateway.
/// </summary>
/// <example>
/// <code>
/// ortcClient.Disconnect();
/// </code>
/// </example>
public void Disconnect()
{
// Clear subscribed channels
_subscribedChannels.Clear();
#region Sanity Checks
if (!IsConnecting && !IsConnected)
{
DelegateExceptionCallback(new OrtcException("Not connected"));
}
else
#endregion
{
DoDisconnect();
}
}
/// <summary>
/// Indicates whether is subscribed to a channel.
/// </summary>
/// <param name="channel">The channel name.</param>
/// <returns>
/// <c>true</c> if subscribed to the channel; otherwise, <c>false</c>.
/// </returns>
public bool IsSubscribed(string channel)
{
var result = false;
#region Sanity Checks
if (!IsConnected)
{
DelegateExceptionCallback(new OrtcException("Not connected"));
}
else if (string.IsNullOrEmpty(channel))
{
DelegateExceptionCallback(new OrtcException("Channel is null or empty"));
}
else if (!channel.OrtcIsValidInput())
{
DelegateExceptionCallback(new OrtcException("Channel has invalid characters"));
}
else
#endregion
{
result = false;
if (_subscribedChannels.ContainsKey(channel))
{
ChannelSubscription channelSubscription = null;
_subscribedChannels.TryGetValue(channel, out channelSubscription);
if (channelSubscription != null && channelSubscription.IsSubscribed)
{
result = true;
}
}
}
return result;
}
protected List<string> SplitMessage(byte[] channelBytes, string message)
{
message = message.Replace(Environment.NewLine, "\n");
var messageBytes = Encoding.UTF8.GetBytes(message);
var messageParts = new List<string>();
var pos = 0;
int remaining;
// Multi part
while ((remaining = messageBytes.Length - pos) > 0)
{
var messagePart = remaining >= MAX_MESSAGE_SIZE - channelBytes.Length
? new byte[MAX_MESSAGE_SIZE - channelBytes.Length]
: new byte[remaining];
Array.Copy(messageBytes, pos, messagePart, 0, messagePart.Length);
#if UNITY_WSA
messageParts.Add(Encoding.UTF8.GetString(messagePart, 0, messagePart.Length));
#else
messageParts.Add(Encoding.UTF8.GetString(messagePart));
#endif
pos += messagePart.Length;
}
return messageParts;
}
#endregion
#region Private Methods (13)
private string GetChannelHash(string channel, string channelToValidate)
{
foreach (var keyValuePair in _permissions)
{
if (keyValuePair.Key == channel)
return keyValuePair.Value;
if (keyValuePair.Key == channelToValidate)
return keyValuePair.Value;
}
return null;
}
/// <summary>
/// Processes the operation validated.
/// </summary>
/// <param name="arguments">The arguments.</param>
private void ProcessOperationValidated(string arguments)
{
if (!string.IsNullOrEmpty(arguments))
{
var isValid = false;
// Try to match with authentication
var validatedAuthMatch = Regex.Match(arguments, VALIDATED_PATTERN);
if (validatedAuthMatch.Success)
{
isValid = true;
var userPermissions = string.Empty;
if (validatedAuthMatch.Groups["up"].Length > 0)
{
userPermissions = validatedAuthMatch.Groups["up"].Value;
}
if (validatedAuthMatch.Groups["set"].Length > 0)
{
// _sessionExpirationTime = int.Parse(validatedAuthMatch.Groups["set"].Value);
}
if (!string.IsNullOrEmpty(userPermissions) && userPermissions != "null")
{
var matchCollection = Regex.Matches(userPermissions, PERMISSIONS_PATTERN);
var permissions = new List<KeyValuePair<string, string>>();
foreach (Match match in matchCollection)
{
var channel = match.Groups["key"].Value;
var hash = match.Groups["value"].Value;
permissions.Add(new KeyValuePair<string, string>(channel, hash));
}
_permissions = new List<KeyValuePair<string, string>>(permissions);
}
}
if (isValid)
{
IsConnecting = false;
if (_alreadyConnectedFirstTime)
{
var channelsToRemove = new List<string>();
// Subscribe to the previously subscribed channels
foreach (var item in _subscribedChannels)
{
var channel = item.Key;
var channelSubscription = item.Value;
// Subscribe again
if (channelSubscription.SubscribeOnReconnected &&
(channelSubscription.IsSubscribing || channelSubscription.IsSubscribed))
{
channelSubscription.IsSubscribing = true;
channelSubscription.IsSubscribed = false;
var domainChannelCharacterIndex = channel.IndexOf(':');
var channelToValidate = channel;
if (domainChannelCharacterIndex > 0)
{
channelToValidate = channel.Substring(0, domainChannelCharacterIndex + 1) + "*";
}
var hash = GetChannelHash(channel, channelToValidate);
var s = string.Format("subscribe;{0};{1};{2};{3}", _applicationKey, _authenticationToken,
channel, hash);
DoSend(s);
}
else
{
channelsToRemove.Add(channel);
}
}
for (var i = 0; i < channelsToRemove.Count; i++)
{
ChannelSubscription removeResult = null;
_subscribedChannels.TryRemove(channelsToRemove[i], out removeResult);
}
// Clean messages buffer (can have lost message parts in memory)
_multiPartMessagesBuffer.Clear();
DelegateReconnectedCallback();
}
else
{
_alreadyConnectedFirstTime = true;
// Clear subscribed channels
_subscribedChannels.Clear();
DelegateConnectedCallback();
}
if (arguments.IndexOf("busy") < 0)
{
StopReconnect();
}
}
}
}
/// <summary>
/// Processes the operation subscribed.
/// </summary>
/// <param name="arguments">The arguments.</param>
private void ProcessOperationSubscribed(string arguments)
{
if (!string.IsNullOrEmpty(arguments))
{
var subscribedMatch = Regex.Match(arguments, CHANNEL_PATTERN);
if (subscribedMatch.Success)
{
var channelSubscribed = string.Empty;
if (subscribedMatch.Groups["channel"].Length > 0)
{
channelSubscribed = subscribedMatch.Groups["channel"].Value;
}
if (!string.IsNullOrEmpty(channelSubscribed))
{
ChannelSubscription channelSubscription = null;
_subscribedChannels.TryGetValue(channelSubscribed, out channelSubscription);
if (channelSubscription != null)
{
channelSubscription.IsSubscribing = false;
channelSubscription.IsSubscribed = true;
}
DelegateSubscribedCallback(channelSubscribed);
}
}
}
}
/// <summary>
/// Processes the operation unsubscribed.
/// </summary>
/// <param name="arguments">The arguments.</param>
private void ProcessOperationUnsubscribed(string arguments)
{
// UnityEngine.Debug.Log("ProcessOperationUnsubscribed");
if (!string.IsNullOrEmpty(arguments))
{
var unsubscribedMatch = Regex.Match(arguments, CHANNEL_PATTERN);
if (unsubscribedMatch.Success)
{
var channelUnsubscribed = string.Empty;
if (unsubscribedMatch.Groups["channel"].Length > 0)
{
channelUnsubscribed = unsubscribedMatch.Groups["channel"].Value;
}
if (!string.IsNullOrEmpty(channelUnsubscribed))
{
ChannelSubscription channelSubscription = null;
_subscribedChannels.TryGetValue(channelUnsubscribed, out channelSubscription);
if (channelSubscription != null)
{
channelSubscription.IsSubscribed = false;
}
DelegateUnsubscribedCallback(channelUnsubscribed);
}
}
}
}
/// <summary>
/// Processes the operation error.
/// </summary>
/// <param name="arguments">The arguments.</param>
private void ProcessOperationError(string arguments)
{
if (!string.IsNullOrEmpty(arguments))
{
var errorMatch = Regex.Match(arguments, EXCEPTION_PATTERN);
if (errorMatch.Success)
{
var op = string.Empty;
var error = string.Empty;
var channel = string.Empty;
if (errorMatch.Groups["op"].Length > 0)
{
op = errorMatch.Groups["op"].Value;
}
if (errorMatch.Groups["error"].Length > 0)
{
error = errorMatch.Groups["error"].Value;
}
if (errorMatch.Groups["channel"].Length > 0)
{
channel = errorMatch.Groups["channel"].Value;
}
if (!string.IsNullOrEmpty(error))
{
DelegateExceptionCallback(new OrtcException(error));
}
if (!string.IsNullOrEmpty(op))
{
switch (op)
{
case "validate":
if (!string.IsNullOrEmpty(error) &&
(error.Contains("Unable to connect") || error.Contains("Server is too busy")))
{
DelegateExceptionCallback(new Exception(error));
DoReconnectOrDisconnect();
}
else
{
DoDisconnect();
}
break;
case "subscribe":
if (!string.IsNullOrEmpty(channel))
{
ChannelSubscription channelSubscription = null;
_subscribedChannels.TryGetValue(channel, out channelSubscription);
if (channelSubscription != null)
{
channelSubscription.IsSubscribing = false;
}
}
break;
case "subscribe_maxsize":
case "unsubscribe_maxsize":
case "send_maxsize":
if (!string.IsNullOrEmpty(channel))
{
ChannelSubscription channelSubscription = null;
_subscribedChannels.TryGetValue(channel, out channelSubscription);
if (channelSubscription != null)
{
channelSubscription.IsSubscribing = false;
}
}
DoDisconnect();
break;
default:
break;
}
}
}
}
}
private void ProcessOperationReceived(string message)
{
var receivedMatch = Regex.Match(message, RECEIVED_PATTERN);
// Received
if (receivedMatch.Success)
{
var channelReceived = string.Empty;
var messageReceived = string.Empty;
if (receivedMatch.Groups["channel"].Length > 0)
{
channelReceived = receivedMatch.Groups["channel"].Value;
}
if (receivedMatch.Groups["message"].Length > 0)
{
messageReceived = receivedMatch.Groups["message"].Value;
}
if (!string.IsNullOrEmpty(channelReceived) && !string.IsNullOrEmpty(messageReceived) &&
_subscribedChannels.ContainsKey(channelReceived))
{
messageReceived =
messageReceived.Replace(@"\\n", Environment.NewLine)
.Replace("\\\\\"", @"""")
.Replace("\\\\\\\\", @"\");
// Multi part
var multiPartMatch = Regex.Match(messageReceived, MULTI_PART_MESSAGE_PATTERN);
var messageId = string.Empty;
var messageCurrentPart = 1;
var messageTotalPart = 1;
var lastPart = false;
#if !UNITY_WSA || UNITY_EDITOR
RealtimeDictionary<int, BufferedMessage> messageParts = null;
#else
ConcurrentDictionary<int, BufferedMessage> messageParts = null;
#endif
if (multiPartMatch.Success)
{
if (multiPartMatch.Groups["messageId"].Length > 0)
{
messageId = multiPartMatch.Groups["messageId"].Value;
}
if (multiPartMatch.Groups["messageCurrentPart"].Length > 0)
{
messageCurrentPart = int.Parse(multiPartMatch.Groups["messageCurrentPart"].Value);
}
if (multiPartMatch.Groups["messageTotalPart"].Length > 0)
{
messageTotalPart = int.Parse(multiPartMatch.Groups["messageTotalPart"].Value);
}
if (multiPartMatch.Groups["message"].Length > 0)
{
messageReceived = multiPartMatch.Groups["message"].Value;
}
}
lock (_multiPartMessagesBuffer)
{
// Is a message part
if (!string.IsNullOrEmpty(messageId))
{
if (!_multiPartMessagesBuffer.ContainsKey(messageId))
{
_multiPartMessagesBuffer.TryAdd(messageId,
#if !UNITY_WSA || UNITY_EDITOR
new RealtimeDictionary<int, BufferedMessage>());
#else
new ConcurrentDictionary<int, BufferedMessage>());
#endif
}
_multiPartMessagesBuffer.TryGetValue(messageId, out messageParts);
if (messageParts != null)
{
lock (messageParts)
{
messageParts.TryAdd(messageCurrentPart,
new BufferedMessage(messageCurrentPart, messageReceived));
// Last message part
if (messageParts.Count == messageTotalPart)
{
//messageParts.Sort();
lastPart = true;
}
}
}
}
// Message does not have multipart, like the messages received at announcement channels
else
{
lastPart = true;
}
if (lastPart)
{
if (_subscribedChannels.ContainsKey(channelReceived))
{
ChannelSubscription channelSubscription = null;
_subscribedChannels.TryGetValue(channelReceived, out channelSubscription);
if (channelSubscription != null)
{
var ev = channelSubscription.OnMessage;
if (ev != null)
{
if (!string.IsNullOrEmpty(messageId) &&
_multiPartMessagesBuffer.ContainsKey(messageId))
{
messageReceived = string.Empty;
//lock (messageParts)
//{
var bufferedMultiPartMessages = new List<BufferedMessage>();
foreach (var part in messageParts.Keys)
{
bufferedMultiPartMessages.Add(messageParts[part]);
}
bufferedMultiPartMessages.Sort();
foreach (var part in bufferedMultiPartMessages)
{
if (part != null)
{
messageReceived = string.Format("{0}{1}", messageReceived,
part.Message);
}
}
//}
// Remove from messages buffer
#if !UNITY_WSA || UNITY_EDITOR
RealtimeDictionary<int, BufferedMessage> removeResult = null;
#else
ConcurrentDictionary<int, BufferedMessage> removeResult = null;
#endif
_multiPartMessagesBuffer.TryRemove(messageId, out removeResult);
}
if (!string.IsNullOrEmpty(messageReceived))
{
RealtimeProxy.RunOnMainThread(
() => { ev(channelReceived, messageReceived); });
}
}
}
}
}
}
}
}
else
{
// Unknown
DelegateExceptionCallback(new OrtcException(string.Format("Unknown message received: {0}", message)));
}
}
/// <summary>
/// Do the Connect Task
/// </summary>
private void DoConnect()
{
IsConnecting = true;
if (IsCluster)
{
ClusterClient.GetClusterServer(ClusterUrl, _applicationKey, (exception, s) =>
{
if (exception != null || string.IsNullOrEmpty(s))
{
DoReconnectOrDisconnect();
DelegateExceptionCallback(new OrtcException("Connection Failed. Unable to get URL from cluster"));
}
else
{
Url = s;
IsCluster = true;
DoConnectInternal();
}
});
}
else
{
DoConnectInternal();
}
}
private void DoConnectInternal()
{
if (!string.IsNullOrEmpty(Url))
{
try
{
CreateConnection(Url.StartsWith("https"));
IsConnecting = true;
_reconnectTimer.Start();
// use socket
_webSocketConnection.Open(Url);
// Just in case the server does not respond
_waitingServerResponse = true;
}
catch (Exception ex)
{
DoReconnectOrDisconnect();
DelegateExceptionCallback(new OrtcException("Connection Failed. " + ex.Message));
}
}
}
/// <summary>
/// Disconnect the TCP client.
/// </summary>
private void DoDisconnect()
{
_forcedClosed = true;
StopReconnect();
if (IsConnecting || IsConnected || (_webSocketConnection != null && _webSocketConnection.IsOpen))
{
try
{
IsConnecting = false;
IsConnected = false;
_webSocketConnection.Close();
}
catch (Exception ex)
{
DelegateExceptionCallback(new OrtcException(string.Format("Error disconnecting: {0}", ex)));
DelegateDisconnectedCallback();
DisposeConnection();
}
}
else
{
DelegateDisconnectedCallback();
DisposeConnection();
}
}
/// <summary>
/// Sends a message through the TCP client.
/// </summary>
/// <param name="message"></param>
private void DoSend(string message)
{
try
{
_webSocketConnection.Send(message);
}
catch (Exception ex)
{
DelegateExceptionCallback(new OrtcException(string.Format("Unable to send: {0}", ex)));
}
}
private void DoReconnectOrDisconnect()
{
if (EnableReconnect)
DoReconnect();
else
DoDisconnect();
}
private void DoReconnect()
{
IsConnecting = true;
_reconnectTimer.Start();
}
private void StopReconnect()
{
IsConnecting = false;
_reconnectTimer.Stop();
}
#endregion
#region Events handlers (6)
private void _reconnectTimer_Elapsed()
{
if (!IsConnected)
{
if (_waitingServerResponse)
{
_waitingServerResponse = false;
DelegateExceptionCallback(new OrtcException("Unable to connect"));
}
DelegateReconnectingCallback();
DoConnect();
}
}
private void _heartbeatTimer_Elapsed()
{
if (IsConnected)
{
DoSend("b");
}
}
/// <summary>
/// </summary>
private void _webSocketConnection_OnOpened()
{
Debug.Log("Ortc.Opened");
}
/// <summary>
/// </summary>
private void _webSocketConnection_OnClosed()
{
IsConnected = false;
if (!_forcedClosed && EnableReconnect)
DoReconnect();
else
DoDisconnect();
}
/// <summary>
/// </summary>
/// <param name="error"></param>
private void _webSocketConnection_OnError(string error)
{
DelegateExceptionCallback(new OrtcException(error));
}
/// <summary>
/// </summary>
/// <param name="message"></param>
private void WebSocketConnectionOnMessage(string message)
{
if (!string.IsNullOrEmpty(message))
{
// Open
if (message == "o")
{
try
{
SessionId = Strings.GenerateId(16);
string s;
if (HeartbeatActive)
{
s = string.Format("validate;{0};{1};{2};{3};{4};{5};{6}", _applicationKey,
_authenticationToken, AnnouncementSubChannel, SessionId,
ConnectionMetadata, HeartbeatTime, HeartbeatFails);
}
else
{
s = string.Format("validate;{0};{1};{2};{3};{4}", _applicationKey, _authenticationToken,
AnnouncementSubChannel, SessionId, ConnectionMetadata);
}
DoSend(s);
}
catch (Exception ex)
{
DelegateExceptionCallback(new OrtcException(string.Format("Exception sending validate: {0}", ex)));
}
}
// Heartbeat
else if (message == "h")
{
// Do nothing
}
else
{
message = message.Replace("\\\"", @"""");
// UnityEngine.Debug.Log(message);
// Operation
var operationMatch = Regex.Match(message, OPERATION_PATTERN);
// Debug.Log(operationMatch.Success);
if (operationMatch.Success)
{
var operation = operationMatch.Groups["op"].Value;
var arguments = operationMatch.Groups["args"].Value;
// Debug.Log(operation);
// Debug.Log(arguments);
switch (operation)
{
case "ortc-validated":
ProcessOperationValidated(arguments);
break;
case "ortc-subscribed":
ProcessOperationSubscribed(arguments);
break;
case "ortc-unsubscribed":
ProcessOperationUnsubscribed(arguments);
break;
case "ortc-error":
ProcessOperationError(arguments);
break;
default:
// Unknown operation
DelegateExceptionCallback(
new OrtcException(string.Format(
"Unknown operation \"{0}\" for the message \"{1}\"", operation, message)));
DoDisconnect();
break;
}
}
else
{
// Close
var closeOperationMatch = Regex.Match(message, CLOSE_PATTERN);
if (!closeOperationMatch.Success)
{
ProcessOperationReceived(message);
}
}
}
}
}
#endregion
#region Events calls (7)
private void DelegateConnectedCallback()
{
IsConnected = true;
IsConnecting = false;
_reconnectTimer.Stop();
//_heartbeatTimer.Start();
RealtimeProxy.RunOnMainThread(() =>
{
Debug.Log("Ortc.Connected");
var ev = OnConnected;
if (ev != null)
{
ev();
}
});
}
private void DelegateDisconnectedCallback()
{
IsConnected = false;
IsConnecting = false;
_alreadyConnectedFirstTime = false;
_reconnectTimer.Stop();
//_heartbeatTimer.Stop();
// Clear user permissions
_permissions.Clear();
DisposeConnection();
RealtimeProxy.RunOnMainThread(() =>
{
Debug.Log("Ortc.Disconnected");
var ev = OnDisconnected;
if (ev != null)
{
ev();
}
});
}
private void DelegateSubscribedCallback(string channel)
{
RealtimeProxy.RunOnMainThread(() =>
{
Debug.Log("Ortc.Subscribed " + channel);
var ev = OnSubscribed;
if (ev != null)
{
ev(channel);
}
});
}
private void DelegateUnsubscribedCallback(string channel)
{
RealtimeProxy.RunOnMainThread(() =>
{
Debug.Log("Ortc.Unsubscribed " + channel);
var ev = OnUnsubscribed;
if (ev != null)
{
ev(channel);
}
});
}
private void DelegateExceptionCallback(Exception ex)
{
RealtimeProxy.RunOnMainThread(() =>
{
var ev = OnException;
if (ev != null)
{
ev(ex);
}
});
}
private void DelegateReconnectingCallback()
{
RealtimeProxy.RunOnMainThread(() =>
{
Debug.Log("Ortc.Reconnecting");
var ev = OnReconnecting;
if (ev != null)
{
ev();
}
});
}
private void DelegateReconnectedCallback()
{
IsConnected = true;
IsConnecting = false;
_reconnectTimer.Stop();
RealtimeProxy.RunOnMainThread(() =>
{
Debug.Log("Ortc.Reconnected");
var ev = OnReconnected;
if (ev != null)
{
ev();
}
});
}
#endregion
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// Convert.ToUInt16(string,IFormatProvider)
/// </summary>
public class ConvertToUInt1618
{
public static int Main()
{
ConvertToUInt1618 convertToUInt1618 = new ConvertToUInt1618();
TestLibrary.TestFramework.BeginTestCase("ConvertToUInt1618");
if (convertToUInt1618.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Convert to UInt16 from string 1");
try
{
string strVal = UInt16.MaxValue.ToString();
ushort ushortVal = Convert.ToUInt16(strVal, null);
if (ushortVal != UInt16.MaxValue)
{
TestLibrary.TestFramework.LogError("001", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Convert to UInt16 from string 2");
try
{
string strVal = UInt16.MaxValue.ToString();
CultureInfo myculture = new CultureInfo("en-us");
IFormatProvider provider = myculture.NumberFormat;
ushort ushortVal = Convert.ToUInt16(strVal, provider);
if (ushortVal != UInt16.MaxValue)
{
TestLibrary.TestFramework.LogError("003", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Convert to UInt16 from string 3");
try
{
string strVal = UInt16.MinValue.ToString();
ushort ushortVal = Convert.ToUInt16(strVal, null);
if (ushortVal != UInt16.MinValue)
{
TestLibrary.TestFramework.LogError("005", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert to UInt16 from string 4");
try
{
string strVal = "-" + UInt16.MinValue.ToString();
ushort ushortVal = Convert.ToUInt16(strVal, null);
if (ushortVal != UInt16.MinValue)
{
TestLibrary.TestFramework.LogError("007", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Convert to UInt16 from string 5");
try
{
int intVal = this.GetInt32(0, (int)UInt16.MaxValue);
string strVal = "+" + intVal.ToString();
ushort ushortVal = Convert.ToUInt16(strVal, null);
if (ushortVal != (UInt16)intVal)
{
TestLibrary.TestFramework.LogError("009", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Convert to UInt16 from string 6");
try
{
string strVal = null;
ushort ushortVal = Convert.ToUInt16(strVal, null);
if (ushortVal != 0)
{
TestLibrary.TestFramework.LogError("011", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: the string represents a number less than MinValue");
try
{
int intVal = this.GetInt32(1, Int32.MaxValue);
string strVal = "-" + intVal.ToString();
ushort ushortVal = Convert.ToUInt16(strVal, null);
TestLibrary.TestFramework.LogError("N001", "the string represents a number less than MinValue but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: the string represents a number greater than MaxValue");
try
{
int intVal = this.GetInt32((int)UInt16.MaxValue + 1, Int32.MaxValue);
string strVal = intVal.ToString();
ushort ushortVal = Convert.ToUInt16(strVal, null);
TestLibrary.TestFramework.LogError("N003", "the string represents a number greater than MaxValue but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: the string does not consist of an optional sign followed by a sequence of digits ");
try
{
string strVal = "helloworld";
ushort ushortVal = Convert.ToUInt16(strVal, null);
TestLibrary.TestFramework.LogError("N005", "the string does not consist of an optional sign followed by a sequence of digits but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: the string is empty string");
try
{
string strVal = string.Empty;
ushort ushortVal = Convert.ToUInt16(strVal, null);
TestLibrary.TestFramework.LogError("N007", "the string is empty string but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region HelpMethod
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics.Log;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV1
{
internal partial class DiagnosticIncrementalAnalyzer : BaseDiagnosticIncrementalAnalyzer
{
private readonly int _correlationId;
private readonly MemberRangeMap _memberRangeMap;
private readonly AnalyzerExecutor _executor;
private readonly StateManager _stateManger;
private readonly SimpleTaskQueue _eventQueue;
public DiagnosticIncrementalAnalyzer(
DiagnosticAnalyzerService owner,
int correlationId,
Workspace workspace,
HostAnalyzerManager analyzerManager,
AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
: base(owner, workspace, analyzerManager, hostDiagnosticUpdateSource)
{
_correlationId = correlationId;
_memberRangeMap = new MemberRangeMap();
_executor = new AnalyzerExecutor(this);
_eventQueue = new SimpleTaskQueue(TaskScheduler.Default);
_stateManger = new StateManager(analyzerManager);
_stateManger.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;
}
private void OnProjectAnalyzerReferenceChanged(object sender, ProjectAnalyzerReferenceChangedEventArgs e)
{
if (e.Removed.Length == 0)
{
// nothing to refresh
return;
}
// guarantee order of the events.
var asyncToken = Owner.Listener.BeginAsyncOperation(nameof(OnProjectAnalyzerReferenceChanged));
_eventQueue.ScheduleTask(() => ClearProjectStatesAsync(e.Project, e.Removed, CancellationToken.None), CancellationToken.None).CompletesAsyncOperation(asyncToken);
}
public override Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken))
{
// we remove whatever information we used to have on document open/close and re-calculate diagnostics
// we had to do this since some diagnostic analyzer changes its behavior based on whether the document is opened or not.
// so we can't use cached information.
ClearDocumentStates(document, _stateManger.GetStateSets(document.Project), raiseEvent: true, cancellationToken: cancellationToken);
return SpecializedTasks.EmptyTask;
}
}
public override Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken))
{
// we don't need the info for closed file
_memberRangeMap.Remove(document.Id);
// we remove whatever information we used to have on document open/close and re-calculate diagnostics
// we had to do this since some diagnostic analyzer changes its behavior based on whether the document is opened or not.
// so we can't use cached information.
ClearDocumentStates(document, _stateManger.GetStateSets(document.Project), raiseEvent: false, cancellationToken: cancellationToken);
return SpecializedTasks.EmptyTask;
}
}
private bool CheckOption(Workspace workspace, string language, bool documentOpened)
{
var optionService = workspace.Services.GetService<IOptionService>();
if (optionService == null || optionService.GetOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, language))
{
return true;
}
if (documentOpened)
{
return true;
}
return false;
}
public override async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
await AnalyzeSyntaxAsync(document, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeSyntaxAsync(Document document, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
{
try
{
if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen()))
{
return;
}
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var dataVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
var versions = new VersionArgument(textVersion, dataVersion);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var fullSpan = root == null ? null : (TextSpan?)root.FullSpan;
var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, cancellationToken);
var openedDocument = document.IsOpen();
foreach (var stateSet in _stateManger.GetOrUpdateStateSets(document.Project))
{
if (userDiagnosticDriver.IsAnalyzerSuppressed(stateSet.Analyzer))
{
await HandleSuppressedAnalyzerAsync(document, stateSet, StateType.Syntax, cancellationToken).ConfigureAwait(false);
}
else if (await ShouldRunAnalyzerForStateTypeAsync(userDiagnosticDriver, stateSet.Analyzer, StateType.Syntax, diagnosticIds).ConfigureAwait(false) &&
(skipClosedFileChecks || ShouldRunAnalyzerForClosedFile(openedDocument, stateSet.Analyzer)))
{
var data = await _executor.GetSyntaxAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsUpdated(StateType.Syntax, document.Id, stateSet, new SolutionArgument(document), data.Items);
continue;
}
var state = stateSet.GetState(StateType.Syntax);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Syntax, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
await AnalyzeDocumentAsync(document, bodyOpt, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
{
try
{
if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen()))
{
return;
}
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
var dataVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
var versions = new VersionArgument(textVersion, dataVersion, projectVersion);
if (bodyOpt == null)
{
await AnalyzeDocumentAsync(document, versions, diagnosticIds, skipClosedFileChecks, cancellationToken).ConfigureAwait(false);
}
else
{
// only open file can go this route
await AnalyzeBodyDocumentAsync(document, bodyOpt, versions, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task AnalyzeBodyDocumentAsync(Document document, SyntaxNode member, VersionArgument versions, CancellationToken cancellationToken)
{
try
{
// syntax facts service must exist, otherwise, this method won't have called.
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var memberId = syntaxFacts.GetMethodLevelMemberId(root, member);
var spanBasedDriver = new DiagnosticAnalyzerDriver(document, member.FullSpan, root, this, cancellationToken);
var documentBasedDriver = new DiagnosticAnalyzerDriver(document, root.FullSpan, root, this, cancellationToken);
foreach (var stateSet in _stateManger.GetOrUpdateStateSets(document.Project))
{
if (spanBasedDriver.IsAnalyzerSuppressed(stateSet.Analyzer))
{
await HandleSuppressedAnalyzerAsync(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false);
}
else if (await ShouldRunAnalyzerForStateTypeAsync(spanBasedDriver, stateSet.Analyzer, StateType.Document).ConfigureAwait(false))
{
var supportsSemanticInSpan = await stateSet.Analyzer.SupportsSpanBasedSemanticDiagnosticAnalysisAsync(spanBasedDriver).ConfigureAwait(false);
var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver;
var ranges = _memberRangeMap.GetSavedMemberRange(stateSet.Analyzer, document);
var data = await _executor.GetDocumentBodyAnalysisDataAsync(
stateSet, versions, userDiagnosticDriver, root, member, memberId, supportsSemanticInSpan, ranges).ConfigureAwait(false);
_memberRangeMap.UpdateMemberRange(stateSet.Analyzer, document, versions.TextVersion, memberId, member.FullSpan, ranges);
var state = stateSet.GetState(StateType.Document);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsUpdated(StateType.Document, document.Id, stateSet, new SolutionArgument(document), data.Items);
continue;
}
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task AnalyzeDocumentAsync(Document document, VersionArgument versions, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
{
try
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var fullSpan = root == null ? null : (TextSpan?)root.FullSpan;
var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, cancellationToken);
bool openedDocument = document.IsOpen();
foreach (var stateSet in _stateManger.GetOrUpdateStateSets(document.Project))
{
if (userDiagnosticDriver.IsAnalyzerSuppressed(stateSet.Analyzer))
{
await HandleSuppressedAnalyzerAsync(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false);
}
else if (await ShouldRunAnalyzerForStateTypeAsync(userDiagnosticDriver, stateSet.Analyzer, StateType.Document, diagnosticIds).ConfigureAwait(false) &&
(skipClosedFileChecks || ShouldRunAnalyzerForClosedFile(openedDocument, stateSet.Analyzer)))
{
var data = await _executor.GetDocumentAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsUpdated(StateType.Document, document.Id, stateSet, new SolutionArgument(document), data.Items);
continue;
}
if (openedDocument)
{
_memberRangeMap.Touch(stateSet.Analyzer, document, versions.TextVersion);
}
var state = stateSet.GetState(StateType.Document);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
{
await AnalyzeProjectAsync(project, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeProjectAsync(Project project, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken)
{
try
{
if (!skipClosedFileChecks && !CheckOption(project.Solution.Workspace, project.Language, documentOpened: project.Documents.Any(d => d.IsOpen())))
{
return;
}
var projectTextVersion = await project.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false);
var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
var analyzerDriver = new DiagnosticAnalyzerDriver(project, this, cancellationToken);
var versions = new VersionArgument(projectTextVersion, semanticVersion, projectVersion);
foreach (var stateSet in _stateManger.GetOrUpdateStateSets(project))
{
if (analyzerDriver.IsAnalyzerSuppressed(stateSet.Analyzer))
{
await HandleSuppressedAnalyzerAsync(project, stateSet, cancellationToken).ConfigureAwait(false);
}
else if (await ShouldRunAnalyzerForStateTypeAsync(analyzerDriver, stateSet.Analyzer, StateType.Project, diagnosticIds).ConfigureAwait(false) &&
(skipClosedFileChecks || ShouldRunAnalyzerForClosedFile(openedDocument: false, analyzer: stateSet.Analyzer)))
{
var data = await _executor.GetProjectAnalysisDataAsync(analyzerDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseProjectDiagnosticsUpdated(project, stateSet, data.Items);
continue;
}
var state = stateSet.GetState(StateType.Project);
await PersistProjectData(project, state, data).ConfigureAwait(false);
RaiseProjectDiagnosticsUpdatedIfNeeded(project, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private static async Task PersistProjectData(Project project, DiagnosticState state, AnalysisData data)
{
// TODO: Cancellation is not allowed here to prevent data inconsistency. But there is still a possibility of data inconsistency due to
// things like exception. For now, I am letting it go and let v2 engine take care of it properly. If v2 doesnt come online soon enough
// more refactoring is required on project state.
// clear all existing data
state.Remove(project.Id);
foreach (var document in project.Documents)
{
state.Remove(document.Id);
}
// quick bail out
if (data.Items.Length == 0)
{
return;
}
// save new data
var group = data.Items.GroupBy(d => d.DocumentId);
foreach (var kv in group)
{
if (kv.Key == null)
{
// save project scope diagnostics
await state.PersistAsync(project, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false);
continue;
}
// save document scope diagnostics
var document = project.GetDocument(kv.Key);
if (document == null)
{
continue;
}
await state.PersistAsync(document, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false);
}
}
public override void RemoveDocument(DocumentId documentId)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None))
{
_memberRangeMap.Remove(documentId);
foreach (var stateSet in _stateManger.GetStateSets(documentId.ProjectId))
{
stateSet.Remove(documentId);
var solutionArgs = new SolutionArgument(null, documentId.ProjectId, documentId);
for (var stateType = 0; stateType < s_stateTypeCount; stateType++)
{
RaiseDiagnosticsUpdated((StateType)stateType, documentId, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
}
}
}
}
public override void RemoveProject(ProjectId projectId)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None))
{
foreach (var stateSet in _stateManger.GetStateSets(projectId))
{
stateSet.Remove(projectId);
var solutionArgs = new SolutionArgument(null, projectId, null);
RaiseDiagnosticsUpdated(StateType.Project, projectId, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
}
}
_stateManger.RemoveStateSet(projectId);
}
public override async Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> diagnostics, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: false, diagnostics: diagnostics, cancellationToken: cancellationToken);
return await getter.TryGetAsync().ConfigureAwait(false);
}
public override async Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: true, cancellationToken: cancellationToken);
var result = await getter.TryGetAsync().ConfigureAwait(false);
Contract.Requires(result);
return getter.Diagnostics;
}
private bool ShouldRunAnalyzerForClosedFile(bool openedDocument, DiagnosticAnalyzer analyzer)
{
// we have opened document, doesnt matter
if (openedDocument)
{
return true;
}
return Owner.GetDiagnosticDescriptors(analyzer).Any(d => d.DefaultSeverity != DiagnosticSeverity.Hidden);
}
private async Task<bool> ShouldRunAnalyzerForStateTypeAsync(DiagnosticAnalyzerDriver driver, DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds)
{
return await ShouldRunAnalyzerForStateTypeAsync(driver, analyzer, stateTypeId, diagnosticIds, Owner.GetDiagnosticDescriptors).ConfigureAwait(false);
}
private static async Task<bool> ShouldRunAnalyzerForStateTypeAsync(DiagnosticAnalyzerDriver driver, DiagnosticAnalyzer analyzer, StateType stateTypeId,
ImmutableHashSet<string> diagnosticIds = null, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getDescriptors = null)
{
Debug.Assert(!driver.IsAnalyzerSuppressed(analyzer));
if (diagnosticIds != null && getDescriptors(analyzer).All(d => !diagnosticIds.Contains(d.Id)))
{
return false;
}
switch (stateTypeId)
{
case StateType.Syntax:
return await analyzer.SupportsSyntaxDiagnosticAnalysisAsync(driver).ConfigureAwait(false);
case StateType.Document:
return await analyzer.SupportsSemanticDiagnosticAnalysisAsync(driver).ConfigureAwait(false);
case StateType.Project:
return await analyzer.SupportsProjectDiagnosticAnalysisAsync(driver).ConfigureAwait(false);
default:
throw ExceptionUtilities.Unreachable;
}
}
// internal for testing purposes only.
internal void ForceAnalyzeAllDocuments(Project project, DiagnosticAnalyzer analyzer, CancellationToken cancellationToken)
{
var diagnosticIds = Owner.GetDiagnosticDescriptors(analyzer).Select(d => d.Id).ToImmutableHashSet();
ReanalyzeAllDocumentsAsync(project, diagnosticIds, cancellationToken).Wait(cancellationToken);
}
public override void LogAnalyzerCountSummary()
{
DiagnosticAnalyzerLogger.LogAnalyzerCrashCountSummary(_correlationId, DiagnosticLogAggregator);
DiagnosticAnalyzerLogger.LogAnalyzerTypeCountSummary(_correlationId, DiagnosticLogAggregator);
// reset the log aggregator
ResetDiagnosticLogAggregator();
}
private static bool CheckSyntaxVersions(Document document, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) &&
document.CanReusePersistedSyntaxTreeVersion(versions.DataVersion, existingData.DataVersion);
}
private static bool CheckSemanticVersions(Document document, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) &&
document.Project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion);
}
private static bool CheckSemanticVersions(Project project, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return VersionStamp.CanReusePersistedVersion(versions.TextVersion, existingData.TextVersion) &&
project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion);
}
private void RaiseDocumentDiagnosticsUpdatedIfNeeded(
StateType type, Document document, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
var noItems = existingItems.Length == 0 && newItems.Length == 0;
if (noItems)
{
return;
}
RaiseDiagnosticsUpdated(type, document.Id, stateSet, new SolutionArgument(document), newItems);
}
private void RaiseProjectDiagnosticsUpdatedIfNeeded(
Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
var noItems = existingItems.Length == 0 && newItems.Length == 0;
if (noItems)
{
return;
}
RaiseProjectDiagnosticsRemovedIfNeeded(project, stateSet, existingItems, newItems);
RaiseProjectDiagnosticsUpdated(project, stateSet, newItems);
}
private void RaiseProjectDiagnosticsRemovedIfNeeded(
Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
if (existingItems.Length == 0)
{
return;
}
var removedItems = existingItems.GroupBy(d => d.DocumentId).Select(g => g.Key).Except(newItems.GroupBy(d => d.DocumentId).Select(g => g.Key));
foreach (var documentId in removedItems)
{
if (documentId == null)
{
RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), ImmutableArray<DiagnosticData>.Empty);
continue;
}
var document = project.GetDocument(documentId);
var argument = documentId == null ? new SolutionArgument(null, documentId.ProjectId, documentId) : new SolutionArgument(document);
RaiseDiagnosticsUpdated(StateType.Project, documentId, stateSet, argument, ImmutableArray<DiagnosticData>.Empty);
}
}
private void RaiseProjectDiagnosticsUpdated(Project project, StateSet stateSet, ImmutableArray<DiagnosticData> diagnostics)
{
var group = diagnostics.GroupBy(d => d.DocumentId);
foreach (var kv in group)
{
if (kv.Key == null)
{
RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), kv.ToImmutableArrayOrEmpty());
continue;
}
RaiseDiagnosticsUpdated(StateType.Project, kv.Key, stateSet, new SolutionArgument(project.GetDocument(kv.Key)), kv.ToImmutableArrayOrEmpty());
}
}
private static ImmutableArray<DiagnosticData> GetDiagnosticData(ILookup<DocumentId, DiagnosticData> lookup, DocumentId documentId)
{
return lookup.Contains(documentId) ? lookup[documentId].ToImmutableArrayOrEmpty() : ImmutableArray<DiagnosticData>.Empty;
}
private void RaiseDiagnosticsUpdated(
StateType type, object key, StateSet stateSet, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics)
{
if (Owner == null)
{
return;
}
// get right arg id for the given analyzer
var id = stateSet.ErrorSourceName != null ?
(object)new HostAnalyzerKey(stateSet.Analyzer, type, key, stateSet.ErrorSourceName) : (object)new ArgumentKey(stateSet.Analyzer, type, key);
Owner.RaiseDiagnosticsUpdated(this,
new DiagnosticsUpdatedArgs(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId, diagnostics));
}
private ImmutableArray<DiagnosticData> UpdateDocumentDiagnostics(
AnalysisData existingData, ImmutableArray<TextSpan> range, ImmutableArray<DiagnosticData> memberDiagnostics,
SyntaxTree tree, SyntaxNode member, int memberId)
{
// get old span
var oldSpan = range[memberId];
// get old diagnostics
var diagnostics = existingData.Items;
// check quick exit cases
if (diagnostics.Length == 0 && memberDiagnostics.Length == 0)
{
return diagnostics;
}
// simple case
if (diagnostics.Length == 0 && memberDiagnostics.Length > 0)
{
return memberDiagnostics;
}
// regular case
var result = new List<DiagnosticData>();
// update member location
Contract.Requires(member.FullSpan.Start == oldSpan.Start);
var delta = member.FullSpan.End - oldSpan.End;
var replaced = false;
foreach (var diagnostic in diagnostics)
{
if (diagnostic.TextSpan.Start < oldSpan.Start)
{
result.Add(diagnostic);
continue;
}
if (!replaced)
{
result.AddRange(memberDiagnostics);
replaced = true;
}
if (oldSpan.End <= diagnostic.TextSpan.Start)
{
result.Add(UpdatePosition(diagnostic, tree, delta));
continue;
}
}
// if it haven't replaced, replace it now
if (!replaced)
{
result.AddRange(memberDiagnostics);
replaced = true;
}
return result.ToImmutableArray();
}
private DiagnosticData UpdatePosition(DiagnosticData diagnostic, SyntaxTree tree, int delta)
{
var start = Math.Min(Math.Max(diagnostic.TextSpan.Start + delta, 0), tree.Length);
var newSpan = new TextSpan(start, start >= tree.Length ? 0 : diagnostic.TextSpan.Length);
var mappedLineInfo = tree.GetMappedLineSpan(newSpan);
var originalLineInfo = tree.GetLineSpan(newSpan);
return new DiagnosticData(
diagnostic.Id,
diagnostic.Category,
diagnostic.Message,
diagnostic.ENUMessageForBingSearch,
diagnostic.Severity,
diagnostic.DefaultSeverity,
diagnostic.IsEnabledByDefault,
diagnostic.WarningLevel,
diagnostic.CustomTags,
diagnostic.Properties,
diagnostic.Workspace,
diagnostic.ProjectId,
diagnostic.DocumentId,
newSpan,
mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(),
mappedStartLine: mappedLineInfo.StartLinePosition.Line,
mappedStartColumn: mappedLineInfo.StartLinePosition.Character,
mappedEndLine: mappedLineInfo.EndLinePosition.Line,
mappedEndColumn: mappedLineInfo.EndLinePosition.Character,
originalFilePath: originalLineInfo.Path,
originalStartLine: originalLineInfo.StartLinePosition.Line,
originalStartColumn: originalLineInfo.StartLinePosition.Character,
originalEndLine: originalLineInfo.EndLinePosition.Line,
originalEndColumn: originalLineInfo.EndLinePosition.Character,
description: diagnostic.Description,
helpLink: diagnostic.HelpLink);
}
private static IEnumerable<DiagnosticData> GetDiagnosticData(Document document, SyntaxTree tree, TextSpan? span, IEnumerable<Diagnostic> diagnostics)
{
return diagnostics != null ? diagnostics.Where(dx => ShouldIncludeDiagnostic(dx, tree, span)).Select(d => DiagnosticData.Create(document, d)) : null;
}
private static bool ShouldIncludeDiagnostic(Diagnostic diagnostic, SyntaxTree tree, TextSpan? span)
{
if (diagnostic == null)
{
return false;
}
if (diagnostic.Location == null || diagnostic.Location == Location.None)
{
return false;
}
if (diagnostic.Location.SourceTree != tree)
{
return false;
}
if (span == null)
{
return true;
}
return span.Value.Contains(diagnostic.Location.SourceSpan);
}
private static IEnumerable<DiagnosticData> GetDiagnosticData(Project project, IEnumerable<Diagnostic> diagnostics)
{
if (diagnostics == null)
{
yield break;
}
foreach (var diagnostic in diagnostics)
{
if (diagnostic.Location == null || diagnostic.Location == Location.None)
{
yield return DiagnosticData.Create(project, diagnostic);
continue;
}
var document = project.GetDocument(diagnostic.Location.SourceTree);
if (document == null)
{
continue;
}
yield return DiagnosticData.Create(document, diagnostic);
}
}
private static async Task<IEnumerable<DiagnosticData>> GetSyntaxDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
{
using (Logger.LogBlock(FunctionId.Diagnostics_SyntaxDiagnostic, GetSyntaxLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false);
var diagnostics = await userDiagnosticDriver.GetSyntaxDiagnosticsAsync(analyzer).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private static async Task<IEnumerable<DiagnosticData>> GetSemanticDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
{
using (Logger.LogBlock(FunctionId.Diagnostics_SemanticDiagnostic, GetSemanticLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false);
var diagnostics = await userDiagnosticDriver.GetSemanticDiagnosticsAsync(analyzer).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private static async Task<IEnumerable<DiagnosticData>> GetProjectDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer, Action<Project, DiagnosticAnalyzer, CancellationToken> forceAnalyzeAllDocuments)
{
using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, userDiagnosticDriver.Project, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var diagnostics = await userDiagnosticDriver.GetProjectDiagnosticsAsync(analyzer, forceAnalyzeAllDocuments).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Project, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private void ClearDocumentStates(Document document, IEnumerable<StateSet> states, bool raiseEvent, CancellationToken cancellationToken)
{
// Compiler + User diagnostics
foreach (var state in states)
{
for (var stateType = 0; stateType < s_stateTypeCount; stateType++)
{
cancellationToken.ThrowIfCancellationRequested();
ClearDocumentState(document, state, (StateType)stateType, raiseEvent);
}
}
}
private void ClearDocumentState(Document document, StateSet stateSet, StateType type, bool raiseEvent)
{
var state = stateSet.GetState(type);
// remove saved info
state.Remove(document.Id);
if (raiseEvent)
{
// raise diagnostic updated event
var documentId = document.Id;
var solutionArgs = new SolutionArgument(document);
RaiseDiagnosticsUpdated(type, document.Id, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
}
}
private void ClearProjectStatesAsync(Project project, IEnumerable<StateSet> states, CancellationToken cancellationToken)
{
foreach (var document in project.Documents)
{
ClearDocumentStates(document, states, raiseEvent: true, cancellationToken: cancellationToken);
}
foreach (var stateSet in states)
{
cancellationToken.ThrowIfCancellationRequested();
ClearProjectState(project, stateSet);
}
}
private void ClearProjectState(Project project, StateSet stateSet)
{
var state = stateSet.GetState(StateType.Project);
// remove saved cache
state.Remove(project.Id);
// raise diagnostic updated event
var solutionArgs = new SolutionArgument(project);
RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty);
}
private async Task HandleSuppressedAnalyzerAsync(Document document, StateSet stateSet, StateType type, CancellationToken cancellationToken)
{
var state = stateSet.GetState(type);
var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
if (existingData?.Items.Length > 0)
{
ClearDocumentState(document, stateSet, type, raiseEvent: true);
}
}
private async Task HandleSuppressedAnalyzerAsync(Project project, StateSet stateSet, CancellationToken cancellationToken)
{
var state = stateSet.GetState(StateType.Project);
var existingData = await state.TryGetExistingDataAsync(project, cancellationToken).ConfigureAwait(false);
if (existingData?.Items.Length > 0)
{
ClearProjectState(project, stateSet);
}
}
private static string GetSyntaxLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer)
{
return string.Format("syntax: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString());
}
private static string GetSemanticLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer)
{
return string.Format("semantic: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString());
}
private static string GetProjectLogMessage(Project project, DiagnosticAnalyzer analyzer)
{
return string.Format("project: {0}, {1}", project.FilePath ?? project.Name, analyzer.ToString());
}
private static string GetResetLogMessage(Document document)
{
return string.Format("document reset: {0}", document.FilePath ?? document.Name);
}
private static string GetOpenLogMessage(Document document)
{
return string.Format("document open: {0}", document.FilePath ?? document.Name);
}
private static string GetRemoveLogMessage(DocumentId id)
{
return string.Format("document remove: {0}", id.ToString());
}
private static string GetRemoveLogMessage(ProjectId id)
{
return string.Format("project remove: {0}", id.ToString());
}
#region unused
public override Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Messages;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs
{
/// <summary>
/// Packets for SmbWriteRaw Request
/// </summary>
public class SmbWriteRawRequestPacket : SmbSingleRequestPacket
{
#region Fields
private SMB_COM_WRITE_RAW_Request_SMB_Parameters smbParameters;
private SMB_COM_WRITE_RAW_Request_SMB_Data smbData;
#endregion
#region Properties
/// <summary>
/// get or set the Smb_Parameters:SMB_COM_WRITE_RAW_Request_SMB_Parameters
/// </summary>
public SMB_COM_WRITE_RAW_Request_SMB_Parameters SmbParameters
{
get
{
return this.smbParameters;
}
set
{
this.smbParameters = value;
}
}
/// <summary>
/// get or set the Smb_Data:SMB_COM_WRITE_RAW_Request_SMB_Data
/// </summary>
public SMB_COM_WRITE_RAW_Request_SMB_Data SmbData
{
get
{
return this.smbData;
}
set
{
this.smbData = value;
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public SmbWriteRawRequestPacket()
: base()
{
this.InitDefaultValue();
}
/// <summary>
/// Constructor: Create a request directly from a buffer.
/// </summary>
public SmbWriteRawRequestPacket(byte[] data)
: base(data)
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
public SmbWriteRawRequestPacket(SmbWriteRawRequestPacket packet)
: base(packet)
{
this.InitDefaultValue();
this.smbParameters.WordCount = packet.SmbParameters.WordCount;
this.smbParameters.FID = packet.SmbParameters.FID;
this.smbParameters.CountOfBytes = packet.SmbParameters.CountOfBytes;
this.smbParameters.Reserved1 = packet.SmbParameters.Reserved1;
this.smbParameters.Offset = packet.SmbParameters.Offset;
this.smbParameters.Timeout = packet.SmbParameters.Timeout;
this.smbParameters.WriteMode = packet.SmbParameters.WriteMode;
this.smbParameters.Reserved2 = packet.SmbParameters.Reserved2;
this.smbParameters.DataLength = packet.SmbParameters.DataLength;
this.smbParameters.DataOffset = packet.SmbParameters.DataOffset;
this.smbParameters.OffsetHigh = packet.SmbParameters.OffsetHigh;
this.smbData.ByteCount = packet.SmbData.ByteCount;
if (packet.smbData.Pad != null)
{
this.smbData.Pad = new byte[packet.smbData.Pad.Length];
Array.Copy(packet.smbData.Pad, this.smbData.Pad, packet.smbData.Pad.Length);
}
else
{
this.smbData.Pad = new byte[0];
}
if (packet.smbData.Data != null)
{
this.smbData.Data = new byte[packet.smbData.Data.Length];
Array.Copy(packet.smbData.Data, this.smbData.Data, packet.smbData.Data.Length);
}
else
{
this.smbData.Data = new byte[0];
}
}
#endregion
#region override methods
/// <summary>
/// to create an instance of the StackPacket class that is identical to the current StackPacket.
/// </summary>
/// <returns>a new Packet cloned from this.</returns>
public override StackPacket Clone()
{
return new SmbWriteRawRequestPacket(this);
}
/// <summary>
/// Encode the struct of SMB_COM_WRITE_RAW_Request_SMB_Parameters into the struct of SmbParameters
/// </summary>
protected override void EncodeParameters()
{
this.smbParametersBlock = CifsMessageUtils.ToStuct<SmbParameters>(
CifsMessageUtils.ToBytes<SMB_COM_WRITE_RAW_Request_SMB_Parameters>(this.smbParameters));
}
/// <summary>
/// Encode the struct of SMB_COM_WRITE_RAW_Request_SMB_Data into the struct of SmbData
/// </summary>
protected override void EncodeData()
{
this.smbDataBlock.ByteCount = this.SmbData.ByteCount;
this.smbDataBlock.Bytes = new byte[this.smbDataBlock.ByteCount];
using (MemoryStream memoryStream = new MemoryStream(this.smbDataBlock.Bytes))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
if (this.smbData.Pad != null)
{
channel.WriteBytes(this.smbData.Pad);
}
if (this.smbData.Data != null)
{
channel.WriteBytes(this.smbData.Data);
}
channel.EndWriteGroup();
}
}
}
/// <summary>
/// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters.
/// </summary>
protected override void DecodeParameters()
{
this.smbParameters = TypeMarshal.ToStruct<SMB_COM_WRITE_RAW_Request_SMB_Parameters>(
TypeMarshal.ToBytes(this.smbParametersBlock));
}
/// <summary>
/// to decode the smb data: from the general SmbDada to the concrete Smb Data.
/// </summary>
protected override void DecodeData()
{
using (MemoryStream memoryStream = new MemoryStream(CifsMessageUtils.ToBytes<SmbData>(this.smbDataBlock)))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.smbData.ByteCount = channel.Read<ushort>();
// pad:
if ((Marshal.SizeOf(this.SmbHeader) + Marshal.SizeOf(this.SmbParameters)
+ Marshal.SizeOf(this.smbData.ByteCount)) % 2 != 0)
{
this.smbData.Pad = channel.ReadBytes(1);
}
else
{
this.smbData.Pad = new byte[0];
}
this.smbData.Data = channel.ReadBytes(this.smbData.ByteCount - this.smbData.Pad.Length);
}
}
}
#endregion
#region initialize fields with default value
/// <summary>
/// init packet, set default field data
/// </summary>
private void InitDefaultValue()
{
this.smbData.Pad = new byte[0];
this.smbData.Data = new byte[0];
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.