context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Runtime.ExceptionServices; using System.Runtime.Serialization; using System.Security; using System.Text; using System.Threading; namespace System { /// <summary>Represents one or more errors that occur during application execution.</summary> /// <remarks> /// <see cref="AggregateException"/> is used to consolidate multiple failures into a single, throwable /// exception object. /// </remarks> [Serializable] [DebuggerDisplay("Count = {InnerExceptionCount}")] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class AggregateException : Exception { private ReadOnlyCollection<Exception> m_innerExceptions; // Complete set of exceptions. Do not rename (binary serialization) /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class. /// </summary> public AggregateException() : base(SR.AggregateException_ctor_DefaultMessage) { m_innerExceptions = new ReadOnlyCollection<Exception>(Array.Empty<Exception>()); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// a specified error message. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> public AggregateException(string message) : base(message) { m_innerExceptions = new ReadOnlyCollection<Exception>(Array.Empty<Exception>()); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerException"/> argument /// is null.</exception> public AggregateException(string message, Exception innerException) : base(message, innerException) { if (innerException == null) { throw new ArgumentNullException(nameof(innerException)); } m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[] { innerException }); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(IEnumerable<Exception> innerExceptions) : this(SR.AggregateException_ctor_DefaultMessage, innerExceptions) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(params Exception[] innerExceptions) : this(SR.AggregateException_ctor_DefaultMessage, innerExceptions) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(string message, IEnumerable<Exception> innerExceptions) // If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along // null typed correctly. Otherwise, create an IList from the enumerable and pass that along. : this(message, innerExceptions as IList<Exception> ?? (innerExceptions == null ? (List<Exception>)null : new List<Exception>(innerExceptions))) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and references to the inner exceptions that are the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> public AggregateException(string message, params Exception[] innerExceptions) : this(message, (IList<Exception>)innerExceptions) { } /// <summary> /// Allocates a new aggregate exception with the specified message and list of inner exceptions. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptions">The exceptions that are the cause of the current exception.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptions"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is /// null.</exception> private AggregateException(string message, IList<Exception> innerExceptions) : base(message, innerExceptions != null && innerExceptions.Count > 0 ? innerExceptions[0] : null) { if (innerExceptions == null) { throw new ArgumentNullException(nameof(innerExceptions)); } // Copy exceptions to our internal array and validate them. We must copy them, // because we're going to put them into a ReadOnlyCollection which simply reuses // the list passed in to it. We don't want callers subsequently mutating. Exception[] exceptionsCopy = new Exception[innerExceptions.Count]; for (int i = 0; i < exceptionsCopy.Length; i++) { exceptionsCopy[i] = innerExceptions[i]; if (exceptionsCopy[i] == null) { throw new ArgumentException(SR.AggregateException_ctor_InnerExceptionNull); } } m_innerExceptions = new ReadOnlyCollection<Exception>(exceptionsCopy); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with /// references to the inner exception dispatch info objects that represent the cause of this exception. /// </summary> /// <param name="innerExceptionInfos"> /// Information about the exceptions that are the cause of the current exception. /// </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is /// null.</exception> internal AggregateException(IEnumerable<ExceptionDispatchInfo> innerExceptionInfos) : this(SR.AggregateException_ctor_DefaultMessage, innerExceptionInfos) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with a specified error /// message and references to the inner exception dispatch info objects that represent the cause of /// this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptionInfos"> /// Information about the exceptions that are the cause of the current exception. /// </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is /// null.</exception> internal AggregateException(string message, IEnumerable<ExceptionDispatchInfo> innerExceptionInfos) // If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along // null typed correctly. Otherwise, create an IList from the enumerable and pass that along. : this(message, innerExceptionInfos as IList<ExceptionDispatchInfo> ?? (innerExceptionInfos == null ? (List<ExceptionDispatchInfo>)null : new List<ExceptionDispatchInfo>(innerExceptionInfos))) { } /// <summary> /// Allocates a new aggregate exception with the specified message and list of inner /// exception dispatch info objects. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerExceptionInfos"> /// Information about the exceptions that are the cause of the current exception. /// </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="innerExceptionInfos"/> argument /// is null.</exception> /// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is /// null.</exception> private AggregateException(string message, IList<ExceptionDispatchInfo> innerExceptionInfos) : base(message, innerExceptionInfos != null && innerExceptionInfos.Count > 0 && innerExceptionInfos[0] != null ? innerExceptionInfos[0].SourceException : null) { if (innerExceptionInfos == null) { throw new ArgumentNullException(nameof(innerExceptionInfos)); } // Copy exceptions to our internal array and validate them. We must copy them, // because we're going to put them into a ReadOnlyCollection which simply reuses // the list passed in to it. We don't want callers subsequently mutating. Exception[] exceptionsCopy = new Exception[innerExceptionInfos.Count]; for (int i = 0; i < exceptionsCopy.Length; i++) { var edi = innerExceptionInfos[i]; if (edi != null) exceptionsCopy[i] = edi.SourceException; if (exceptionsCopy[i] == null) { throw new ArgumentException(SR.AggregateException_ctor_InnerExceptionNull); } } m_innerExceptions = new ReadOnlyCollection<Exception>(exceptionsCopy); } /// <summary> /// Initializes a new instance of the <see cref="AggregateException"/> class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds /// the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that /// contains contextual information about the source or destination. </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The exception could not be deserialized correctly.</exception> protected AggregateException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } Exception[] innerExceptions = info.GetValue("InnerExceptions", typeof(Exception[])) as Exception[]; if (innerExceptions == null) { throw new SerializationException(SR.AggregateException_DeserializationFailure); } m_innerExceptions = new ReadOnlyCollection<Exception>(innerExceptions); } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with information about /// the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds /// the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that /// contains contextual information about the source or destination. </param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception> public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); Exception[] innerExceptions = new Exception[m_innerExceptions.Count]; m_innerExceptions.CopyTo(innerExceptions, 0); info.AddValue("InnerExceptions", innerExceptions, typeof(Exception[])); } /// <summary> /// Returns the <see cref="System.AggregateException"/> that is the root cause of this exception. /// </summary> public override Exception GetBaseException() { // Returns the first inner AggregateException that contains more or less than one inner exception // Recursively traverse the inner exceptions as long as the inner exception of type AggregateException and has only one inner exception Exception back = this; AggregateException backAsAggregate = this; while (backAsAggregate != null && backAsAggregate.InnerExceptions.Count == 1) { back = back.InnerException; backAsAggregate = back as AggregateException; } return back; } /// <summary> /// Gets a read-only collection of the <see cref="T:System.Exception"/> instances that caused the /// current exception. /// </summary> public ReadOnlyCollection<Exception> InnerExceptions { get { return m_innerExceptions; } } /// <summary> /// Invokes a handler on each <see cref="T:System.Exception"/> contained by this <see /// cref="AggregateException"/>. /// </summary> /// <param name="predicate">The predicate to execute for each exception. The predicate accepts as an /// argument the <see cref="T:System.Exception"/> to be processed and returns a Boolean to indicate /// whether the exception was handled.</param> /// <remarks> /// Each invocation of the <paramref name="predicate"/> returns true or false to indicate whether the /// <see cref="T:System.Exception"/> was handled. After all invocations, if any exceptions went /// unhandled, all unhandled exceptions will be put into a new <see cref="AggregateException"/> /// which will be thrown. Otherwise, the <see cref="Handle"/> method simply returns. If any /// invocations of the <paramref name="predicate"/> throws an exception, it will halt the processing /// of any more exceptions and immediately propagate the thrown exception as-is. /// </remarks> /// <exception cref="AggregateException">An exception contained by this <see /// cref="AggregateException"/> was not handled.</exception> /// <exception cref="T:System.ArgumentNullException">The <paramref name="predicate"/> argument is /// null.</exception> public void Handle(Func<Exception, bool> predicate) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } List<Exception> unhandledExceptions = null; for (int i = 0; i < m_innerExceptions.Count; i++) { // If the exception was not handled, lazily allocate a list of unhandled // exceptions (to be rethrown later) and add it. if (!predicate(m_innerExceptions[i])) { if (unhandledExceptions == null) { unhandledExceptions = new List<Exception>(); } unhandledExceptions.Add(m_innerExceptions[i]); } } // If there are unhandled exceptions remaining, throw them. if (unhandledExceptions != null) { throw new AggregateException(Message, unhandledExceptions); } } /// <summary> /// Flattens the inner instances of <see cref="AggregateException"/> by expanding its contained <see cref="Exception"/> instances /// into a new <see cref="AggregateException"/> /// </summary> /// <returns>A new, flattened <see cref="AggregateException"/>.</returns> /// <remarks> /// If any inner exceptions are themselves instances of /// <see cref="AggregateException"/>, this method will recursively flatten all of them. The /// inner exceptions returned in the new <see cref="AggregateException"/> /// will be the union of all of the inner exceptions from exception tree rooted at the provided /// <see cref="AggregateException"/> instance. /// </remarks> public AggregateException Flatten() { // Initialize a collection to contain the flattened exceptions. List<Exception> flattenedExceptions = new List<Exception>(); // Create a list to remember all aggregates to be flattened, this will be accessed like a FIFO queue List<AggregateException> exceptionsToFlatten = new List<AggregateException>(); exceptionsToFlatten.Add(this); int nDequeueIndex = 0; // Continue removing and recursively flattening exceptions, until there are no more. while (exceptionsToFlatten.Count > nDequeueIndex) { // dequeue one from exceptionsToFlatten IList<Exception> currentInnerExceptions = exceptionsToFlatten[nDequeueIndex++].InnerExceptions; for (int i = 0; i < currentInnerExceptions.Count; i++) { Exception currentInnerException = currentInnerExceptions[i]; if (currentInnerException == null) { continue; } AggregateException currentInnerAsAggregate = currentInnerException as AggregateException; // If this exception is an aggregate, keep it around for later. Otherwise, // simply add it to the list of flattened exceptions to be returned. if (currentInnerAsAggregate != null) { exceptionsToFlatten.Add(currentInnerAsAggregate); } else { flattenedExceptions.Add(currentInnerException); } } } return new AggregateException(Message, flattenedExceptions); } /// <summary>Gets a message that describes the exception.</summary> public override string Message { get { if (m_innerExceptions.Count == 0) { return base.Message; } StringBuilder sb = StringBuilderCache.Acquire(); sb.Append(base.Message); sb.Append(' '); for (int i = 0; i < m_innerExceptions.Count; i++) { sb.Append('('); sb.Append(m_innerExceptions[i].Message); sb.Append(") "); } sb.Length -= 1; return StringBuilderCache.GetStringAndRelease(sb); } } /// <summary> /// Creates and returns a string representation of the current <see cref="AggregateException"/>. /// </summary> /// <returns>A string representation of the current exception.</returns> public override string ToString() { StringBuilder text = new StringBuilder(); text.Append(base.ToString()); for (int i = 0; i < m_innerExceptions.Count; i++) { text.AppendLine(); text.Append("---> "); text.AppendFormat(CultureInfo.InvariantCulture, SR.AggregateException_InnerException, i); text.Append(m_innerExceptions[i].ToString()); text.Append("<---"); text.AppendLine(); } return text.ToString(); } /// <summary> /// This helper property is used by the DebuggerDisplay. /// /// Note that we don't want to remove this property and change the debugger display to {InnerExceptions.Count} /// because DebuggerDisplay should be a single property access or parameterless method call, so that the debugger /// can use a fast path without using the expression evaluator. /// /// See https://docs.microsoft.com/en-us/visualstudio/debugger/using-the-debuggerdisplay-attribute /// </summary> private int InnerExceptionCount { get { return InnerExceptions.Count; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using QuantConnect.Data; namespace QuantConnect.Securities { /// <summary> /// Provides a means of keeping track of the different cash holdings of an algorithm /// </summary> public class CashBook : IDictionary<string, Cash> { /// <summary> /// Gets the base currency used /// </summary> public const string AccountCurrency = "USD"; private readonly Dictionary<string, Cash> _currencies; /// <summary> /// Gets the total value of the cash book in units of the base currency /// </summary> public decimal TotalValueInAccountCurrency { get { return _currencies.Values.Sum(x => x.ValueInAccountCurrency); } } /// <summary> /// Initializes a new instance of the <see cref="CashBook"/> class. /// </summary> public CashBook() { _currencies = new Dictionary<string, Cash>(); _currencies.Add(AccountCurrency, new Cash(AccountCurrency, 0, 1.0m)); } /// <summary> /// Adds a new cash of the specified symbol and quantity /// </summary> /// <param name="symbol">The symbol used to reference the new cash</param> /// <param name="quantity">The amount of new cash to start</param> /// <param name="conversionRate">The conversion rate used to determine the initial /// portfolio value/starting capital impact caused by this currency position.</param> public void Add(string symbol, decimal quantity, decimal conversionRate) { var cash = new Cash(symbol, quantity, conversionRate); _currencies.Add(symbol, cash); } /// <summary> /// Checks the current subscriptions and adds necessary currency pair feeds to provide real time conversion data /// </summary> /// <param name="securities">The SecurityManager for the algorithm</param> /// <param name="subscriptions">The SubscriptionManager for the algorithm</param> /// <param name="marketHoursDatabase">A security exchange hours provider instance used to resolve exchange hours for new subscriptions</param> /// <returns>Returns a list of added currency securities</returns> public List<Security> EnsureCurrencyDataFeeds(SecurityManager securities, SubscriptionManager subscriptions, MarketHoursDatabase marketHoursDatabase) { var addedSecurities = new List<Security>(); foreach (var cash in _currencies.Values) { var security = cash.EnsureCurrencyDataFeed(securities, subscriptions, marketHoursDatabase); if (security != null) { addedSecurities.Add(security); } } return addedSecurities; } /// <summary> /// Converts a quantity of source currency units into the specified destination currency /// </summary> /// <param name="sourceQuantity">The quantity of source currency to be converted</param> /// <param name="sourceCurrency">The source currency symbol</param> /// <param name="destinationCurrency">The destination currency symbol</param> /// <returns>The converted value</returns> public decimal Convert(decimal sourceQuantity, string sourceCurrency, string destinationCurrency) { var source = this[sourceCurrency]; var destination = this[destinationCurrency]; var conversionRate = source.ConversionRate*destination.ConversionRate; return sourceQuantity*conversionRate; } /// <summary> /// Converts a quantity of source currency units into the account currency /// </summary> /// <param name="sourceQuantity">The quantity of source currency to be converted</param> /// <param name="sourceCurrency">The source currency symbol</param> /// <returns>The converted value</returns> public decimal ConvertToAccountCurrency(decimal sourceQuantity, string sourceCurrency) { return Convert(sourceQuantity, sourceCurrency, AccountCurrency); } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A string that represents the current object. /// </returns> /// <filterpriority>2</filterpriority> public override string ToString() { var sb = new StringBuilder(); sb.AppendLine(string.Format("{0} {1,7} {2,10} = {3}", "Symbol", "Quantity", "Conversion", "Value in " + AccountCurrency)); foreach (var value in Values) { sb.AppendLine(value.ToString()); } sb.AppendLine("-----------------------------------------"); sb.AppendLine(string.Format("CashBook Total Value: {0}", TotalValueInAccountCurrency.ToString("C"))); return sb.ToString(); } #region IDictionary Implementation /// <summary> /// Gets the count of Cash items in this CashBook. /// </summary> /// <value>The count.</value> public int Count { get { return _currencies.Count; } } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value> public bool IsReadOnly { get { return ((IDictionary<string, Cash>) _currencies).IsReadOnly; } } /// <summary> /// Add the specified item to this CashBook. /// </summary> /// <param name="item">KeyValuePair of symbol -> Cash item</param> public void Add(KeyValuePair<string, Cash> item) { _currencies.Add(item.Key, item.Value); } /// <summary> /// Add the specified key and value. /// </summary> /// <param name="symbol">The symbol of the Cash value.</param> /// <param name="value">Value.</param> public void Add(string symbol, Cash value) { _currencies.Add(symbol, value); } /// <summary> /// Clear this instance of all Cash entries. /// </summary> public void Clear() { _currencies.Clear(); } /// <summary> /// Remove the Cash item corresponding to the specified symbol /// </summary> /// <param name="symbol">The symbolto be removed</param> public bool Remove(string symbol) { return _currencies.Remove (symbol); } /// <summary> /// Remove the specified item. /// </summary> /// <param name="item">Item.</param> public bool Remove(KeyValuePair<string, Cash> item) { return _currencies.Remove(item.Key); } /// <summary> /// Determines whether the current instance contains an entry with the specified symbol. /// </summary> /// <returns><c>true</c>, if key was contained, <c>false</c> otherwise.</returns> /// <param name="symbol">Key.</param> public bool ContainsKey(string symbol) { return _currencies.ContainsKey(symbol); } /// <summary> /// Try to get the value. /// </summary> /// <remarks>To be added.</remarks> /// <returns><c>true</c>, if get value was tryed, <c>false</c> otherwise.</returns> /// <param name="symbol">The symbol.</param> /// <param name="value">Value.</param> public bool TryGetValue(string symbol, out Cash value) { return _currencies.TryGetValue(symbol, out value); } /// <summary> /// Determines whether the current collection contains the specified value. /// </summary> /// <param name="item">Item.</param> public bool Contains(KeyValuePair<string, Cash> item) { return _currencies.Contains(item); } /// <summary> /// Copies to the specified array. /// </summary> /// <param name="array">Array.</param> /// <param name="arrayIndex">Array index.</param> public void CopyTo(KeyValuePair<string, Cash>[] array, int arrayIndex) { ((IDictionary<string, Cash>) _currencies).CopyTo(array, arrayIndex); } /// <summary> /// Gets or sets the <see cref="QuantConnect.Securities.Cash"/> with the specified symbol. /// </summary> /// <param name="symbol">Symbol.</param> public Cash this[string symbol] { get { Cash cash; if (!_currencies.TryGetValue(symbol, out cash)) { throw new Exception("This cash symbol (" + symbol + ") was not found in your cash book."); } return cash; } set { _currencies[symbol] = value; } } /// <summary> /// Gets the keys. /// </summary> /// <value>The keys.</value> public ICollection<string> Keys { get { return _currencies.Keys; } } /// <summary> /// Gets the values. /// </summary> /// <value>The values.</value> public ICollection<Cash> Values { get { return _currencies.Values; } } /// <summary> /// Gets the enumerator. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<KeyValuePair<string, Cash>> GetEnumerator() { return _currencies.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable) _currencies).GetEnumerator(); } #endregion } }
using System; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Runtime; namespace Orleans.Internal { public static class OrleansTaskExtentions { internal static readonly Task<object> CanceledTask = TaskFromCanceled<object>(); internal static readonly Task<object> CompletedTask = Task.FromResult(default(object)); /// <summary> /// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task"/>. /// </summary> /// <param name="task">The task.</param> public static Task<object> ToUntypedTask(this Task task) { switch (task.Status) { case TaskStatus.RanToCompletion: return CompletedTask; case TaskStatus.Faulted: return TaskFromFaulted(task); case TaskStatus.Canceled: return CanceledTask; default: return ConvertAsync(task); } async Task<object> ConvertAsync(Task asyncTask) { await asyncTask; return null; } } /// <summary> /// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{T}"/>. /// </summary> /// <typeparam name="T">The underlying type of <paramref name="task"/>.</typeparam> /// <param name="task">The task.</param> public static Task<object> ToUntypedTask<T>(this Task<T> task) { if (typeof(T) == typeof(object)) return task as Task<object>; switch (task.Status) { case TaskStatus.RanToCompletion: return Task.FromResult((object)GetResult(task)); case TaskStatus.Faulted: return TaskFromFaulted(task); case TaskStatus.Canceled: return CanceledTask; default: return ConvertAsync(task); } async Task<object> ConvertAsync(Task<T> asyncTask) { return await asyncTask.ConfigureAwait(false); } } /// <summary> /// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{T}"/>. /// </summary> /// <typeparam name="T">The underlying type of <paramref name="task"/>.</typeparam> /// <param name="task">The task.</param> internal static Task<T> ToTypedTask<T>(this Task<object> task) { if (typeof(T) == typeof(object)) return task as Task<T>; switch (task.Status) { case TaskStatus.RanToCompletion: return Task.FromResult((T)GetResult(task)); case TaskStatus.Faulted: return TaskFromFaulted<T>(task); case TaskStatus.Canceled: return TaskFromCanceled<T>(); default: return ConvertAsync(task); } async Task<T> ConvertAsync(Task<object> asyncTask) { var result = await asyncTask.ConfigureAwait(false); if (result is null) { if (!NullabilityHelper<T>.IsNullableType) { ThrowInvalidTaskResultType(typeof(T)); } return default; } return (T)result; } } private static class NullabilityHelper<T> { /// <summary> /// True if <typeparamref name="T" /> is an instance of a nullable type (a reference type or <see cref="Nullable{T}"/>), otherwise false. /// </summary> public static readonly bool IsNullableType = !typeof(T).IsValueType || typeof(T).IsConstructedGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowInvalidTaskResultType(Type type) { var message = $"Expected result of type {type} but encountered a null value. This may be caused by a grain call filter swallowing an exception."; throw new InvalidOperationException(message); } /// <summary> /// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{Object}"/>. /// </summary> /// <param name="task">The task.</param> public static Task<object> ToUntypedTask(this Task<object> task) { return task; } private static Task<object> TaskFromFaulted(Task task) { var completion = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); completion.SetException(task.Exception.InnerExceptions); return completion.Task; } private static Task<T> TaskFromFaulted<T>(Task task) { var completion = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously); completion.SetException(task.Exception.InnerExceptions); return completion.Task; } private static Task<T> TaskFromCanceled<T>() { var completion = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously); completion.SetCanceled(); return completion.Task; } public static async Task LogException(this Task task, ILogger logger, ErrorCode errorCode, string message) { try { await task; } catch (Exception exc) { var ignored = task.Exception; // Observe exception logger.Error(errorCode, message, exc); throw; } } // Executes an async function such as Exception is never thrown but rather always returned as a broken task. public static async Task SafeExecute(Func<Task> action) { await action(); } public static async Task ExecuteAndIgnoreException(Func<Task> action) { try { await action(); } catch (Exception) { // dont re-throw, just eat it. } } internal static String ToString(this Task t) { return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status)); } internal static String ToString<T>(this Task<T> t) { return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status)); } public static void WaitWithThrow(this Task task, TimeSpan timeout) { if (!task.Wait(timeout)) { throw new TimeoutException($"Task.WaitWithThrow has timed out after {timeout}."); } } internal static T WaitForResultWithThrow<T>(this Task<T> task, TimeSpan timeout) { if (!task.Wait(timeout)) { throw new TimeoutException($"Task<T>.WaitForResultWithThrow has timed out after {timeout}."); } return task.Result; } /// <summary> /// This will apply a timeout delay to the task, allowing us to exit early /// </summary> /// <param name="taskToComplete">The task we will timeout after timeSpan</param> /// <param name="timeout">Amount of time to wait before timing out</param> /// <param name="exceptionMessage">Text to put into the timeout exception message</param> /// <exception cref="TimeoutException">If we time out we will get this exception</exception> /// <returns>The completed task</returns> public static async Task WithTimeout(this Task taskToComplete, TimeSpan timeout, string exceptionMessage = null) { if (taskToComplete.IsCompleted) { await taskToComplete; return; } var timeoutCancellationTokenSource = new CancellationTokenSource(); var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); // We got done before the timeout, or were able to complete before this code ran, return the result if (taskToComplete == completedTask) { timeoutCancellationTokenSource.Cancel(); // Await this so as to propagate the exception correctly await taskToComplete; return; } // We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur taskToComplete.Ignore(); var errorMessage = exceptionMessage ?? $"WithTimeout has timed out after {timeout}"; throw new TimeoutException(errorMessage); } /// <summary> /// This will apply a timeout delay to the task, allowing us to exit early /// </summary> /// <param name="taskToComplete">The task we will timeout after timeSpan</param> /// <param name="timeSpan">Amount of time to wait before timing out</param> /// <param name="exceptionMessage">Text to put into the timeout exception message</param> /// <exception cref="TimeoutException">If we time out we will get this exception</exception> /// <exception cref="TimeoutException">If we time out we will get this exception</exception> /// <returns>The value of the completed task</returns> public static async Task<T> WithTimeout<T>(this Task<T> taskToComplete, TimeSpan timeSpan, string exceptionMessage = null) { if (taskToComplete.IsCompleted) { return await taskToComplete; } var timeoutCancellationTokenSource = new CancellationTokenSource(); var completedTask = await Task.WhenAny(taskToComplete, Task.Delay(timeSpan, timeoutCancellationTokenSource.Token)); // We got done before the timeout, or were able to complete before this code ran, return the result if (taskToComplete == completedTask) { timeoutCancellationTokenSource.Cancel(); // Await this so as to propagate the exception correctly return await taskToComplete; } // We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur taskToComplete.Ignore(); var errorMessage = exceptionMessage ?? $"WithTimeout has timed out after {timeSpan}"; throw new TimeoutException(errorMessage); } /// <summary> /// For making an uncancellable task cancellable, by ignoring its result. /// </summary> /// <param name="taskToComplete">The task to wait for unless cancelled</param> /// <param name="cancellationToken">A cancellation token for cancelling the wait</param> /// <param name="message">Message to set in the exception</param> /// <returns></returns> internal static async Task WithCancellation( this Task taskToComplete, CancellationToken cancellationToken, string message) { try { await taskToComplete.WithCancellation(cancellationToken); } catch (TaskCanceledException ex) { throw new TaskCanceledException(message, ex); } } /// <summary> /// For making an uncancellable task cancellable, by ignoring its result. /// </summary> /// <param name="taskToComplete">The task to wait for unless cancelled</param> /// <param name="cancellationToken">A cancellation token for cancelling the wait</param> /// <returns></returns> internal static Task WithCancellation(this Task taskToComplete, CancellationToken cancellationToken) { if (taskToComplete.IsCompleted || !cancellationToken.CanBeCanceled) { return taskToComplete; } else if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<object>(cancellationToken); } else { return MakeCancellable(taskToComplete, cancellationToken); } } private static async Task MakeCancellable(Task task, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); using (cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken), useSynchronizationContext: false)) { var firstToComplete = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false); if (firstToComplete != task) { task.Ignore(); } await firstToComplete.ConfigureAwait(false); } } /// <summary> /// For making an uncancellable task cancellable, by ignoring its result. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="taskToComplete">The task to wait for unless cancelled</param> /// <param name="cancellationToken">A cancellation token for cancelling the wait</param> /// <param name="message">Message to set in the exception</param> /// <returns></returns> internal static async Task<T> WithCancellation<T>( this Task<T> taskToComplete, CancellationToken cancellationToken, string message) { try { return await taskToComplete.WithCancellation(cancellationToken); } catch (TaskCanceledException ex) { throw new TaskCanceledException(message, ex); } } /// <summary> /// For making an uncancellable task cancellable, by ignoring its result. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="taskToComplete">The task to wait for unless cancelled</param> /// <param name="cancellationToken">A cancellation token for cancelling the wait</param> /// <returns></returns> internal static Task<T> WithCancellation<T>(this Task<T> taskToComplete, CancellationToken cancellationToken) { if (taskToComplete.IsCompleted || !cancellationToken.CanBeCanceled) { return taskToComplete; } else if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<T>(cancellationToken); } else { return MakeCancellable(taskToComplete, cancellationToken); } } private static async Task<T> MakeCancellable<T>(Task<T> task, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously); using (cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken), useSynchronizationContext: false)) { var firstToComplete = await Task.WhenAny(task, tcs.Task).ConfigureAwait(false); if (firstToComplete != task) { task.Ignore(); } return await firstToComplete.ConfigureAwait(false); } } internal static Task WrapInTask(Action action) { try { action(); return Task.CompletedTask; } catch (Exception exc) { return Task.FromException<object>(exc); } } internal static Task<T> ConvertTaskViaTcs<T>(Task<T> task) { if (task == null) return Task.FromResult(default(T)); var resolver = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously); if (task.Status == TaskStatus.RanToCompletion) { resolver.TrySetResult(task.Result); } else if (task.IsFaulted) { resolver.TrySetException(task.Exception.InnerExceptions); } else if (task.IsCanceled) { resolver.TrySetException(new TaskCanceledException(task)); } else { if (task.Status == TaskStatus.Created) task.Start(); task.ContinueWith(t => { if (t.IsFaulted) { resolver.TrySetException(t.Exception.InnerExceptions); } else if (t.IsCanceled) { resolver.TrySetException(new TaskCanceledException(t)); } else { resolver.TrySetResult(t.GetResult()); } }); } return resolver.Task; } //The rationale for GetAwaiter().GetResult() instead of .Result //is presented at https://github.com/aspnet/Security/issues/59. internal static T GetResult<T>(this Task<T> task) { return task.GetAwaiter().GetResult(); } internal static void GetResult(this Task task) { task.GetAwaiter().GetResult(); } internal static Task WhenCancelled(this CancellationToken token) { if (token.IsCancellationRequested) { return Task.CompletedTask; } var waitForCancellation = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); token.Register(obj => { var tcs = (TaskCompletionSource<object>)obj; tcs.TrySetResult(null); }, waitForCancellation); return waitForCancellation.Task; } } } namespace Orleans { /// <summary> /// A special void 'Done' Task that is already in the RunToCompletion state. /// Equivalent to Task.FromResult(1). /// </summary> public static class TaskDone { /// <summary> /// A special 'Done' Task that is already in the RunToCompletion state /// </summary> [Obsolete("Use Task.CompletedTask")] public static Task Done => Task.CompletedTask; } }
#region Copyright & License // // Author: Ian Davis <ian.f.davis@gmail.com> Copyright (c) 2007, Ian Davs // // Portions of this software were developed for NUnit. See NOTICE.txt for more // information. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #endregion using System; using System.Collections; using System.Collections.Generic; using Ensurance.MessageWriters; using Ensurance.Properties; namespace Ensurance.Constraints { #region CollectionConstraint /// <summary> /// CollectionConstraint is the abstract base class for constraints that /// operate on collections. /// </summary> public abstract class CollectionConstraint : Constraint { /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> /// <exception cref="ArgumentException">if actual is not an ICollection</exception> public override bool Matches( object actual ) { Actual = actual; ICollection collection = actual as ICollection; if ( collection == null ) { throw new ArgumentException( Resources.ValueMustBeCollection, "actual" ); } return doMatch( collection ); } /// <summary> /// Protected method to be implemented by derived classes /// </summary> /// <param name="collecton"></param> /// <returns></returns> protected abstract bool doMatch( ICollection collecton ); #region Nested type: CollectionTally /// <summary> /// CollectionTally counts (tallies) the number of occurences of each /// object in one or more enuerations. /// </summary> protected internal class CollectionTally { // Internal dictionary used to count occurences // We use this for any null entries found, since the key to a // dictionary may not be null. private static object NULL = new object(); private Dictionary<object, int> _tallyDictionary = new Dictionary<object, int>(); /// <summary> /// Construct a CollectionTally object from a collection /// </summary> /// <param name="c"></param> public CollectionTally( IEnumerable c ) { foreach (object obj in c) { setTally( obj, getTally( obj ) + 1 ); } } /// <summary> /// Get the count of the number of times an object is present in the /// tally /// </summary> public int this[ object obj ] { get { return getTally( obj ); } } private int getTally( object obj ) { if ( obj == null ) { obj = NULL; } object val = null; if ( _tallyDictionary.ContainsKey( obj ) ) { val = _tallyDictionary[obj]; } return val == null ? 0 : (int) val; } private void setTally( object obj, int tally ) { if ( obj == null ) { obj = NULL; } if ( !_tallyDictionary.ContainsKey( obj ) ) { _tallyDictionary.Add( obj, tally ); } else { _tallyDictionary[obj] = tally; } } /// <summary> /// Remove the counts for a collection from the tally, so long as /// their are sufficient items to remove. The tallies are not /// permitted to become negative. /// </summary> /// <param name="c">The collection to remove</param> /// <returns>True if there were enough items to remove, otherwise false</returns> public bool CanRemove( IEnumerable c ) { foreach (object obj in c) { int tally = getTally( obj ); if ( tally > 0 ) { setTally( obj, tally - 1 ); } else { return false; } } return true; } /// <summary> /// Test whether all the counts are equal to a given value /// </summary> /// <param name="count">The value to be looked for</param> /// <returns>True if all counts are equal to the value, otherwise false</returns> public bool AllCountsEqualTo( int count ) { foreach (int entry in _tallyDictionary.Values) { if ( entry != count ) { return false; } } return true; } } #endregion } #endregion #region UniqueItemsConstraint /// <summary> /// UniqueItemsConstraint tests whether all the items in a collection are /// unique. /// </summary> public class UniqueItemsConstraint : CollectionConstraint { /// <summary> /// Apply the item constraint to each item in the collection, failing if /// any item fails. /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch( ICollection actual ) { return new CollectionTally( actual ).AllCountsEqualTo( 1 ); } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> /// <exception cref="ArgumentNullException">if the message writer is null.</exception> public override void WriteDescriptionTo( MessageWriter writer ) { if ( writer == null ) { throw new ArgumentNullException( "writer" ); } writer.Write( Resources.AllItemsUnique ); } } #endregion #region CollectionContainsConstraint /// <summary> /// CollectionContainsConstraint is used to test whether a collection /// contains an _expected object as a member. /// </summary> public class CollectionContainsConstraint : CollectionConstraint { private object _expected; /// <summary> /// Construct a CollectionContainsConstraint /// </summary> /// <param name="expected"></param> public CollectionContainsConstraint( object expected ) { _expected = expected; } /// <summary> /// Test whether the expected item is contained in the collection /// </summary> /// <param name="actual"></param> /// <returns></returns> protected override bool doMatch( ICollection actual ) { foreach (object obj in actual) { if ( Equals( obj, _expected ) ) { return true; } } return false; } /// <summary> /// Write a descripton of the constraint to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> /// <exception cref="ArgumentNullException">if the message writer is null.</exception> public override void WriteDescriptionTo( MessageWriter writer ) { if ( writer == null ) { throw new ArgumentNullException( "writer" ); } writer.WritePredicate( Resources.CollectionContaining ); writer.WriteExpectedValue( _expected ); } } #endregion #region CollectionEquivalentConstraint /// <summary> /// CollectionEquivalentCOnstraint is used to determine whether two /// collections are equivalent. /// </summary> public class CollectionEquivalentConstraint : CollectionConstraint { private IEnumerable _expected; /// <summary> /// Construct a CollectionEquivalentConstraint /// </summary> /// <param name="expected"></param> public CollectionEquivalentConstraint( IEnumerable expected ) { _expected = expected; } /// <summary> /// Test whether two collections are equivalent /// </summary> /// <param name="actual">The actual.</param> /// <returns></returns> protected override bool doMatch( ICollection actual ) { // This is just an optimization if ( _expected is ICollection ) { if ( actual.Count != ( (ICollection) _expected ).Count ) { return false; } } CollectionTally tally = new CollectionTally( _expected ); return tally.CanRemove( actual ) && tally.AllCountsEqualTo( 0 ); } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> /// <exception cref="ArgumentNullException">if the message writer is null.</exception> public override void WriteDescriptionTo( MessageWriter writer ) { if ( writer == null ) { throw new ArgumentNullException( "writer" ); } writer.WritePredicate( Resources.EquivalentTo ); writer.WriteExpectedValue( _expected ); } } #endregion #region CollectionSubsetConstraint /// <summary> /// CollectionSubsetConstraint is used to determine whether one collection /// is a subset of another /// </summary> public class CollectionSubsetConstraint : CollectionConstraint { private IEnumerable _expected; /// <summary> /// Construct a CollectionSubsetConstraint /// </summary> /// <param name="expected">The collection that the actual value is expected to be a subset of</param> public CollectionSubsetConstraint( IEnumerable expected ) { _expected = expected; } /// <summary> /// Test whether the actual collection is a subset of the expected /// collection provided. /// </summary> /// <param name="actual">The actual.</param> /// <returns></returns> protected override bool doMatch( ICollection actual ) { return new CollectionTally( _expected ).CanRemove( actual ); } /// <summary> /// Write a description of this constraint to a MessageWriter /// </summary> /// <param name="writer">The writer on which the description is displayed</param> /// <exception cref="ArgumentNullException">if the message writer is null.</exception> public override void WriteDescriptionTo( MessageWriter writer ) { if ( writer == null ) { throw new ArgumentNullException( "writer" ); } writer.WritePredicate( Resources.SubsetOf ); writer.WriteExpectedValue( _expected ); } } #endregion }
#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.Algo.Candles.Compression.Algo File: VolumeProfileHelper.cs Created: 2015, 12, 2, 8:18 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Candles.Compression { using System; using System.Linq; using StockSharp.Messages; /// <summary> /// Extension class for <see cref="VolumeProfileBuilder"/>. /// </summary> public static class VolumeProfileHelper { /// <summary> /// The total volume of bids in the <see cref="VolumeProfileBuilder"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>The total volume of bids.</returns> public static decimal TotalBuyVolume(this VolumeProfileBuilder volumeProfile) { if (volumeProfile == null) throw new ArgumentNullException(nameof(volumeProfile)); return volumeProfile.PriceLevels.Select(p => p.BuyVolume).Sum(); } /// <summary> /// The total volume of asks in the <see cref="VolumeProfileBuilder"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>The total volume of asks.</returns> public static decimal TotalSellVolume(this VolumeProfileBuilder volumeProfile) { if (volumeProfile == null) throw new ArgumentNullException(nameof(volumeProfile)); return volumeProfile.PriceLevels.Select(p => p.SellVolume).Sum(); } /// <summary> /// The total number of bids in the <see cref="VolumeProfileBuilder"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>The total number of bids.</returns> public static decimal TotalBuyCount(this VolumeProfileBuilder volumeProfile) { if (volumeProfile == null) throw new ArgumentNullException(nameof(volumeProfile)); return volumeProfile.PriceLevels.Select(p => p.BuyCount).Sum(); } /// <summary> /// The total number of asks in the <see cref="VolumeProfileBuilder"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>The total number of asks.</returns> public static decimal TotalSellCount(this VolumeProfileBuilder volumeProfile) { if (volumeProfile == null) throw new ArgumentNullException(nameof(volumeProfile)); return volumeProfile.PriceLevels.Select(p => p.SellCount).Sum(); } /// <summary> /// POC (Point Of Control) returns <see cref="CandlePriceLevel"/> which had the maximum volume. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>The <see cref="CandlePriceLevel"/> which had the maximum volume.</returns> public static CandlePriceLevel PoC(this VolumeProfileBuilder volumeProfile) { if (volumeProfile == null) throw new ArgumentNullException(nameof(volumeProfile)); var max = volumeProfile.PriceLevels.Select(p => p.BuyVolume + p.SellVolume).Max(); return volumeProfile.PriceLevels.FirstOrDefault(p => p.BuyVolume + p.SellVolume == max); } /// <summary> /// The total volume of bids which was above <see cref="PoC"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>The total volume of bids.</returns> public static decimal BuyVolAbovePoC(this VolumeProfileBuilder volumeProfile) { var poc = volumeProfile.PoC(); return volumeProfile.PriceLevels.Where(p => p.Price > poc.Price).Select(p => p.BuyVolume).Sum(); } /// <summary> /// The total volume of bids which was below <see cref="PoC"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>The total volume of bids.</returns> public static decimal BuyVolBelowPoC(this VolumeProfileBuilder volumeProfile) { var poc = volumeProfile.PoC(); return volumeProfile.PriceLevels.Where(p => p.Price < poc.Price).Select(p => p.BuyVolume).Sum(); } /// <summary> /// The total volume of asks which was above <see cref="PoC"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>The total volume of asks.</returns> public static decimal SellVolAbovePoC(this VolumeProfileBuilder volumeProfile) { var poc = volumeProfile.PoC(); return volumeProfile.PriceLevels.Where(p => p.Price > poc.Price).Select(p => p.SellVolume).Sum(); } /// <summary> /// The total volume of asks which was below <see cref="PoC"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>The total volume of asks.</returns> public static decimal SellVolBelowPoC(this VolumeProfileBuilder volumeProfile) { var poc = volumeProfile.PoC(); return volumeProfile.PriceLevels.Where(p => p.Price < poc.Price).Select(p => p.SellVolume).Sum(); } /// <summary> /// The total volume which was above <see cref="PoC"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>Total volume.</returns> public static decimal VolumeAbovePoC(this VolumeProfileBuilder volumeProfile) { return volumeProfile.BuyVolAbovePoC() + volumeProfile.SellVolAbovePoC(); } /// <summary> /// The total volume which was below <see cref="PoC"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>Total volume.</returns> public static decimal VolumeBelowPoC(this VolumeProfileBuilder volumeProfile) { return volumeProfile.BuyVolBelowPoC() + volumeProfile.SellVolBelowPoC(); } /// <summary> /// The difference between <see cref="TotalBuyVolume"/> and <see cref="TotalSellVolume"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>Delta.</returns> public static decimal Delta(this VolumeProfileBuilder volumeProfile) { return volumeProfile.TotalBuyVolume() - volumeProfile.TotalSellVolume(); } /// <summary> /// It returns the price level at which the maximum <see cref="Delta"/> is passed. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns><see cref="CandlePriceLevel"/>.</returns> public static CandlePriceLevel PriceLevelOfMaxDelta(this VolumeProfileBuilder volumeProfile) { if (volumeProfile == null) throw new ArgumentNullException(nameof(volumeProfile)); var delta = volumeProfile.PriceLevels.Select(p => p.BuyVolume - p.SellVolume).Max(); return volumeProfile.PriceLevels.FirstOrDefault(p => p.BuyVolume - p.SellVolume == delta); } /// <summary> /// It returns the price level at which the minimum <see cref="Delta"/> is passed. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>The price level.</returns> public static CandlePriceLevel PriceLevelOfMinDelta(this VolumeProfileBuilder volumeProfile) { if (volumeProfile == null) throw new ArgumentNullException(nameof(volumeProfile)); var delta = volumeProfile.PriceLevels.Select(p => p.BuyVolume - p.SellVolume).Min(); return volumeProfile.PriceLevels.FirstOrDefault(p => p.BuyVolume - p.SellVolume == delta); } /// <summary> /// The total Delta which was above <see cref="PoC"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>Delta.</returns> public static decimal DeltaAbovePoC(this VolumeProfileBuilder volumeProfile) { return volumeProfile.BuyVolAbovePoC() - volumeProfile.SellVolAbovePoC(); } /// <summary> /// The total Delta which was below <see cref="PoC"/>. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <returns>Delta.</returns> public static decimal DeltaBelowPoC(this VolumeProfileBuilder volumeProfile) { return volumeProfile.BuyVolBelowPoC() - volumeProfile.SellVolBelowPoC(); } /// <summary> /// To update the profile with new value. /// </summary> /// <param name="volumeProfile">Volume profile.</param> /// <param name="transform">The data source transformation.</param> public static void Update(this VolumeProfileBuilder volumeProfile, ICandleBuilderValueTransform transform) { if (volumeProfile == null) throw new ArgumentNullException(nameof(volumeProfile)); if (transform == null) throw new ArgumentNullException(nameof(transform)); volumeProfile.Update(transform.Price, transform.Volume, transform.Side); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Management.Automation; using System.Management.Automation.Internal; using System.Reflection; namespace Microsoft.PowerShell.Commands { /// <summary> /// Class with member information that this cmdlet writes to the pipeline. /// </summary> public class MemberDefinition { /// <summary> /// Returns the member definition. /// </summary> public override string ToString() { return Definition; } /// <summary> /// Initializes a new instance of this class. /// </summary> public MemberDefinition(string typeName, string name, PSMemberTypes memberType, string definition) { Name = name; Definition = definition; MemberType = memberType; TypeName = typeName; } /// <summary> /// Type name. /// </summary> public string TypeName { get; } /// <summary> /// Member name. /// </summary> public string Name { get; } /// <summary> /// Member type. /// </summary> public PSMemberTypes MemberType { get; } /// <summary> /// Member definition. /// </summary> public string Definition { get; } } /// <summary> /// This class implements get-member command. /// </summary> [Cmdlet(VerbsCommon.Get, "Member", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113322", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(MemberDefinition))] public class GetMemberCommand : PSCmdlet { /// <summary> /// The object to retrieve properties from. /// </summary> [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set; get; } /// <summary> /// The member names to be retrieved. /// </summary> [Parameter(Position = 0)] [ValidateNotNullOrEmpty] public string[] Name { set; get; } = new string[] { "*" }; /// <summary> /// The member types to be retrieved. /// </summary> [Parameter] [Alias("Type")] public PSMemberTypes MemberType { set; get; } = PSMemberTypes.All; /// <summary> /// View from which the members are retrieved. /// </summary> [Parameter] public PSMemberViewTypes View { get; set; } = PSMemberViewTypes.Adapted | PSMemberViewTypes.Extended; private bool _staticParameter = false; /// <summary> /// True if we should return static members. /// </summary> [Parameter] public SwitchParameter Static { set { _staticParameter = value; } get { return _staticParameter; } } /// <summary> /// Gets or sets the force property. /// </summary> /// <remarks> /// Gives the Member matcher guidance on how vigorous the Match should be. /// If set to true all members in a given view + membertype are displayed. /// This parameter is added to hide Get/Set property accessor methods by default. /// If a user wants to see these methods, -force should be set to true. /// </remarks> [Parameter] public SwitchParameter Force { get { return (_matchOptions == MshMemberMatchOptions.IncludeHidden); } set { if (value) { // Include hidden members if force parameter is set _matchOptions = MshMemberMatchOptions.IncludeHidden; } else { _matchOptions = MshMemberMatchOptions.None; } } } private MshMemberMatchOptions _matchOptions = MshMemberMatchOptions.None; private HybridDictionary _typesAlreadyDisplayed = new HybridDictionary(); /// <summary> /// This method implements the ProcessRecord method for get-member command. /// </summary> protected override void ProcessRecord() { if (this.InputObject == null || this.InputObject == AutomationNull.Value) { return; } Type baseObjectAsType = null; string typeName; Adapter staticAdapter = null; if (this.Static == true) { staticAdapter = PSObject.dotNetStaticAdapter; object baseObject = this.InputObject.BaseObject; baseObjectAsType = baseObject as System.Type ?? baseObject.GetType(); typeName = baseObjectAsType.FullName; } else { var typeNames = this.InputObject.InternalTypeNames; if (typeNames.Count != 0) { typeName = typeNames[0]; } else { // This is never used for display. It is used only as a key to typesAlreadyDisplayed typeName = "<null>"; } } if (_typesAlreadyDisplayed.Contains(typeName)) { return; } else { _typesAlreadyDisplayed.Add(typeName, string.Empty); } PSMemberTypes memberTypeToSearch = MemberType; PSMemberViewTypes viewToSearch = View; if (((View & PSMemberViewTypes.Extended) == 0) && (!typeof(PSMemberSet).ToString().Equals(typeName, StringComparison.OrdinalIgnoreCase))) { // PSMemberSet is an internal memberset and its properties/methods are populated differently. // PSMemberSet instance is created to represent PSExtended, PSAdapted, PSBase, PSObject hidden // properties. We should honor extended properties for such case. // request is to search dotnet or adapted or both members. // dotnet,adapted members cannot be Script*,Note*,Code* memberTypeToSearch ^= (PSMemberTypes.AliasProperty | PSMemberTypes.CodeMethod | PSMemberTypes.CodeProperty | PSMemberTypes.MemberSet | PSMemberTypes.NoteProperty | PSMemberTypes.PropertySet | PSMemberTypes.ScriptMethod | PSMemberTypes.ScriptProperty); } if (((View & PSMemberViewTypes.Adapted) == 0) && (View & PSMemberViewTypes.Base) == 0) { // base and adapted are not mentioned in the view so ignore respective properties memberTypeToSearch ^= (PSMemberTypes.Property | PSMemberTypes.ParameterizedProperty | PSMemberTypes.Method); } if (((View & PSMemberViewTypes.Base) == PSMemberViewTypes.Base) && (InputObject.InternalBaseDotNetAdapter == null)) { // the input object don't have a custom adapter.. // for this case adapted view and base view are the same. viewToSearch |= PSMemberViewTypes.Adapted; } PSMemberInfoCollection<PSMemberInfo> membersToSearch; if (this.Static == true) { membersToSearch = staticAdapter.BaseGetMembers<PSMemberInfo>(baseObjectAsType); } else { Collection<CollectionEntry<PSMemberInfo>> memberCollection = PSObject.GetMemberCollection(viewToSearch); membersToSearch = new PSMemberInfoIntegratingCollection<PSMemberInfo>(this.InputObject, memberCollection); } foreach (string nameElement in this.Name) { ReadOnlyPSMemberInfoCollection<PSMemberInfo> readOnlyMembers; readOnlyMembers = membersToSearch.Match(nameElement, memberTypeToSearch, _matchOptions); MemberDefinition[] members = new MemberDefinition[readOnlyMembers.Count]; int resultCount = 0; foreach (PSMemberInfo member in readOnlyMembers) { if (!Force) { PSMethod memberAsPSMethod = member as PSMethod; if ((memberAsPSMethod != null) && (memberAsPSMethod.IsSpecial)) { continue; } } members[resultCount] = new MemberDefinition(typeName, member.Name, member.MemberType, member.ToString()); resultCount++; } Array.Sort<MemberDefinition>(members, 0, resultCount, new MemberComparer()); for (int index = 0; index < resultCount; index++) { this.WriteObject(members[index]); } } } private class MemberComparer : System.Collections.Generic.IComparer<MemberDefinition> { public int Compare(MemberDefinition first, MemberDefinition second) { int result = string.Compare(first.MemberType.ToString(), second.MemberType.ToString(), StringComparison.OrdinalIgnoreCase); if (result != 0) { return result; } return string.Compare(first.Name, second.Name, StringComparison.OrdinalIgnoreCase); } } /// <summary> /// This method implements the End method for get-member command. /// </summary> protected override void EndProcessing() { if (_typesAlreadyDisplayed.Count == 0) { ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException(GetMember.NoObjectSpecified), "NoObjectInGetMember", ErrorCategory.CloseError, null); WriteError(errorRecord); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V10.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V10.Services; namespace Google.Ads.GoogleAds.Tests.V10.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedOfflineUserDataJobServiceClientTest { [Category("Autogenerated")][Test] public void CreateOfflineUserDataJobRequestObject() { moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient> mockGrpcClient = new moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateOfflineUserDataJobRequest request = new CreateOfflineUserDataJobRequest { CustomerId = "customer_id3b3724cb", Job = new gagvr::OfflineUserDataJob(), ValidateOnly = true, EnableMatchRateRangePreview = false, }; CreateOfflineUserDataJobResponse expectedResponse = new CreateOfflineUserDataJobResponse { ResourceNameAsOfflineUserDataJobName = gagvr::OfflineUserDataJobName.FromCustomerOfflineUserDataUpdate("[CUSTOMER_ID]", "[OFFLINE_USER_DATA_UPDATE_ID]"), }; mockGrpcClient.Setup(x => x.CreateOfflineUserDataJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OfflineUserDataJobServiceClient client = new OfflineUserDataJobServiceClientImpl(mockGrpcClient.Object, null); CreateOfflineUserDataJobResponse response = client.CreateOfflineUserDataJob(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task CreateOfflineUserDataJobRequestObjectAsync() { moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient> mockGrpcClient = new moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateOfflineUserDataJobRequest request = new CreateOfflineUserDataJobRequest { CustomerId = "customer_id3b3724cb", Job = new gagvr::OfflineUserDataJob(), ValidateOnly = true, EnableMatchRateRangePreview = false, }; CreateOfflineUserDataJobResponse expectedResponse = new CreateOfflineUserDataJobResponse { ResourceNameAsOfflineUserDataJobName = gagvr::OfflineUserDataJobName.FromCustomerOfflineUserDataUpdate("[CUSTOMER_ID]", "[OFFLINE_USER_DATA_UPDATE_ID]"), }; mockGrpcClient.Setup(x => x.CreateOfflineUserDataJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CreateOfflineUserDataJobResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OfflineUserDataJobServiceClient client = new OfflineUserDataJobServiceClientImpl(mockGrpcClient.Object, null); CreateOfflineUserDataJobResponse responseCallSettings = await client.CreateOfflineUserDataJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); CreateOfflineUserDataJobResponse responseCancellationToken = await client.CreateOfflineUserDataJobAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void CreateOfflineUserDataJob() { moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient> mockGrpcClient = new moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateOfflineUserDataJobRequest request = new CreateOfflineUserDataJobRequest { CustomerId = "customer_id3b3724cb", Job = new gagvr::OfflineUserDataJob(), }; CreateOfflineUserDataJobResponse expectedResponse = new CreateOfflineUserDataJobResponse { ResourceNameAsOfflineUserDataJobName = gagvr::OfflineUserDataJobName.FromCustomerOfflineUserDataUpdate("[CUSTOMER_ID]", "[OFFLINE_USER_DATA_UPDATE_ID]"), }; mockGrpcClient.Setup(x => x.CreateOfflineUserDataJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OfflineUserDataJobServiceClient client = new OfflineUserDataJobServiceClientImpl(mockGrpcClient.Object, null); CreateOfflineUserDataJobResponse response = client.CreateOfflineUserDataJob(request.CustomerId, request.Job); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task CreateOfflineUserDataJobAsync() { moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient> mockGrpcClient = new moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateOfflineUserDataJobRequest request = new CreateOfflineUserDataJobRequest { CustomerId = "customer_id3b3724cb", Job = new gagvr::OfflineUserDataJob(), }; CreateOfflineUserDataJobResponse expectedResponse = new CreateOfflineUserDataJobResponse { ResourceNameAsOfflineUserDataJobName = gagvr::OfflineUserDataJobName.FromCustomerOfflineUserDataUpdate("[CUSTOMER_ID]", "[OFFLINE_USER_DATA_UPDATE_ID]"), }; mockGrpcClient.Setup(x => x.CreateOfflineUserDataJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CreateOfflineUserDataJobResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OfflineUserDataJobServiceClient client = new OfflineUserDataJobServiceClientImpl(mockGrpcClient.Object, null); CreateOfflineUserDataJobResponse responseCallSettings = await client.CreateOfflineUserDataJobAsync(request.CustomerId, request.Job, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); CreateOfflineUserDataJobResponse responseCancellationToken = await client.CreateOfflineUserDataJobAsync(request.CustomerId, request.Job, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void AddOfflineUserDataJobOperationsRequestObject() { moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient> mockGrpcClient = new moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); AddOfflineUserDataJobOperationsRequest request = new AddOfflineUserDataJobOperationsRequest { ResourceNameAsOfflineUserDataJobName = gagvr::OfflineUserDataJobName.FromCustomerOfflineUserDataUpdate("[CUSTOMER_ID]", "[OFFLINE_USER_DATA_UPDATE_ID]"), Operations = { new OfflineUserDataJobOperation(), }, EnablePartialFailure = true, ValidateOnly = true, EnableWarnings = true, }; AddOfflineUserDataJobOperationsResponse expectedResponse = new AddOfflineUserDataJobOperationsResponse { PartialFailureError = new gr::Status(), Warning = new gr::Status(), }; mockGrpcClient.Setup(x => x.AddOfflineUserDataJobOperations(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OfflineUserDataJobServiceClient client = new OfflineUserDataJobServiceClientImpl(mockGrpcClient.Object, null); AddOfflineUserDataJobOperationsResponse response = client.AddOfflineUserDataJobOperations(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task AddOfflineUserDataJobOperationsRequestObjectAsync() { moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient> mockGrpcClient = new moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); AddOfflineUserDataJobOperationsRequest request = new AddOfflineUserDataJobOperationsRequest { ResourceNameAsOfflineUserDataJobName = gagvr::OfflineUserDataJobName.FromCustomerOfflineUserDataUpdate("[CUSTOMER_ID]", "[OFFLINE_USER_DATA_UPDATE_ID]"), Operations = { new OfflineUserDataJobOperation(), }, EnablePartialFailure = true, ValidateOnly = true, EnableWarnings = true, }; AddOfflineUserDataJobOperationsResponse expectedResponse = new AddOfflineUserDataJobOperationsResponse { PartialFailureError = new gr::Status(), Warning = new gr::Status(), }; mockGrpcClient.Setup(x => x.AddOfflineUserDataJobOperationsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AddOfflineUserDataJobOperationsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OfflineUserDataJobServiceClient client = new OfflineUserDataJobServiceClientImpl(mockGrpcClient.Object, null); AddOfflineUserDataJobOperationsResponse responseCallSettings = await client.AddOfflineUserDataJobOperationsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); AddOfflineUserDataJobOperationsResponse responseCancellationToken = await client.AddOfflineUserDataJobOperationsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void AddOfflineUserDataJobOperations() { moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient> mockGrpcClient = new moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); AddOfflineUserDataJobOperationsRequest request = new AddOfflineUserDataJobOperationsRequest { ResourceNameAsOfflineUserDataJobName = gagvr::OfflineUserDataJobName.FromCustomerOfflineUserDataUpdate("[CUSTOMER_ID]", "[OFFLINE_USER_DATA_UPDATE_ID]"), Operations = { new OfflineUserDataJobOperation(), }, }; AddOfflineUserDataJobOperationsResponse expectedResponse = new AddOfflineUserDataJobOperationsResponse { PartialFailureError = new gr::Status(), Warning = new gr::Status(), }; mockGrpcClient.Setup(x => x.AddOfflineUserDataJobOperations(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OfflineUserDataJobServiceClient client = new OfflineUserDataJobServiceClientImpl(mockGrpcClient.Object, null); AddOfflineUserDataJobOperationsResponse response = client.AddOfflineUserDataJobOperations(request.ResourceName, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task AddOfflineUserDataJobOperationsAsync() { moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient> mockGrpcClient = new moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); AddOfflineUserDataJobOperationsRequest request = new AddOfflineUserDataJobOperationsRequest { ResourceNameAsOfflineUserDataJobName = gagvr::OfflineUserDataJobName.FromCustomerOfflineUserDataUpdate("[CUSTOMER_ID]", "[OFFLINE_USER_DATA_UPDATE_ID]"), Operations = { new OfflineUserDataJobOperation(), }, }; AddOfflineUserDataJobOperationsResponse expectedResponse = new AddOfflineUserDataJobOperationsResponse { PartialFailureError = new gr::Status(), Warning = new gr::Status(), }; mockGrpcClient.Setup(x => x.AddOfflineUserDataJobOperationsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AddOfflineUserDataJobOperationsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OfflineUserDataJobServiceClient client = new OfflineUserDataJobServiceClientImpl(mockGrpcClient.Object, null); AddOfflineUserDataJobOperationsResponse responseCallSettings = await client.AddOfflineUserDataJobOperationsAsync(request.ResourceName, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); AddOfflineUserDataJobOperationsResponse responseCancellationToken = await client.AddOfflineUserDataJobOperationsAsync(request.ResourceName, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void AddOfflineUserDataJobOperationsResourceNames() { moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient> mockGrpcClient = new moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); AddOfflineUserDataJobOperationsRequest request = new AddOfflineUserDataJobOperationsRequest { ResourceNameAsOfflineUserDataJobName = gagvr::OfflineUserDataJobName.FromCustomerOfflineUserDataUpdate("[CUSTOMER_ID]", "[OFFLINE_USER_DATA_UPDATE_ID]"), Operations = { new OfflineUserDataJobOperation(), }, }; AddOfflineUserDataJobOperationsResponse expectedResponse = new AddOfflineUserDataJobOperationsResponse { PartialFailureError = new gr::Status(), Warning = new gr::Status(), }; mockGrpcClient.Setup(x => x.AddOfflineUserDataJobOperations(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); OfflineUserDataJobServiceClient client = new OfflineUserDataJobServiceClientImpl(mockGrpcClient.Object, null); AddOfflineUserDataJobOperationsResponse response = client.AddOfflineUserDataJobOperations(request.ResourceNameAsOfflineUserDataJobName, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task AddOfflineUserDataJobOperationsResourceNamesAsync() { moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient> mockGrpcClient = new moq::Mock<OfflineUserDataJobService.OfflineUserDataJobServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); AddOfflineUserDataJobOperationsRequest request = new AddOfflineUserDataJobOperationsRequest { ResourceNameAsOfflineUserDataJobName = gagvr::OfflineUserDataJobName.FromCustomerOfflineUserDataUpdate("[CUSTOMER_ID]", "[OFFLINE_USER_DATA_UPDATE_ID]"), Operations = { new OfflineUserDataJobOperation(), }, }; AddOfflineUserDataJobOperationsResponse expectedResponse = new AddOfflineUserDataJobOperationsResponse { PartialFailureError = new gr::Status(), Warning = new gr::Status(), }; mockGrpcClient.Setup(x => x.AddOfflineUserDataJobOperationsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<AddOfflineUserDataJobOperationsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); OfflineUserDataJobServiceClient client = new OfflineUserDataJobServiceClientImpl(mockGrpcClient.Object, null); AddOfflineUserDataJobOperationsResponse responseCallSettings = await client.AddOfflineUserDataJobOperationsAsync(request.ResourceNameAsOfflineUserDataJobName, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); AddOfflineUserDataJobOperationsResponse responseCancellationToken = await client.AddOfflineUserDataJobOperationsAsync(request.ResourceNameAsOfflineUserDataJobName, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System.Collections.Generic; using Mono.Cecil; namespace SharpLang.CompilerServices { public class MemberEqualityComparer : IEqualityComparer<TypeReference>, IEqualityComparer<MethodReference>, IEqualityComparer<FieldReference> { public static readonly MemberEqualityComparer Default = new MemberEqualityComparer(); public bool Equals(TypeReference x, TypeReference y) { return AreSame(x, y); } public bool Equals(MethodReference x, MethodReference y) { return AreSame(x, y); } public bool Equals(FieldReference x, FieldReference y) { if (ReferenceEquals(x, y)) return true; return AreSame(x, y); } public int GetHashCode(TypeReference typeReference) { unchecked { var metadataType = GetUnifiedMetadataType(typeReference); var result = ((byte)metadataType).GetHashCode(); var typeSpecification = typeReference as TypeSpecification; if (typeSpecification != null) { result ^= GetHashCode(typeSpecification.ElementType); var genericInstanceType = typeSpecification as GenericInstanceType; if (genericInstanceType != null) { foreach (var arg in genericInstanceType.GenericArguments) result = result * 23 + GetHashCode(arg); } } else { // TODO: Not sure if comparing declaring type should be done for GenericParameter if (typeReference.DeclaringType != null) result ^= GetHashCode(typeReference.DeclaringType); var genericParameter = typeReference as GenericParameter; if (genericParameter != null) { result ^= genericParameter.Position; } else { result ^= typeReference.Name.GetHashCode(); result ^= typeReference.Namespace.GetHashCode(); } } return result; } } public int GetHashCode(MethodReference methodReference) { unchecked { int result; var genericInstanceMethod = methodReference as GenericInstanceMethod; if (genericInstanceMethod != null) { result = GetHashCode(genericInstanceMethod.ElementMethod); foreach (var arg in genericInstanceMethod.GenericArguments) result = result * 23 + GetHashCode(arg); } else { result = methodReference.Name.GetHashCode(); result ^= GetHashCode(methodReference.DeclaringType); // TODO: Investigate why hashing parameter types seems to cause issues (virtual methods with no slots) foreach (var parameter in methodReference.Parameters) result = result * 23 + GetHashCode(parameter.ParameterType); } return result; } } public int GetHashCode(FieldReference fieldReference) { unchecked { var result = fieldReference.Name.GetHashCode(); result ^= GetHashCode(fieldReference.DeclaringType); return result; } } static bool AreSame(FieldReference a, FieldReference b) { if (a.Name != b.Name) return false; if (!AreSame(a.DeclaringType, b.DeclaringType)) return false; if (!AreSame(a.FieldType, b.FieldType)) return false; return true; } static bool AreSame(MethodReference a, MethodReference b) { if (ReferenceEquals(a, b)) return true; if (a.Name != b.Name) return false; if (!AreSame(a.DeclaringType, b.DeclaringType)) return false; if (a.HasGenericParameters != b.HasGenericParameters) return false; if (a.IsGenericInstance != b.IsGenericInstance) return false; if (a.IsGenericInstance && !AreSame(((GenericInstanceMethod)a).GenericArguments, ((GenericInstanceMethod)b).GenericArguments)) return false; if (a.HasGenericParameters && a.GenericParameters.Count != b.GenericParameters.Count) return false; if (!AreSame(a.ReturnType, b.ReturnType)) return false; if (a.HasParameters != b.HasParameters) return false; if (a.HasParameters != b.HasParameters) return false; if (a.HasParameters && !AreSame(a.Parameters, b.Parameters)) return false; return true; } static bool AreSame(Mono.Collections.Generic.Collection<TypeReference> a, Mono.Collections.Generic.Collection<TypeReference> b) { var count = a.Count; if (count != b.Count) return false; if (count == 0) return true; for (int i = 0; i < count; i++) if (!AreSame(a[i], b[i])) return false; return true; } static bool AreSame(Mono.Collections.Generic.Collection<ParameterDefinition> a, Mono.Collections.Generic.Collection<ParameterDefinition> b) { var count = a.Count; if (count != b.Count) return false; if (count == 0) return true; for (int i = 0; i < count; i++) if (!AreSame(a[i].ParameterType, b[i].ParameterType)) return false; return true; } static bool AreSame(TypeSpecification a, TypeSpecification b) { if (!AreSame(a.ElementType, b.ElementType)) return false; if (a.IsGenericInstance) return AreSame((GenericInstanceType)a, (GenericInstanceType)b); if (a.IsRequiredModifier || a.IsOptionalModifier) return AreSame((IModifierType)a, (IModifierType)b); if (a.IsArray) return AreSame((ArrayType)a, (ArrayType)b); return true; } static bool AreSame(ArrayType a, ArrayType b) { if (a.Rank != b.Rank) return false; // TODO: dimensions return true; } static bool AreSame(IModifierType a, IModifierType b) { return AreSame(a.ModifierType, b.ModifierType); } static bool AreSame(GenericInstanceType a, GenericInstanceType b) { if (a.GenericArguments.Count != b.GenericArguments.Count) return false; for (int i = 0; i < a.GenericArguments.Count; i++) if (!AreSame(a.GenericArguments[i], b.GenericArguments[i])) return false; return true; } static bool AreSame(GenericParameter a, GenericParameter b) { return a.Position == b.Position; } static bool AreSame(TypeReference a, TypeReference b) { if (ReferenceEquals(a, b)) return true; if (a == null || b == null) return false; if (GetUnifiedMetadataType(a) != GetUnifiedMetadataType(b)) return false; if (a.IsGenericParameter) return AreSame((GenericParameter)a, (GenericParameter)b); if (a is TypeSpecification) return AreSame((TypeSpecification)a, (TypeSpecification)b); if (a.Name != b.Name || a.Namespace != b.Namespace) return false; //TODO: check scope if (!AreSame(a.DeclaringType, b.DeclaringType)) return false; if (!a.HasGenericParameters && !b.HasGenericParameters && !(a is GenericInstanceType) && !(b is GenericInstanceType)) if (a.Resolve().Module != b.Resolve().Module) return false; return true; } private static MetadataType GetUnifiedMetadataType(TypeReference typeReference) { // Sometimes, IsValueType is not properly set in type references, so let's map it to Class. var metadataType = typeReference.MetadataType; if (metadataType == MetadataType.ValueType) metadataType = MetadataType.Class; return metadataType; } } }
using System; using System.Collections.Generic; using UnityEngine; namespace UnityStandardAssets.Water { [ExecuteInEditMode] // Make water live-update even when not in play mode public class Water : MonoBehaviour { public enum WaterMode { Simple = 0, Reflective = 1, Refractive = 2, }; public WaterMode waterMode = WaterMode.Refractive; public bool disablePixelLights = true; public int textureSize = 256; public float clipPlaneOffset = 0.07f; public LayerMask reflectLayers = -1; public LayerMask refractLayers = -1; private Dictionary<Camera, Camera> m_ReflectionCameras = new Dictionary<Camera, Camera>(); // Camera -> Camera table private Dictionary<Camera, Camera> m_RefractionCameras = new Dictionary<Camera, Camera>(); // Camera -> Camera table private RenderTexture m_ReflectionTexture; private RenderTexture m_RefractionTexture; private WaterMode m_HardwareWaterSupport = WaterMode.Refractive; private int m_OldReflectionTextureSize; private int m_OldRefractionTextureSize; private static bool s_InsideWater; // This is called when it's known that the object will be rendered by some // camera. We render reflections / refractions and do other updates here. // Because the script executes in edit mode, reflections for the scene view // camera will just work! public void OnWillRenderObject() { if (!enabled || !GetComponent<Renderer>() || !GetComponent<Renderer>().sharedMaterial || !GetComponent<Renderer>().enabled) { return; } Camera cam = Camera.current; if (!cam) { return; } // Safeguard from recursive water reflections. if (s_InsideWater) { return; } s_InsideWater = true; // Actual water rendering mode depends on both the current setting AND // the hardware support. There's no point in rendering refraction textures // if they won't be visible in the end. m_HardwareWaterSupport = FindHardwareWaterSupport(); WaterMode mode = GetWaterMode(); Camera reflectionCamera, refractionCamera; CreateWaterObjects(cam, out reflectionCamera, out refractionCamera); // find out the reflection plane: position and normal in world space Vector3 pos = transform.position; Vector3 normal = transform.up; // Optionally disable pixel lights for reflection/refraction int oldPixelLightCount = QualitySettings.pixelLightCount; if (disablePixelLights) { QualitySettings.pixelLightCount = 0; } UpdateCameraModes(cam, reflectionCamera); UpdateCameraModes(cam, refractionCamera); // Render reflection if needed if (mode >= WaterMode.Reflective) { // Reflect camera around reflection plane float d = -Vector3.Dot(normal, pos) - clipPlaneOffset; Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d); Matrix4x4 reflection = Matrix4x4.zero; CalculateReflectionMatrix(ref reflection, reflectionPlane); Vector3 oldpos = cam.transform.position; Vector3 newpos = reflection.MultiplyPoint(oldpos); reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection; // Setup oblique projection matrix so that near plane is our reflection // plane. This way we clip everything below/above it for free. Vector4 clipPlane = CameraSpacePlane(reflectionCamera, pos, normal, 1.0f); reflectionCamera.projectionMatrix = cam.CalculateObliqueMatrix(clipPlane); // Set custom culling matrix from the current camera reflectionCamera.cullingMatrix = cam.projectionMatrix * cam.worldToCameraMatrix; reflectionCamera.cullingMask = ~(1 << 4) & reflectLayers.value; // never render water layer reflectionCamera.targetTexture = m_ReflectionTexture; bool oldCulling = GL.invertCulling; GL.invertCulling = !oldCulling; reflectionCamera.transform.position = newpos; Vector3 euler = cam.transform.eulerAngles; reflectionCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z); reflectionCamera.Render(); reflectionCamera.transform.position = oldpos; GL.invertCulling = oldCulling; GetComponent<Renderer>().sharedMaterial.SetTexture("_ReflectionTex", m_ReflectionTexture); } // Render refraction if (mode >= WaterMode.Refractive) { refractionCamera.worldToCameraMatrix = cam.worldToCameraMatrix; // Setup oblique projection matrix so that near plane is our reflection // plane. This way we clip everything below/above it for free. Vector4 clipPlane = CameraSpacePlane(refractionCamera, pos, normal, -1.0f); refractionCamera.projectionMatrix = cam.CalculateObliqueMatrix(clipPlane); // Set custom culling matrix from the current camera refractionCamera.cullingMatrix = cam.projectionMatrix * cam.worldToCameraMatrix; refractionCamera.cullingMask = ~(1 << 4) & refractLayers.value; // never render water layer refractionCamera.targetTexture = m_RefractionTexture; refractionCamera.transform.position = cam.transform.position; refractionCamera.transform.rotation = cam.transform.rotation; refractionCamera.Render(); GetComponent<Renderer>().sharedMaterial.SetTexture("_RefractionTex", m_RefractionTexture); } // Restore pixel light count if (disablePixelLights) { QualitySettings.pixelLightCount = oldPixelLightCount; } // Setup shader keywords based on water mode switch (mode) { case WaterMode.Simple: Shader.EnableKeyword("WATER_SIMPLE"); Shader.DisableKeyword("WATER_REFLECTIVE"); Shader.DisableKeyword("WATER_REFRACTIVE"); break; case WaterMode.Reflective: Shader.DisableKeyword("WATER_SIMPLE"); Shader.EnableKeyword("WATER_REFLECTIVE"); Shader.DisableKeyword("WATER_REFRACTIVE"); break; case WaterMode.Refractive: Shader.DisableKeyword("WATER_SIMPLE"); Shader.DisableKeyword("WATER_REFLECTIVE"); Shader.EnableKeyword("WATER_REFRACTIVE"); break; } s_InsideWater = false; } // Cleanup all the objects we possibly have created void OnDisable() { if (m_ReflectionTexture) { DestroyImmediate(m_ReflectionTexture); m_ReflectionTexture = null; } if (m_RefractionTexture) { DestroyImmediate(m_RefractionTexture); m_RefractionTexture = null; } foreach (var kvp in m_ReflectionCameras) { DestroyImmediate((kvp.Value).gameObject); } m_ReflectionCameras.Clear(); foreach (var kvp in m_RefractionCameras) { DestroyImmediate((kvp.Value).gameObject); } m_RefractionCameras.Clear(); } // This just sets up some matrices in the material; for really // old cards to make water texture scroll. void Update() { if (!GetComponent<Renderer>()) { return; } Material mat = GetComponent<Renderer>().sharedMaterial; if (!mat) { return; } Vector4 waveSpeed = mat.GetVector("WaveSpeed"); float waveScale = mat.GetFloat("_WaveScale"); Vector4 waveScale4 = new Vector4(waveScale, waveScale, waveScale * 0.4f, waveScale * 0.45f); // Time since level load, and do intermediate calculations with doubles double t = Time.timeSinceLevelLoad / 20.0; Vector4 offsetClamped = new Vector4( (float)Math.IEEERemainder(waveSpeed.x * waveScale4.x * t, 1.0), (float)Math.IEEERemainder(waveSpeed.y * waveScale4.y * t, 1.0), (float)Math.IEEERemainder(waveSpeed.z * waveScale4.z * t, 1.0), (float)Math.IEEERemainder(waveSpeed.w * waveScale4.w * t, 1.0) ); mat.SetVector("_WaveOffset", offsetClamped); mat.SetVector("_WaveScale4", waveScale4); } void UpdateCameraModes(Camera src, Camera dest) { if (dest == null) { return; } // set water camera to clear the same way as current camera dest.clearFlags = src.clearFlags; dest.backgroundColor = src.backgroundColor; if (src.clearFlags == CameraClearFlags.Skybox) { Skybox sky = src.GetComponent<Skybox>(); Skybox mysky = dest.GetComponent<Skybox>(); if (!sky || !sky.material) { mysky.enabled = false; } else { mysky.enabled = true; mysky.material = sky.material; } } // update other values to match current camera. // even if we are supplying custom camera&projection matrices, // some of values are used elsewhere (e.g. skybox uses far plane) dest.farClipPlane = src.farClipPlane; dest.nearClipPlane = src.nearClipPlane; dest.orthographic = src.orthographic; dest.fieldOfView = src.fieldOfView; dest.aspect = src.aspect; dest.orthographicSize = src.orthographicSize; } // On-demand create any objects we need for water void CreateWaterObjects(Camera currentCamera, out Camera reflectionCamera, out Camera refractionCamera) { WaterMode mode = GetWaterMode(); reflectionCamera = null; refractionCamera = null; if (mode >= WaterMode.Reflective) { // Reflection render texture if (!m_ReflectionTexture || m_OldReflectionTextureSize != textureSize) { if (m_ReflectionTexture) { DestroyImmediate(m_ReflectionTexture); } m_ReflectionTexture = new RenderTexture(textureSize, textureSize, 16); m_ReflectionTexture.name = "__WaterReflection" + GetInstanceID(); m_ReflectionTexture.isPowerOfTwo = true; m_ReflectionTexture.hideFlags = HideFlags.DontSave; m_OldReflectionTextureSize = textureSize; } // Camera for reflection m_ReflectionCameras.TryGetValue(currentCamera, out reflectionCamera); if (!reflectionCamera) // catch both not-in-dictionary and in-dictionary-but-deleted-GO { GameObject go = new GameObject("Water Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox)); reflectionCamera = go.GetComponent<Camera>(); reflectionCamera.enabled = false; reflectionCamera.transform.position = transform.position; reflectionCamera.transform.rotation = transform.rotation; reflectionCamera.gameObject.AddComponent<FlareLayer>(); go.hideFlags = HideFlags.HideAndDontSave; m_ReflectionCameras[currentCamera] = reflectionCamera; } } if (mode >= WaterMode.Refractive) { // Refraction render texture if (!m_RefractionTexture || m_OldRefractionTextureSize != textureSize) { if (m_RefractionTexture) { DestroyImmediate(m_RefractionTexture); } m_RefractionTexture = new RenderTexture(textureSize, textureSize, 16); m_RefractionTexture.name = "__WaterRefraction" + GetInstanceID(); m_RefractionTexture.isPowerOfTwo = true; m_RefractionTexture.hideFlags = HideFlags.DontSave; m_OldRefractionTextureSize = textureSize; } // Camera for refraction m_RefractionCameras.TryGetValue(currentCamera, out refractionCamera); if (!refractionCamera) // catch both not-in-dictionary and in-dictionary-but-deleted-GO { GameObject go = new GameObject("Water Refr Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox)); refractionCamera = go.GetComponent<Camera>(); refractionCamera.enabled = false; refractionCamera.transform.position = transform.position; refractionCamera.transform.rotation = transform.rotation; refractionCamera.gameObject.AddComponent<FlareLayer>(); go.hideFlags = HideFlags.HideAndDontSave; m_RefractionCameras[currentCamera] = refractionCamera; } } } WaterMode GetWaterMode() { if (m_HardwareWaterSupport < waterMode) { return m_HardwareWaterSupport; } return waterMode; } WaterMode FindHardwareWaterSupport() { if (!SystemInfo.supportsRenderTextures || !GetComponent<Renderer>()) { return WaterMode.Simple; } Material mat = GetComponent<Renderer>().sharedMaterial; if (!mat) { return WaterMode.Simple; } string mode = mat.GetTag("WATERMODE", false); if (mode == "Refractive") { return WaterMode.Refractive; } if (mode == "Reflective") { return WaterMode.Reflective; } return WaterMode.Simple; } // Given position/normal of the plane, calculates plane in camera space. 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)); } // Calculates reflection matrix around the given plane static void CalculateReflectionMatrix(ref Matrix4x4 reflectionMat, Vector4 plane) { reflectionMat.m00 = (1F - 2F * plane[0] * plane[0]); reflectionMat.m01 = (- 2F * plane[0] * plane[1]); reflectionMat.m02 = (- 2F * plane[0] * plane[2]); reflectionMat.m03 = (- 2F * plane[3] * plane[0]); reflectionMat.m10 = (- 2F * plane[1] * plane[0]); reflectionMat.m11 = (1F - 2F * plane[1] * plane[1]); reflectionMat.m12 = (- 2F * plane[1] * plane[2]); reflectionMat.m13 = (- 2F * plane[3] * plane[1]); reflectionMat.m20 = (- 2F * plane[2] * plane[0]); reflectionMat.m21 = (- 2F * plane[2] * plane[1]); reflectionMat.m22 = (1F - 2F * plane[2] * plane[2]); reflectionMat.m23 = (- 2F * plane[3] * plane[2]); reflectionMat.m30 = 0F; reflectionMat.m31 = 0F; reflectionMat.m32 = 0F; reflectionMat.m33 = 1F; } } }
namespace RibbonGallery { 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.kryptonRibbon = new ComponentFactory.Krypton.Ribbon.KryptonRibbon(); this.kryptonContextMenuItem1 = new ComponentFactory.Krypton.Toolkit.KryptonContextMenuItem(); this.kryptonRibbonTab1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab(); this.kryptonRibbonGroup1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.kryptonRibbonGroupTriple1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple(); this.kryptonRibbonGroupButton1 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroupButton3 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton(); this.kryptonRibbonGroup2 = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup(); this.galleryNormal = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupGallery(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.galleryRanges = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupGallery(); this.kryptonGalleryRange5 = new ComponentFactory.Krypton.Ribbon.KryptonGalleryRange(); this.kryptonGalleryRange6 = new ComponentFactory.Krypton.Ribbon.KryptonGalleryRange(); this.kryptonGalleryRange7 = new ComponentFactory.Krypton.Ribbon.KryptonGalleryRange(); this.galleryCustom = new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupGallery(); this.kryptonGalleryRange1 = new ComponentFactory.Krypton.Ribbon.KryptonGalleryRange(); this.kryptonGalleryRange2 = new ComponentFactory.Krypton.Ribbon.KryptonGalleryRange(); this.kryptonGalleryRange3 = new ComponentFactory.Krypton.Ribbon.KryptonGalleryRange(); this.kryptonGalleryRange4 = new ComponentFactory.Krypton.Ribbon.KryptonGalleryRange(); this.kryptonFillPanel = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.kryptonPanel1 = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.kryptonLabelExplain = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.kryptonLabelTitle = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.kryptonManager1 = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components); ((System.ComponentModel.ISupportInitialize)(this.kryptonRibbon)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonFillPanel)).BeginInit(); this.kryptonFillPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).BeginInit(); this.kryptonPanel1.SuspendLayout(); this.SuspendLayout(); // // kryptonRibbon // this.kryptonRibbon.HideRibbonSize = new System.Drawing.Size(100, 100); this.kryptonRibbon.Name = "kryptonRibbon"; this.kryptonRibbon.RibbonAppButton.AppButtonMenuItems.AddRange(new ComponentFactory.Krypton.Toolkit.KryptonContextMenuItemBase[] { this.kryptonContextMenuItem1}); this.kryptonRibbon.RibbonAppButton.AppButtonShowRecentDocs = false; this.kryptonRibbon.RibbonTabs.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonTab[] { this.kryptonRibbonTab1}); this.kryptonRibbon.SelectedContext = null; this.kryptonRibbon.SelectedTab = this.kryptonRibbonTab1; this.kryptonRibbon.Size = new System.Drawing.Size(769, 114); this.kryptonRibbon.TabIndex = 0; // // kryptonContextMenuItem1 // this.kryptonContextMenuItem1.Image = ((System.Drawing.Image)(resources.GetObject("kryptonContextMenuItem1.Image"))); this.kryptonContextMenuItem1.Text = "E&xit"; this.kryptonContextMenuItem1.Click += new System.EventHandler(this.kryptonContextMenuItem1_Click); // // kryptonRibbonTab1 // this.kryptonRibbonTab1.Groups.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup[] { this.kryptonRibbonGroup1, this.kryptonRibbonGroup2}); // // kryptonRibbonGroup1 // this.kryptonRibbonGroup1.AllowCollapsed = false; this.kryptonRibbonGroup1.Image = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroup1.Image"))); this.kryptonRibbonGroup1.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.kryptonRibbonGroupTriple1}); this.kryptonRibbonGroup1.KeyTipGroup = "P"; this.kryptonRibbonGroup1.TextLine1 = "Palettes"; // // kryptonRibbonGroupTriple1 // this.kryptonRibbonGroupTriple1.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupItem[] { this.kryptonRibbonGroupButton1, this.kryptonRibbonGroupButton2, this.kryptonRibbonGroupButton3}); this.kryptonRibbonGroupTriple1.MaximumSize = ComponentFactory.Krypton.Ribbon.GroupItemSize.Medium; this.kryptonRibbonGroupTriple1.MinimumSize = ComponentFactory.Krypton.Ribbon.GroupItemSize.Medium; // // kryptonRibbonGroupButton1 // this.kryptonRibbonGroupButton1.ButtonType = ComponentFactory.Krypton.Ribbon.GroupButtonType.Check; this.kryptonRibbonGroupButton1.Checked = true; this.kryptonRibbonGroupButton1.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton1.ImageSmall"))); this.kryptonRibbonGroupButton1.TextLine1 = "Office 2010"; this.kryptonRibbonGroupButton1.TextLine2 = "Blue"; this.kryptonRibbonGroupButton1.Click += new System.EventHandler(this.kryptonRibbonGroupButton1_Click); // // kryptonRibbonGroupButton2 // this.kryptonRibbonGroupButton2.ButtonType = ComponentFactory.Krypton.Ribbon.GroupButtonType.Check; this.kryptonRibbonGroupButton2.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton2.ImageSmall"))); this.kryptonRibbonGroupButton2.TextLine1 = "Office 2007"; this.kryptonRibbonGroupButton2.TextLine2 = "Silver"; this.kryptonRibbonGroupButton2.Click += new System.EventHandler(this.kryptonRibbonGroupButton2_Click); // // kryptonRibbonGroupButton3 // this.kryptonRibbonGroupButton3.ButtonType = ComponentFactory.Krypton.Ribbon.GroupButtonType.Check; this.kryptonRibbonGroupButton3.ImageSmall = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroupButton3.ImageSmall"))); this.kryptonRibbonGroupButton3.TextLine1 = "Sparkle Orange"; this.kryptonRibbonGroupButton3.Click += new System.EventHandler(this.kryptonRibbonGroupButton3_Click); // // kryptonRibbonGroup2 // this.kryptonRibbonGroup2.Image = ((System.Drawing.Image)(resources.GetObject("kryptonRibbonGroup2.Image"))); this.kryptonRibbonGroup2.Items.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupContainer[] { this.galleryNormal, this.galleryRanges, this.galleryCustom}); this.kryptonRibbonGroup2.TextLine1 = "Galleries"; // // galleryNormal // this.galleryNormal.DropButtonItemWidth = 6; this.galleryNormal.ImageLarge = ((System.Drawing.Image)(resources.GetObject("galleryNormal.ImageLarge"))); this.galleryNormal.ImageList = this.imageList1; // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "flag_australia.png"); this.imageList1.Images.SetKeyName(1, "flag_bahamas.png"); this.imageList1.Images.SetKeyName(2, "flag_belgium.png"); this.imageList1.Images.SetKeyName(3, "flag_brazil.png"); this.imageList1.Images.SetKeyName(4, "flag_canada.png"); this.imageList1.Images.SetKeyName(5, "flag_england.png"); this.imageList1.Images.SetKeyName(6, "flag_germany.png"); this.imageList1.Images.SetKeyName(7, "flag_jamaica.png"); this.imageList1.Images.SetKeyName(8, "flag_norway.png"); this.imageList1.Images.SetKeyName(9, "flag_scotland.png"); this.imageList1.Images.SetKeyName(10, "flag_south_africa.png"); this.imageList1.Images.SetKeyName(11, "flag_spain.png"); this.imageList1.Images.SetKeyName(12, "flag_switzerland.png"); this.imageList1.Images.SetKeyName(13, "flag_united_kingdom.png"); this.imageList1.Images.SetKeyName(14, "flag_usa.png"); this.imageList1.Images.SetKeyName(15, "flag_wales.png"); // // galleryRanges // this.galleryRanges.DropButtonItemWidth = 6; this.galleryRanges.DropButtonRanges.AddRange(new ComponentFactory.Krypton.Ribbon.KryptonGalleryRange[] { this.kryptonGalleryRange5, this.kryptonGalleryRange6, this.kryptonGalleryRange7}); this.galleryRanges.ImageLarge = ((System.Drawing.Image)(resources.GetObject("galleryRanges.ImageLarge"))); this.galleryRanges.ImageList = this.imageList1; this.galleryRanges.KeyTip = "Y"; // // kryptonGalleryRange5 // this.kryptonGalleryRange5.Heading = "Users"; this.kryptonGalleryRange5.ImageIndexEnd = 5; this.kryptonGalleryRange5.ImageIndexStart = 0; // // kryptonGalleryRange6 // this.kryptonGalleryRange6.Heading = "Managers"; this.kryptonGalleryRange6.ImageIndexEnd = 11; this.kryptonGalleryRange6.ImageIndexStart = 6; // // kryptonGalleryRange7 // this.kryptonGalleryRange7.Heading = "Others"; this.kryptonGalleryRange7.ImageIndexEnd = 15; this.kryptonGalleryRange7.ImageIndexStart = 12; // // galleryCustom // this.galleryCustom.DropButtonItemWidth = 6; this.galleryCustom.ImageLarge = ((System.Drawing.Image)(resources.GetObject("galleryCustom.ImageLarge"))); this.galleryCustom.ImageList = this.imageList1; this.galleryCustom.KeyTip = "Z"; this.galleryCustom.GalleryDropMenu += new System.EventHandler<ComponentFactory.Krypton.Ribbon.GalleryDropMenuEventArgs>(this.galleryCustom_GalleryDropMenu); // // kryptonGalleryRange1 // this.kryptonGalleryRange1.Heading = "Group 1"; this.kryptonGalleryRange1.ImageIndexEnd = 4; this.kryptonGalleryRange1.ImageIndexStart = 0; // // kryptonGalleryRange2 // this.kryptonGalleryRange2.Heading = "Group 2"; this.kryptonGalleryRange2.ImageIndexEnd = 9; this.kryptonGalleryRange2.ImageIndexStart = 5; // // kryptonGalleryRange3 // this.kryptonGalleryRange3.Heading = "Group 3"; this.kryptonGalleryRange3.ImageIndexEnd = 14; this.kryptonGalleryRange3.ImageIndexStart = 10; // // kryptonGalleryRange4 // this.kryptonGalleryRange4.Heading = "Group 4"; this.kryptonGalleryRange4.ImageIndexEnd = 20; this.kryptonGalleryRange4.ImageIndexStart = 15; // // kryptonFillPanel // this.kryptonFillPanel.Controls.Add(this.kryptonPanel1); this.kryptonFillPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.kryptonFillPanel.Location = new System.Drawing.Point(0, 114); this.kryptonFillPanel.Name = "kryptonFillPanel"; this.kryptonFillPanel.Size = new System.Drawing.Size(769, 174); this.kryptonFillPanel.TabIndex = 1; // // kryptonPanel1 // this.kryptonPanel1.Controls.Add(this.kryptonLabelExplain); this.kryptonPanel1.Controls.Add(this.kryptonLabelTitle); this.kryptonPanel1.Location = new System.Drawing.Point(16, 16); this.kryptonPanel1.Name = "kryptonPanel1"; this.kryptonPanel1.PanelBackStyle = ComponentFactory.Krypton.Toolkit.PaletteBackStyle.PanelAlternate; this.kryptonPanel1.Size = new System.Drawing.Size(335, 101); this.kryptonPanel1.TabIndex = 0; // // kryptonLabelExplain // this.kryptonLabelExplain.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.NormalPanel; this.kryptonLabelExplain.Location = new System.Drawing.Point(8, 36); this.kryptonLabelExplain.Name = "kryptonLabelExplain"; this.kryptonLabelExplain.Size = new System.Drawing.Size(312, 49); this.kryptonLabelExplain.TabIndex = 1; this.kryptonLabelExplain.Values.Text = "The Left gallery shows a standard drop down of all images.\r\nThe Middle gallery pr" + "ovides grouping in the drop down.\r\nThe Right gallery customizes the drop down me" + "nu.\r\n"; // // kryptonLabelTitle // this.kryptonLabelTitle.LabelStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.TitlePanel; this.kryptonLabelTitle.Location = new System.Drawing.Point(8, 8); this.kryptonLabelTitle.Name = "kryptonLabelTitle"; this.kryptonLabelTitle.Size = new System.Drawing.Size(84, 28); this.kryptonLabelTitle.TabIndex = 0; this.kryptonLabelTitle.Values.Text = "Galleries"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(769, 288); this.Controls.Add(this.kryptonFillPanel); this.Controls.Add(this.kryptonRibbon); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(381, 322); this.Name = "Form1"; this.Text = "Ribbon Gallery"; ((System.ComponentModel.ISupportInitialize)(this.kryptonRibbon)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonFillPanel)).EndInit(); this.kryptonFillPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).EndInit(); this.kryptonPanel1.ResumeLayout(false); this.kryptonPanel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private ComponentFactory.Krypton.Ribbon.KryptonRibbon kryptonRibbon; private ComponentFactory.Krypton.Ribbon.KryptonRibbonTab kryptonRibbonTab1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup1; private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonFillPanel; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupTriple kryptonRibbonGroupTriple1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton2; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupButton kryptonRibbonGroupButton3; private System.Windows.Forms.ImageList imageList1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroup kryptonRibbonGroup2; private ComponentFactory.Krypton.Ribbon.KryptonGalleryRange kryptonGalleryRange1; private ComponentFactory.Krypton.Ribbon.KryptonGalleryRange kryptonGalleryRange2; private ComponentFactory.Krypton.Ribbon.KryptonGalleryRange kryptonGalleryRange3; private ComponentFactory.Krypton.Ribbon.KryptonGalleryRange kryptonGalleryRange4; private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager1; private ComponentFactory.Krypton.Toolkit.KryptonContextMenuItem kryptonContextMenuItem1; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupGallery galleryNormal; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupGallery galleryRanges; private ComponentFactory.Krypton.Ribbon.KryptonGalleryRange kryptonGalleryRange5; private ComponentFactory.Krypton.Ribbon.KryptonGalleryRange kryptonGalleryRange6; private ComponentFactory.Krypton.Ribbon.KryptonGalleryRange kryptonGalleryRange7; private ComponentFactory.Krypton.Ribbon.KryptonRibbonGroupGallery galleryCustom; private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanel1; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabelExplain; private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabelTitle; } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MGTK.EventArguments; using MGTK.Services; namespace MGTK.Controls { public class TrackBar : Control { private TrackBarOrientation orientation; public int TickFrequency = 1; public TickStyle tickStyle = TickStyle.BottomRight; public int SmallChange = 1; public int LargeChange = 5; public int minimum = 0; public int maximum = 10; private int _value; private int sliderSize = 11; private int tickSize = 4; protected Button btnSlider; private bool mouseDown = false; private int sbPosWhenMouseDown = 0; private int mousePosWhenMouseDown = 0; private int valueWhenMouseDown = 0; private double TotalMilliseconds = 0; private int MsToNextIndex = 150; private double LastUpdateIndexChange; public int Value { get { return _value; } set { _value = value; CapValue(); SetSliderPosAccordingToValue(); if (ValueChanged != null) ValueChanged(this, new EventArgs()); } } public int Minimum { get { return minimum; } set { minimum = value; CapValue(); } } public int Maximum { get { return maximum; } set { maximum = value; CapValue(); } } public TrackBarOrientation Orientation { get { return orientation; } set { orientation = value; ConfigureSlider(); } } public TickStyle TickStyle { get { return tickStyle; } set { tickStyle = value; ConfigureSlider(); } } public int TickSize { get { return tickSize; } set { tickSize = value; ConfigureSlider(); } } public DrawTickRoutine AlternativeTickDraw; public event EventHandler ValueChanged; public TrackBar(Form formowner) : base(formowner) { btnSlider = new Button(formowner); btnSlider.Parent = this; btnSlider.MouseLeftPressed += new EventHandler(btnSlider_MouseLeftPressed); btnSlider.Frame = btnSlider.FramePressed = Theme.SliderButtonFrame; btnSlider.KeyDown += new ControlKeyEventHandler(TrackBar_KeyDown); Controls.Add(btnSlider); this.WidthChanged += new EventHandler(TrackBar_SizeChanged); this.HeightChanged += new EventHandler(TrackBar_SizeChanged); this.KeyDown += new ControlKeyEventHandler(TrackBar_KeyDown); this.MouseLeftDown += new EventHandler(TrackBar_MouseLeftDown); ConfigureSlider(); } int ChangeValueMouseDown; bool mouseDownLargeChange = false; void TrackBar_MouseLeftDown(object sender, EventArgs e) { if (gameTime.TotalGameTime.TotalMilliseconds - LastUpdateIndexChange > MsToNextIndex) { if (!mouseDownLargeChange) { if (Orientation == TrackBarOrientation.Horizontal) { if (WindowManager.MouseX < OwnerX + X + btnSlider.X) ChangeValueMouseDown = -LargeChange; else if (WindowManager.MouseX > OwnerX + X + btnSlider.X + btnSlider.Width) ChangeValueMouseDown = LargeChange; } else if (Orientation == TrackBarOrientation.Vertical) { if (WindowManager.MouseY < OwnerY + Y + btnSlider.Y) ChangeValueMouseDown = LargeChange; else if (WindowManager.MouseY > OwnerY + Y + btnSlider.Y + btnSlider.Height) ChangeValueMouseDown = -LargeChange; } mouseDownLargeChange = true; } if (Orientation == TrackBarOrientation.Horizontal) { if (WindowManager.MouseX < OwnerX + X + btnSlider.X && ChangeValueMouseDown < 0) Value += ChangeValueMouseDown; else if (WindowManager.MouseX > OwnerX + X + btnSlider.X + btnSlider.Width && ChangeValueMouseDown > 0) Value += ChangeValueMouseDown; } else if (Orientation == TrackBarOrientation.Vertical) { if (WindowManager.MouseY < OwnerY + Y + btnSlider.Y && ChangeValueMouseDown > 0) Value += ChangeValueMouseDown; else if (WindowManager.MouseY > OwnerY + Y + btnSlider.Y + btnSlider.Height && ChangeValueMouseDown < 0) Value += ChangeValueMouseDown; } LastUpdateIndexChange = gameTime.TotalGameTime.TotalMilliseconds; } } void TrackBar_KeyDown(object sender, ControlKeyEventArgs e) { if (gameTime.TotalGameTime.TotalMilliseconds - LastUpdateIndexChange > MsToNextIndex) { if ((e.Key == Keys.Down && Orientation == TrackBarOrientation.Vertical) || (e.Key == Keys.Up && Orientation == TrackBarOrientation.Horizontal) || e.Key == Keys.Left) Value--; else if ((e.Key == Keys.Up && Orientation == TrackBarOrientation.Vertical) || (e.Key == Keys.Down && Orientation == TrackBarOrientation.Horizontal) || e.Key == Keys.Right) Value++; else if (e.Key == Keys.PageDown && Orientation == TrackBarOrientation.Vertical) Value -= LargeChange; else if (e.Key == Keys.PageUp && Orientation == TrackBarOrientation.Vertical) Value += LargeChange; else if (e.Key == Keys.PageDown && Orientation == TrackBarOrientation.Horizontal) Value += LargeChange; else if (e.Key == Keys.PageUp && Orientation == TrackBarOrientation.Horizontal) Value -= LargeChange; LastUpdateIndexChange = gameTime.TotalGameTime.TotalMilliseconds; } } void TrackBar_SizeChanged(object sender, EventArgs e) { ConfigureSlider(); } private void CapValue() { if (Value < minimum) Value = minimum; if (Value > maximum) Value = maximum; } void btnSlider_MouseLeftPressed(object sender, EventArgs e) { if (!mouseDown) { sbPosWhenMouseDown = GetTickPos(Value - Minimum); mousePosWhenMouseDown = GetWindowManagerMousePos(); valueWhenMouseDown = Value; mouseDown = true; } } public override void Update() { TotalMilliseconds = gameTime.TotalGameTime.TotalMilliseconds; if (!WindowManager.MouseLeftPressed) { mouseDown = false; mouseDownLargeChange = false; } if (mouseDown) { int mSub; if (Orientation == TrackBarOrientation.Horizontal) mSub = GetWindowManagerMousePos() - mousePosWhenMouseDown; else mSub = mousePosWhenMouseDown - GetWindowManagerMousePos(); Value = (int)(valueWhenMouseDown + (mSub + sliderSize / 2) / GetTickIntervalSize()); } base.Update(); } public override void Draw() { btnSlider.Z = Z - 0.001f; if (TickStyle != TickStyle.None) { for (int i = 0; i < Maximum - Minimum + 1; i++) { DrawTick(i); } } if (Orientation == TrackBarOrientation.Horizontal) DrawingService.DrawFrame(spriteBatch, Theme.SliderBarFrame, OwnerX + X, OwnerY + Y + Height / 2 - 2, Width, 4, Z - 0.000001f); else DrawingService.DrawFrame(spriteBatch, Theme.SliderBarFrame, OwnerX + X + Width / 2 - 2, OwnerY + Y, 4, Height, Z - 0.000001f); base.Draw(); } protected void DrawTick(int i) { if (AlternativeTickDraw != null) { AlternativeTickDraw(i); return; } int tX = 0, tY = 0; int tW = 0, tH = 0; if (TickStyle == TickStyle.BottomRight || TickStyle == TickStyle.Both) { if (Orientation == TrackBarOrientation.Horizontal) { tX = GetTickPos(i); tY = Height - TickSize; tW = 1; tH = TickSize; } else { tX = Width - TickSize; tY = GetTickPos(i); tW = TickSize; tH = 1; } DrawingService.DrawRectangle(spriteBatch, Theme.Dot, ForeColor, OwnerX + X + tX, OwnerY + Y + tY, tW, tH, Z - 0.00001f); } if (TickStyle == TickStyle.TopLeft || TickStyle == TickStyle.Both) { if (Orientation == TrackBarOrientation.Horizontal) { tX = GetTickPos(i); tY = 0; tW = 1; tH = TickSize; } else { tX = 0; tY = GetTickPos(i); tW = TickSize; tH = 1; } DrawingService.DrawRectangle(spriteBatch, Theme.Dot, ForeColor, OwnerX + X + tX, OwnerY + Y + tY, tW, tH, Z - 0.00001f); } } private void ConfigureSlider() { btnSlider.X = 0; btnSlider.Y = 0; if (Orientation == TrackBarOrientation.Horizontal) { btnSlider.Width = sliderSize; if (TickStyle == TickStyle.None) btnSlider.Height = Height; else if (TickStyle == TickStyle.BottomRight || TickStyle == TickStyle.TopLeft) btnSlider.Height = Height - TickSize - 1; else if (TickStyle == TickStyle.Both) { btnSlider.Y = TickSize + 1; btnSlider.Height = Height - TickSize * 2 - 2; } if (TickStyle == TickStyle.TopLeft) btnSlider.Y = TickSize + 1; } else { btnSlider.Height = sliderSize; if (TickStyle == TickStyle.None) btnSlider.Width = Width; else if (TickStyle == TickStyle.BottomRight || TickStyle == TickStyle.TopLeft) btnSlider.Width = Width - TickSize - 1; else if (TickStyle == TickStyle.Both) { btnSlider.X = TickSize + 1; btnSlider.Width = Width - TickSize * 2 - 2; } if (TickStyle == TickStyle.TopLeft) btnSlider.X = TickSize + 1; } SetSliderPosAccordingToValue(); } private void SetSliderPosAccordingToValue() { if (Orientation == TrackBarOrientation.Horizontal) btnSlider.X = GetTickPos(Value - Minimum) - btnSlider.Width / 2; else btnSlider.Y = Height - GetTickPos(Value - Minimum) + btnSlider.Height / 2 - (Height - (Maximum - Minimum) * GetTickIntervalSize()); } private int GetTickIntervalSize() { int tIS = (int)((GetControlSize() - sliderSize) / (decimal)(Maximum - Minimum)); if (tIS <= 0) tIS = 1; return tIS; } private int GetControlSize() { if (Orientation == TrackBarOrientation.Horizontal) return Width; return Height; } private int GetWindowManagerMousePos() { if (Orientation == TrackBarOrientation.Horizontal) return WindowManager.MouseX; return WindowManager.MouseY; } private int GetTickPos(int position) { return GetTickIntervalSize() * position + sliderSize / 2; } } public delegate void DrawTickRoutine(int i); public enum TrackBarOrientation { Horizontal = 0, Vertical = 1 } public enum TickStyle { None = 0, TopLeft = 1, BottomRight = 2, Both = 3 } }
// <copyright file="Baggage.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Linq; using OpenTelemetry.Context; using OpenTelemetry.Internal; namespace OpenTelemetry { /// <summary> /// Baggage implementation. /// </summary> /// <remarks> /// Spec reference: <a href="https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/baggage/api.md">Baggage API</a>. /// </remarks> public readonly struct Baggage : IEquatable<Baggage> { private static readonly RuntimeContextSlot<BaggageHolder> RuntimeContextSlot = RuntimeContext.RegisterSlot<BaggageHolder>("otel.baggage"); private static readonly Dictionary<string, string> EmptyBaggage = new Dictionary<string, string>(); private readonly Dictionary<string, string> baggage; /// <summary> /// Initializes a new instance of the <see cref="Baggage"/> struct. /// </summary> /// <param name="baggage">Baggage key/value pairs.</param> internal Baggage(Dictionary<string, string> baggage) { this.baggage = baggage; } /// <summary> /// Gets or sets the current <see cref="Baggage"/>. /// </summary> /// <remarks> /// Note: <see cref="Current"/> returns a forked version of the current /// Baggage. Changes to the forked version will not automatically be /// reflected back on <see cref="Current"/>. To update <see /// cref="Current"/> either use one of the static methods that target /// <see cref="Current"/> as the default source or set <see /// cref="Current"/> to a new instance of <see cref="Baggage"/>. /// Examples: /// <code> /// Baggage.SetBaggage("newKey1", "newValue1"); // Updates Baggage.Current with 'newKey1' /// Baggage.SetBaggage("newKey2", "newValue2"); // Updates Baggage.Current with 'newKey2' /// </code> /// Or: /// <code> /// var baggageCopy = Baggage.Current; /// Baggage.SetBaggage("newKey1", "newValue1"); // Updates Baggage.Current with 'newKey1' /// var newBaggage = baggageCopy /// .SetBaggage("newKey2", "newValue2"); /// .SetBaggage("newKey3", "newValue3"); /// // Sets Baggage.Current to 'newBaggage' which will override any /// // changes made to Baggage.Current after the copy was made. For example /// // the 'newKey1' change is lost. /// Baggage.Current = newBaggage; /// </code> /// </remarks> public static Baggage Current { get => RuntimeContextSlot.Get()?.Baggage ?? default; set => EnsureBaggageHolder().Baggage = value; } /// <summary> /// Gets the number of key/value pairs in the baggage. /// </summary> public int Count => this.baggage?.Count ?? 0; /// <summary> /// Compare two entries of <see cref="Baggage"/> for equality. /// </summary> /// <param name="left">First Entry to compare.</param> /// <param name="right">Second Entry to compare.</param> public static bool operator ==(Baggage left, Baggage right) => left.Equals(right); /// <summary> /// Compare two entries of <see cref="Baggage"/> for not equality. /// </summary> /// <param name="left">First Entry to compare.</param> /// <param name="right">Second Entry to compare.</param> public static bool operator !=(Baggage left, Baggage right) => !(left == right); /// <summary> /// Create a <see cref="Baggage"/> instance from dictionary of baggage key/value pairs. /// </summary> /// <param name="baggageItems">Baggage key/value pairs.</param> /// <returns><see cref="Baggage"/>.</returns> public static Baggage Create(Dictionary<string, string> baggageItems = null) { if (baggageItems == null) { return default; } Dictionary<string, string> baggageCopy = new Dictionary<string, string>(baggageItems.Count, StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, string> baggageItem in baggageItems) { if (string.IsNullOrEmpty(baggageItem.Value)) { baggageCopy.Remove(baggageItem.Key); continue; } baggageCopy[baggageItem.Key] = baggageItem.Value; } return new Baggage(baggageCopy); } /// <summary> /// Returns the name/value pairs in the <see cref="Baggage"/>. /// </summary> /// <param name="baggage">Optional <see cref="Baggage"/>. <see cref="Current"/> is used if not specified.</param> /// <returns>Baggage key/value pairs.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "This was agreed on to be the friendliest API surface")] public static IReadOnlyDictionary<string, string> GetBaggage(Baggage baggage = default) => baggage == default ? Current.GetBaggage() : baggage.GetBaggage(); /// <summary> /// Returns an enumerator that iterates through the <see cref="Baggage"/>. /// </summary> /// <param name="baggage">Optional <see cref="Baggage"/>. <see cref="Current"/> is used if not specified.</param> /// <returns><see cref="Dictionary{TKey, TValue}.Enumerator"/>.</returns> public static Dictionary<string, string>.Enumerator GetEnumerator(Baggage baggage = default) => baggage == default ? Current.GetEnumerator() : baggage.GetEnumerator(); /// <summary> /// Returns the value associated with the given name, or <see langword="null"/> if the given name is not present. /// </summary> /// <param name="name">Baggage item name.</param> /// <param name="baggage">Optional <see cref="Baggage"/>. <see cref="Current"/> is used if not specified.</param> /// <returns>Baggage item or <see langword="null"/> if nothing was found.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "This was agreed on to be the friendliest API surface")] public static string GetBaggage(string name, Baggage baggage = default) => baggage == default ? Current.GetBaggage(name) : baggage.GetBaggage(name); /// <summary> /// Returns a new <see cref="Baggage"/> which contains the new key/value pair. /// </summary> /// <param name="name">Baggage item name.</param> /// <param name="value">Baggage item value.</param> /// <param name="baggage">Optional <see cref="Baggage"/>. <see cref="Current"/> is used if not specified.</param> /// <returns>New <see cref="Baggage"/> containing the key/value pair.</returns> /// <remarks>Note: The <see cref="Baggage"/> returned will be set as the new <see cref="Current"/> instance.</remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "This was agreed on to be the friendliest API surface")] public static Baggage SetBaggage(string name, string value, Baggage baggage = default) { var baggageHolder = EnsureBaggageHolder(); lock (baggageHolder) { return baggageHolder.Baggage = baggage == default ? baggageHolder.Baggage.SetBaggage(name, value) : baggage.SetBaggage(name, value); } } /// <summary> /// Returns a new <see cref="Baggage"/> which contains the new key/value pair. /// </summary> /// <param name="baggageItems">Baggage key/value pairs.</param> /// <param name="baggage">Optional <see cref="Baggage"/>. <see cref="Current"/> is used if not specified.</param> /// <returns>New <see cref="Baggage"/> containing the key/value pair.</returns> /// <remarks>Note: The <see cref="Baggage"/> returned will be set as the new <see cref="Current"/> instance.</remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "This was agreed on to be the friendliest API surface")] public static Baggage SetBaggage(IEnumerable<KeyValuePair<string, string>> baggageItems, Baggage baggage = default) { var baggageHolder = EnsureBaggageHolder(); lock (baggageHolder) { return baggageHolder.Baggage = baggage == default ? baggageHolder.Baggage.SetBaggage(baggageItems) : baggage.SetBaggage(baggageItems); } } /// <summary> /// Returns a new <see cref="Baggage"/> with the key/value pair removed. /// </summary> /// <param name="name">Baggage item name.</param> /// <param name="baggage">Optional <see cref="Baggage"/>. <see cref="Current"/> is used if not specified.</param> /// <returns>New <see cref="Baggage"/> containing the key/value pair.</returns> /// <remarks>Note: The <see cref="Baggage"/> returned will be set as the new <see cref="Current"/> instance.</remarks> public static Baggage RemoveBaggage(string name, Baggage baggage = default) { var baggageHolder = EnsureBaggageHolder(); lock (baggageHolder) { return baggageHolder.Baggage = baggage == default ? baggageHolder.Baggage.RemoveBaggage(name) : baggage.RemoveBaggage(name); } } /// <summary> /// Returns a new <see cref="Baggage"/> with all the key/value pairs removed. /// </summary> /// <param name="baggage">Optional <see cref="Baggage"/>. <see cref="Current"/> is used if not specified.</param> /// <returns>New <see cref="Baggage"/> containing the key/value pair.</returns> /// <remarks>Note: The <see cref="Baggage"/> returned will be set as the new <see cref="Current"/> instance.</remarks> public static Baggage ClearBaggage(Baggage baggage = default) { var baggageHolder = EnsureBaggageHolder(); lock (baggageHolder) { return baggageHolder.Baggage = baggage == default ? baggageHolder.Baggage.ClearBaggage() : baggage.ClearBaggage(); } } /// <summary> /// Returns the name/value pairs in the <see cref="Baggage"/>. /// </summary> /// <returns>Baggage key/value pairs.</returns> public IReadOnlyDictionary<string, string> GetBaggage() => this.baggage ?? EmptyBaggage; /// <summary> /// Returns the value associated with the given name, or <see langword="null"/> if the given name is not present. /// </summary> /// <param name="name">Baggage item name.</param> /// <returns>Baggage item or <see langword="null"/> if nothing was found.</returns> public string GetBaggage(string name) { Guard.ThrowIfNullOrEmpty(name); return this.baggage != null && this.baggage.TryGetValue(name, out string value) ? value : null; } /// <summary> /// Returns a new <see cref="Baggage"/> which contains the new key/value pair. /// </summary> /// <param name="name">Baggage item name.</param> /// <param name="value">Baggage item value.</param> /// <returns>New <see cref="Baggage"/> containing the key/value pair.</returns> public Baggage SetBaggage(string name, string value) { if (string.IsNullOrEmpty(value)) { return this.RemoveBaggage(name); } return new Baggage( new Dictionary<string, string>(this.baggage ?? EmptyBaggage, StringComparer.OrdinalIgnoreCase) { [name] = value, }); } /// <summary> /// Returns a new <see cref="Baggage"/> which contains the new key/value pair. /// </summary> /// <param name="baggageItems">Baggage key/value pairs.</param> /// <returns>New <see cref="Baggage"/> containing the key/value pair.</returns> public Baggage SetBaggage(params KeyValuePair<string, string>[] baggageItems) => this.SetBaggage((IEnumerable<KeyValuePair<string, string>>)baggageItems); /// <summary> /// Returns a new <see cref="Baggage"/> which contains the new key/value pair. /// </summary> /// <param name="baggageItems">Baggage key/value pairs.</param> /// <returns>New <see cref="Baggage"/> containing the key/value pair.</returns> public Baggage SetBaggage(IEnumerable<KeyValuePair<string, string>> baggageItems) { if (baggageItems?.Any() != true) { return this; } var newBaggage = new Dictionary<string, string>(this.baggage ?? EmptyBaggage, StringComparer.OrdinalIgnoreCase); foreach (var item in baggageItems) { if (string.IsNullOrEmpty(item.Value)) { newBaggage.Remove(item.Key); } else { newBaggage[item.Key] = item.Value; } } return new Baggage(newBaggage); } /// <summary> /// Returns a new <see cref="Baggage"/> with the key/value pair removed. /// </summary> /// <param name="name">Baggage item name.</param> /// <returns>New <see cref="Baggage"/> containing the key/value pair.</returns> public Baggage RemoveBaggage(string name) { var baggage = new Dictionary<string, string>(this.baggage ?? EmptyBaggage, StringComparer.OrdinalIgnoreCase); baggage.Remove(name); return new Baggage(baggage); } /// <summary> /// Returns a new <see cref="Baggage"/> with all the key/value pairs removed. /// </summary> /// <returns>New <see cref="Baggage"/> containing the key/value pair.</returns> public Baggage ClearBaggage() => default; /// <summary> /// Returns an enumerator that iterates through the <see cref="Baggage"/>. /// </summary> /// <returns><see cref="Dictionary{TKey, TValue}.Enumerator"/>.</returns> public Dictionary<string, string>.Enumerator GetEnumerator() => (this.baggage ?? EmptyBaggage).GetEnumerator(); /// <inheritdoc/> public bool Equals(Baggage other) { bool baggageIsNullOrEmpty = this.baggage == null || this.baggage.Count <= 0; if (baggageIsNullOrEmpty != (other.baggage == null || other.baggage.Count <= 0)) { return false; } return baggageIsNullOrEmpty || this.baggage.SequenceEqual(other.baggage); } /// <inheritdoc/> public override bool Equals(object obj) => (obj is Baggage baggage) && this.Equals(baggage); /// <inheritdoc/> public override int GetHashCode() { var baggage = this.baggage ?? EmptyBaggage; unchecked { int res = 17; foreach (var item in baggage) { res = (res * 23) + baggage.Comparer.GetHashCode(item.Key); res = (res * 23) + item.Value.GetHashCode(); } return res; } } private static BaggageHolder EnsureBaggageHolder() { var baggageHolder = RuntimeContextSlot.Get(); if (baggageHolder == null) { baggageHolder = new BaggageHolder(); RuntimeContextSlot.Set(baggageHolder); } return baggageHolder; } private class BaggageHolder { public Baggage Baggage; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.Runtime; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; namespace System.IdentityModel { internal static class SecurityUtils { public const string Identities = "Identities"; private static IIdentity s_anonymousIdentity; // these should be kept in sync with IIS70 public const string AuthTypeNTLM = "NTLM"; public const string AuthTypeNegotiate = "Negotiate"; public const string AuthTypeKerberos = "Kerberos"; public const string AuthTypeAnonymous = ""; public const string AuthTypeCertMap = "SSL/PCT"; // mapped from a cert public const string AuthTypeBasic = "Basic"; //LogonUser internal static IIdentity AnonymousIdentity { get { if (s_anonymousIdentity == null) { s_anonymousIdentity = SecurityUtils.CreateIdentity(string.Empty); } return s_anonymousIdentity; } } public static DateTime MaxUtcDateTime { get { // + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow. return new DateTime(DateTime.MaxValue.Ticks - TimeSpan.TicksPerDay, DateTimeKind.Utc); } } public static DateTime MinUtcDateTime { get { // + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow. return new DateTime(DateTime.MinValue.Ticks + TimeSpan.TicksPerDay, DateTimeKind.Utc); } } internal static IIdentity CreateIdentity(string name, string authenticationType) { return new GenericIdentity(name, authenticationType); } internal static IIdentity CreateIdentity(string name) { return new GenericIdentity(name); } internal static byte[] CloneBuffer(byte[] buffer) { return CloneBuffer(buffer, 0, buffer.Length); } internal static byte[] CloneBuffer(byte[] buffer, int offset, int len) { DiagnosticUtility.DebugAssert(offset >= 0, "Negative offset passed to CloneBuffer."); DiagnosticUtility.DebugAssert(len >= 0, "Negative len passed to CloneBuffer."); DiagnosticUtility.DebugAssert(buffer.Length - offset >= len, "Invalid parameters to CloneBuffer."); byte[] copy = Fx.AllocateByteArray(len); Buffer.BlockCopy(buffer, offset, copy, 0, len); return copy; } internal static bool MatchesBuffer(byte[] src, byte[] dst) { return MatchesBuffer(src, 0, dst, 0); } internal static bool MatchesBuffer(byte[] src, int srcOffset, byte[] dst, int dstOffset) { DiagnosticUtility.DebugAssert(dstOffset >= 0, "Negative dstOffset passed to MatchesBuffer."); DiagnosticUtility.DebugAssert(srcOffset >= 0, "Negative srcOffset passed to MatchesBuffer."); // defensive programming if ((dstOffset < 0) || (srcOffset < 0)) return false; if (src == null || srcOffset >= src.Length) return false; if (dst == null || dstOffset >= dst.Length) return false; if ((src.Length - srcOffset) != (dst.Length - dstOffset)) return false; for (int i = srcOffset, j = dstOffset; i < src.Length; i++, j++) { if (src[i] != dst[j]) return false; } return true; } internal static ReadOnlyCollection<IAuthorizationPolicy> CreateAuthorizationPolicies(ClaimSet claimSet) { return CreateAuthorizationPolicies(claimSet, SecurityUtils.MaxUtcDateTime); } internal static ReadOnlyCollection<IAuthorizationPolicy> CreateAuthorizationPolicies(ClaimSet claimSet, DateTime expirationTime) { List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1); policies.Add(new UnconditionalPolicy(claimSet, expirationTime)); return policies.AsReadOnly(); } internal static AuthorizationContext CreateDefaultAuthorizationContext(IList<IAuthorizationPolicy> authorizationPolicies) { AuthorizationContext _authorizationContext; // This is faster than Policy evaluation. if (authorizationPolicies != null && authorizationPolicies.Count == 1 && authorizationPolicies[0] is UnconditionalPolicy) { _authorizationContext = new SimpleAuthorizationContext(authorizationPolicies); } // degenerate case else if (authorizationPolicies == null || authorizationPolicies.Count <= 0) { return DefaultAuthorizationContext.Empty; } else { // there are some policies, run them until they are all done DefaultEvaluationContext evaluationContext = new DefaultEvaluationContext(); object[] policyState = new object[authorizationPolicies.Count]; object done = new object(); int oldContextCount; do { oldContextCount = evaluationContext.Generation; for (int i = 0; i < authorizationPolicies.Count; i++) { if (policyState[i] == done) continue; IAuthorizationPolicy policy = authorizationPolicies[i]; if (policy == null) { policyState[i] = done; continue; } if (policy.Evaluate(evaluationContext, ref policyState[i])) { policyState[i] = done; } } } while (oldContextCount < evaluationContext.Generation); _authorizationContext = new DefaultAuthorizationContext(evaluationContext); } return _authorizationContext; } internal static string ClaimSetToString(ClaimSet claimSet) { StringBuilder sb = new StringBuilder(); sb.AppendLine("ClaimSet ["); for (int i = 0; i < claimSet.Count; i++) { Claim claim = claimSet[i]; if (claim != null) { sb.Append(" "); sb.AppendLine(claim.ToString()); } } string prefix = "] by "; ClaimSet issuer = claimSet; do { issuer = issuer.Issuer; sb.AppendFormat("{0}{1}", prefix, issuer == claimSet ? "Self" : (issuer.Count <= 0 ? "Unknown" : issuer[0].ToString())); prefix = " -> "; } while (issuer.Issuer != issuer); return sb.ToString(); } internal static IIdentity CloneIdentityIfNecessary(IIdentity identity) { if (identity != null) { throw ExceptionHelper.PlatformNotSupported(); } return identity; } internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid) { return CloneWindowsIdentityIfNecessary(wid, wid.AuthenticationType); } internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid, string authenticationType) { if (wid != null) { IntPtr token = wid.AccessToken.DangerousGetHandle(); if (token != null) { return UnsafeCreateWindowsIdentityFromToken(token, authenticationType); } } return wid; } private static IntPtr UnsafeGetWindowsIdentityToken(WindowsIdentity wid) { return wid.AccessToken.DangerousGetHandle(); } private static WindowsIdentity UnsafeCreateWindowsIdentityFromToken(IntPtr token, string authenticationType) { if (authenticationType != null) { return new WindowsIdentity(token, authenticationType); } else { return new WindowsIdentity(token); } } internal static ClaimSet CloneClaimSetIfNecessary(ClaimSet claimSet) { if (claimSet != null) { throw ExceptionHelper.PlatformNotSupported(); } return claimSet; } internal static ReadOnlyCollection<ClaimSet> CloneClaimSetsIfNecessary(ReadOnlyCollection<ClaimSet> claimSets) { throw ExceptionHelper.PlatformNotSupported(); } internal static void DisposeClaimSetIfNecessary(ClaimSet claimSet) { throw ExceptionHelper.PlatformNotSupported(); } internal static void DisposeClaimSetsIfNecessary(ReadOnlyCollection<ClaimSet> claimSets) { throw ExceptionHelper.PlatformNotSupported(); } internal static string GetCertificateId(X509Certificate2 certificate) { StringBuilder str = new StringBuilder(256); AppendCertificateIdentityName(str, certificate); return str.ToString(); } internal static void AppendCertificateIdentityName(StringBuilder str, X509Certificate2 certificate) { string value = certificate.SubjectName.Name; if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.DnsName, false); if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.SimpleName, false); if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.EmailName, false); if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.UpnName, false); } } } } // Same format as X509Identity str.Append(String.IsNullOrEmpty(value) ? "<x509>" : value); str.Append("; "); str.Append(certificate.Thumbprint); } internal static ReadOnlyCollection<IAuthorizationPolicy> CloneAuthorizationPoliciesIfNecessary(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies) { if (authorizationPolicies != null && authorizationPolicies.Count > 0) { bool clone = false; for (int i = 0; i < authorizationPolicies.Count; ++i) { UnconditionalPolicy policy = authorizationPolicies[i] as UnconditionalPolicy; if (policy != null && policy.IsDisposable) { clone = true; break; } } if (clone) { List<IAuthorizationPolicy> ret = new List<IAuthorizationPolicy>(authorizationPolicies.Count); for (int i = 0; i < authorizationPolicies.Count; ++i) { UnconditionalPolicy policy = authorizationPolicies[i] as UnconditionalPolicy; if (policy != null) { ret.Add(policy.Clone()); } else { ret.Add(authorizationPolicies[i]); } } return new ReadOnlyCollection<IAuthorizationPolicy>(ret); } } return authorizationPolicies; } public static void DisposeAuthorizationPoliciesIfNecessary(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies) { if (authorizationPolicies != null && authorizationPolicies.Count > 0) { for (int i = 0; i < authorizationPolicies.Count; ++i) { DisposeIfNecessary(authorizationPolicies[i] as UnconditionalPolicy); } } } public static void DisposeIfNecessary(IDisposable obj) { if (obj != null) { obj.Dispose(); } } // This is the workaround, Since store.Certificates returns a full collection // of certs in store. These are holding native resources. internal static void ResetAllCertificates(X509Certificate2Collection certificates) { if (certificates != null) { for (int i = 0; i < certificates.Count; ++i) { ResetCertificate(certificates[i]); } } } internal static void ResetCertificate(X509Certificate2 certificate) { // Check that Dispose() and Reset() do the same thing certificate.Dispose(); } } internal static class EmptyReadOnlyCollection<T> { public static ReadOnlyCollection<T> Instance = new ReadOnlyCollection<T>(new List<T>()); } internal class SimpleAuthorizationContext : AuthorizationContext { private SecurityUniqueId _id; private UnconditionalPolicy _policy; private IDictionary<string, object> _properties; public SimpleAuthorizationContext(IList<IAuthorizationPolicy> authorizationPolicies) { _policy = (UnconditionalPolicy)authorizationPolicies[0]; Dictionary<string, object> properties = new Dictionary<string, object>(); if (_policy.PrimaryIdentity != null && _policy.PrimaryIdentity != SecurityUtils.AnonymousIdentity) { List<IIdentity> identities = new List<IIdentity>(); identities.Add(_policy.PrimaryIdentity); properties.Add(SecurityUtils.Identities, identities); } _properties = properties; } public override string Id { get { if (_id == null) _id = SecurityUniqueId.Create(); return _id.Value; } } public override ReadOnlyCollection<ClaimSet> ClaimSets { get { return _policy.Issuances; } } public override DateTime ExpirationTime { get { return _policy.ExpirationTime; } } public override IDictionary<string, object> Properties { get { return _properties; } } } }
namespace Projections { 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.m_tabControl = new System.Windows.Forms.TabControl(); this.m_geocentricTabPage = new System.Windows.Forms.TabPage(); this.m_geodesicTabPage = new System.Windows.Forms.TabPage(); this.m_localCartesianPage = new System.Windows.Forms.TabPage(); this.m_albersPage = new System.Windows.Forms.TabPage(); this.m_typeIIProjections = new System.Windows.Forms.TabPage(); this.m_typeIIIProjPage = new System.Windows.Forms.TabPage(); this.m_polarStereoPage = new System.Windows.Forms.TabPage(); this.m_sphericalPage = new System.Windows.Forms.TabPage(); this.m_ellipticPage = new System.Windows.Forms.TabPage(); this.m_ellipsoidPage = new System.Windows.Forms.TabPage(); this.m_miscPage = new System.Windows.Forms.TabPage(); this.m_geoidPage = new System.Windows.Forms.TabPage(); this.m_gravityPage = new System.Windows.Forms.TabPage(); this.m_magneticPage = new System.Windows.Forms.TabPage(); this.m_polyPage = new System.Windows.Forms.TabPage(); this.m_accumPage = new System.Windows.Forms.TabPage(); this.m_tabControl.SuspendLayout(); this.SuspendLayout(); // // m_tabControl // this.m_tabControl.Controls.Add(this.m_geocentricTabPage); this.m_tabControl.Controls.Add(this.m_geodesicTabPage); this.m_tabControl.Controls.Add(this.m_localCartesianPage); this.m_tabControl.Controls.Add(this.m_albersPage); this.m_tabControl.Controls.Add(this.m_typeIIProjections); this.m_tabControl.Controls.Add(this.m_typeIIIProjPage); this.m_tabControl.Controls.Add(this.m_polarStereoPage); this.m_tabControl.Controls.Add(this.m_sphericalPage); this.m_tabControl.Controls.Add(this.m_ellipticPage); this.m_tabControl.Controls.Add(this.m_ellipsoidPage); this.m_tabControl.Controls.Add(this.m_miscPage); this.m_tabControl.Controls.Add(this.m_geoidPage); this.m_tabControl.Controls.Add(this.m_gravityPage); this.m_tabControl.Controls.Add(this.m_magneticPage); this.m_tabControl.Controls.Add(this.m_polyPage); this.m_tabControl.Controls.Add(this.m_accumPage); this.m_tabControl.Dock = System.Windows.Forms.DockStyle.Fill; this.m_tabControl.Location = new System.Drawing.Point(0, 0); this.m_tabControl.Name = "m_tabControl"; this.m_tabControl.SelectedIndex = 0; this.m_tabControl.ShowToolTips = true; this.m_tabControl.Size = new System.Drawing.Size(944, 262); this.m_tabControl.TabIndex = 0; // // m_geocentricTabPage // this.m_geocentricTabPage.Location = new System.Drawing.Point(4, 22); this.m_geocentricTabPage.Name = "m_geocentricTabPage"; this.m_geocentricTabPage.Size = new System.Drawing.Size(936, 236); this.m_geocentricTabPage.TabIndex = 1; this.m_geocentricTabPage.Text = "Geocentric"; this.m_geocentricTabPage.UseVisualStyleBackColor = true; // // m_geodesicTabPage // this.m_geodesicTabPage.Location = new System.Drawing.Point(4, 22); this.m_geodesicTabPage.Name = "m_geodesicTabPage"; this.m_geodesicTabPage.Padding = new System.Windows.Forms.Padding(3); this.m_geodesicTabPage.Size = new System.Drawing.Size(936, 236); this.m_geodesicTabPage.TabIndex = 0; this.m_geodesicTabPage.Text = "Geodesic"; this.m_geodesicTabPage.ToolTipText = "Geodesic, GeodesicExact, GeodesicLine, & GeodesicLineExact"; this.m_geodesicTabPage.UseVisualStyleBackColor = true; // // m_localCartesianPage // this.m_localCartesianPage.Location = new System.Drawing.Point(4, 22); this.m_localCartesianPage.Name = "m_localCartesianPage"; this.m_localCartesianPage.Size = new System.Drawing.Size(936, 236); this.m_localCartesianPage.TabIndex = 2; this.m_localCartesianPage.Text = "LocalCartesian"; this.m_localCartesianPage.UseVisualStyleBackColor = true; // // m_albersPage // this.m_albersPage.Location = new System.Drawing.Point(4, 22); this.m_albersPage.Name = "m_albersPage"; this.m_albersPage.Size = new System.Drawing.Size(936, 236); this.m_albersPage.TabIndex = 3; this.m_albersPage.Text = "Type I Projections"; this.m_albersPage.ToolTipText = "Albers Equal Area, Lambert Conformal Conic, Transverse Mercator, and Transverse M" + "ercator Exact Projections"; this.m_albersPage.UseVisualStyleBackColor = true; // // m_typeIIProjections // this.m_typeIIProjections.Location = new System.Drawing.Point(4, 22); this.m_typeIIProjections.Name = "m_typeIIProjections"; this.m_typeIIProjections.Size = new System.Drawing.Size(936, 236); this.m_typeIIProjections.TabIndex = 4; this.m_typeIIProjections.Text = "Type II Projections"; this.m_typeIIProjections.ToolTipText = "Azimuth Equidistant, Cassini Soldner, and Gnomonic Projections"; this.m_typeIIProjections.UseVisualStyleBackColor = true; // // m_typeIIIProjPage // this.m_typeIIIProjPage.Location = new System.Drawing.Point(4, 22); this.m_typeIIIProjPage.Name = "m_typeIIIProjPage"; this.m_typeIIIProjPage.Size = new System.Drawing.Size(936, 236); this.m_typeIIIProjPage.TabIndex = 11; this.m_typeIIIProjPage.Text = "Type III Projections"; this.m_typeIIIProjPage.ToolTipText = "MGRS/OSGB/UTMUPS"; this.m_typeIIIProjPage.UseVisualStyleBackColor = true; // // m_polarStereoPage // this.m_polarStereoPage.Location = new System.Drawing.Point(4, 22); this.m_polarStereoPage.Name = "m_polarStereoPage"; this.m_polarStereoPage.Size = new System.Drawing.Size(936, 236); this.m_polarStereoPage.TabIndex = 5; this.m_polarStereoPage.Text = "Polar Stereographic"; this.m_polarStereoPage.UseVisualStyleBackColor = true; // // m_sphericalPage // this.m_sphericalPage.Location = new System.Drawing.Point(4, 22); this.m_sphericalPage.Name = "m_sphericalPage"; this.m_sphericalPage.Size = new System.Drawing.Size(936, 236); this.m_sphericalPage.TabIndex = 6; this.m_sphericalPage.Text = "Spherical Harmonics"; this.m_sphericalPage.ToolTipText = "Spherical Harmonic, Spherical Harmonic 1, and Spherical Harmonic 2"; this.m_sphericalPage.UseVisualStyleBackColor = true; // // m_ellipticPage // this.m_ellipticPage.Location = new System.Drawing.Point(4, 22); this.m_ellipticPage.Name = "m_ellipticPage"; this.m_ellipticPage.Size = new System.Drawing.Size(936, 236); this.m_ellipticPage.TabIndex = 7; this.m_ellipticPage.Text = "Elliptic Function"; this.m_ellipticPage.UseVisualStyleBackColor = true; // // m_ellipsoidPage // this.m_ellipsoidPage.Location = new System.Drawing.Point(4, 22); this.m_ellipsoidPage.Name = "m_ellipsoidPage"; this.m_ellipsoidPage.Size = new System.Drawing.Size(936, 236); this.m_ellipsoidPage.TabIndex = 8; this.m_ellipsoidPage.Text = "Ellipsoid"; this.m_ellipsoidPage.UseVisualStyleBackColor = true; // // m_miscPage // this.m_miscPage.Location = new System.Drawing.Point(4, 22); this.m_miscPage.Name = "m_miscPage"; this.m_miscPage.Size = new System.Drawing.Size(936, 236); this.m_miscPage.TabIndex = 9; this.m_miscPage.Text = "Miscellaneous"; this.m_miscPage.ToolTipText = "DDS/Geohash"; this.m_miscPage.UseVisualStyleBackColor = true; // // m_geoidPage // this.m_geoidPage.Location = new System.Drawing.Point(4, 22); this.m_geoidPage.Name = "m_geoidPage"; this.m_geoidPage.Size = new System.Drawing.Size(936, 236); this.m_geoidPage.TabIndex = 10; this.m_geoidPage.Text = "Geoid"; this.m_geoidPage.UseVisualStyleBackColor = true; // // m_gravityPage // this.m_gravityPage.Location = new System.Drawing.Point(4, 22); this.m_gravityPage.Name = "m_gravityPage"; this.m_gravityPage.Size = new System.Drawing.Size(936, 236); this.m_gravityPage.TabIndex = 12; this.m_gravityPage.Text = "Gravity"; this.m_gravityPage.ToolTipText = "GravityModel/GravityCircle/NormalGravity"; this.m_gravityPage.UseVisualStyleBackColor = true; // // m_magneticPage // this.m_magneticPage.Location = new System.Drawing.Point(4, 22); this.m_magneticPage.Name = "m_magneticPage"; this.m_magneticPage.Size = new System.Drawing.Size(936, 236); this.m_magneticPage.TabIndex = 13; this.m_magneticPage.Text = "Magnetic"; this.m_magneticPage.ToolTipText = "MagneticModel/MagneticCircle"; this.m_magneticPage.UseVisualStyleBackColor = true; // // m_polyPage // this.m_polyPage.Location = new System.Drawing.Point(4, 22); this.m_polyPage.Name = "m_polyPage"; this.m_polyPage.Size = new System.Drawing.Size(936, 236); this.m_polyPage.TabIndex = 14; this.m_polyPage.Text = "PolygonArea"; this.m_polyPage.UseVisualStyleBackColor = true; // // m_accumPage // this.m_accumPage.Location = new System.Drawing.Point(4, 22); this.m_accumPage.Name = "m_accumPage"; this.m_accumPage.Size = new System.Drawing.Size(936, 236); this.m_accumPage.TabIndex = 15; this.m_accumPage.Text = "Accumulator"; this.m_accumPage.UseVisualStyleBackColor = true; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(944, 262); this.Controls.Add(this.m_tabControl); this.Name = "Form1"; this.Text = "Projections"; this.m_tabControl.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabControl m_tabControl; private System.Windows.Forms.TabPage m_geodesicTabPage; private System.Windows.Forms.TabPage m_geocentricTabPage; private System.Windows.Forms.TabPage m_localCartesianPage; private System.Windows.Forms.TabPage m_albersPage; private System.Windows.Forms.TabPage m_typeIIProjections; private System.Windows.Forms.TabPage m_polarStereoPage; private System.Windows.Forms.TabPage m_sphericalPage; private System.Windows.Forms.TabPage m_ellipticPage; private System.Windows.Forms.TabPage m_ellipsoidPage; private System.Windows.Forms.TabPage m_miscPage; private System.Windows.Forms.TabPage m_geoidPage; private System.Windows.Forms.TabPage m_typeIIIProjPage; private System.Windows.Forms.TabPage m_gravityPage; private System.Windows.Forms.TabPage m_magneticPage; private System.Windows.Forms.TabPage m_polyPage; private System.Windows.Forms.TabPage m_accumPage; } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * 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.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IWarehouseDocumentApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Search warehouseDocuments by filter /// </summary> /// <remarks> /// Returns the list of warehouseDocuments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;WarehouseDocument&gt;</returns> List<WarehouseDocument> GetWarehouseDocumentByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search warehouseDocuments by filter /// </summary> /// <remarks> /// Returns the list of warehouseDocuments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;WarehouseDocument&gt;</returns> ApiResponse<List<WarehouseDocument>> GetWarehouseDocumentByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a warehouseDocument by id /// </summary> /// <remarks> /// Returns the warehouseDocument identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseDocumentId">Id of the warehouseDocument to be returned.</param> /// <returns>WarehouseDocument</returns> WarehouseDocument GetWarehouseDocumentById (int? warehouseDocumentId); /// <summary> /// Get a warehouseDocument by id /// </summary> /// <remarks> /// Returns the warehouseDocument identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseDocumentId">Id of the warehouseDocument to be returned.</param> /// <returns>ApiResponse of WarehouseDocument</returns> ApiResponse<WarehouseDocument> GetWarehouseDocumentByIdWithHttpInfo (int? warehouseDocumentId); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Search warehouseDocuments by filter /// </summary> /// <remarks> /// Returns the list of warehouseDocuments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;WarehouseDocument&gt;</returns> System.Threading.Tasks.Task<List<WarehouseDocument>> GetWarehouseDocumentByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search warehouseDocuments by filter /// </summary> /// <remarks> /// Returns the list of warehouseDocuments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;WarehouseDocument&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<WarehouseDocument>>> GetWarehouseDocumentByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a warehouseDocument by id /// </summary> /// <remarks> /// Returns the warehouseDocument identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseDocumentId">Id of the warehouseDocument to be returned.</param> /// <returns>Task of WarehouseDocument</returns> System.Threading.Tasks.Task<WarehouseDocument> GetWarehouseDocumentByIdAsync (int? warehouseDocumentId); /// <summary> /// Get a warehouseDocument by id /// </summary> /// <remarks> /// Returns the warehouseDocument identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseDocumentId">Id of the warehouseDocument to be returned.</param> /// <returns>Task of ApiResponse (WarehouseDocument)</returns> System.Threading.Tasks.Task<ApiResponse<WarehouseDocument>> GetWarehouseDocumentByIdAsyncWithHttpInfo (int? warehouseDocumentId); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class WarehouseDocumentApi : IWarehouseDocumentApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="WarehouseDocumentApi"/> class. /// </summary> /// <returns></returns> public WarehouseDocumentApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="WarehouseDocumentApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public WarehouseDocumentApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Search warehouseDocuments by filter Returns the list of warehouseDocuments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;WarehouseDocument&gt;</returns> public List<WarehouseDocument> GetWarehouseDocumentByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<WarehouseDocument>> localVarResponse = GetWarehouseDocumentByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search warehouseDocuments by filter Returns the list of warehouseDocuments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;WarehouseDocument&gt;</returns> public ApiResponse< List<WarehouseDocument> > GetWarehouseDocumentByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/warehouseDocument/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWarehouseDocumentByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<WarehouseDocument>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<WarehouseDocument>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<WarehouseDocument>))); } /// <summary> /// Search warehouseDocuments by filter Returns the list of warehouseDocuments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;WarehouseDocument&gt;</returns> public async System.Threading.Tasks.Task<List<WarehouseDocument>> GetWarehouseDocumentByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<WarehouseDocument>> localVarResponse = await GetWarehouseDocumentByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search warehouseDocuments by filter Returns the list of warehouseDocuments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;WarehouseDocument&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<WarehouseDocument>>> GetWarehouseDocumentByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/warehouseDocument/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWarehouseDocumentByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<WarehouseDocument>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<WarehouseDocument>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<WarehouseDocument>))); } /// <summary> /// Get a warehouseDocument by id Returns the warehouseDocument identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseDocumentId">Id of the warehouseDocument to be returned.</param> /// <returns>WarehouseDocument</returns> public WarehouseDocument GetWarehouseDocumentById (int? warehouseDocumentId) { ApiResponse<WarehouseDocument> localVarResponse = GetWarehouseDocumentByIdWithHttpInfo(warehouseDocumentId); return localVarResponse.Data; } /// <summary> /// Get a warehouseDocument by id Returns the warehouseDocument identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseDocumentId">Id of the warehouseDocument to be returned.</param> /// <returns>ApiResponse of WarehouseDocument</returns> public ApiResponse< WarehouseDocument > GetWarehouseDocumentByIdWithHttpInfo (int? warehouseDocumentId) { // verify the required parameter 'warehouseDocumentId' is set if (warehouseDocumentId == null) throw new ApiException(400, "Missing required parameter 'warehouseDocumentId' when calling WarehouseDocumentApi->GetWarehouseDocumentById"); var localVarPath = "/v1.0/warehouseDocument/{warehouseDocumentId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (warehouseDocumentId != null) localVarPathParams.Add("warehouseDocumentId", Configuration.ApiClient.ParameterToString(warehouseDocumentId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWarehouseDocumentById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<WarehouseDocument>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (WarehouseDocument) Configuration.ApiClient.Deserialize(localVarResponse, typeof(WarehouseDocument))); } /// <summary> /// Get a warehouseDocument by id Returns the warehouseDocument identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseDocumentId">Id of the warehouseDocument to be returned.</param> /// <returns>Task of WarehouseDocument</returns> public async System.Threading.Tasks.Task<WarehouseDocument> GetWarehouseDocumentByIdAsync (int? warehouseDocumentId) { ApiResponse<WarehouseDocument> localVarResponse = await GetWarehouseDocumentByIdAsyncWithHttpInfo(warehouseDocumentId); return localVarResponse.Data; } /// <summary> /// Get a warehouseDocument by id Returns the warehouseDocument identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseDocumentId">Id of the warehouseDocument to be returned.</param> /// <returns>Task of ApiResponse (WarehouseDocument)</returns> public async System.Threading.Tasks.Task<ApiResponse<WarehouseDocument>> GetWarehouseDocumentByIdAsyncWithHttpInfo (int? warehouseDocumentId) { // verify the required parameter 'warehouseDocumentId' is set if (warehouseDocumentId == null) throw new ApiException(400, "Missing required parameter 'warehouseDocumentId' when calling WarehouseDocumentApi->GetWarehouseDocumentById"); var localVarPath = "/v1.0/warehouseDocument/{warehouseDocumentId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (warehouseDocumentId != null) localVarPathParams.Add("warehouseDocumentId", Configuration.ApiClient.ParameterToString(warehouseDocumentId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWarehouseDocumentById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<WarehouseDocument>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (WarehouseDocument) Configuration.ApiClient.Deserialize(localVarResponse, typeof(WarehouseDocument))); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Controls.GridView.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls { public partial class GridView : ViewBase, System.Windows.Markup.IAddChild { #region Methods and constructors protected virtual new void AddChild(Object column) { } protected virtual new void AddText(string text) { } protected internal override void ClearItem(ListViewItem item) { } protected internal override System.Windows.Automation.Peers.IViewAutomationPeer GetAutomationPeer(ListView parent) { return default(System.Windows.Automation.Peers.IViewAutomationPeer); } public static GridViewColumnCollection GetColumnCollection(System.Windows.DependencyObject element) { return default(GridViewColumnCollection); } public GridView() { } protected internal override void PrepareItem(ListViewItem item) { } public static void SetColumnCollection(System.Windows.DependencyObject element, GridViewColumnCollection collection) { } public static bool ShouldSerializeColumnCollection(System.Windows.DependencyObject obj) { return default(bool); } void System.Windows.Markup.IAddChild.AddChild(Object column) { } void System.Windows.Markup.IAddChild.AddText(string text) { } #endregion #region Properties and indexers public bool AllowsColumnReorder { get { return default(bool); } set { } } public System.Windows.Style ColumnHeaderContainerStyle { get { return default(System.Windows.Style); } set { } } public ContextMenu ColumnHeaderContextMenu { get { return default(ContextMenu); } set { } } public string ColumnHeaderStringFormat { get { return default(string); } set { } } public System.Windows.DataTemplate ColumnHeaderTemplate { get { return default(System.Windows.DataTemplate); } set { } } public DataTemplateSelector ColumnHeaderTemplateSelector { get { return default(DataTemplateSelector); } set { } } public Object ColumnHeaderToolTip { get { return default(Object); } set { } } public GridViewColumnCollection Columns { get { Contract.Ensures(Contract.Result<System.Windows.Controls.GridViewColumnCollection>() != null); return default(GridViewColumnCollection); } } internal protected override Object DefaultStyleKey { get { return default(Object); } } public static System.Windows.ResourceKey GridViewItemContainerStyleKey { get { Contract.Ensures(Contract.Result<System.Windows.ResourceKey>() != null); return default(System.Windows.ResourceKey); } } public static System.Windows.ResourceKey GridViewScrollViewerStyleKey { get { Contract.Ensures(Contract.Result<System.Windows.ResourceKey>() != null); return default(System.Windows.ResourceKey); } } public static System.Windows.ResourceKey GridViewStyleKey { get { Contract.Ensures(Contract.Result<System.Windows.ResourceKey>() != null); return default(System.Windows.ResourceKey); } } internal protected override Object ItemContainerDefaultStyleKey { get { return default(Object); } } #endregion #region Fields public readonly static System.Windows.DependencyProperty AllowsColumnReorderProperty; public readonly static System.Windows.DependencyProperty ColumnCollectionProperty; public readonly static System.Windows.DependencyProperty ColumnHeaderContainerStyleProperty; public readonly static System.Windows.DependencyProperty ColumnHeaderContextMenuProperty; public readonly static System.Windows.DependencyProperty ColumnHeaderStringFormatProperty; public readonly static System.Windows.DependencyProperty ColumnHeaderTemplateProperty; public readonly static System.Windows.DependencyProperty ColumnHeaderTemplateSelectorProperty; public readonly static System.Windows.DependencyProperty ColumnHeaderToolTipProperty; #endregion } }
#region License // // Copyright (c) 2018, Fluent Migrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Linq; using System.Reflection; using FluentMigrator.Expressions; using FluentMigrator.Runner; using FluentMigrator.Runner.Initialization; using FluentMigrator.Runner.Processors; using FluentMigrator.Runner.VersionTableInfo; using Moq; using NUnit.Framework; using Shouldly; namespace FluentMigrator.Tests.Unit { [TestFixture] [Obsolete] public class ObsoleteVersionLoaderTests { [Test] public void CanLoadCustomVersionTableMetaData() { var runnerContext = new Mock<IRunnerContext>(); var runner = new Mock<IMigrationRunner>(); runner.SetupGet(r => r.Processor.Options).Returns(new ProcessorOptions()); runner.SetupGet(r => r.RunnerContext).Returns(runnerContext.Object); var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new VersionLoader(runner.Object, asm, ConventionSets.NoSchemaName, conventions, runnerContext.Object); var versionTableMetaData = loader.GetVersionTableMetaData(); versionTableMetaData.ShouldBeOfType<TestVersionTableMetaData>(); } [Test] public void CanLoadDefaultVersionTableMetaData() { var runnerContext = new Mock<IRunnerContext>(); var runner = new Mock<IMigrationRunner>(); runner.SetupGet(r => r.Processor.Options).Returns(new ProcessorOptions()); runner.SetupGet(r => r.RunnerContext).Returns(runnerContext.Object); var conventions = new MigrationRunnerConventions(); var asm = "s".GetType().Assembly; var loader = new VersionLoader(runner.Object, asm, ConventionSets.NoSchemaName, conventions, runnerContext.Object); var versionTableMetaData = loader.GetVersionTableMetaData(); versionTableMetaData.ShouldBeOfType<DefaultVersionTableMetaData>(); } [Test] [Obsolete("Use dependency injection to access 'application state'.")] public void CanSetupApplicationContext() { var applicationContext = "Test context"; var runnerContext = new Mock<IRunnerContext>(); runnerContext.SetupGet(r => r.ApplicationContext).Returns(applicationContext); var runner = new Mock<IMigrationRunner>(); runner.SetupGet(r => r.Processor.Options).Returns(new ProcessorOptions()); runner.SetupGet(r => r.RunnerContext).Returns(runnerContext.Object); var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new VersionLoader(runner.Object, asm, ConventionSets.NoSchemaName, conventions, runnerContext.Object); var versionTableMetaData = loader.GetVersionTableMetaData(); versionTableMetaData.ApplicationContext.ShouldBe(applicationContext); } [Test] public void DeleteVersionShouldExecuteDeleteDataExpression() { var runnerContext = new Mock<IRunnerContext>(); var processor = new Mock<IMigrationProcessor>(); var runner = new Mock<IMigrationRunner>(); runner.SetupGet(r => r.Processor).Returns(processor.Object); runner.SetupGet(r => r.RunnerContext).Returns(runnerContext.Object); var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new VersionLoader(runner.Object, asm, ConventionSets.NoSchemaName, conventions, runnerContext.Object); processor.Setup(p => p.Process(It.Is<DeleteDataExpression>(expression => expression.SchemaName == loader.VersionTableMetaData.SchemaName && expression.TableName == loader.VersionTableMetaData.TableName && expression.Rows.All( definition => definition.All( pair => pair.Key == loader.VersionTableMetaData.ColumnName && pair.Value.Equals(1L)))))) .Verifiable(); loader.DeleteVersion(1); processor.VerifyAll(); } [Test] public void RemoveVersionTableShouldBehaveAsExpected() { var runnerContext = new Mock<IRunnerContext>(); var processor = new Mock<IMigrationProcessor>(); var runner = new Mock<IMigrationRunner>(); runner.SetupGet(r => r.Processor).Returns(processor.Object); runner.SetupGet(r => r.RunnerContext).Returns(runnerContext.Object); var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new VersionLoader(runner.Object, asm, ConventionSets.NoSchemaName, conventions, runnerContext.Object); processor.Setup(p => p.Process(It.Is<DeleteTableExpression>(expression => expression.SchemaName == loader.VersionTableMetaData.SchemaName && expression.TableName == loader.VersionTableMetaData.TableName))) .Verifiable(); processor.Setup(p => p.Process(It.Is<DeleteSchemaExpression>(expression => expression.SchemaName == loader.VersionTableMetaData.SchemaName))) .Verifiable(); loader.RemoveVersionTable(); processor.VerifyAll(); } [Test] public void RemoveVersionTableShouldNotRemoveSchemaIfItDidNotOwnTheSchema() { var runnerContext = new Mock<IRunnerContext>(); var processor = new Mock<IMigrationProcessor>(); var runner = new Mock<IMigrationRunner>(); runner.SetupGet(r => r.Processor).Returns(processor.Object); runner.SetupGet(r => r.RunnerContext).Returns(runnerContext.Object); var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new VersionLoader(runner.Object, asm, ConventionSets.NoSchemaName, conventions, runnerContext.Object); ((TestVersionTableMetaData) loader.VersionTableMetaData).OwnsSchema = false; processor.Setup(p => p.Process(It.Is<DeleteTableExpression>(expression => expression.SchemaName == loader.VersionTableMetaData.SchemaName && expression.TableName == loader.VersionTableMetaData.TableName))) .Verifiable(); loader.RemoveVersionTable(); processor.Verify(p => p.Process(It.IsAny<DeleteSchemaExpression>()), Times.Never()); } [Test] public void UpdateVersionShouldExecuteInsertDataExpression() { var runnerContext = new Mock<IRunnerContext>(); var processor = new Mock<IMigrationProcessor>(); var runner = new Mock<IMigrationRunner>(); runner.SetupGet(r => r.Processor).Returns(processor.Object); runner.SetupGet(r => r.RunnerContext).Returns(runnerContext.Object); var conventions = new MigrationRunnerConventions(); var asm = Assembly.GetExecutingAssembly(); var loader = new VersionLoader(runner.Object, asm, ConventionSets.NoSchemaName, conventions, runnerContext.Object); processor.Setup(p => p.Process(It.Is<InsertDataExpression>(expression => expression.SchemaName == loader.VersionTableMetaData.SchemaName && expression.TableName == loader.VersionTableMetaData.TableName && expression.Rows.Any( definition => definition.Any( pair => pair.Key == loader.VersionTableMetaData.ColumnName && pair.Value.Equals(1L)))))) .Verifiable(); loader.UpdateVersionInfo(1); processor.VerifyAll(); } [Test] public void VersionSchemaMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse() { var runnerContext = new Mock<IRunnerContext>(); var conventions = new MigrationRunnerConventions(); var processor = new Mock<IMigrationProcessor>(); var runner = new Mock<IMigrationRunner>(); var asm = Assembly.GetExecutingAssembly(); runner.SetupGet(r => r.Processor).Returns(processor.Object); runner.SetupGet(r => r.RunnerContext).Returns(runnerContext.Object); processor.Setup(p => p.SchemaExists(It.IsAny<string>())).Returns(false); var loader = new VersionLoader(runner.Object, asm, ConventionSets.NoSchemaName, conventions, runnerContext.Object); loader.LoadVersionInfo(); runner.Verify(r => r.Up(loader.VersionSchemaMigration), Times.Once()); } [Test] public void VersionMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse() { var runnerContext = new Mock<IRunnerContext>(); var conventions = new MigrationRunnerConventions(); var processor = new Mock<IMigrationProcessor>(); var runner = new Mock<IMigrationRunner>(); var asm = Assembly.GetExecutingAssembly(); runner.SetupGet(r => r.Processor).Returns(processor.Object); runner.SetupGet(r => r.RunnerContext).Returns(runnerContext.Object); processor.Setup(p => p.TableExists(new TestVersionTableMetaData().SchemaName, TestVersionTableMetaData.TABLE_NAME)).Returns(false); var loader = new VersionLoader(runner.Object, asm, ConventionSets.NoSchemaName, conventions, runnerContext.Object); loader.LoadVersionInfo(); runner.Verify(r => r.Up(loader.VersionMigration), Times.Once()); } [Test] public void VersionUniqueMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse() { var runnerContext = new Mock<IRunnerContext>(); var conventions = new MigrationRunnerConventions(); var processor = new Mock<IMigrationProcessor>(); var runner = new Mock<IMigrationRunner>(); var asm = Assembly.GetExecutingAssembly(); runner.SetupGet(r => r.Processor).Returns(processor.Object); runner.SetupGet(r => r.RunnerContext).Returns(runnerContext.Object); processor.Setup(p => p.ColumnExists(new TestVersionTableMetaData().SchemaName, TestVersionTableMetaData.TABLE_NAME, TestVersionTableMetaData.APPLIED_ON_COLUMN_NAME)).Returns(false); var loader = new VersionLoader(runner.Object, asm, ConventionSets.NoSchemaName, conventions, runnerContext.Object); loader.LoadVersionInfo(); runner.Verify(r => r.Up(loader.VersionUniqueMigration), Times.Once()); } [Test] public void VersionDescriptionMigrationOnlyRunOnceEvenIfExistenceChecksReturnFalse() { var runnerContext = new Mock<IRunnerContext>(); var conventions = new MigrationRunnerConventions(); var processor = new Mock<IMigrationProcessor>(); var runner = new Mock<IMigrationRunner>(); var asm = Assembly.GetExecutingAssembly(); runner.SetupGet(r => r.Processor).Returns(processor.Object); runner.SetupGet(r => r.RunnerContext).Returns(runnerContext.Object); processor.Setup(p => p.ColumnExists(new TestVersionTableMetaData().SchemaName, TestVersionTableMetaData.TABLE_NAME, TestVersionTableMetaData.APPLIED_ON_COLUMN_NAME)).Returns(false); var loader = new VersionLoader(runner.Object, asm, ConventionSets.NoSchemaName, conventions, runnerContext.Object); loader.LoadVersionInfo(); runner.Verify(r => r.Up(loader.VersionDescriptionMigration), Times.Once()); } } }
// 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 DivideScalarSingle() { var test = new SimpleBinaryOpTest__DivideScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.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 (Sse.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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__DivideScalarSingle { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int Op2ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static SimpleBinaryOpTest__DivideScalarSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__DivideScalarSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.DivideScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.DivideScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.DivideScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.DivideScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.DivideScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.DivideScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.DivideScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.DivideScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.DivideScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.DivideScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__DivideScalarSingle(); var result = Sse.DivideScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.DivideScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(left[0] / right[0]) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.DivideScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core.Logging; using Umbraco.Core.Models.EntityBase; namespace Umbraco.Core.Cache { /// <summary> /// The default cache policy for retrieving a single entity /// </summary> /// <typeparam name="TEntity"></typeparam> /// <typeparam name="TId"></typeparam> /// <remarks> /// This cache policy uses sliding expiration and caches instances for 5 minutes. However if allow zero count is true, then we use the /// default policy with no expiry. /// </remarks> internal class DefaultRepositoryCachePolicy<TEntity, TId> : RepositoryCachePolicyBase<TEntity, TId> where TEntity : class, IAggregateRoot { private readonly RepositoryCachePolicyOptions _options; public DefaultRepositoryCachePolicy(IRuntimeCacheProvider cache, RepositoryCachePolicyOptions options) : base(cache) { if (options == null) throw new ArgumentNullException("options"); _options = options; } protected string GetCacheIdKey(object id) { if (id == null) throw new ArgumentNullException("id"); return string.Format("{0}{1}", GetCacheTypeKey(), id); } protected string GetCacheTypeKey() { return string.Format("uRepo_{0}_", typeof(TEntity).Name); } public override void CreateOrUpdate(TEntity entity, Action<TEntity> persistMethod) { if (entity == null) throw new ArgumentNullException("entity"); if (persistMethod == null) throw new ArgumentNullException("persistMethod"); try { persistMethod(entity); //set the disposal action SetCacheAction(() => { //just to be safe, we cannot cache an item without an identity if (entity.HasIdentity) { Cache.InsertCacheItem(GetCacheIdKey(entity.Id), () => entity, timeout: TimeSpan.FromMinutes(5), isSliding: true); } //If there's a GetAllCacheAllowZeroCount cache, ensure it is cleared Cache.ClearCacheItem(GetCacheTypeKey()); }); } catch { //set the disposal action SetCacheAction(() => { //if an exception is thrown we need to remove the entry from cache, this is ONLY a work around because of the way // that we cache entities: http://issues.umbraco.org/issue/U4-4259 Cache.ClearCacheItem(GetCacheIdKey(entity.Id)); //If there's a GetAllCacheAllowZeroCount cache, ensure it is cleared Cache.ClearCacheItem(GetCacheTypeKey()); }); throw; } } public override void Remove(TEntity entity, Action<TEntity> persistMethod) { if (entity == null) throw new ArgumentNullException("entity"); if (persistMethod == null) throw new ArgumentNullException("persistMethod"); try { persistMethod(entity); } finally { //set the disposal action var cacheKey = GetCacheIdKey(entity.Id); SetCacheAction(() => { Cache.ClearCacheItem(cacheKey); //If there's a GetAllCacheAllowZeroCount cache, ensure it is cleared Cache.ClearCacheItem(GetCacheTypeKey()); }); } } public override TEntity Get(TId id, Func<TId, TEntity> getFromRepo) { if (getFromRepo == null) throw new ArgumentNullException("getFromRepo"); var cacheKey = GetCacheIdKey(id); var fromCache = Cache.GetCacheItem<TEntity>(cacheKey); if (fromCache != null) return fromCache; var entity = getFromRepo(id); //set the disposal action SetCacheAction(cacheKey, entity); return entity; } public override TEntity Get(TId id) { var cacheKey = GetCacheIdKey(id); return Cache.GetCacheItem<TEntity>(cacheKey); } public override bool Exists(TId id, Func<TId, bool> getFromRepo) { if (getFromRepo == null) throw new ArgumentNullException("getFromRepo"); var cacheKey = GetCacheIdKey(id); var fromCache = Cache.GetCacheItem<TEntity>(cacheKey); return fromCache != null || getFromRepo(id); } public override TEntity[] GetAll(TId[] ids, Func<TId[], IEnumerable<TEntity>> getFromRepo) { if (getFromRepo == null) throw new ArgumentNullException("getFromRepo"); if (ids.Any()) { var entities = ids.Select(Get).ToArray(); if (ids.Length.Equals(entities.Length) && entities.Any(x => x == null) == false) return entities; } else { var allEntities = GetAllFromCache(); if (allEntities.Any()) { if (_options.GetAllCacheValidateCount) { //Get count of all entities of current type (TEntity) to ensure cached result is correct var totalCount = _options.PerformCount(); if (allEntities.Length == totalCount) return allEntities; } else { return allEntities; } } else if (_options.GetAllCacheAllowZeroCount) { //if the repository allows caching a zero count, then check the zero count cache if (HasZeroCountCache()) { //there is a zero count cache so return an empty list return new TEntity[] {}; } } } //we need to do the lookup from the repo var entityCollection = getFromRepo(ids) //ensure we don't include any null refs in the returned collection! .WhereNotNull() .ToArray(); //set the disposal action SetCacheAction(ids, entityCollection); return entityCollection; } /// <summary> /// Looks up the zero count cache, must return null if it doesn't exist /// </summary> /// <returns></returns> protected bool HasZeroCountCache() { var zeroCount = Cache.GetCacheItem<TEntity[]>(GetCacheTypeKey()); return (zeroCount != null && zeroCount.Any() == false); } /// <summary> /// Performs the lookup for all entities of this type from the cache /// </summary> /// <returns></returns> protected TEntity[] GetAllFromCache() { var allEntities = Cache.GetCacheItemsByKeySearch<TEntity>(GetCacheTypeKey()) .WhereNotNull() .ToArray(); return allEntities.Any() ? allEntities : new TEntity[] {}; } /// <summary> /// Sets the action to execute on disposal for a single entity /// </summary> /// <param name="cacheKey"></param> /// <param name="entity"></param> protected virtual void SetCacheAction(string cacheKey, TEntity entity) { if (entity == null) return; SetCacheAction(() => { //just to be safe, we cannot cache an item without an identity if (entity.HasIdentity) { Cache.InsertCacheItem(cacheKey, () => entity, timeout: TimeSpan.FromMinutes(5), isSliding: true); } }); } /// <summary> /// Sets the action to execute on disposal for an entity collection /// </summary> /// <param name="ids"></param> /// <param name="entityCollection"></param> protected virtual void SetCacheAction(TId[] ids, TEntity[] entityCollection) { SetCacheAction(() => { //This option cannot execute if we are looking up specific Ids if (ids.Any() == false && entityCollection.Length == 0 && _options.GetAllCacheAllowZeroCount) { //there was nothing returned but we want to cache a zero count result so add an TEntity[] to the cache // to signify that there is a zero count cache //NOTE: Don't set expiry/sliding for a zero count Cache.InsertCacheItem(GetCacheTypeKey(), () => new TEntity[] {}); } else { //This is the default behavior, we'll individually cache each item so that if/when these items are resolved // by id, they are returned from the already existing cache. foreach (var entity in entityCollection.WhereNotNull()) { var localCopy = entity; //just to be safe, we cannot cache an item without an identity if (localCopy.HasIdentity) { Cache.InsertCacheItem(GetCacheIdKey(entity.Id), () => localCopy, timeout: TimeSpan.FromMinutes(5), isSliding: true); } } } }); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Purpose: This class will encapsulate an uint and ** provide an Object representation of it. ** ** ===========================================================*/ namespace System { using System.Globalization; using System; using System.Runtime; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; // * Wrapper for unsigned 32 bit integers. [Serializable] [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] [System.Runtime.InteropServices.ComVisible(true)] public struct UInt32 : IComparable, IFormattable, IConvertible , IComparable<UInt32>, IEquatable<UInt32> { private uint m_value; public const uint MaxValue = (uint)0xffffffff; public const uint MinValue = 0U; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt32, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is UInt32) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. uint i = (uint)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException(Environment.GetResourceString("Arg_MustBeUInt32")); } public int CompareTo(UInt32 value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(Object obj) { if (!(obj is UInt32)) { return false; } return m_value == ((UInt32)obj).m_value; } [System.Runtime.Versioning.NonVersionable] public bool Equals(UInt32 obj) { return m_value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return ((int) m_value); } // The base 10 representation of the number with no extra padding. [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static uint Parse(String s) { return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static uint Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseUInt32(s, style, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] public static uint Parse(String s, IFormatProvider provider) { return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static uint Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider)); } [CLSCompliant(false)] public static bool TryParse(String s, out UInt32 result) { return Number.TryParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } [CLSCompliant(false)] public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt32 result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.UInt32; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return m_value; } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "UInt32", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed partial class ExpressionBinder { // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- private sealed class ExplicitConversion { private readonly ExpressionBinder _binder; private Expr _exprSrc; private readonly CType _typeSrc; private readonly CType _typeDest; private readonly ExprClass _exprTypeDest; // This is for lambda error reporting. The reason we have this is because we // store errors for lambda conversions, and then we don't bind the conversion // again to report errors. Consider the following case: // // int? x = () => null; // // When we try to convert the lambda to the nullable type int?, we first // attempt the conversion to int. If that fails, then we know there is no // conversion to int?, since int is a predef type. We then look for UserDefined // conversions, and fail. When we report the errors, we ask the lambda for its // conversion errors. But since we attempted its conversion to int and not int?, // we report the wrong error. This field is to keep track of the right type // to report the error on, so that when the lambda conversion fails, it reports // errors on the correct type. private readonly CType _pDestinationTypeForLambdaErrorReporting; private Expr _exprDest; private readonly bool _needsExprDest; private readonly CONVERTTYPE _flags; // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- public ExplicitConversion(ExpressionBinder binder, Expr exprSrc, CType typeSrc, ExprClass typeDest, CType pDestinationTypeForLambdaErrorReporting, bool needsExprDest, CONVERTTYPE flags) { _binder = binder; _exprSrc = exprSrc; _typeSrc = typeSrc; _typeDest = typeDest.Type; _pDestinationTypeForLambdaErrorReporting = pDestinationTypeForLambdaErrorReporting; _exprTypeDest = typeDest; _needsExprDest = needsExprDest; _flags = flags; _exprDest = null; } public Expr ExprDest { get { return _exprDest; } } /* * BindExplicitConversion * * This is a complex routine with complex parameter. Generally, this should * be called through one of the helper methods that insulates you * from the complexity of the interface. This routine handles all the logic * associated with explicit conversions. * * Note that this function calls BindImplicitConversion first, so the main * logic is only concerned with conversions that can be made explicitly, but * not implicitly. */ public bool Bind() { // To test for a standard conversion, call canConvert(exprSrc, typeDest, STANDARDANDCONVERTTYPE.NOUDC) and // canConvert(typeDest, typeSrc, STANDARDANDCONVERTTYPE.NOUDC). Debug.Assert((_flags & CONVERTTYPE.STANDARD) == 0); // 13.2 Explicit conversions // // The following conversions are classified as explicit conversions: // // * All implicit conversions // * Explicit numeric conversions // * Explicit enumeration conversions // * Explicit reference conversions // * Explicit interface conversions // * Unboxing conversions // * Explicit type parameter conversions // * User-defined explicit conversions // * Explicit nullable conversions // * Lifted user-defined explicit conversions // // Explicit conversions can occur in cast expressions (14.6.6). // // The explicit conversions that are not implicit conversions are conversions that cannot be // proven always to succeed, conversions that are known possibly to lose information, and // conversions across domains of types sufficiently different to merit explicit notation. // The set of explicit conversions includes all implicit conversions. // Don't try user-defined conversions now because we'll try them again later. if (_binder.BindImplicitConversion(_exprSrc, _typeSrc, _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.ISEXPLICIT)) { return true; } if (_typeSrc == null || _typeDest == null || _typeSrc is ErrorType || _typeDest is ErrorType || _typeDest.IsNeverSameType()) { return false; } if (_typeDest is NullableType) { // This is handled completely by BindImplicitConversion. return false; } if (_typeSrc is NullableType) { return bindExplicitConversionFromNub(); } if (bindExplicitConversionFromArrayToIList()) { return true; } // if we were casting an integral constant to another constant type, // then, if the constant were in range, then the above call would have succeeded. // But it failed, and so we know that the constant is not in range switch (_typeDest.GetTypeKind()) { default: Debug.Fail($"Bad type kind: {_typeDest.GetTypeKind()}"); return false; case TypeKind.TK_VoidType: return false; // Can't convert to a method group or anon method. case TypeKind.TK_NullType: return false; // Can never convert TO the null type. case TypeKind.TK_TypeParameterType: if (bindExplicitConversionToTypeVar()) { return true; } break; case TypeKind.TK_ArrayType: if (bindExplicitConversionToArray((ArrayType)_typeDest)) { return true; } break; case TypeKind.TK_PointerType: if (bindExplicitConversionToPointer()) { return true; } break; case TypeKind.TK_AggregateType: { AggCastResult result = bindExplicitConversionToAggregate(_typeDest as AggregateType); if (result == AggCastResult.Success) { return true; } if (result == AggCastResult.Abort) { return false; } break; } } // No built-in conversion was found. Maybe a user-defined conversion? if (0 == (_flags & CONVERTTYPE.NOUDC)) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromNub() { Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); // If S and T are value types and there is a builtin conversion from S => T then there is an // explicit conversion from S? => T that throws on null. if (_typeDest.IsValType() && _binder.BindExplicitConversion(null, _typeSrc.StripNubs(), _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _flags | CONVERTTYPE.NOUDC)) { if (_needsExprDest) { Expr valueSrc = _exprSrc; if (valueSrc.Type is NullableType) { valueSrc = _binder.BindNubValue(valueSrc); } Debug.Assert(valueSrc.Type == _typeSrc.StripNubs()); if (!_binder.BindExplicitConversion(valueSrc, valueSrc.Type, _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.NOUDC)) { Debug.Fail("BindExplicitConversion failed unexpectedly"); return false; } if (_exprDest is ExprUserDefinedConversion udc) { udc.Argument = _exprSrc; } } return true; } if ((_flags & CONVERTTYPE.NOUDC) == 0) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromArrayToIList() { // 13.2.2 // // The explicit reference conversions are: // // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and // their base interfaces, provided there is an explicit reference conversion from S to T. Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); if (!(_typeSrc is ArrayType arrSrc) || !arrSrc.IsSZArray || !(_typeDest is AggregateType aggDest) || !aggDest.isInterfaceType() || aggDest.GetTypeArgsAll().Count != 1) { return false; } AggregateSymbol aggIList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !GetSymbolLoader().IsBaseAggregate(aggIList, aggDest.getAggregate())) && (aggIReadOnlyList == null || !GetSymbolLoader().IsBaseAggregate(aggIReadOnlyList, aggDest.getAggregate()))) { return false; } CType typeArr = arrSrc.GetElementType(); CType typeLst = aggDest.GetTypeArgsAll()[0]; if (!CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionToTypeVar() { // 13.2.3 Explicit reference conversions // // For a type-parameter T that is known to be a reference type (25.7), the following // explicit reference conversions exist: // // * From the effective base class C of T to T and from any base class of C to T. // * From any interface-type to T. // * From a type-parameter U to T provided that T depends on U (25.7). Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); // NOTE: for the flags, we have to use EXPRFLAG.EXF_FORCE_UNBOX (not EXPRFLAG.EXF_REFCHECK) even when // we know that the type is a reference type. The verifier expects all code for // type parameters to behave as if the type parameter is a value type. // The jitter should be smart about it.... if (_typeSrc.isInterfaceType() || _binder.canConvert(_typeDest, _typeSrc, CONVERTTYPE.NOUDC)) { if (!_needsExprDest) { return true; } // There is an explicit, possibly unboxing, conversion from Object or any interface to // a type variable. This will involve a type check and possibly an unbox. // There is an explicit conversion from non-interface X to the type var iff there is an // implicit conversion from the type var to X. if (_typeSrc is TypeParameterType) { // Need to box first before unboxing. Expr exprT; ExprClass exprObj = GetExprFactory().CreateClass(_binder.GetPredefindType(PredefinedType.PT_OBJECT)); _binder.bindSimpleCast(_exprSrc, exprObj, out exprT, EXPRFLAG.EXF_FORCE_BOX); _exprSrc = exprT; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_UNBOX); return true; } return false; } private bool bindExplicitConversionFromIListToArray(ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and their base interfaces // to a one-dimensional array-type S[], provided there is an implicit or explicit reference conversion from // S[] to System.Collections.Generic.IList<T> or System.Collections.Generic.IReadOnlyList<T>. This is precisely when either S and T // are the same type or there is an implicit or explicit reference conversion from S to T. if (!arrayDest.IsSZArray || !(_typeSrc is AggregateType aggSrc) || !aggSrc.isInterfaceType() || aggSrc.GetTypeArgsAll().Count != 1) { return false; } AggregateSymbol aggIList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !GetSymbolLoader().IsBaseAggregate(aggIList, aggSrc.getAggregate())) && (aggIReadOnlyList == null || !GetSymbolLoader().IsBaseAggregate(aggIReadOnlyList, aggSrc.getAggregate()))) { return false; } CType typeArr = arrayDest.GetElementType(); CType typeLst = aggSrc.GetTypeArgsAll()[0]; Debug.Assert(!typeArr.IsNeverSameType()); if (typeArr != typeLst && !CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionFromArrayToArray(ArrayType arraySrc, ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From an array-type S with an element type SE to an array-type T with an element type // TE, provided all of the following are true: // // * S and T differ only in element type. (In other words, S and T have the same number // of dimensions.) // // * An explicit reference conversion exists from SE to TE. if (arraySrc.rank != arrayDest.rank || arraySrc.IsSZArray != arrayDest.IsSZArray) { return false; // Ranks do not match. } if (CConversions.FExpRefConv(GetSymbolLoader(), arraySrc.GetElementType(), arrayDest.GetElementType())) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } return false; } private bool bindExplicitConversionToArray(ArrayType arrayDest) { Debug.Assert(_typeSrc != null); Debug.Assert(arrayDest != null); if (_typeSrc is ArrayType arrSrc) { return bindExplicitConversionFromArrayToArray(arrSrc, arrayDest); } if (bindExplicitConversionFromIListToArray(arrayDest)) { return true; } // 13.2.2 // // The explicit reference conversions are: // // * From System.Array and the interfaces it implements, to any array-type. if (_binder.canConvert(_binder.GetPredefindType(PredefinedType.PT_ARRAY), _typeSrc, CONVERTTYPE.NOUDC)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } return false; } private bool bindExplicitConversionToPointer() { // 27.4 Pointer conversions // // in an unsafe context, the set of available explicit conversions (13.2) is extended to // include the following explicit pointer conversions: // // * From any pointer-type to any other pointer-type. // * From sbyte, byte, short, ushort, int, uint, long, or ulong to any pointer-type. if (_typeSrc is PointerType || _typeSrc.fundType() <= FUNDTYPE.FT_LASTINTEGRAL && _typeSrc.isNumericType()) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return true; } return false; } // 13.2.2 Explicit enumeration conversions // // The explicit enumeration conversions are: // // * From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or // decimal to any enum-type. // // * From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, char, // float, double, or decimal. // // * From any enum-type to any other enum-type. // // * An explicit enumeration conversion between two types is processed by treating any // participating enum-type as the underlying type of that enum-type, and then performing // an implicit or explicit numeric conversion between the resulting types. private AggCastResult bindExplicitConversionFromEnumToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.isEnumType()) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (aggDest.isPredefAgg(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromEnumToDecimal(aggTypeDest); } if (!aggDest.getThisType().isNumericType() && !aggDest.IsEnum() && !(aggDest.IsPredefined() && aggDest.GetPredefType() == PredefinedType.PT_CHAR)) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } else if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionFromDecimalToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(_typeSrc.isPredefType(PredefinedType.PT_DECIMAL)); // There is an explicit conversion from decimal to all integral types. if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // All casts from decimal to integer types are bound as user-defined conversions. bool bIsConversionOK = true; if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. CType underlyingType = aggTypeDest.underlyingType(); bIsConversionOK = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, underlyingType, _needsExprDest, out _exprDest, false); if (bIsConversionOK) { // upcast to the Enum type _binder.bindSimpleCast(_exprDest, _exprTypeDest, out _exprDest); } } return bIsConversionOK ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromEnumToDecimal(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); Debug.Assert(aggTypeDest.isPredefType(PredefinedType.PT_DECIMAL)); AggregateType underlyingType = _typeSrc.underlyingType() as AggregateType; // Need to first cast the source expr to its underlying type. Expr exprCast; if (_exprSrc == null) { exprCast = null; } else { ExprClass underlyingExpr = GetExprFactory().CreateClass(underlyingType); _binder.bindSimpleCast(_exprSrc, underlyingExpr, out exprCast); } // There is always an implicit conversion from any integral type to decimal. if (exprCast.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(exprCast, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // Conversions from integral types to decimal are always bound as a user-defined conversion. if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bool ok = _binder.bindUserDefinedConversion(exprCast, underlyingType, aggTypeDest, _needsExprDest, out _exprDest, false); Debug.Assert(ok); } return AggCastResult.Success; } private AggCastResult bindExplicitConversionToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (!aggDest.IsEnum()) { return AggCastResult.Failure; } if (_typeSrc.isPredefType(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromDecimalToEnum(aggTypeDest); } if (_typeSrc.isNumericType() || (_typeSrc.isPredefined() && _typeSrc.getPredefType() == PredefinedType.PT_CHAR)) { // Transform constant to constant. if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } else if (_typeSrc.isPredefined() && (_typeSrc.isPredefType(PredefinedType.PT_OBJECT) || _typeSrc.isPredefType(PredefinedType.PT_VALUE) || _typeSrc.isPredefType(PredefinedType.PT_ENUM))) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenSimpleTypes(AggregateType aggTypeDest) { // 13.2.1 // // Because the explicit conversions include all implicit and explicit numeric conversions, // it is always possible to convert from any numeric-type to any other numeric-type using // a cast expression (14.6.6). Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.isSimpleType() || !aggTypeDest.isSimpleType()) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.getAggregate(); Debug.Assert(_typeSrc.isPredefined() && aggDest.IsPredefined()); PredefinedType ptSrc = _typeSrc.getPredefType(); PredefinedType ptDest = aggDest.GetPredefType(); Debug.Assert((int)ptSrc < NUM_SIMPLE_TYPES && (int)ptDest < NUM_SIMPLE_TYPES); ConvKind convertKind = GetConvKind(ptSrc, ptDest); // Identity and implicit conversions should already have been handled. Debug.Assert(convertKind != ConvKind.Implicit); Debug.Assert(convertKind != ConvKind.Identity); if (convertKind != ConvKind.Explicit) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } bool bConversionOk = true; if (_needsExprDest) { // Explicit conversions involving decimals are bound as user-defined conversions. if (isUserDefinedConversion(ptSrc, ptDest)) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bConversionOk = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, aggTypeDest, _needsExprDest, out _exprDest, false); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, (_flags & CONVERTTYPE.CHECKOVERFLOW) != 0 ? EXPRFLAG.EXF_CHECKOVERFLOW : 0); } } return bConversionOk ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenAggregates(AggregateType aggTypeDest) { // 13.2.3 // // The explicit reference conversions are: // // * From object to any reference-type. // * From any class-type S to any class-type T, provided S is a base class of T. // * From any class-type S to any interface-type T, provided S is not sealed and // provided S does not implement T. // * From any interface-type S to any class-type T, provided T is not sealed or provided // T implements S. // * From any interface-type S to any interface-type T, provided S is not derived from T. Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!(_typeSrc is AggregateType atSrc)) { return AggCastResult.Failure; } AggregateSymbol aggSrc = atSrc.getAggregate(); AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (GetSymbolLoader().HasBaseConversion(aggTypeDest, atSrc)) { if (_needsExprDest) { if (aggDest.IsValueType() && aggSrc.getThisType().fundType() == FUNDTYPE.FT_REF) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc?.Flags & EXPRFLAG.EXF_CANTBENULL ?? 0)); } } return AggCastResult.Success; } if ((aggSrc.IsClass() && !aggSrc.IsSealed() && aggDest.IsInterface()) || (aggSrc.IsInterface() && aggDest.IsClass() && !aggDest.IsSealed()) || (aggSrc.IsInterface() && aggDest.IsInterface()) || CConversions.HasGenericDelegateExplicitReferenceConversion(GetSymbolLoader(), _typeSrc, aggTypeDest)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc?.Flags & EXPRFLAG.EXF_CANTBENULL ?? 0)); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromPointerToInt(AggregateType aggTypeDest) { // 27.4 Pointer conversions // in an unsafe context, the set of available explicit conversions (13.2) is extended to include // the following explicit pointer conversions: // // * From any pointer-type to sbyte, byte, short, ushort, int, uint, long, or ulong. if (!(_typeSrc is PointerType) || aggTypeDest.fundType() > FUNDTYPE.FT_LASTINTEGRAL || !aggTypeDest.isNumericType()) { return AggCastResult.Failure; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionFromTypeVarToAggregate(AggregateType aggTypeDest) { // 13.2.3 Explicit reference conversions // // For a type-parameter T that is known to be a reference type (25.7), the following // explicit reference conversions exist: // // * From T to any interface-type I provided there isn't already an implicit reference // conversion from T to I. if (!(_typeSrc is TypeParameterType)) { return AggCastResult.Failure; } if (aggTypeDest.getAggregate().IsInterface()) { // Explicit conversion of type variables to interfaces. if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_BOX | EXPRFLAG.EXF_REFCHECK); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); AggCastResult result = bindExplicitConversionFromEnumToAggregate(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionToEnum(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenSimpleTypes(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenAggregates(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionFromPointerToInt(aggTypeDest); if (result != AggCastResult.Failure) { return result; } if (_typeSrc is VoidType) { // No conversion is allowed to or from a void type (user defined or otherwise) // This is most likely the result of a failed anonymous method or member group conversion return AggCastResult.Abort; } result = bindExplicitConversionFromTypeVarToAggregate(aggTypeDest); if (result != AggCastResult.Failure) { return result; } return AggCastResult.Failure; } private SymbolLoader GetSymbolLoader() { return _binder.GetSymbolLoader(); } private ExprFactory GetExprFactory() { return _binder.GetExprFactory(); } } } }
// 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.Linq; using System.Collections.Generic; namespace System.Buffers.Text.Tests { // // General purpose raw test data. // internal static partial class TestData { public static readonly IEnumerable<byte> s_precisions = new byte[] { StandardFormat.NoPrecision, 0, 1, 3, 10, StandardFormat.MaxPrecision }; public static IEnumerable<object[]> IntegerTypesTheoryData => IntegerTypes.Select(t => new object[] { t }); public static IEnumerable<Type> IntegerTypes { get { yield return typeof(sbyte); yield return typeof(byte); yield return typeof(short); yield return typeof(ushort); yield return typeof(int); yield return typeof(uint); yield return typeof(long); yield return typeof(ulong); } } public static IEnumerable<bool> BooleanTestData { get { yield return true; yield return false; } } public static IEnumerable<sbyte> SByteTestData { get { foreach (long l in Int64TestData) { if (l >= sbyte.MinValue && l <= sbyte.MaxValue) { yield return (sbyte)l; } } } } public static IEnumerable<byte> ByteTestData { get { foreach (long l in Int64TestData) { if (l >= byte.MinValue && l <= byte.MaxValue) { yield return (byte)l; } } } } public static IEnumerable<short> Int16TestData { get { foreach (long l in Int64TestData) { if (l >= short.MinValue && l <= short.MaxValue) { yield return (short)l; } } } } public static IEnumerable<ushort> UInt16TestData { get { foreach (long l in Int64TestData) { if (l >= ushort.MinValue && l <= ushort.MaxValue) { yield return (ushort)l; } } } } public static IEnumerable<int> Int32TestData { get { foreach (long l in Int64TestData) { if (l >= int.MinValue && l <= int.MaxValue) { yield return (int)l; } } } } public static IEnumerable<uint> UInt32TestData { get { foreach (long l in Int64TestData) { if (l >= uint.MinValue && l <= uint.MaxValue) { yield return (uint)l; } } } } public static IEnumerable<long> Int64TestData { get { yield return 0L; yield return 1L; yield return 123L; yield return -123L; yield return 1234L; yield return -1234L; yield return 12345L; yield return -12345L; yield return 4294967294999999999L; // uint.MaxValue * Billion - 1 yield return 4294967295000000000L; // uint.MaxValue * Billion yield return 4294967295000000001L; // uint.MaxValue * Billion + 1 yield return -4294967294999999999L; // -(uint.MaxValue * Billion - 1) yield return -4294967295000000000L; // -(uint.MaxValue * Billion) yield return -4294967295000000001L; // -(uint.MaxValue * Billion + 1) yield return 4294967296000000000L; // (uint.MaxValue + 1) * Billion yield return -4294967296000000000L; // -(uint.MaxValue + 1) * Billion long powerOf10 = 1L; for (int i = 0; i < 21; i++) { powerOf10 *= 10L; yield return powerOf10 - 1; yield return powerOf10; yield return -(powerOf10 - 1); yield return -powerOf10; } yield return sbyte.MinValue; yield return sbyte.MinValue - 1; yield return sbyte.MinValue + 1; yield return sbyte.MaxValue; yield return sbyte.MaxValue - 1; yield return sbyte.MaxValue + 1; yield return short.MinValue; yield return short.MinValue - 1; yield return short.MinValue + 1; yield return short.MaxValue; yield return short.MaxValue - 1; yield return short.MaxValue + 1; yield return int.MinValue; yield return ((long)int.MinValue) - 1; yield return int.MinValue + 1; yield return int.MaxValue; yield return int.MaxValue - 1; yield return ((long)int.MaxValue) + 1; yield return long.MinValue; yield return long.MinValue + 1; yield return long.MaxValue; yield return long.MaxValue - 1; yield return byte.MaxValue; yield return byte.MaxValue - 1; yield return ushort.MaxValue; yield return ushort.MaxValue - 1; yield return uint.MaxValue; yield return uint.MaxValue - 1; } } public static IEnumerable<ulong> UInt64TestData { get { foreach (long l in Int64TestData) { if (l >= 0) { yield return (ulong)l; } } yield return long.MaxValue + 1LU; yield return ulong.MaxValue - 1LU; yield return ulong.MaxValue; } } public static IEnumerable<decimal> DecimalTestData { get { foreach (long l in Int64TestData) { yield return l; } yield return decimal.MinValue; yield return decimal.MaxValue; // negative 0m. The formatter is expected *not* to emit a minus sign in this case. yield return (new MutableDecimal() { High = 0, Mid = 0, Low = 0, IsNegative = true }).ToDecimal(); yield return 0.304m; // Round down yield return -0.304m; yield return 0.305m; // Round up yield return -0.305m; yield return 999.99m; yield return -999.99m; yield return 0.000123456m; yield return -0.000123456m; // Explicit trailing 0's (Decimal can and does preserve these by setting the Scale appropriately) yield return 1.00m; yield return 0.00m; yield return -1.00m; yield return -0.00m; } } public static IEnumerable<double> DoubleTestData { get { foreach (long l in Int64TestData) { yield return l; } yield return 1.23; } } public static IEnumerable<float> SingleTestData { get { foreach (long d in DoubleTestData) { float f = d; if (!float.IsInfinity(f)) yield return f; } } } public static IEnumerable<Guid> GuidTestData { get { yield return new Guid("CB0AFB61-6F04-401A-BBEA-C0FC0B6E4E51"); yield return new Guid("FC1911F9-9EED-4CA8-AC8B-CEEE1EBE2C72"); } } public static IEnumerable<DateTime> DateTimeTestData { get { { // Kind == Unspecified TimeSpan offset = new TimeSpan(hours: 8, minutes: 0, seconds: 0); DateTimeOffset dto = new DateTimeOffset(year: 2017, month: 1, day: 13, hour: 3, minute: 45, second: 32, offset: offset); yield return dto.DateTime; } { // Kind == Utc TimeSpan offset = new TimeSpan(hours: 8, minutes: 0, seconds: 0); DateTimeOffset dto = new DateTimeOffset(year: 2017, month: 1, day: 13, hour: 3, minute: 45, second: 32, offset: offset); yield return dto.UtcDateTime; } { // Kind == Local TimeSpan offset = new TimeSpan(hours: 8, minutes: 0, seconds: 0); DateTimeOffset dto = new DateTimeOffset(year: 2017, month: 1, day: 13, hour: 3, minute: 45, second: 32, offset: offset); yield return dto.LocalDateTime; } { // Kind == Local TimeSpan offset = new TimeSpan(hours: -9, minutes: 0, seconds: 0); DateTimeOffset dto = new DateTimeOffset(year: 2017, month: 1, day: 13, hour: 3, minute: 45, second: 32, offset: offset); yield return dto.LocalDateTime; } } } public static IEnumerable<DateTimeOffset> DateTimeOffsetTestData { get { yield return DateTimeOffset.MinValue; yield return DateTimeOffset.MaxValue; yield return new DateTimeOffset(year: 2017, month: 1, day: 13, hour: 3, minute: 45, second: 32, new TimeSpan(hours: 8, minutes: 0, seconds: 0)); yield return new DateTimeOffset(year: 2017, month: 1, day: 13, hour: 3, minute: 45, second: 32, new TimeSpan(hours: -8, minutes: 0, seconds: 0)); yield return new DateTimeOffset(year: 2017, month: 12, day: 31, hour: 23, minute: 59, second: 58, new TimeSpan(hours: 14, minutes: 0, seconds: 0)); yield return new DateTimeOffset(year: 2017, month: 12, day: 31, hour: 23, minute: 59, second: 58, new TimeSpan(hours: -14, minutes: 0, seconds: 0)); foreach (PseudoDateTime pseudoDateTime in PseudoDateTimeTestData) { if (pseudoDateTime.ExpectSuccess) { TimeSpan offset = new TimeSpan(hours: pseudoDateTime.OffsetHours, minutes: pseudoDateTime.OffsetMinutes, seconds: 0); if (pseudoDateTime.OffsetNegative) { offset = -offset; } DateTimeOffset dto = new DateTimeOffset(year: pseudoDateTime.Year, month: pseudoDateTime.Month, day: pseudoDateTime.Day, hour: pseudoDateTime.Hour, minute: pseudoDateTime.Minute, second: pseudoDateTime.Second, offset: offset); if (pseudoDateTime.Fraction != 0) { dto += new TimeSpan(ticks: pseudoDateTime.Fraction); } yield return dto; } } } } public static IEnumerable<TimeSpan> TimeSpanTestData { get { yield return TimeSpan.MinValue; yield return TimeSpan.MaxValue; yield return new TimeSpan(ticks: 0); yield return new TimeSpan(ticks: 1); yield return new TimeSpan(ticks: -1); yield return new TimeSpan(ticks: 12345L); yield return new TimeSpan(ticks: -12345L); yield return new TimeSpan(days: 4, hours: 9, minutes: 8, seconds: 6, milliseconds: 0); yield return new TimeSpan(days: -4, hours: 9, minutes: 8, seconds: 6, milliseconds: 0); yield return new TimeSpan(days: 4, hours: 9, minutes: 8, seconds: 6, milliseconds: 5); yield return new TimeSpan(days: -4, hours: 9, minutes: 8, seconds: 6, milliseconds: 5); yield return new TimeSpan(days: 54, hours: 10, minutes: 11, seconds: 12, milliseconds: 13); yield return new TimeSpan(days: -54, hours: 10, minutes: 11, seconds: 12, milliseconds: 13); yield return new TimeSpan(days: 54, hours: 10, minutes: 11, seconds: 12, milliseconds: 999); } } public static IEnumerable<string> NumberTestData { get { yield return ""; yield return "+"; yield return "-"; yield return "0"; yield return "+0"; yield return "-0"; yield return "0.0"; yield return "-0.0"; yield return "123.45"; yield return "+123.45"; yield return "-123.45"; yield return "++123.45"; yield return "--123.45"; yield return "5."; yield return ".6"; yield return "5."; yield return "."; yield return "000000123.45"; yield return "0.000045"; yield return "000000123.000045"; yield return decimal.MinValue.ToString("G"); yield return decimal.MaxValue.ToString("G"); yield return float.MinValue.ToString("G9"); yield return float.MaxValue.ToString("G9"); yield return float.Epsilon.ToString("G9"); yield return double.MinValue.ToString("G17"); yield return double.MaxValue.ToString("G17"); yield return double.Epsilon.ToString("G9"); yield return "1e"; yield return "1e+"; yield return "1e-"; yield return "1e10"; yield return "1e+10"; yield return "1e-10"; yield return "1E10"; yield return "1E+10"; yield return "1E-10"; yield return "1e+9"; yield return "1e-9"; yield return "1e+9"; yield return "1e+90"; yield return "1e-90"; yield return "1e+90"; yield return "1e+400"; yield return "1e-400"; yield return "1e+400"; yield return "-1e+400"; yield return "-1e-400"; yield return "-1e+400"; yield return "1e+/"; yield return "1e/"; yield return "1e-/"; yield return "1e+:"; yield return "1e:"; yield return "1e-:"; yield return "1e"; yield return "1e/"; yield return "1e:"; yield return "0.5555555555555555555555555555555555555555555555555"; yield return "0.66666666666666666666666666665"; yield return "0.6666666666666666666666666666500000000000000000000000000000000000000000000000000000000000000"; yield return "0.6666666666666666666666666666500000000000000000000"; yield return "0.6666666666666666666666666666666666666666666666665"; yield return "0.9999999999999999999999999999999999999999999999999"; // Crazy case that's expected to yield "Decimal.MaxValue / 10" // ( = 7922816251426433759354395034m (= High = 0x19999999, Mid = 0x99999999, Low = 0x9999999A)) // and does thanks to a special overflow code path inside the Number->Decimal converter. yield return "0.79228162514264337593543950335" + "5" + "E28"; // Exercise post-rounding overflow check. yield return "0.79228162514264337593543950335" + "5" + "E29"; // Excercise the 20-digit lookahead inside the rounding logic inside the Number->Decimal converter. yield return "0.222222222222222222222222222255000000000000000000000000000000000000"; // Code coverage for MutableDecimal.DecAdd() yield return "4611686018427387903.752"; // Code coverage: "round X where {Epsilon > X >= 2.470328229206232730000000E-324} up to Epsilon" yield return "2.470328229206232730000000E-324"; // Code coverage: underflow yield return "2.470328229206232730000000E-325"; yield return "3.402823E+38"; //Single.MaxValue yield return "3.402824E+38"; //Just over Single.MaxValue yield return "-3.402823E+38"; //Single.MinValue yield return "-3.402824E+38"; //Just under Single.MinValue yield return "1.79769313486232E+308"; //Double.MaxValue yield return "1.79769313486233E+308"; //Just over Double.MaxValue yield return "-1.79769313486232E+308"; //Double.MinValue yield return "-1.79769313486233E+308"; //Just under Double.MinValue // Ensures that the NumberBuffer capacity is consistent with Desktop's. yield return ".2222222222222222222222222222500000000000000000001"; } } public static IEnumerable<PseudoDateTime> PseudoDateTimeTestData { get { foreach (int year in new int[] { 2000, 2001, 2002, 2003, 2004, 2010, 2012, 2013, 2014, 2, 9999 }) { for (int month = 1; month <= 12; month++) { int daysInMonth = DateTime.DaysInMonth(year: year, month: month); foreach (int day in new int[] { 1, 9, 10, daysInMonth }) { yield return new PseudoDateTime(year: year, month: month, day: day, hour: 3, minute: 15, second: 45, expectSuccess: true); } yield return new PseudoDateTime(year: year, month: month, day: (daysInMonth + 1), hour: 23, minute: 15, second: 45, expectSuccess: false); } } // Test data at the edge of the valid ranges. yield return new PseudoDateTime(year: 1, month: 1, day: 1, hour: 14, minute: 0, second: 0, expectSuccess: true); yield return new PseudoDateTime(year: 9999, month: 12, day: 31, hour: 9, minute: 0, second: 0, expectSuccess: true); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 14, minute: 0, second: 0, expectSuccess: true); yield return new PseudoDateTime(year: 2017, month: 12, day: 1, hour: 14, minute: 0, second: 0, expectSuccess: true); // Day range is month/year dependent. Was already covered above. yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 14, minute: 0, second: 0, expectSuccess: true); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, expectSuccess: true); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 23, minute: 0, second: 0, expectSuccess: true); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 59, second: 0, expectSuccess: true); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 59, expectSuccess: true); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, fraction: 9999999, offsetNegative: false, offsetHours: 0, offsetMinutes: 0, expectSuccess: true); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, fraction: 0, offsetNegative: false, offsetHours: 13, offsetMinutes: 59, expectSuccess: true); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, fraction: 0, offsetNegative: false, offsetHours: 14, offsetMinutes: 0, expectSuccess: true); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, fraction: 0, offsetNegative: true, offsetHours: 13, offsetMinutes: 59, expectSuccess: true); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, fraction: 0, offsetNegative: true, offsetHours: 14, offsetMinutes: 0, expectSuccess: true); // Test data outside the valid ranges. yield return new PseudoDateTime(year: 0, month: 1, day: 1, hour: 24, minute: 0, second: 0, expectSuccess: false); yield return new PseudoDateTime(year: 2017, month: 0, day: 1, hour: 24, minute: 0, second: 0, expectSuccess: false); yield return new PseudoDateTime(year: 2017, month: 13, day: 1, hour: 24, minute: 0, second: 0, expectSuccess: false); // Day range is month/year dependent. Was already covered above. yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 60, minute: 0, second: 0, expectSuccess: false); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 60, second: 0, expectSuccess: false); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 60, expectSuccess: false); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, fraction: 0, offsetNegative: true, offsetHours: 0, offsetMinutes: 60, expectSuccess: false); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, fraction: 0, offsetNegative: false, offsetHours: 14, offsetMinutes: 1, expectSuccess: false); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, fraction: 0, offsetNegative: false, offsetHours: 15, offsetMinutes: 0, expectSuccess: false); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, fraction: 0, offsetNegative: true, offsetHours: 14, offsetMinutes: 1, expectSuccess: false); yield return new PseudoDateTime(year: 2017, month: 1, day: 1, hour: 0, minute: 0, second: 0, fraction: 0, offsetNegative: true, offsetHours: 15, offsetMinutes: 0, expectSuccess: false); // Past the end of time. yield return new PseudoDateTime(year: 9999, month: 12, day: 31, hour: 23, minute: 59, second: 59, fraction: 9999999, offsetNegative: true, offsetHours: 0, offsetMinutes: 1, expectSuccess: false); yield return new PseudoDateTime(year: 1, month: 1, day: 1, hour: 0, minute: 0, second: 0, fraction: 0, offsetNegative: false, offsetHours: 0, offsetMinutes: 1, expectSuccess: false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Linq; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Text; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.Xml; using System.Security.Cryptography.X509Certificates; using Xunit; using Test.Cryptography; namespace System.Security.Cryptography.Pkcs.Tests { public static class CmsRecipientCollectionTests { [Fact] public static void Nullary() { CmsRecipientCollection c = new CmsRecipientCollection(); AssertEquals(c, Array.Empty<CmsRecipient>()); } [Fact] public static void Oneary() { CmsRecipient a0 = s_cr0; CmsRecipientCollection c = new CmsRecipientCollection(a0); AssertEquals(c, new CmsRecipient[] { a0 }); } [Fact] public static void Twoary() { CmsRecipient a0 = s_cr0; CmsRecipientCollection c = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, new X509Certificate2Collection(a0.Certificate)); Assert.Equal(1, c.Count); CmsRecipient actual = c[0]; Assert.Equal(a0.RecipientIdentifierType, actual.RecipientIdentifierType); Assert.Equal(a0.Certificate, actual.Certificate); } [Fact] public static void Twoary_Ski() { CmsRecipient a0 = s_cr0; CmsRecipientCollection c = new CmsRecipientCollection(SubjectIdentifierType.SubjectKeyIdentifier, new X509Certificate2Collection(a0.Certificate)); Assert.Equal(1, c.Count); CmsRecipient actual = c[0]; Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, actual.RecipientIdentifierType); Assert.Equal(a0.Certificate, actual.Certificate); } [Fact] public static void Twoary_Negative() { object ignore; Assert.Throws<NullReferenceException>(() => ignore = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, null)); } [Fact] public static void Add() { CmsRecipient a0 = s_cr0; CmsRecipient a1 = s_cr1; CmsRecipient a2 = s_cr2; CmsRecipientCollection c = new CmsRecipientCollection(); int index; index = c.Add(a0); Assert.Equal(0, index); index = c.Add(a1); Assert.Equal(1, index); index = c.Add(a2); Assert.Equal(2, index); AssertEquals(c, new CmsRecipient[] { a0, a1, a2 }); } [Fact] public static void Remove() { CmsRecipient a0 = s_cr0; CmsRecipient a1 = s_cr1; CmsRecipient a2 = s_cr2; CmsRecipientCollection c = new CmsRecipientCollection(); int index; index = c.Add(a0); Assert.Equal(0, index); index = c.Add(a1); Assert.Equal(1, index); index = c.Add(a2); Assert.Equal(2, index); c.Remove(a1); AssertEquals(c, new CmsRecipient[] { a0, a2 }); } [Fact] public static void AddNegative() { CmsRecipientCollection c = new CmsRecipientCollection(); Assert.Throws<ArgumentNullException>(() => c.Add(null)); } [Fact] public static void RemoveNegative() { CmsRecipientCollection c = new CmsRecipientCollection(); Assert.Throws<ArgumentNullException>(() => c.Remove(null)); } [Fact] public static void RemoveNonExistent() { CmsRecipientCollection c = new CmsRecipientCollection(); CmsRecipient a0 = s_cr0; c.Remove(a0); // You can "remove" items that aren't in the collection - this is defined as a NOP. } [Fact] public static void IndexOutOfBounds() { CmsRecipient a0 = s_cr0; CmsRecipient a1 = s_cr1; CmsRecipient a2 = s_cr2; CmsRecipientCollection c = new CmsRecipientCollection(); c.Add(a0); c.Add(a1); c.Add(a2); object ignore = null; Assert.Throws<ArgumentOutOfRangeException>(() => ignore = c[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ignore = c[3]); } [Fact] public static void CopyExceptions() { CmsRecipient a0 = s_cr0; CmsRecipient a1 = s_cr1; CmsRecipient a2 = s_cr2; CmsRecipientCollection c = new CmsRecipientCollection(); c.Add(a0); c.Add(a1); c.Add(a2); CmsRecipient[] a = new CmsRecipient[3]; Assert.Throws<ArgumentNullException>(() => c.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(a, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(a, 3)); Assert.Throws<ArgumentException>(() => c.CopyTo(a, 1)); ICollection ic = c; Assert.Throws<ArgumentNullException>(() => ic.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ic.CopyTo(a, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ic.CopyTo(a, 3)); Assert.Throws<ArgumentException>(() => ic.CopyTo(a, 1)); Assert.Throws<ArgumentException>(() => ic.CopyTo(new CmsRecipient[2, 2], 1)); Assert.Throws<InvalidCastException>(() => ic.CopyTo(new int[10], 1)); // Array has non-zero lower bound Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 }); Assert.Throws<IndexOutOfRangeException>(() => ic.CopyTo(array, 0)); } private static void AssertEquals(CmsRecipientCollection c, IList<CmsRecipient> expected) { Assert.Equal(expected.Count, c.Count); for (int i = 0; i < c.Count; i++) { Assert.Equal(expected[i], c[i]); } int index = 0; foreach (CmsRecipient a in c) { Assert.Equal(expected[index++], a); } Assert.Equal(c.Count, index); ValidateEnumerator(c.GetEnumerator(), expected); ValidateEnumerator(((ICollection)c).GetEnumerator(), expected); { CmsRecipient[] dumped = new CmsRecipient[c.Count + 3]; c.CopyTo(dumped, 2); Assert.Equal(null, dumped[0]); Assert.Equal(null, dumped[1]); Assert.Equal(null, dumped[dumped.Length - 1]); Assert.Equal<CmsRecipient>(expected, dumped.Skip(2).Take(c.Count)); } { CmsRecipient[] dumped = new CmsRecipient[c.Count + 3]; ((ICollection)c).CopyTo(dumped, 2); Assert.Equal(null, dumped[0]); Assert.Equal(null, dumped[1]); Assert.Equal(null, dumped[dumped.Length - 1]); Assert.Equal<CmsRecipient>(expected, dumped.Skip(2).Take(c.Count)); } } private static void ValidateEnumerator(IEnumerator enumerator, IList<CmsRecipient> expected) { foreach (CmsRecipient e in expected) { Assert.True(enumerator.MoveNext()); CmsRecipient actual = (CmsRecipient)(enumerator.Current); Assert.Equal(e, actual); } Assert.False(enumerator.MoveNext()); } private static readonly CmsRecipient s_cr0 = new CmsRecipient(Certificates.RSAKeyTransfer1.GetCertificate()); private static readonly CmsRecipient s_cr1 = new CmsRecipient(Certificates.RSAKeyTransfer2.GetCertificate()); private static readonly CmsRecipient s_cr2 = new CmsRecipient(Certificates.RSAKeyTransfer3.GetCertificate()); } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using AllReady.Models; namespace AllReady.Migrations { [DbContext(typeof(AllReadyContext))] [Migration("20151203025955_OrganizationSkills")] partial class OrganizationSkills { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("AllReady.Models.Activity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CampaignId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ActivitySignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ActivityId"); b.Property<string>("AdditionalInfo"); b.Property<DateTime?>("CheckinDateTime"); b.Property<string>("PreferredEmail"); b.Property<string>("PreferredPhoneNumber"); b.Property<DateTime>("SignupDateTime"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ActivitySkill", b => { b.Property<int>("ActivityId"); b.Property<int>("SkillId"); b.HasKey("ActivityId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ActivityId"); b.Property<string>("Description"); b.Property<DateTimeOffset?>("EndDateTime"); b.Property<string>("Name") .IsRequired(); b.Property<int>("NumberOfVolunteersRequired"); b.Property<DateTimeOffset?>("StartDateTime"); b.Property<int?>("TenantId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("Name"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<int?>("TenantId"); b.Property<string>("TimeZoneId") .IsRequired(); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignImpactId"); b.Property<string>("Description"); b.Property<DateTimeOffset>("EndDateTime"); b.Property<string>("FullDescription"); b.Property<string>("ImageUrl"); b.Property<int?>("LocationId"); b.Property<int>("ManagingTenantId"); b.Property<string>("Name") .IsRequired(); b.Property<string>("OrganizerId"); b.Property<DateTimeOffset>("StartDateTime"); b.Property<string>("TimeZoneId") .IsRequired(); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.Property<int>("CampaignId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("CampaignId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.CampaignImpact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CurrentImpactLevel"); b.Property<bool>("Display"); b.Property<int>("ImpactType"); b.Property<int>("NumericImpactGoal"); b.Property<string>("TextualImpactGoal"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CampaignId"); b.Property<int?>("TenantId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Contact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Email"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<string>("PhoneNumber"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address1"); b.Property<string>("Address2"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Name"); b.Property<string>("PhoneNumber"); b.Property<string>("PostalCodePostalCode"); b.Property<string>("State"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b => { b.Property<string>("PostalCode"); b.Property<string>("City"); b.Property<string>("State"); b.HasKey("PostalCode"); }); modelBuilder.Entity("AllReady.Models.Resource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CategoryTag"); b.Property<string>("Description"); b.Property<string>("MediaUrl"); b.Property<string>("Name"); b.Property<DateTime>("PublishDateBegin"); b.Property<DateTime>("PublishDateEnd"); b.Property<string>("ResourceUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<string>("Name") .IsRequired(); b.Property<int?>("OwningOrganizationId"); b.Property<int?>("ParentSkillId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Status"); b.Property<DateTime>("StatusDateTimeUtc"); b.Property<string>("StatusDescription"); b.Property<int?>("TaskId"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.Property<int>("TaskId"); b.Property<int>("SkillId"); b.HasKey("TaskId", "SkillId"); }); modelBuilder.Entity("AllReady.Models.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("LocationId"); b.Property<string>("LogoUrl"); b.Property<string>("Name") .IsRequired(); b.Property<string>("WebUrl"); b.HasKey("Id"); }); modelBuilder.Entity("AllReady.Models.TenantContact", b => { b.Property<int>("TenantId"); b.Property<int>("ContactId"); b.Property<int>("ContactType"); b.HasKey("TenantId", "ContactId", "ContactType"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.Property<string>("UserId"); b.Property<int>("SkillId"); b.HasKey("UserId", "SkillId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("AllReady.Models.Activity", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.ActivitySignup", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.ActivitySkill", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); }); modelBuilder.Entity("AllReady.Models.AllReadyTask", b => { b.HasOne("AllReady.Models.Activity") .WithMany() .HasForeignKey("ActivityId"); b.HasOne("AllReady.Models.Tenant") .WithMany() .HasForeignKey("TenantId"); }); modelBuilder.Entity("AllReady.Models.ApplicationUser", b => { b.HasOne("AllReady.Models.Tenant") .WithMany() .HasForeignKey("TenantId"); }); modelBuilder.Entity("AllReady.Models.Campaign", b => { b.HasOne("AllReady.Models.CampaignImpact") .WithMany() .HasForeignKey("CampaignImpactId"); b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); b.HasOne("AllReady.Models.Tenant") .WithMany() .HasForeignKey("ManagingTenantId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("OrganizerId"); }); modelBuilder.Entity("AllReady.Models.CampaignContact", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); }); modelBuilder.Entity("AllReady.Models.CampaignSponsors", b => { b.HasOne("AllReady.Models.Campaign") .WithMany() .HasForeignKey("CampaignId"); b.HasOne("AllReady.Models.Tenant") .WithMany() .HasForeignKey("TenantId"); }); modelBuilder.Entity("AllReady.Models.Location", b => { b.HasOne("AllReady.Models.PostalCodeGeo") .WithMany() .HasForeignKey("PostalCodePostalCode"); }); modelBuilder.Entity("AllReady.Models.Skill", b => { b.HasOne("AllReady.Models.Tenant") .WithMany() .HasForeignKey("OwningOrganizationId"); b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("ParentSkillId"); }); modelBuilder.Entity("AllReady.Models.TaskSignup", b => { b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("AllReady.Models.TaskSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.AllReadyTask") .WithMany() .HasForeignKey("TaskId"); }); modelBuilder.Entity("AllReady.Models.Tenant", b => { b.HasOne("AllReady.Models.Location") .WithMany() .HasForeignKey("LocationId"); }); modelBuilder.Entity("AllReady.Models.TenantContact", b => { b.HasOne("AllReady.Models.Contact") .WithMany() .HasForeignKey("ContactId"); b.HasOne("AllReady.Models.Tenant") .WithMany() .HasForeignKey("TenantId"); }); modelBuilder.Entity("AllReady.Models.UserSkill", b => { b.HasOne("AllReady.Models.Skill") .WithMany() .HasForeignKey("SkillId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("AllReady.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. <michaldominik@gmail.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. // // // //////////////////////////////////////////////////////////////////////////////// namespace Diva.Editor.Timeline { using System; using Gtk; using Cairo; using Gdv; using TimeSpan = Gdv.TimeSpan; using Util; public abstract class ClipElement : ViewElement, IMovable, IFloating, ITracking { // Fields ////////////////////////////////////////////////////// protected TimeSpan timeSpan; protected TimeSpan backupSpan; protected int track; protected int backupTrack; protected MediaItem mediaItem; // For display only // Properties ////////////////////////////////////////////////// public override Gdk.Rectangle DrawingRect { get { // If out of view range, return zero Gdk.Rectangle totalRect = modelRoot.Timeline.ViewportRectangle; if (! (timeSpan.IntersectsWith (modelRoot.Timeline.DisplayedTimeSpan))) return Gdk.Rectangle.Zero; int startX = Math.Max (totalRect.Left, modelRoot.Timeline.TimeToPixel (timeSpan.Start)); int endX = Math.Min (totalRect.Width, modelRoot.Timeline.TimeToPixel (timeSpan.End)); return new Gdk.Rectangle (startX, Helper.GetYForTrackNo (modelRoot, track), endX - startX + 1, 32); } } // FIXME: Make private? public bool LeftCut { get { return (timeSpan.Start < modelRoot.Timeline.DisplayedTimeSpan.Start) ? true : false; } } // FIXME: Make private? public bool RightCut { get { return (timeSpan.End > modelRoot.Timeline.DisplayedTimeSpan.End) ? true : false; } } public virtual Time CurrentPosition { get { return timeSpan.Start; } set { timeSpan.MoveTo (value); Invalidate (); } } public Time SavedPosition { get { return backupSpan.Start ; } } public virtual int CurrentTrack { get { return track; } set { track = value; Invalidate (); } } public int SavedTrack { get { return backupTrack; } } Gdv.Color MediaItemColor { get { if (mediaItem is Gdv.AVItem) return Gdv.Color.FromTango (ColorTango.Chameleon1); else if (mediaItem is Gdv.PhotoItem) return Gdv.Color.FromTango (ColorTango.Butter1); else if (mediaItem is Gdv.AudioItem) return Gdv.Color.FromTango (ColorTango.SkyBlue1); else return Gdv.Color.FromTango (ColorTango.Chameleon1); } } // Public methods ////////////////////////////////////////////// /* CONSTRUCTOR */ public ClipElement (Model.Root modelRoot, TimeSpan span, int track, MediaItem item) : base (modelRoot, ElementLayer.Clip) { timeSpan = span; backupSpan = TimeSpan.Empty; this.track = track; backupTrack = -1; mediaItem = item; } public override void Draw (Graphics gr, Gdk.Rectangle rect) { Gdk.Rectangle clipRect = DrawingRect; CairoCut cutMode = CairoCut.None; CairoState stateMode = CairoState.Normal; // Check the cuts if (LeftCut) cutMode = cutMode | CairoCut.Left; if (RightCut) cutMode = cutMode | CairoCut.Right; // Check the state // FIXME: We've got a helper in base class for that, don't we? switch (state) { case ViewElementState.Active: stateMode = CairoState.Active; break; case ViewElementState.Drag: stateMode = CairoState.Drag; break; default: stateMode = CairoState.Normal; break; } // Get a formatted string string str = String.Format ("<b>{0}</b>", StringFu.Markupize (mediaItem.Name)); // Draw if (mediaItem is IThumbnailable && (mediaItem as IThumbnailable).SmallThumbnail != null) ReadyMade.Clip (gr, clipRect.Left, clipRect.Top, clipRect.Width, MediaItemColor, str, (mediaItem as IThumbnailable).SmallThumbnail, cutMode, stateMode); else ReadyMade.Clip (gr, clipRect.Left, clipRect.Top, clipRect.Width, MediaItemColor, str, cutMode, stateMode); base.Draw (gr, rect); } /* IFloating */ public void SaveThyself () { backupSpan = timeSpan; backupTrack = track; } /* IFloating */ public void RestoreThyself () { timeSpan = backupSpan; track = backupTrack; } /* IFloating */ public void LooseThyself () { backupSpan = TimeSpan.Empty; backupTrack = -1; } /* IFloating */ public virtual void SyncThyself () { LooseThyself (); } } }
using System; using System.Collections.Generic; using Sep.Git.Tfs.Core.TfsInterop; using Sep.Git.Tfs.Commands; namespace Sep.Git.Tfs.Core { class DerivedGitTfsRemote : IGitTfsRemote { private readonly string _tfsUrl; private readonly string _tfsRepositoryPath; public DerivedGitTfsRemote(string tfsUrl, string tfsRepositoryPath) { _tfsUrl = tfsUrl; _tfsRepositoryPath = tfsRepositoryPath; } GitTfsException DerivedRemoteException { get { return new GitTfsException("Unable to locate a remote for <" + _tfsUrl + ">" + _tfsRepositoryPath) .WithRecommendation("Try using `git tfs bootstrap` to auto-init TFS remotes.") .WithRecommendation("Try setting a legacy-url for an existing remote."); } } public bool IsDerived { get { return true; } } public string Id { get { return "(derived)"; } set { throw DerivedRemoteException; } } public string TfsUrl { get { return _tfsUrl; } set { throw DerivedRemoteException; } } public bool Autotag { get { throw DerivedRemoteException; } set { throw DerivedRemoteException; } } public string TfsUsername { get { throw DerivedRemoteException; } set { throw DerivedRemoteException; } } public string TfsPassword { get { throw DerivedRemoteException; } set { throw DerivedRemoteException; } } public string TfsRepositoryPath { get { return _tfsRepositoryPath; } set { throw DerivedRemoteException; } } public string[] TfsSubtreePaths { get { throw DerivedRemoteException; } } #region Equality public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(DerivedGitTfsRemote)) return false; return Equals((DerivedGitTfsRemote)obj); } private bool Equals(DerivedGitTfsRemote other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other._tfsUrl, _tfsUrl) && Equals(other._tfsRepositoryPath, _tfsRepositoryPath); } public override int GetHashCode() { unchecked { return ((_tfsUrl != null ? _tfsUrl.GetHashCode() : 0) * 397) ^ (_tfsRepositoryPath != null ? _tfsRepositoryPath.GetHashCode() : 0); } } public static bool operator ==(DerivedGitTfsRemote left, DerivedGitTfsRemote right) { return Equals(left, right); } public static bool operator !=(DerivedGitTfsRemote left, DerivedGitTfsRemote right) { return !Equals(left, right); } #endregion #region All this is not implemented public string IgnoreRegexExpression { get { throw DerivedRemoteException; } set { throw DerivedRemoteException; } } public string IgnoreExceptRegexExpression { get { throw DerivedRemoteException; } set { throw DerivedRemoteException; } } public IGitRepository Repository { get { throw DerivedRemoteException; } set { throw DerivedRemoteException; } } public ITfsHelper Tfs { get { throw DerivedRemoteException; } set { throw DerivedRemoteException; } } public int MaxChangesetId { get { throw DerivedRemoteException; } set { throw DerivedRemoteException; } } public string MaxCommitHash { get { throw DerivedRemoteException; } set { throw DerivedRemoteException; } } public string RemoteRef { get { throw DerivedRemoteException; } } public bool IsSubtree { get { return false; } } public bool IsSubtreeOwner { get { return false; } } public string OwningRemoteId { get { return null; } } public string Prefix { get { return null; } } public bool ExportMetadatas { get; set; } public Dictionary<string, string> ExportWorkitemsMapping { get; set; } public int? InitialChangeset { get { throw DerivedRemoteException; } set { throw DerivedRemoteException; } } public bool ShouldSkip(string path) { throw DerivedRemoteException; } public IGitTfsRemote InitBranch(RemoteOptions remoteOptions, string tfsRepositoryPath, int shaRootChangesetId, bool fetchParentBranch, string gitBranchNameExpected = null, IRenameResult renameResult = null) { throw new NotImplementedException(); } public string GetPathInGitRepo(string tfsPath) { throw DerivedRemoteException; } public IFetchResult Fetch(bool stopOnFailMergeCommit = false, int lastChangesetIdToFetch = -1, IRenameResult renameResult = null) { throw DerivedRemoteException; } public IFetchResult FetchWithMerge(int mergeChangesetId, bool stopOnFailMergeCommit = false, IRenameResult renameResult = null, params string[] parentCommitsHashes) { throw DerivedRemoteException; } public void QuickFetch() { throw DerivedRemoteException; } public void QuickFetch(int changesetId) { throw DerivedRemoteException; } public void Unshelve(string a, string b, string c, Action<Exception> h, bool force) { throw DerivedRemoteException; } public void Shelve(string shelvesetName, string treeish, TfsChangesetInfo parentChangeset, CheckinOptions options, bool evaluateCheckinPolicies) { throw DerivedRemoteException; } public bool HasShelveset(string shelvesetName) { throw DerivedRemoteException; } public int CheckinTool(string head, TfsChangesetInfo parentChangeset) { throw DerivedRemoteException; } public int Checkin(string treeish, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null) { throw DerivedRemoteException; } public int Checkin(string head, string parent, TfsChangesetInfo parentChangeset, CheckinOptions options, string sourceTfsPath = null) { throw DerivedRemoteException; } public void CleanupWorkspace() { throw DerivedRemoteException; } public void CleanupWorkspaceDirectory() { throw DerivedRemoteException; } public ITfsChangeset GetChangeset(int changesetId) { throw DerivedRemoteException; } public void UpdateTfsHead(string commitHash, int changesetId) { throw DerivedRemoteException; } public void EnsureTfsAuthenticated() { throw DerivedRemoteException; } public bool MatchesUrlAndRepositoryPath(string tfsUrl, string tfsRepositoryPath) { throw DerivedRemoteException; } public RemoteInfo RemoteInfo { get { throw DerivedRemoteException; } } public void Merge(string sourceTfsPath, string targetTfsPath) { throw DerivedRemoteException; } #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. // Match is the result class for a regex search. // It returns the location, length, and substring for // the entire match as well as every captured group. // Match is also used during the search to keep track of each capture for each group. This is // done using the "_matches" array. _matches[x] represents an array of the captures for group x. // This array consists of start and length pairs, and may have empty entries at the end. _matchcount[x] // stores how many captures a group has. Note that _matchcount[x]*2 is the length of all the valid // values in _matches. _matchcount[x]*2-2 is the Start of the last capture, and _matchcount[x]*2-1 is the // Length of the last capture // // For example, if group 2 has one capture starting at position 4 with length 6, // _matchcount[2] == 1 // _matches[2][0] == 4 // _matches[2][1] == 6 // // Values in the _matches array can also be negative. This happens when using the balanced match // construct, "(?<start-end>...)". When the "end" group matches, a capture is added for both the "start" // and "end" groups. The capture added for "start" receives the negative values, and these values point to // the next capture to be balanced. They do NOT point to the capture that "end" just balanced out. The negative // values are indices into the _matches array transformed by the formula -3-x. This formula also untransforms. // using System.Collections; using System.Collections.Generic; using System.Globalization; namespace System.Text.RegularExpressions { /// <summary> /// Represents the results from a single regular expression match. /// </summary> public class Match : Group { internal static Match s_empty = new Match(null, 1, String.Empty, 0, 0, 0); internal GroupCollection _groupcoll; // input to the match internal Regex _regex; internal int _textbeg; internal int _textpos; internal int _textend; internal int _textstart; // output from the match internal int[][] _matches; internal int[] _matchcount; internal bool _balancing; // whether we've done any balancing with this match. If we // have done balancing, we'll need to do extra work in Tidy(). /// <summary> /// Returns an empty Match object. /// </summary> public static Match Empty { get { return s_empty; } } internal Match(Regex regex, int capcount, String text, int begpos, int len, int startpos) : base(text, new int[2], 0) { _regex = regex; _matchcount = new int[capcount]; _matches = new int[capcount][]; _matches[0] = _caps; _textbeg = begpos; _textend = begpos + len; _textstart = startpos; _balancing = false; // No need for an exception here. This is only called internally, so we'll use an Assert instead System.Diagnostics.Debug.Assert(!(_textbeg < 0 || _textstart < _textbeg || _textend < _textstart || _text.Length < _textend), "The parameters are out of range."); } /* * Nonpublic set-text method */ internal virtual void Reset(Regex regex, String text, int textbeg, int textend, int textstart) { _regex = regex; _text = text; _textbeg = textbeg; _textend = textend; _textstart = textstart; for (int i = 0; i < _matchcount.Length; i++) { _matchcount[i] = 0; } _balancing = false; } public virtual GroupCollection Groups { get { if (_groupcoll == null) _groupcoll = new GroupCollection(this, null); return _groupcoll; } } /// <summary> /// Returns a new Match with the results for the next match, starting /// at the position at which the last match ended (at the character beyond the last /// matched character). /// </summary> public Match NextMatch() { if (_regex == null) return this; return _regex.Run(false, _length, _text, _textbeg, _textend - _textbeg, _textpos); } /// <summary> /// Returns the expansion of the passed replacement pattern. For /// example, if the replacement pattern is ?$1$2?, Result returns the concatenation /// of Group(1).ToString() and Group(2).ToString(). /// </summary> public virtual String Result(String replacement) { RegexReplacement repl; if (replacement == null) throw new ArgumentNullException("replacement"); if (_regex == null) throw new NotSupportedException(SR.NoResultOnFailed); repl = (RegexReplacement)_regex._replref.Get(); if (repl == null || !repl.Pattern.Equals(replacement)) { repl = RegexParser.ParseReplacement(replacement, _regex._caps, _regex._capsize, _regex._capnames, _regex._roptions); _regex._replref.Cache(repl); } return repl.Replacement(this); } /* * Used by the replacement code */ internal virtual String GroupToStringImpl(int groupnum) { int c = _matchcount[groupnum]; if (c == 0) return String.Empty; int[] matches = _matches[groupnum]; return _text.Substring(matches[(c - 1) * 2], matches[(c * 2) - 1]); } /* * Used by the replacement code */ internal String LastGroupToStringImpl() { return GroupToStringImpl(_matchcount.Length - 1); } /* * Convert to a thread-safe object by precomputing cache contents */ /// <summary> /// Returns a Match instance equivalent to the one supplied that is safe to share /// between multiple threads. /// </summary> static internal Match Synchronized(Match inner) { if (inner == null) throw new ArgumentNullException("inner"); int numgroups = inner._matchcount.Length; // Populate all groups by looking at each one for (int i = 0; i < numgroups; i++) { Group group = inner.Groups[i]; // Depends on the fact that Group.Synchronized just // operates on and returns the same instance System.Text.RegularExpressions.Group.Synchronized(group); } return inner; } /* * Nonpublic builder: add a capture to the group specified by "cap" */ internal virtual void AddMatch(int cap, int start, int len) { int capcount; if (_matches[cap] == null) _matches[cap] = new int[2]; capcount = _matchcount[cap]; if (capcount * 2 + 2 > _matches[cap].Length) { int[] oldmatches = _matches[cap]; int[] newmatches = new int[capcount * 8]; for (int j = 0; j < capcount * 2; j++) newmatches[j] = oldmatches[j]; _matches[cap] = newmatches; } _matches[cap][capcount * 2] = start; _matches[cap][capcount * 2 + 1] = len; _matchcount[cap] = capcount + 1; } /* * Nonpublic builder: Add a capture to balance the specified group. This is used by the balanced match construct. (?<foo-foo2>...) If there were no such thing as backtracking, this would be as simple as calling RemoveMatch(cap). However, since we have backtracking, we need to keep track of everything. */ internal virtual void BalanceMatch(int cap) { int capcount; int target; _balancing = true; // we'll look at the last capture first capcount = _matchcount[cap]; target = capcount * 2 - 2; // first see if it is negative, and therefore is a reference to the next available // capture group for balancing. If it is, we'll reset target to point to that capture. if (_matches[cap][target] < 0) target = -3 - _matches[cap][target]; // move back to the previous capture target -= 2; // if the previous capture is a reference, just copy that reference to the end. Otherwise, point to it. if (target >= 0 && _matches[cap][target] < 0) AddMatch(cap, _matches[cap][target], _matches[cap][target + 1]); else AddMatch(cap, -3 - target, -4 - target /* == -3 - (target + 1) */ ); } /* * Nonpublic builder: removes a group match by capnum */ internal virtual void RemoveMatch(int cap) { _matchcount[cap]--; } /* * Nonpublic: tells if a group was matched by capnum */ internal virtual bool IsMatched(int cap) { return cap < _matchcount.Length && _matchcount[cap] > 0 && _matches[cap][_matchcount[cap] * 2 - 1] != (-3 + 1); } /* * Nonpublic: returns the index of the last specified matched group by capnum */ internal virtual int MatchIndex(int cap) { int i = _matches[cap][_matchcount[cap] * 2 - 2]; if (i >= 0) return i; return _matches[cap][-3 - i]; } /* * Nonpublic: returns the length of the last specified matched group by capnum */ internal virtual int MatchLength(int cap) { int i = _matches[cap][_matchcount[cap] * 2 - 1]; if (i >= 0) return i; return _matches[cap][-3 - i]; } /* * Nonpublic: tidy the match so that it can be used as an immutable result */ internal virtual void Tidy(int textpos) { int[] interval; interval = _matches[0]; _index = interval[0]; _length = interval[1]; _textpos = textpos; _capcount = _matchcount[0]; if (_balancing) { // The idea here is that we want to compact all of our unbalanced captures. To do that we // use j basically as a count of how many unbalanced captures we have at any given time // (really j is an index, but j/2 is the count). First we skip past all of the real captures // until we find a balance captures. Then we check each subsequent entry. If it's a balance // capture (it's negative), we decrement j. If it's a real capture, we increment j and copy // it down to the last free position. for (int cap = 0; cap < _matchcount.Length; cap++) { int limit; int[] matcharray; limit = _matchcount[cap] * 2; matcharray = _matches[cap]; int i = 0; int j; for (i = 0; i < limit; i++) { if (matcharray[i] < 0) break; } for (j = i; i < limit; i++) { if (matcharray[i] < 0) { // skip negative values j--; } else { // but if we find something positive (an actual capture), copy it back to the last // unbalanced position. if (i != j) matcharray[j] = matcharray[i]; j++; } } _matchcount[cap] = j / 2; } _balancing = false; } } #if DEBUG internal bool Debug { get { if (_regex == null) return false; return _regex.Debug; } } internal virtual void Dump() { int i, j; for (i = 0; i < _matchcount.Length; i++) { System.Diagnostics.Debug.WriteLine("Capnum " + i.ToString(CultureInfo.InvariantCulture) + ":"); for (j = 0; j < _matchcount[i]; j++) { String text = ""; if (_matches[i][j * 2] >= 0) text = _text.Substring(_matches[i][j * 2], _matches[i][j * 2 + 1]); System.Diagnostics.Debug.WriteLine(" (" + _matches[i][j * 2].ToString(CultureInfo.InvariantCulture) + "," + _matches[i][j * 2 + 1].ToString(CultureInfo.InvariantCulture) + ") " + text); } } } #endif } /* * MatchSparse is for handling the case where slots are * sparsely arranged (e.g., if somebody says use slot 100000) */ internal class MatchSparse : Match { // the lookup hashtable new internal Dictionary<Int32, Int32> _caps; /* * Nonpublic constructor */ internal MatchSparse(Regex regex, Dictionary<Int32, Int32> caps, int capcount, String text, int begpos, int len, int startpos) : base(regex, capcount, text, begpos, len, startpos) { _caps = caps; } public override GroupCollection Groups { get { if (_groupcoll == null) _groupcoll = new GroupCollection(this, _caps); return _groupcoll; } } #if DEBUG internal override void Dump() { if (_caps != null) { foreach (KeyValuePair<int, int> kvp in _caps) { System.Diagnostics.Debug.WriteLine("Slot " + kvp.Key.ToString() + " -> " + kvp.Value.ToString()); } } base.Dump(); } #endif } }
// 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.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; namespace System.Linq.Parallel.Tests { public static class UnorderedSources { /// <summary> /// Returns a default ParallelQuery source. /// </summary> /// For most instances when dealing with unordered input, the individual source does not matter. /// /// Instead, that is reserved for ordered, where partitioning and dealing with indices has important /// secondary effects. The goal of unordered input, then, is mostly to make sure the query works. /// <param name="count">The count of elements.</param> /// <returns>A ParallelQuery with elements running from 0 to count - 1</returns> public static ParallelQuery<int> Default(int count) { return Default(0, count); } /// <summary> /// Returns a default ParallelQuery source. /// </summary> /// For most instances when dealing with unordered input, the individual source does not matter. /// /// Instead, that is reserved for ordered, where partitioning and dealing with indices has important /// secondary effects. The goal of unordered input, then, is mostly to make sure the query works. /// <param name="start">The starting element.</param> /// <param name="count">The count of elements.</param> /// <returns>A ParallelQuery with elements running from 0 to count - 1</returns> public static ParallelQuery<int> Default(int start, int count) { // Of the underlying types used elsewhere, some have "problems", // in the sense that they may be too-easily indexible. // For instance, Array and List are both trivially range partitionable and indexible. // A parallelized Enumerable.Range is being used (not easily partitionable or indexible), // but at the moment ParallelEnumerable.Range is being used for speed and ease of use. // ParallelEnumerable.Range is not trivially indexible, but is easily range partitioned. return ParallelEnumerable.Range(start, count); } // Get a set of ranges, of each count in `counts`. // The start of each range is determined by passing the count into the `start` predicate. public static IEnumerable<object[]> Ranges(Func<int, int> start, IEnumerable<int> counts) { foreach (int count in counts) { int s = start(count); foreach (Labeled<ParallelQuery<int>> query in LabeledRanges(s, count)) { yield return new object[] { query, count, s }; } } } /// <summary> /// Get a set of ranges, starting at `start`, and running for each count in `counts`. /// </summary> /// <param name="start">The starting element of the range.</param> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and the third is the start.</returns> public static IEnumerable<object[]> Ranges(int start, IEnumerable<int> counts) { foreach (object[] parms in Ranges(x => start, counts)) yield return parms; } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// and the second element is the count</returns> public static IEnumerable<object[]> Ranges(int[] counts) { foreach (object[] parms in Ranges(counts.Cast<int>())) yield return parms; } /// <summary> /// Get a set of ranges, starting at 0, and having OuterLoopCount elements. /// </summary> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// and the second element is the count</returns> public static IEnumerable<object[]> OuterLoopRanges() { foreach (object[] parms in Ranges(new[] { Sources.OuterLoopCount })) yield return parms; } /// <summary> /// Get a set of ranges, starting at `start`, and running for each count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="start">The starting element of the range.</param> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and the third is the start.</returns> public static IEnumerable<object[]> Ranges(int start, int[] counts) { foreach (object[] parms in Ranges(start, counts.Cast<int>())) yield return parms; } /// <summary> /// Return pairs of ranges, both from 0 to each respective count in `counts`. /// </summary> /// <remarks>This version is a wrapper for use from the MemberData attribute.</remarks> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, and the fourth element is the right count, .</returns> public static IEnumerable<object[]> BinaryRanges(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in BinaryRanges(leftCounts.Cast<int>(), rightCounts.Cast<int>())) yield return parms; } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <param name="counts">The sizes of ranges to return.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// and the second element is the count</returns> public static IEnumerable<object[]> Ranges(IEnumerable<int> counts) { foreach (object[] parms in Ranges(x => 0, counts)) yield return parms.Take(2).ToArray(); } /// <summary> /// Return pairs of ranges, both from 0 to each respective count in `counts`. /// </summary> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, and the fourth element is the right count.</returns> public static IEnumerable<object[]> BinaryRanges(IEnumerable<int> leftCounts, IEnumerable<int> rightCounts) { IEnumerable<object[]> rightRanges = Ranges(rightCounts); foreach (object[] left in Ranges(leftCounts)) { foreach (object[] right in rightRanges) { yield return left.Concat(right).ToArray(); } } } /// <summary> /// Return pairs of ranges, for each respective count in `counts`. /// </summary> /// <param name="leftCounts">The sizes of left ranges to return.</param> /// <param name="rightStart">A predicate to determine the start of the right range, by passing the left and right range size.</param> /// <param name="rightCounts">The sizes of right ranges to return.</param> /// <returns>Entries for test data. /// The first element is the left Labeled{ParallelQuery{int}} range, the second element is the left count, /// the third element is the right Labeled{ParallelQuery{int}} range, the fourth element is the right count, /// and the fifth is the right start.</returns> public static IEnumerable<object[]> BinaryRanges(IEnumerable<int> leftCounts, Func<int, int, int> rightStart, IEnumerable<int> rightCounts) { foreach (object[] left in Ranges(leftCounts)) { foreach (object[] right in Ranges(right => rightStart((int)left[1], right), rightCounts)) { yield return left.Concat(right).ToArray(); } } } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks> /// This is useful for things like showing an average (via the use of `x => (double)SumRange(0, x) / x`) /// </remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <param name="modifiers">A set of modifiers to return as additional parameters.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and one additional element for each modifier.</returns> public static IEnumerable<object[]> Ranges<T>(IEnumerable<int> counts, Func<int, T> modifiers) { foreach (object[] parms in Ranges(counts)) { int count = (int)parms[1]; yield return parms.Concat(new object[] { modifiers(count) }).ToArray(); } } /// <summary> /// Get a set of ranges, starting at 0, and running for each count in `counts`. /// </summary> /// <remarks> /// This is useful for things like dealing with `Max(predicate)`, /// allowing multiple predicate values for the same source count to be tested. /// The number of variations is equal to the longest modifier enumeration (all others will cycle). /// </remarks> /// <param name="counts">The sizes of ranges to return.</param> /// <param name="modifiers">A set of modifiers to return as additional parameters.</param> /// <returns>Entries for test data. /// The first element is the Labeled{ParallelQuery{int}} range, /// the second element is the count, and one additional element for each modifier.</returns> public static IEnumerable<object[]> Ranges<T>(IEnumerable<int> counts, Func<int, IEnumerable<T>> modifiers) { foreach (object[] parms in Ranges(counts)) { foreach (T mod in modifiers((int)parms[1])) { yield return parms.Concat(new object[] { mod }).ToArray(); } } } // Return an enumerable which throws on first MoveNext. // Useful for testing promptness of cancellation. public static IEnumerable<object[]> ThrowOnFirstEnumeration() { yield return new object[] { Labeled.Label("ThrowOnFirstEnumeration", Enumerables<int>.ThrowOnEnumeration().AsParallel()), 8 }; } public static IEnumerable<Labeled<ParallelQuery<int>>> LabeledRanges(int start, int count) { yield return Labeled.Label("ParallelEnumerable.Range", ParallelEnumerable.Range(start, count)); yield return Labeled.Label("Enumerable.Range", Enumerable.Range(start, count).AsParallel()); int[] rangeArray = Enumerable.Range(start, count).ToArray(); yield return Labeled.Label("Array", rangeArray.AsParallel()); IList<int> rangeList = rangeArray.ToList(); yield return Labeled.Label("List", rangeList.AsParallel()); yield return Labeled.Label("Partitioner", Partitioner.Create(rangeArray).AsParallel()); // PLINQ doesn't currently have any special code paths for readonly collections. If it ever does, this should be uncommented. // yield return Labeled.Label("ReadOnlyCollection", new ReadOnlyCollection<int>(rangeList).AsParallel()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Xml; using System.Runtime.Serialization; using System.Xml.Serialization; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.ServiceModel.Syndication { // NOTE: This class implements Clone so if you add any members, please update the copy ctor public class SyndicationItem : IExtensibleSyndicationObject { private Collection<SyndicationPerson> _authors; private Uri _baseUri; private Collection<SyndicationCategory> _categories; private SyndicationContent _content; private Collection<SyndicationPerson> _contributors; private TextSyndicationContent _copyright; private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject(); private string _id; private DateTimeOffset _lastUpdatedTime; private Collection<SyndicationLink> _links; private DateTimeOffset _publishDate; private SyndicationFeed _sourceFeed; private TextSyndicationContent _summary; private TextSyndicationContent _title; public SyndicationItem() : this(null, null, null) { } public SyndicationItem(string title, string content, Uri itemAlternateLink) : this(title, content, itemAlternateLink, null, DateTimeOffset.MinValue) { } public SyndicationItem(string title, string content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime) : this(title, (content != null) ? new TextSyndicationContent(content) : null, itemAlternateLink, id, lastUpdatedTime) { } public SyndicationItem(string title, SyndicationContent content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime) { if (title != null) { this.Title = new TextSyndicationContent(title); } _content = content; if (itemAlternateLink != null) { this.Links.Add(SyndicationLink.CreateAlternateLink(itemAlternateLink)); } _id = id; _lastUpdatedTime = lastUpdatedTime; } protected SyndicationItem(SyndicationItem source) { if (source == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("source"); } _extensions = source._extensions.Clone(); _authors = FeedUtils.ClonePersons(source._authors); _categories = FeedUtils.CloneCategories(source._categories); _content = (source._content != null) ? source._content.Clone() : null; _contributors = FeedUtils.ClonePersons(source._contributors); _copyright = FeedUtils.CloneTextContent(source._copyright); _id = source._id; _lastUpdatedTime = source._lastUpdatedTime; _links = FeedUtils.CloneLinks(source._links); _publishDate = source._publishDate; if (source.SourceFeed != null) { _sourceFeed = source._sourceFeed.Clone(false); _sourceFeed.Items = new Collection<SyndicationItem>(); } _summary = FeedUtils.CloneTextContent(source._summary); _baseUri = source._baseUri; _title = FeedUtils.CloneTextContent(source._title); } public Dictionary<XmlQualifiedName, string> AttributeExtensions { get { return _extensions.AttributeExtensions; } } public Collection<SyndicationPerson> Authors { get { if (_authors == null) { _authors = new NullNotAllowedCollection<SyndicationPerson>(); } return _authors; } } public Uri BaseUri { get { return _baseUri; } set { _baseUri = value; } } public Collection<SyndicationCategory> Categories { get { if (_categories == null) { _categories = new NullNotAllowedCollection<SyndicationCategory>(); } return _categories; } } public SyndicationContent Content { get { return _content; } set { _content = value; } } public Collection<SyndicationPerson> Contributors { get { if (_contributors == null) { _contributors = new NullNotAllowedCollection<SyndicationPerson>(); } return _contributors; } } public TextSyndicationContent Copyright { get { return _copyright; } set { _copyright = value; } } public SyndicationElementExtensionCollection ElementExtensions { get { return _extensions.ElementExtensions; } } public string Id { get { return _id; } set { _id = value; } } public DateTimeOffset LastUpdatedTime { get { return _lastUpdatedTime; } set { _lastUpdatedTime = value; } } public Collection<SyndicationLink> Links { get { if (_links == null) { _links = new NullNotAllowedCollection<SyndicationLink>(); } return _links; } } public DateTimeOffset PublishDate { get { return _publishDate; } set { _publishDate = value; } } public SyndicationFeed SourceFeed { get { return _sourceFeed; } set { _sourceFeed = value; } } public TextSyndicationContent Summary { get { return _summary; } set { _summary = value; } } public TextSyndicationContent Title { get { return _title; } set { _title = value; } } public static SyndicationItem Load(XmlReader reader) { return Load<SyndicationItem>(reader); } public static TSyndicationItem Load<TSyndicationItem>(XmlReader reader) where TSyndicationItem : SyndicationItem, new() { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } Atom10ItemFormatter<TSyndicationItem> atomSerializer = new Atom10ItemFormatter<TSyndicationItem>(); if (atomSerializer.CanRead(reader)) { atomSerializer.ReadFrom(reader); return atomSerializer.Item as TSyndicationItem; } Rss20ItemFormatter<TSyndicationItem> rssSerializer = new Rss20ItemFormatter<TSyndicationItem>(); if (rssSerializer.CanRead(reader)) { rssSerializer.ReadFrom(reader); return rssSerializer.Item as TSyndicationItem; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnknownItemXml, reader.LocalName, reader.NamespaceURI))); } [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "0#permalink", Justification = "permalink is a term defined in the RSS format")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Permalink", Justification = "permalink is a term defined in the RSS format")] public void AddPermalink(Uri permalink) { if (permalink == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("permalink"); } this.Id = permalink.AbsoluteUri; this.Links.Add(SyndicationLink.CreateAlternateLink(permalink)); } public virtual SyndicationItem Clone() { return new SyndicationItem(this); } public Atom10ItemFormatter GetAtom10Formatter() { return new Atom10ItemFormatter(this); } public Rss20ItemFormatter GetRss20Formatter() { return GetRss20Formatter(true); } public Rss20ItemFormatter GetRss20Formatter(bool serializeExtensionsAsAtom) { return new Rss20ItemFormatter(this, serializeExtensionsAsAtom); } public void SaveAsAtom10(XmlWriter writer) { this.GetAtom10Formatter().WriteTo(writer); } public void SaveAsRss20(XmlWriter writer) { this.GetRss20Formatter().WriteTo(writer); } protected internal virtual SyndicationCategory CreateCategory() { return new SyndicationCategory(); } protected internal virtual SyndicationLink CreateLink() { return new SyndicationLink(); } protected internal virtual SyndicationPerson CreatePerson() { return new SyndicationPerson(); } protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version) { return false; } protected internal virtual bool TryParseContent(XmlReader reader, string contentType, string version, out SyndicationContent content) { content = null; return false; } protected internal virtual bool TryParseElement(XmlReader reader, string version) { return false; } protected internal virtual void WriteAttributeExtensions(XmlWriter writer, string version) { _extensions.WriteAttributeExtensions(writer); } protected internal virtual void WriteElementExtensions(XmlWriter writer, string version) { _extensions.WriteElementExtensions(writer); } internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize) { _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize); } internal void LoadElementExtensions(XmlBuffer buffer) { _extensions.LoadElementExtensions(buffer); } } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using System.IO; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI80; using NUnit.Framework; namespace Net.Pkcs11Interop.Tests.LowLevelAPI80 { /// <summary> /// C_SignInit, C_Sign, C_SignUpdate, C_SignFinal, C_VerifyInit, C_Verify, C_VerifyUpdate and C_VerifyFinal tests. /// </summary> [TestFixture()] public class _21_SignAndVerifyTest { /// <summary> /// C_SignInit, C_Sign, C_VerifyInit and C_Verify test with CKM_RSA_PKCS mechanism. /// </summary> [Test()] public void _01_SignAndVerifySinglePartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs80); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate asymetric key pair ulong pubKeyId = CK.CK_INVALID_HANDLE; ulong privKeyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify signing mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS); // Initialize signing operation rv = pkcs11.C_SignInit(session, ref mechanism, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Get length of signature in first call ulong signatureLen = 0; rv = pkcs11.C_Sign(session, sourceData, Convert.ToUInt64(sourceData.Length), null, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(signatureLen > 0); // Allocate array for signature byte[] signature = new byte[signatureLen]; // Get signature in second call rv = pkcs11.C_Sign(session, sourceData, Convert.ToUInt64(sourceData.Length), signature, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with signature // Initialize verification operation rv = pkcs11.C_VerifyInit(session, ref mechanism, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Verify signature rv = pkcs11.C_Verify(session, sourceData, Convert.ToUInt64(sourceData.Length), signature, Convert.ToUInt64(signature.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with verification result rv = pkcs11.C_DestroyObject(session, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_DestroyObject(session, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_SignInit, C_SignUpdate, C_SignFinal, C_VerifyInit, C_VerifyUpdate and C_VerifyFinal test. /// </summary> [Test()] public void _02_SignAndVerifyMultiPartTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs80); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate asymetric key pair ulong pubKeyId = CK.CK_INVALID_HANDLE; ulong privKeyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify signing mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA1_RSA_PKCS); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); byte[] signature = null; // Multipart signature functions C_SignUpdate and C_SignFinal can be used i.e. for signing of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Initialize signing operation rv = pkcs11.C_SignInit(session, ref mechanism, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Process each individual source data part rv = pkcs11.C_SignUpdate(session, part, Convert.ToUInt64(bytesRead)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Get the length of signature in first call ulong signatureLen = 0; rv = pkcs11.C_SignFinal(session, null, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(signatureLen > 0); // Allocate array for signature signature = new byte[signatureLen]; // Get signature in second call rv = pkcs11.C_SignFinal(session, signature, ref signatureLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Do something interesting with signature // Multipart verification functions C_VerifyUpdate and C_VerifyFinal can be used i.e. for signature verification of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData)) { // Initialize verification operation rv = pkcs11.C_VerifyInit(session, ref mechanism, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Process each individual source data part rv = pkcs11.C_VerifyUpdate(session, part, Convert.ToUInt64(bytesRead)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Verify signature rv = pkcs11.C_VerifyFinal(session, signature, Convert.ToUInt64(signature.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } // Do something interesting with verification result rv = pkcs11.C_DestroyObject(session, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_DestroyObject(session, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
/* Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft 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 C5; using NUnit.Framework; using SCG = System.Collections.Generic; namespace C5UnitTests { class SC : SCG.IComparer<string> { public int Compare(string a, string b) { return a.CompareTo(b); } public void appl(String s) { System.Console.WriteLine("--{0}", s); } } class TenEqualityComparer : SCG.IEqualityComparer<int>, SCG.IComparer<int> { TenEqualityComparer() { } public static TenEqualityComparer Default { get { return new TenEqualityComparer(); } } public int GetHashCode(int item) { return (item / 10).GetHashCode(); } public bool Equals(int item1, int item2) { return item1 / 10 == item2 / 10; } public int Compare(int a, int b) { return (a / 10).CompareTo(b / 10); } } class IC : SCG.IComparer<int>, IComparable<int>, SCG.IComparer<IC>, IComparable<IC> { public int Compare(int a, int b) { return a > b ? 1 : a < b ? -1 : 0; } public int Compare(IC a, IC b) { return a._i > b._i ? 1 : a._i < b._i ? -1 : 0; } private int _i; public int i { get { return _i; } set { _i = value; } } public IC() { } public IC(int i) { _i = i; } public int CompareTo(int that) { return _i > that ? 1 : _i < that ? -1 : 0; } public bool Equals(int that) { return _i == that; } public int CompareTo(IC that) { return _i > that._i ? 1 : _i < that._i ? -1 : 0; } public bool Equals(IC that) { return _i == that._i; } public static bool eq(SCG.IEnumerable<int> me, params int[] that) { int i = 0, maxind = that.Length - 1; foreach (int item in me) if (i > maxind || item != that[i++]) return false; return i == maxind + 1; } public static bool seteq(ICollectionValue<int> me, params int[] that) { int[] me2 = me.ToArray(); Array.Sort(me2); int i = 0, maxind = that.Length - 1; foreach (int item in me2) if (i > maxind || item != that[i++]) return false; return i == maxind + 1; } public static bool seteq(ICollectionValue<KeyValuePair<int, int>> me, params int[] that) { ArrayList<KeyValuePair<int, int>> first = new ArrayList<KeyValuePair<int, int>>(); first.AddAll(me); ArrayList<KeyValuePair<int, int>> other = new ArrayList<KeyValuePair<int, int>>(); for (int i = 0; i < that.Length; i += 2) { other.Add(new KeyValuePair<int, int>(that[i], that[i + 1])); } return other.UnsequencedEquals(first); } } class RevIC : SCG.IComparer<int> { public int Compare(int a, int b) { return a > b ? -1 : a < b ? 1 : 0; } } public class FunEnumerable : SCG.IEnumerable<int> { int size; Fun<int, int> f; public FunEnumerable(int size, Fun<int, int> f) { this.size = size; this.f = f; } public SCG.IEnumerator<int> GetEnumerator() { for (int i = 0; i < size; i++) yield return f(i); } #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion } public class BadEnumerableException : Exception { } public class BadEnumerable<T> : CollectionValueBase<T>, ICollectionValue<T> { T[] contents; Exception exception; public BadEnumerable(Exception exception, params T[] contents) { this.contents = (T[])contents.Clone(); this.exception = exception; } public override SCG.IEnumerator<T> GetEnumerator() { for (int i = 0; i < contents.Length; i++) yield return contents[i]; throw exception; } public override bool IsEmpty { get { return false; } } public override int Count { get { return contents.Length + 1; } } public override Speed CountSpeed { get { return Speed.Constant; } } public override T Choose() { throw exception; } } public class CollectionEventList<T> { ArrayList<CollectionEvent<T>> happened; EventTypeEnum listenTo; SCG.IEqualityComparer<T> itemequalityComparer; public CollectionEventList(SCG.IEqualityComparer<T> itemequalityComparer) { happened = new ArrayList<CollectionEvent<T>>(); this.itemequalityComparer = itemequalityComparer; } public void Listen(ICollectionValue<T> list, EventTypeEnum listenTo) { this.listenTo = listenTo; if ((listenTo & EventTypeEnum.Changed) != 0) list.CollectionChanged += new CollectionChangedHandler<T>(changed); if ((listenTo & EventTypeEnum.Cleared) != 0) list.CollectionCleared += new CollectionClearedHandler<T>(cleared); if ((listenTo & EventTypeEnum.Removed) != 0) list.ItemsRemoved += new ItemsRemovedHandler<T>(removed); if ((listenTo & EventTypeEnum.Added) != 0) list.ItemsAdded += new ItemsAddedHandler<T>(added); if ((listenTo & EventTypeEnum.Inserted) != 0) list.ItemInserted += new ItemInsertedHandler<T>(inserted); if ((listenTo & EventTypeEnum.RemovedAt) != 0) list.ItemRemovedAt += new ItemRemovedAtHandler<T>(removedAt); } public void Add(CollectionEvent<T> e) { happened.Add(e); } /// <summary> /// Check that we have seen exactly the events in expected that match listenTo. /// </summary> /// <param name="expected"></param> public void Check(SCG.IEnumerable<CollectionEvent<T>> expected) { int i = 0; foreach (CollectionEvent<T> expectedEvent in expected) { if ((expectedEvent.Act & listenTo) == 0) continue; if (i >= happened.Count) Assert.Fail(string.Format("Event number {0} did not happen:\n expected {1}", i, expectedEvent)); if (!expectedEvent.Equals(happened[i], itemequalityComparer)) Assert.Fail(string.Format("Event number {0}:\n expected {1}\n but saw {2}", i, expectedEvent, happened[i])); i++; } if (i < happened.Count) Assert.Fail(string.Format("Event number {0} seen but no event expected:\n {1}", i, happened[i])); happened.Clear(); } public void Clear() { happened.Clear(); } public void Print(System.IO.TextWriter writer) { happened.Apply(delegate(CollectionEvent<T> e) { writer.WriteLine(e); }); } void changed(object sender) { happened.Add(new CollectionEvent<T>(EventTypeEnum.Changed, new EventArgs(), sender)); } void cleared(object sender, ClearedEventArgs eventArgs) { happened.Add(new CollectionEvent<T>(EventTypeEnum.Cleared, eventArgs, sender)); } void added(object sender, ItemCountEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventTypeEnum.Added, eventArgs, sender)); } void removed(object sender, ItemCountEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventTypeEnum.Removed, eventArgs, sender)); } void inserted(object sender, ItemAtEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventTypeEnum.Inserted, eventArgs, sender)); } void removedAt(object sender, ItemAtEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventTypeEnum.RemovedAt, eventArgs, sender)); } } public sealed class CollectionEvent<T> { public readonly EventTypeEnum Act; public readonly EventArgs Args; public readonly object Sender; public CollectionEvent(EventTypeEnum act, EventArgs args, object sender) { this.Act = act; this.Args = args; this.Sender = sender; } public bool Equals(CollectionEvent<T> otherEvent, SCG.IEqualityComparer<T> itemequalityComparer) { if (otherEvent == null || Act != otherEvent.Act || !object.ReferenceEquals(Sender, otherEvent.Sender)) return false; switch (Act) { case EventTypeEnum.None: break; case EventTypeEnum.Changed: return true; case EventTypeEnum.Cleared: if (Args is ClearedRangeEventArgs) { ClearedRangeEventArgs a = Args as ClearedRangeEventArgs, o = otherEvent.Args as ClearedRangeEventArgs; if (o == null) return false; return a.Full == o.Full && a.Start == o.Start && a.Count == o.Count; } else { if (otherEvent.Args is ClearedRangeEventArgs) return false; ClearedEventArgs a = Args as ClearedEventArgs, o = otherEvent.Args as ClearedEventArgs; return a.Full == o.Full && a.Count == o.Count; } case EventTypeEnum.Added: { ItemCountEventArgs<T> a = Args as ItemCountEventArgs<T>, o = otherEvent.Args as ItemCountEventArgs<T>; return itemequalityComparer.Equals(a.Item, o.Item) && a.Count == o.Count; } case EventTypeEnum.Removed: { ItemCountEventArgs<T> a = Args as ItemCountEventArgs<T>, o = otherEvent.Args as ItemCountEventArgs<T>; return itemequalityComparer.Equals(a.Item, o.Item) && a.Count == o.Count; } case EventTypeEnum.Inserted: { ItemAtEventArgs<T> a = Args as ItemAtEventArgs<T>, o = otherEvent.Args as ItemAtEventArgs<T>; return a.Index == o.Index && itemequalityComparer.Equals(a.Item, o.Item); } case EventTypeEnum.RemovedAt: { ItemAtEventArgs<T> a = Args as ItemAtEventArgs<T>, o = otherEvent.Args as ItemAtEventArgs<T>; return a.Index == o.Index && itemequalityComparer.Equals(a.Item, o.Item); } } throw new ApplicationException("Illegal Act: " + Act); } public override string ToString() { return string.Format("Act: {0}, Args : {1}, Source : {2}", Act, Args, Sender); } } public class CHC { static public int unsequencedhashcode(params int[] a) { int h = 0; foreach (int i in a) { h += (int)(((uint)i * 1529784657 + 1) ^ ((uint)i * 2912831877) ^ ((uint)i * 1118771817 + 2)); } return h; } static public int sequencedhashcode(params int[] a) { int h = 0; foreach (int i in a) { h = h * 31 + i; } return h; } } //This class is a modified sample from VS2005 beta1 documentation public class RadixFormatProvider : IFormatProvider { RadixFormatter _radixformatter; public RadixFormatProvider(int radix) { if (radix < 2 || radix > 36) throw new ArgumentException(String.Format( "The radix \"{0}\" is not in the range 2..36.", radix)); _radixformatter = new RadixFormatter(radix); } public object GetFormat(Type argType) { if (argType == typeof(ICustomFormatter)) return _radixformatter; else return null; } } //This class is a modified sample from VS2005 beta1 documentation public class RadixFormatter : ICustomFormatter { int radix; public RadixFormatter(int radix) { if (radix < 2 || radix > 36) throw new ArgumentException(String.Format( "The radix \"{0}\" is not in the range 2..36.", radix)); this.radix = radix; } // The value to be formatted is returned as a signed string // of digits from the rDigits array. private static char[] rDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; public string Format(string formatString, object argToBeFormatted, IFormatProvider provider) { /*switch (Type.GetTypeCode(argToBeFormatted.GetType())) { case TypeCode.Boolean: break; case TypeCode.Byte: break; case TypeCode.Char: break; case TypeCode.DBNull: break; case TypeCode.DateTime: break; case TypeCode.Decimal: break; case TypeCode.Double: break; case TypeCode.Empty: break; case TypeCode.Int16: break; case TypeCode.Int32: break; case TypeCode.Int64: break; case TypeCode.Object: break; case TypeCode.SByte: break; case TypeCode.Single: break; case TypeCode.String: break; case TypeCode.UInt16: break; case TypeCode.UInt32: break; case TypeCode.UInt64: break; }*/ int intToBeFormatted; try { intToBeFormatted = (int)argToBeFormatted; } catch (Exception) { if (argToBeFormatted is IFormattable) return ((IFormattable)argToBeFormatted). ToString(formatString, provider); else return argToBeFormatted.ToString(); } return formatInt(intToBeFormatted); } private string formatInt(int intToBeFormatted) { // The formatting is handled here. if (intToBeFormatted == 0) return "0"; int digitIndex = 0; int intPositive; char[] outDigits = new char[31]; // Verify that the argument can be converted to a int integer. // Extract the magnitude for conversion. intPositive = Math.Abs(intToBeFormatted); // Convert the magnitude to a digit string. for (digitIndex = 0; digitIndex <= 32; digitIndex++) { if (intPositive == 0) break; outDigits[outDigits.Length - digitIndex - 1] = rDigits[intPositive % radix]; intPositive /= radix; } // Add a minus sign if the argument is negative. if (intToBeFormatted < 0) outDigits[outDigits.Length - digitIndex++ - 1] = '-'; return new string(outDigits, outDigits.Length - digitIndex, digitIndex); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using System.Diagnostics; using System.IO; using System.Reflection; namespace ChooseAndCopy { public partial class Form1 : Form { Assembly _assembly; Stream _nppStream; StreamReader _StreamReader; public Form1() { InitializeComponent(); } //private void SourceFolder_Bin_btn_Click(object sender, EventArgs e) //{ //} //private void TargetFolder_Bin_btn_Click(object sender, EventArgs e) //{ //} //private void copy_bop_config_btn_Click(object sender, EventArgs e) //{ //} private void SourceFolder_Bin_btn_Click(object sender, EventArgs e) { /* OpenFileDialog openSourceFolder = new OpenFileDialog(); openSourceFolder.ShowReadOnly = true; openSourceFolder.ShowDialog(); this.sourceBinFolder_lable.Text = openSourceFolder.FileName;*/ FolderBrowserDialog binSourceFolder = new FolderBrowserDialog(); binSourceFolder.ShowNewFolderButton = false; binSourceFolder.ShowDialog(); this.sourceBinFolder_lable.Text = binSourceFolder.SelectedPath; ArrayList al = new ArrayList(); al = RearrangerHelper.GetFoldersAndFilesInSourceBinFolder(this.sourceBinFolder_lable.Text); LoadAvailableItems(al, tabPage_BOP); } private void LoadAvailableItems(ArrayList al, TabPage tp) { try { if (tp == this.tabPage_BOP) this.lb1.Items.Clear(); else if (tp == this.tabPage_etc) this.lb3.Items.Clear(); foreach (object o in al) { FolderFile f = (FolderFile)o; string filename = f.name; filename = truncateItemName(filename, tp); //string filetype = f.ft.ToString(); //RearrangerHelper rah = new RearrangerHelper(); if (f.ft == fileType.folder) filename = RearrangerHelper.folderLabel + filename; if (tp == this.tabPage_BOP) lb1.Items.Add(filename); else if (tp == this.tabPage_etc) lb3.Items.Add(filename); } } catch (Exception ex) { //string str = "Exception detected when populating the available files list"; throw new Exception(ex.ToString()); } } private string truncateItemName(string name, TabPage tp) { int length = 0; if (tp == this.tabPage_BOP) length = this.sourceBinFolder_lable.Text.Length; else if (tp == this.tabPage_etc) length = this.sourceEtcFolder_lable.Text.Length; return name.Substring(length + 1); } private void selectBtn_Click(object sender, EventArgs e) { string item; for (int i = 0; i < lb1.Items.Count; i ++ ) { item = lb1.Items[i].ToString(); if (this.lb1.SelectedIndex >= 0) { lb2.Items.Add(this.lb1.Items[this.lb1.SelectedIndex]); this.lb1.Items.RemoveAt(this.lb1.SelectedIndex); i--; } } } private void deselectBtn_Click(object sender, EventArgs e) { string item; for (int i = 0; i < lb2.Items.Count; i++) { item = lb2.Items[i].ToString(); if (this.lb2.SelectedIndex >= 0) { lb1.Items.Add(this.lb2.Items[this.lb2.SelectedIndex]);//this.lb2.Items[this.lb2.SelectedIndex] lb1.Refresh(); this.lb2.Items.RemoveAt(this.lb2.SelectedIndex); } } } private void TargetFolder_Bin_btn_Click(object sender, EventArgs e) { FolderBrowserDialog binSourceFolder = new FolderBrowserDialog(); binSourceFolder.ShowNewFolderButton = false; binSourceFolder.ShowDialog(); //this.sourceBinFolder_lable.Text = binSourceFolder.SelectedPath; if (binSourceFolder.SelectedPath.Contains("bin\\bop_config")) this.bop_config_target_folder_label.Text = binSourceFolder.SelectedPath; else { //this.bop_config_target_folder_label.Text = "Please choose target folder \"bin\\bop_config\"!"; this.bop_config_target_folder_label.Text = ""; MessageBox.Show("Please choose target folder \"bin\\bop_config\"!", "REMINDER",MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void copy_bop_config_btn_Click(object sender, EventArgs e) { if (this.bop_config_target_folder_label.Text != "") { string targetPath = this.bop_config_target_folder_label.Text; string sourcePath = this.sourceBinFolder_lable.Text; bool isBatchMode = false; if (_selectedIndex_bop >= 1) //for batch { isBatchMode = true; if (this.includesAll_btn.Checked == true || this.excludeSelected_btn.Checked == true) { ArrayList al_target_all_selected_nodes = new ArrayList(); ArrayList al_source_all_selected_nodes = new ArrayList(); ArrayList al_excluded_folders = new ArrayList(); bool reselectNeeded = false; //if reselected = true, means files have been excluded, which is not expected. //Then reselecting subfolders/files or changing option is needed. bool isSource = false; al_target_all_selected_nodes = ChooseAndCopy.RearrangerHelper.GetSourceOrTargetFoldersForSelectedNodes(targetPath, _selectedIndex_bop, isSource); isSource = true; al_source_all_selected_nodes = ChooseAndCopy.RearrangerHelper.GetSourceOrTargetFoldersForSelectedNodes(sourcePath, _selectedIndex_bop, isSource); if (this.excludeSelected_btn.Checked == true) { for (int i = 0; i < lb2.Items.Count; i++) { if (lb2.Items[i].ToString().ToLower().Contains("folder : ")) al_excluded_folders.Add(lb2.Items[i].ToString().Remove(0, ChooseAndCopy.RearrangerHelper.folderLabel.Length)); else { //write error log here -- only folders should be selected for batch mode MessageBox.Show("Only folders can be excluded when using Batch Mode!", "REMINDER", MessageBoxButtons.OK, MessageBoxIcon.Error); reselectNeeded = true; } } } if (!reselectNeeded) { if (al_source_all_selected_nodes.Count == al_target_all_selected_nodes.Count) { string _sourcePath; string _targetPath; for (int i = 0; i < al_source_all_selected_nodes.Count; i++) { _sourcePath = al_source_all_selected_nodes[i].ToString(); _targetPath = al_target_all_selected_nodes[i].ToString(); RearrangerHelper.Copy_BOP_ETC_Files(_sourcePath, _targetPath, al_excluded_folders, tabPage_etc, this.filter_out_sys_altsys_files_ckb.Checked, isBatchMode); } foreach (string _target_path_to_open in al_target_all_selected_nodes) { if (this.open_etc_folder_cbx.Checked) { openFolder(_target_path_to_open); } } } } } else { MessageBox.Show("\"Only include selected subfolders/files from the source folder\" does NOT support Batch Mode!", "REMINDER", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else //for just one at one time { isBatchMode = false; ArrayList al_source = new ArrayList(); if (this.includesAll_btn.Checked == true || this.excludeSelected_btn.Checked == true) { for (int i = 0; i < lb1.Items.Count; i++) { al_source.Add(lb1.Items[i].ToString()); } } else if (this.onlySelected_btn.Checked == true) { for (int i = 0; i < lb2.Items.Count; i++) { al_source.Add(lb2.Items[i].ToString()); } } RearrangerHelper.Copy_BOP_ETC_Files(sourcePath, targetPath, al_source, tabPage_BOP, false, isBatchMode); if (this.open_bop_config_folder_cbx.Checked) { string myPath = targetPath; System.Diagnostics.Process prc = new System.Diagnostics.Process(); prc.StartInfo.FileName = myPath; prc.Start(); } } } } private void includesAll_btn_CheckedChanged(object sender, EventArgs e) { if (this.includesAll_btn.Checked == true) { ArrayList al = new ArrayList(); al = RearrangerHelper.GetFoldersAndFilesInSourceBinFolder(this.sourceBinFolder_lable.Text); LoadAvailableItems(al, tabPage_BOP); this.lb2.Items.Clear(); } } private void selectBtn_b_Click(object sender, EventArgs e) { string item; for (int i = 0; i < lb3.Items.Count; i++) { item = lb3.Items[i].ToString(); if (this.lb3.SelectedIndex >= 0) { lb4.Items.Add(this.lb3.Items[this.lb3.SelectedIndex]); this.lb3.Items.RemoveAt(this.lb3.SelectedIndex); i--; } } } private void deselectBtn_b_Click(object sender, EventArgs e) { string item; ArrayList al= new ArrayList(); for (int i = 0; i < lb4.Items.Count; i++) { item = lb4.Items[i].ToString(); if (this.lb4.SelectedIndex >= 0) { //lb3.Items.Add(this.lb4.Items[this.lb4.SelectedIndex]); al.Add(this.lb4.Items[this.lb4.SelectedIndex]); lb3.Items.Add(al[0]); lb3.Refresh(); this.lb4.Items.RemoveAt(this.lb4.SelectedIndex); } } } private void includesAll_btn_CheckedChanged_b(object sender, EventArgs e) { if (this.includesAll_btn_b.Checked == true) { ArrayList al = new ArrayList(); al = RearrangerHelper.GetFoldersAndFilesInSourceBinFolder(this.sourceEtcFolder_lable.Text); LoadAvailableItems(al, tabPage_etc); this.lb4.Items.Clear(); } } private void SourceFolder_etc_btn_Click(object sender, EventArgs e) { FolderBrowserDialog binSourceFolder = new FolderBrowserDialog(); binSourceFolder.ShowNewFolderButton = false; binSourceFolder.ShowDialog(); this.sourceEtcFolder_lable.Text = binSourceFolder.SelectedPath; ArrayList al = new ArrayList(); al = RearrangerHelper.GetFoldersAndFilesInSourceBinFolder(this.sourceEtcFolder_lable.Text); LoadAvailableItems(al, tabPage_etc); } private void TargetFolder_etc_btn_Click(object sender, EventArgs e) { FolderBrowserDialog binSourceFolder = new FolderBrowserDialog(); binSourceFolder.ShowNewFolderButton = false; binSourceFolder.ShowDialog(); this.etc_target_folder_label.Text = binSourceFolder.SelectedPath; } private void copy_etc_btn_Click(object sender, EventArgs e) { string targetPath = this.etc_target_folder_label.Text; string sourcePath = this.sourceEtcFolder_lable.Text; bool isBatchMode; if (_selectedIndex_etc >= 1) //for batch { isBatchMode = true; if (this.includesAll_btn_b.Checked == true || this.excludeSelected_btn_b.Checked == true) { ArrayList al_target_all_selected_nodes = new ArrayList(); ArrayList al_source_all_selected_nodes = new ArrayList(); ArrayList al_excluded_folders = new ArrayList(); bool reselectNeeded = false; //if reselected = true, means files have been excluded, which is not expected. //Then reselecting subfolders/files or changing option is needed. bool isSource = false; al_target_all_selected_nodes = ChooseAndCopy.RearrangerHelper.GetSourceOrTargetFoldersForSelectedNodes(targetPath, _selectedIndex_etc, isSource); isSource = true; al_source_all_selected_nodes = ChooseAndCopy.RearrangerHelper.GetSourceOrTargetFoldersForSelectedNodes(sourcePath, _selectedIndex_etc, isSource); if (this.excludeSelected_btn_b.Checked == true) { for (int i = 0; i < lb4.Items.Count; i++) { if (lb4.Items[i].ToString().ToLower().Contains("folder : ")) al_excluded_folders.Add(lb4.Items[i].ToString().Remove(0, ChooseAndCopy.RearrangerHelper.folderLabel.Length)); else { //write error log here -- only folders should be selected for batch mode MessageBox.Show("Only folders can be excluded when using Batch Mode!", "REMINDER",MessageBoxButtons.OK, MessageBoxIcon.Error); reselectNeeded = true; } } } if (!reselectNeeded) { if (al_source_all_selected_nodes.Count == al_target_all_selected_nodes.Count) { string _sourcePath; string _targetPath; for (int i = 0; i < al_source_all_selected_nodes.Count; i++) { _sourcePath = al_source_all_selected_nodes[i].ToString(); _targetPath = al_target_all_selected_nodes[i].ToString(); RearrangerHelper.Copy_BOP_ETC_Files(_sourcePath, _targetPath, al_excluded_folders, tabPage_etc, this.filter_out_sys_altsys_files_ckb.Checked, isBatchMode); } foreach (string _target_path_to_open in al_target_all_selected_nodes) { if (this.open_etc_folder_cbx.Checked) { openFolder(_target_path_to_open); } } } } } else { MessageBox.Show("\"Only include selected subfolders/files from the source folder\" does NOT support Batch Mode!", "REMINDER",MessageBoxButtons.OK, MessageBoxIcon.Error); } } else //for just one at one time { isBatchMode = false; ArrayList al_source = new ArrayList(); if (this.includesAll_btn_b.Checked == true || this.excludeSelected_btn_b.Checked == true) { for (int i = 0; i < lb3.Items.Count; i++) { al_source.Add(lb3.Items[i].ToString()); } } else if (this.onlySelected_btn_b.Checked == true) { for (int i = 0; i < lb4.Items.Count; i++) { al_source.Add(lb4.Items[i].ToString()); } } RearrangerHelper.Copy_BOP_ETC_Files(sourcePath, targetPath, al_source, tabPage_etc, this.filter_out_sys_altsys_files_ckb.Checked, isBatchMode); if (this.open_etc_folder_cbx.Checked) { openFolder(targetPath); } } } private static void openFolder(string targetPath) { string myPath = targetPath; System.Diagnostics.Process prc = new System.Diagnostics.Process(); prc.StartInfo.FileName = myPath; prc.Start(); } private void SourceFileBtn_Click(object sender, EventArgs e) { OpenFileDialog dlgOpenFile = new OpenFileDialog(); dlgOpenFile.ShowReadOnly = true; dlgOpenFile.ShowDialog(); this.SourceFileName.Text = dlgOpenFile.FileName; } private void TargetFileBtn_Click(object sender, EventArgs e) { OpenFileDialog dlgOpenFile = new OpenFileDialog(); dlgOpenFile.ShowReadOnly = true; dlgOpenFile.ShowDialog(); this.BOP_sysinitFileName.Text = dlgOpenFile.FileName; } private void altsysinitFilePath_TZ_btn_Click(object sender, EventArgs e) { OpenFileDialog dlgOpenFile2 = new OpenFileDialog(); dlgOpenFile2.ShowReadOnly = true; dlgOpenFile2.ShowDialog(); this.altsysinitFilePath.Text = dlgOpenFile2.FileName; } private void sysinitFilePath_TZ_btn_Click(object sender, EventArgs e) { OpenFileDialog dlgOpenFile3 = new OpenFileDialog(); dlgOpenFile3.ShowReadOnly = true; dlgOpenFile3.ShowDialog(); this.sysinitFileFath.Text = dlgOpenFile3.FileName; } private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked == true) { this.comboBox1.Enabled = true; } else { this.comboBox1.Enabled = false; } } private void ReplaceInfoBtn_Click(object sender, EventArgs e) { _selectedIndex = Convert.ToInt16(comboBox1.SelectedItem); ArrayList al_source = new ArrayList(); ArrayList al_dest = new ArrayList(); if (_selectedIndex >= 1) { al_source = ReplaceInfo.ReplacementHelper.GetSourceDirectoriesOfSysinitFilesForSelectedNodes(this.SourceFileName.Text, _selectedIndex); al_dest = ReplaceInfo.ReplacementHelper.GetTargetDirectoriesOfBOPSysinitFilesForSelectedNodes(this.BOP_sysinitFileName.Text, _selectedIndex); if (al_dest.Count == al_source.Count && al_source.Count == _selectedIndex) { for (int i = 0; i < _selectedIndex; i++) { string sourceFileName = al_source[i].ToString(); string targetFileName = al_dest[i].ToString(); int nodeNumber = i + 1; Hashtable ht_extractedInfo = ReplaceInfo.ReplacementHelper.ReadSourceFile(sourceFileName, nodeNumber); ReplaceInfo.ReplacementHelper.ReadTargetFiles(targetFileName, this.altsysinitFilePath.Text, this.sysinitFileFath.Text, ht_extractedInfo, this.openFilesCHKBOX.Checked); } } else { //write error log -- cannot get matched source sysinit files and target BOP_sysinit files, please check!!! } } else { Hashtable ht_extractedInfo = ReplaceInfo.ReplacementHelper.ReadSourceFile(this.SourceFileName.Text, 999); ReplaceInfo.ReplacementHelper.ReadTargetFiles(this.BOP_sysinitFileName.Text, this.altsysinitFilePath.Text, this.sysinitFileFath.Text, ht_extractedInfo, this.openFilesCHKBOX.Checked); } } int _selectedIndex; int _selectedIndex_etc; int _selectedIndex_bop; private void comboBox1_SelectedValueChanged(object sender, EventArgs e) { _selectedIndex = Convert.ToInt16(comboBox1.SelectedItem);//.SelectedIndex; } private void comboBox1_DropDown(object sender, EventArgs e) { comboBox1.Refresh(); System.Object[] ItemObject = new System.Object[13]; for (int i = 1; i <= 13; i++) { ItemObject[i - 1] = i; } if (!comboBox1.Items.Contains(12)) comboBox1.Items.AddRange(ItemObject); } private void checkBox_bop_CheckedChanged(object sender, EventArgs e) { if (checkBox2.Checked == true) { this.comboBox2.Enabled = true; } else { this.comboBox2.Enabled = false; } } private void comboBox_bop_SelectedValueChanged(object sender, EventArgs e) { _selectedIndex_bop = Convert.ToInt16(comboBox2.SelectedItem); } private void comboBox_bop_DropDown(object sender, EventArgs e) { comboBox2.Refresh(); System.Object[] ItemObject = new System.Object[13]; for (int i = 1; i <= 13; i++) { ItemObject[i - 1] = i; } if (!comboBox2.Items.Contains(12)) comboBox2.Items.AddRange(ItemObject); } private void checkBox_etc_CheckedChanged(object sender, EventArgs e) { if (checkBox3.Checked == true) { this.comboBox3.Enabled = true; } else { this.comboBox3.Enabled = false; } } private void comboBox_etc_SelectedValueChanged(object sender, EventArgs e) { _selectedIndex_etc = Convert.ToInt16(comboBox3.SelectedItem); } private void comboBox_etc_DropDown(object sender, EventArgs e) { comboBox3.Refresh(); System.Object[] ItemObject = new System.Object[13]; for (int i = 1; i <= 13; i++) { ItemObject[i - 1] = i; } if (!comboBox3.Items.Contains(12)) comboBox3.Items.AddRange(ItemObject); } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel1.LinkVisited = true; // Navigate to a URL. System.Diagnostics.Process.Start("http://notepad-plus-plus.org/download"); } private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.linkLabel2.LinkVisited = true; // Navigate to a URL. System.Diagnostics.Process.Start("http://winmerge.org/downloads/"); } } }
--- /dev/null 2016-04-26 20:27:44.000000000 -0400 +++ src/System.Net.NetworkInformation/src/SR.cs 2016-04-26 20:28:14.800658000 -0400 @@ -0,0 +1,199 @@ +using System; +using System.Resources; + +namespace FxResources.System.Net.NetworkInformation +{ + internal static class SR + { + + } +} + + +namespace System +{ + internal static class SR + { + private static ResourceManager s_resourceManager; + + private const string s_resourcesName = "FxResources.System.Net.NetworkInformation.SR"; + + internal static string net_bad_mac_address + { + get + { + return SR.GetResourceString("net_bad_mac_address", null); + } + } + + internal static string net_collection_readonly + { + get + { + return SR.GetResourceString("net_collection_readonly", null); + } + } + + internal static string net_completed_result + { + get + { + return SR.GetResourceString("net_completed_result", null); + } + } + + internal static string net_FailedToParseNetworkFile + { + get + { + return SR.GetResourceString("net_FailedToParseNetworkFile", null); + } + } + + internal static string net_InformationUnavailableOnPlatform + { + get + { + return SR.GetResourceString("net_InformationUnavailableOnPlatform", null); + } + } + + internal static string net_io_invalidasyncresult + { + get + { + return SR.GetResourceString("net_io_invalidasyncresult", null); + } + } + + internal static string net_io_invalidendcall + { + get + { + return SR.GetResourceString("net_io_invalidendcall", null); + } + } + + internal static string net_log_exception + { + get + { + return SR.GetResourceString("net_log_exception", null); + } + } + + internal static string net_MethodNotImplementedException + { + get + { + return SR.GetResourceString("net_MethodNotImplementedException", null); + } + } + + internal static string net_NoLoopback + { + get + { + return SR.GetResourceString("net_NoLoopback", null); + } + } + + internal static string net_PInvokeError + { + get + { + return SR.GetResourceString("net_PInvokeError", null); + } + } + + internal static string net_PropertyNotImplementedException + { + get + { + return SR.GetResourceString("net_PropertyNotImplementedException", null); + } + } + + private static ResourceManager ResourceManager + { + get + { + if (SR.s_resourceManager == null) + { + SR.s_resourceManager = new ResourceManager(SR.ResourceType); + } + return SR.s_resourceManager; + } + } + + internal static Type ResourceType + { + get + { + return typeof(FxResources.System.Net.NetworkInformation.SR); + } + } + + internal static string Format(string resourceFormat, params object[] args) + { + if (args == null) + { + return resourceFormat; + } + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, args); + } + return string.Concat(resourceFormat, string.Join(", ", args)); + } + + internal static string Format(string resourceFormat, object p1) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1); + } + return string.Join(", ", new object[] { resourceFormat, p1 }); + } + + internal static string Format(string resourceFormat, object p1, object p2) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1, p2); + } + return string.Join(", ", new object[] { resourceFormat, p1, p2 }); + } + + internal static string Format(string resourceFormat, object p1, object p2, object p3) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1, p2, p3); + } + return string.Join(", ", new object[] { resourceFormat, p1, p2, p3 }); + } + + internal static string GetResourceString(string resourceKey, string defaultString) + { + string str = null; + try + { + str = SR.ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException missingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(str, StringComparison.Ordinal)) + { + return defaultString; + } + return str; + } + + private static bool UsingResourceKeys() + { + return false; + } + } +}
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/type/timeofday.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Type { /// <summary>Holder for reflection information generated from google/type/timeofday.proto</summary> public static partial class TimeofdayReflection { #region Descriptor /// <summary>File descriptor for google/type/timeofday.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TimeofdayReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chtnb29nbGUvdHlwZS90aW1lb2ZkYXkucHJvdG8SC2dvb2dsZS50eXBlIksK", "CVRpbWVPZkRheRINCgVob3VycxgBIAEoBRIPCgdtaW51dGVzGAIgASgFEg8K", "B3NlY29uZHMYAyABKAUSDQoFbmFub3MYBCABKAVCaQoPY29tLmdvb2dsZS50", "eXBlQg5UaW1lT2ZEYXlQcm90b1ABWj5nb29nbGUuZ29sYW5nLm9yZy9nZW5w", "cm90by9nb29nbGVhcGlzL3R5cGUvdGltZW9mZGF5O3RpbWVvZmRheaICA0dU", "UGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.TimeOfDay), global::Google.Type.TimeOfDay.Parser, new[]{ "Hours", "Minutes", "Seconds", "Nanos" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Represents a time of day. The date and time zone are either not significant /// or are specified elsewhere. An API may chose to allow leap seconds. Related /// types are [google.type.Date][google.type.Date] and `google.protobuf.Timestamp`. /// </summary> public sealed partial class TimeOfDay : pb::IMessage<TimeOfDay> { private static readonly pb::MessageParser<TimeOfDay> _parser = new pb::MessageParser<TimeOfDay>(() => new TimeOfDay()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TimeOfDay> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Type.TimeofdayReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeOfDay() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeOfDay(TimeOfDay other) : this() { hours_ = other.hours_; minutes_ = other.minutes_; seconds_ = other.seconds_; nanos_ = other.nanos_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeOfDay Clone() { return new TimeOfDay(this); } /// <summary>Field number for the "hours" field.</summary> public const int HoursFieldNumber = 1; private int hours_; /// <summary> /// Hours of day in 24 hour format. Should be from 0 to 23. An API may choose /// to allow the value "24:00:00" for scenarios like business closing time. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Hours { get { return hours_; } set { hours_ = value; } } /// <summary>Field number for the "minutes" field.</summary> public const int MinutesFieldNumber = 2; private int minutes_; /// <summary> /// Minutes of hour of day. Must be from 0 to 59. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Minutes { get { return minutes_; } set { minutes_ = value; } } /// <summary>Field number for the "seconds" field.</summary> public const int SecondsFieldNumber = 3; private int seconds_; /// <summary> /// Seconds of minutes of the time. Must normally be from 0 to 59. An API may /// allow the value 60 if it allows leap-seconds. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Seconds { get { return seconds_; } set { seconds_ = value; } } /// <summary>Field number for the "nanos" field.</summary> public const int NanosFieldNumber = 4; private int nanos_; /// <summary> /// Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Nanos { get { return nanos_; } set { nanos_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TimeOfDay); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TimeOfDay other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Hours != other.Hours) return false; if (Minutes != other.Minutes) return false; if (Seconds != other.Seconds) return false; if (Nanos != other.Nanos) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Hours != 0) hash ^= Hours.GetHashCode(); if (Minutes != 0) hash ^= Minutes.GetHashCode(); if (Seconds != 0) hash ^= Seconds.GetHashCode(); if (Nanos != 0) hash ^= Nanos.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Hours != 0) { output.WriteRawTag(8); output.WriteInt32(Hours); } if (Minutes != 0) { output.WriteRawTag(16); output.WriteInt32(Minutes); } if (Seconds != 0) { output.WriteRawTag(24); output.WriteInt32(Seconds); } if (Nanos != 0) { output.WriteRawTag(32); output.WriteInt32(Nanos); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Hours != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Hours); } if (Minutes != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Minutes); } if (Seconds != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Seconds); } if (Nanos != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TimeOfDay other) { if (other == null) { return; } if (other.Hours != 0) { Hours = other.Hours; } if (other.Minutes != 0) { Minutes = other.Minutes; } if (other.Seconds != 0) { Seconds = other.Seconds; } if (other.Nanos != 0) { Nanos = other.Nanos; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Hours = input.ReadInt32(); break; } case 16: { Minutes = input.ReadInt32(); break; } case 24: { Seconds = input.ReadInt32(); break; } case 32: { Nanos = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using GenderPayGap.IdentityServer4.Models.Consent; using IdentityServer4; using IdentityServer4.Models; using IdentityServer4.Services; using IdentityServer4.Stores; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System.Linq; using System.Threading.Tasks; namespace GenderPayGap.IdentityServer4.Controllers { /// <summary> /// This controller processes the consent UI /// </summary> [Authorize] public class ConsentController : Controller { private readonly IIdentityServerInteractionService _interaction; private readonly IClientStore _clientStore; private readonly IResourceStore _resourceStore; private readonly ILogger<ConsentController> _logger; public ConsentController( IIdentityServerInteractionService interaction, IClientStore clientStore, IResourceStore resourceStore, ILogger<ConsentController> logger) { _interaction = interaction; _clientStore = clientStore; _resourceStore = resourceStore; _logger = logger; } /// <summary> /// Shows the consent screen /// </summary> /// <param name="returnUrl"></param> /// <returns></returns> [HttpGet] public async Task<IActionResult> Index(string returnUrl) { var vm = await BuildViewModelAsync(returnUrl); if (vm != null) { return View("Index", vm); } return View("Error"); } /// <summary> /// Handles the consent screen postback /// </summary> [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Index(ConsentInputModel model) { var result = await ProcessConsent(model); if (result.IsRedirect) { return Redirect(result.RedirectUri); } if (result.HasValidationError) { ModelState.AddModelError("", result.ValidationError); } if (result.ShowView) { return View("Index", result.ViewModel); } return View("Error"); } /*****************************************/ /* helper APIs for the ConsentController */ /*****************************************/ private async Task<ProcessConsentResult> ProcessConsent(ConsentInputModel model) { var result = new ProcessConsentResult(); ConsentResponse grantedConsent = null; // user clicked 'no' - send back the standard 'access_denied' response if (model.Button == "no") { grantedConsent = ConsentResponse.Denied; } // user clicked 'yes' - validate the data else if (model.Button == "yes" && model != null) { // if the user consented to some scope, build the response model if (model.ScopesConsented != null && model.ScopesConsented.Any()) { var scopes = model.ScopesConsented; if (ConsentOptions.EnableOfflineAccess == false) { scopes = scopes.Where(x => x != IdentityServerConstants.StandardScopes.OfflineAccess); } grantedConsent = new ConsentResponse { RememberConsent = model.RememberConsent, ScopesConsented = scopes.ToArray() }; } else { result.ValidationError = ConsentOptions.MustChooseOneErrorMessage; } } else { result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage; } if (grantedConsent != null) { // validate return url is still valid var request = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); if (request == null) return result; // communicate outcome of consent back to identityserver await _interaction.GrantConsentAsync(request, grantedConsent); // indicate that's it ok to redirect back to authorization endpoint result.RedirectUri = model.ReturnUrl; } else { // we need to redisplay the consent UI result.ViewModel = await BuildViewModelAsync(model.ReturnUrl, model); } return result; } private async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, ConsentInputModel model = null) { var request = await _interaction.GetAuthorizationContextAsync(returnUrl); if (request != null) { var client = await _clientStore.FindEnabledClientByIdAsync(request.ClientId); if (client != null) { var resources = await _resourceStore.FindEnabledResourcesByScopeAsync(request.ScopesRequested); if (resources != null && (resources.IdentityResources.Any() || resources.ApiResources.Any())) { return CreateConsentViewModel(model, returnUrl, request, client, resources); } else { _logger.LogError("No scopes matching: {0}", request.ScopesRequested.Aggregate((x, y) => x + ", " + y)); } } else { _logger.LogError("Invalid client id: {0}", request.ClientId); } } else { _logger.LogError("No consent request matching request: {0}", returnUrl); } return null; } private ConsentViewModel CreateConsentViewModel( ConsentInputModel model, string returnUrl, AuthorizationRequest request, Client client, Resources resources) { var vm = new ConsentViewModel(); vm.RememberConsent = model?.RememberConsent ?? true; vm.ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(); vm.ReturnUrl = returnUrl; vm.ClientName = client.ClientName ?? client.ClientId; vm.ClientUrl = client.ClientUri; vm.ClientLogoUrl = client.LogoUri; vm.AllowRememberConsent = client.AllowRememberConsent; vm.IdentityScopes = resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray(); vm.ResourceScopes = resources.ApiResources.SelectMany(x => x.Scopes).Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray(); if (ConsentOptions.EnableOfflineAccess && resources.OfflineAccess) { vm.ResourceScopes = vm.ResourceScopes.Union(new ScopeViewModel[] { GetOfflineAccessScope(vm.ScopesConsented.Contains(IdentityServerConstants.StandardScopes.OfflineAccess) || model == null) }); } return vm; } private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check) { return new ScopeViewModel { Name = identity.Name, DisplayName = identity.DisplayName, Description = identity.Description, Emphasize = identity.Emphasize, Required = identity.Required, Checked = check || identity.Required }; } public ScopeViewModel CreateScopeViewModel(Scope scope, bool check) { return new ScopeViewModel { Name = scope.Name, DisplayName = scope.DisplayName, Description = scope.Description, Emphasize = scope.Emphasize, Required = scope.Required, Checked = check || scope.Required }; } private ScopeViewModel GetOfflineAccessScope(bool check) { return new ScopeViewModel { Name = IdentityServerConstants.StandardScopes.OfflineAccess, DisplayName = ConsentOptions.OfflineAccessDisplayName, Description = ConsentOptions.OfflineAccessDescription, Emphasize = true, Checked = check }; } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2010 Johannes Rudolph. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Linq.Expressions; using System.Reflection; static partial class MoreEnumerable { /// <summary> /// Appends elements in the sequence as rows of a given <see cref="DataTable"/> object. /// </summary> /// <typeparam name="T">The type of the elements of <paramref name="source"/>.</typeparam> /// <typeparam name="TTable"></typeparam> /// <param name="source">The source.</param> /// <param name="table"></param> /// <returns> /// A <see cref="DataTable"/> or subclass representing the source. /// </returns> /// <remarks>This operator uses immediate execution.</remarks> public static TTable ToDataTable<T, TTable>(this IEnumerable<T> source, TTable table) where TTable : DataTable { return ToDataTable(source, table, null); } /// <summary> /// Appends elements in the sequence as rows of a given <see cref="DataTable"/> /// object with a set of lambda expressions specifying which members (property /// or field) of each element in the sequence will supply the column values. /// </summary> /// <typeparam name="T">The type of the elements of <paramref name="source"/>.</typeparam> /// <param name="source">The source.</param> /// <param name="expressions">Expressions providing access to element members.</param> /// <returns> /// A <see cref="DataTable"/> representing the source. /// </returns> /// <remarks>This operator uses immediate execution.</remarks> public static DataTable ToDataTable<T>(this IEnumerable<T> source, params Expression<Func<T, object>>[] expressions) { return ToDataTable(source, new DataTable(), expressions); } /// <summary> /// Converts a sequence to a <see cref="DataTable"/> object. /// </summary> /// <typeparam name="T">The type of the elements of <paramref name="source"/>.</typeparam> /// <param name="source">The source.</param> /// <returns> /// A <see cref="DataTable"/> representing the source. /// </returns> /// <remarks>This operator uses immediate execution.</remarks> public static DataTable ToDataTable<T>(this IEnumerable<T> source) { return ToDataTable(source, new DataTable()); } /// <summary> /// Appends elements in the sequence as rows of a given <see cref="DataTable"/> /// object with a set of lambda expressions specifying which members (property /// or field) of each element in the sequence will supply the column values. /// </summary> /// <typeparam name="T">The type of the elements of <paramref name="source"/>.</typeparam> /// <typeparam name="TTable">The type of the input and resulting <see cref="DataTable"/> object.</typeparam> /// <param name="source">The source.</param> /// <param name="table">The <see cref="DataTable"/> type of object where to add rows</param> /// <param name="expressions">Expressions providing access to element members.</param> /// <returns> /// A <see cref="DataTable"/> or subclass representing the source. /// </returns> /// <remarks>This operator uses immediate execution.</remarks> public static TTable ToDataTable<T, TTable>(this IEnumerable<T> source, TTable table, params Expression<Func<T, object>>[] expressions) where TTable : DataTable { if (source == null) throw new ArgumentNullException(nameof(source)); if (table == null) throw new ArgumentNullException(nameof(table)); var members = PrepareMemberInfos(expressions).ToArray(); members = BuildOrBindSchema(table, members); var shredder = CreateShredder<T>(members); // // Builds rows out of elements in the sequence and // add them to the table. // table.BeginLoadData(); try { foreach (var element in source) { var row = table.NewRow(); row.ItemArray = shredder(element); table.Rows.Add(row); } } finally { table.EndLoadData(); } return table; } static IEnumerable<MemberInfo> PrepareMemberInfos<T>(ICollection<Expression<Func<T, object>>> expressions) { // // If no lambda expressions supplied then reflect them off the source element type. // if (expressions == null || expressions.Count == 0) { return from m in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance) where m.MemberType == MemberTypes.Field || m.MemberType == MemberTypes.Property && ((PropertyInfo) m).GetIndexParameters().Length == 0 select m; } // // Ensure none of the expressions is null. // if (expressions.Any(e => e == null)) throw new ArgumentException("One of the supplied expressions was null.", nameof(expressions)); try { return expressions.Select(GetAccessedMember); } catch (ArgumentException e) { throw new ArgumentException("One of the supplied expressions is not allowed.", nameof(expressions), e); } MemberInfo GetAccessedMember(LambdaExpression lambda) { var body = lambda.Body; // If it's a field access, boxing was used, we need the field if (body.NodeType == ExpressionType.Convert || body.NodeType == ExpressionType.ConvertChecked) body = ((UnaryExpression)body).Operand; // Check if the member expression is valid and is a "first level" // member access e.g. not a.b.c return body is MemberExpression memberExpression && memberExpression.Expression.NodeType == ExpressionType.Parameter ? memberExpression.Member : throw new ArgumentException($"Illegal expression: {lambda}", nameof(lambda)); } } /// <remarks> /// The resulting array may contain null entries and those represent /// columns for which there is no source member supplying a value. /// </remarks> static MemberInfo[] BuildOrBindSchema(DataTable table, MemberInfo[] members) { // // Retrieve member information needed to // build or validate the table schema. // var columns = table.Columns; var schemas = from m in members let type = m.MemberType == MemberTypes.Property ? ((PropertyInfo) m).PropertyType : ((FieldInfo) m).FieldType select new { Member = m, Type = type.IsGenericType && typeof(Nullable<>) == type.GetGenericTypeDefinition() ? type.GetGenericArguments()[0] : type, Column = columns[m.Name], }; // // If the table has no columns then build the schema. // If it has columns then validate members against the columns // and re-order members to be aligned with column ordering. // if (columns.Count == 0) { columns.AddRange(schemas.Select(m => new DataColumn(m.Member.Name, m.Type)).ToArray()); } else { members = new MemberInfo[columns.Count]; foreach (var info in schemas) { var member = info.Member; var column = info.Column; if (column == null) throw new ArgumentException($"Column named '{member.Name}' is missing.", nameof(table)); if (info.Type != column.DataType) throw new ArgumentException($"Column named '{member.Name}' has wrong data type. It should be {info.Type} when it is {column.DataType}.", nameof(table)); members[column.Ordinal] = member; } } return members; } static Func<T, object[]> CreateShredder<T>(IEnumerable<MemberInfo> members) { var parameter = Expression.Parameter(typeof(T), "e"); // // It is valid for members sequence to have null entries, in // which case a null constant is emitted into the corresponding // row values array. // var initializers = members.Select(m => m != null ? (Expression)CreateMemberAccessor(m) : Expression.Constant(null, typeof(object))); var array = Expression.NewArrayInit(typeof(object), initializers); var lambda = Expression.Lambda<Func<T, object[]>>(array, parameter); return lambda.Compile(); UnaryExpression CreateMemberAccessor(MemberInfo member) { var access = Expression.MakeMemberAccess(parameter, member); return Expression.Convert(access, typeof(object)); } } } }
using System; using System.Runtime.InteropServices; using System.Text; namespace LuaInterface { #pragma warning disable 414 public class MonoPInvokeCallbackAttribute : System.Attribute { private Type type; public MonoPInvokeCallbackAttribute(Type t) { type = t; } } #pragma warning restore 414 public enum LuaTypes : int { LUA_TNONE = -1, LUA_TNIL = 0, LUA_TBOOLEAN = 1, LUA_TLIGHTUSERDATA = 2, LUA_TNUMBER = 3, LUA_TSTRING = 4, LUA_TTABLE = 5, LUA_TFUNCTION = 6, LUA_TUSERDATA = 7, LUA_TTHREAD = 8, } public enum LuaGCOptions { LUA_GCSTOP = 0, LUA_GCRESTART = 1, LUA_GCCOLLECT = 2, LUA_GCCOUNT = 3, LUA_GCCOUNTB = 4, LUA_GCSTEP = 5, LUA_GCSETPAUSE = 6, LUA_GCSETSTEPMUL = 7, } public enum LuaThreadStatus { LUA_YIELD = 1, LUA_ERRRUN = 2, LUA_ERRSYNTAX = 3, LUA_ERRMEM = 4, LUA_ERRERR = 5, } sealed class LuaIndexes { #if LUA_5_3 // for lua5.3 public static int LUA_REGISTRYINDEX = -1000000 - 1000; #else // for lua5.1 or luajit public static int LUA_REGISTRYINDEX = -10000; public static int LUA_GLOBALSINDEX = -10002; #endif } [StructLayout(LayoutKind.Sequential)] public struct ReaderInfo { public String chunkData; public bool finished; } public delegate int LuaCSFunction(IntPtr luaState); public delegate string LuaChunkReader(IntPtr luaState, ref ReaderInfo data, ref uint size); public delegate int LuaFunctionCallback(IntPtr luaState); public class LuaDLL { public static int LUA_MULTRET = -1; #if UNITY_IPHONE && !UNITY_EDITOR const string LUADLL = "__Internal"; #else const string LUADLL = "slua"; #endif // Thread Funcs [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_tothread(IntPtr L, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_xmove(IntPtr from, IntPtr to, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_yield(IntPtr L, int nresults); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_newthread(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_resume(IntPtr L, int narg); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_status(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pushthread(IntPtr L); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gc(IntPtr luaState, LuaGCOptions what, int data); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_typename(IntPtr luaState, int type); public static string lua_typenamestr(IntPtr luaState, LuaTypes type) { IntPtr p = lua_typename(luaState, (int)type); return Marshal.PtrToStringAnsi(p); } public static string luaL_typename(IntPtr luaState, int stackPos) { return LuaDLL.lua_typenamestr(luaState, LuaDLL.lua_type(luaState, stackPos)); } public static bool lua_isfunction(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TFUNCTION; } public static bool lua_islightuserdata(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TLIGHTUSERDATA; } public static bool lua_istable(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TTABLE; } public static bool lua_isthread(IntPtr luaState, int stackPos) { return lua_type(luaState, stackPos) == LuaTypes.LUA_TTHREAD; } public static void luaL_error(IntPtr luaState, string message) { LuaDLL.luaL_where(luaState, 1); LuaDLL.lua_pushstring(luaState, message); LuaDLL.lua_concat(luaState, 2); LuaDLL.lua_error(luaState); } public static void luaL_error(IntPtr luaState, string fmt, params object[] args) { string str = string.Format(fmt, args); luaL_error(luaState, str); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern string luaL_gsub(IntPtr luaState, string str, string pattern, string replacement); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfenv(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_isuserdata(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_lessthan(IntPtr luaState, int stackPos1, int stackPos2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rawequal(IntPtr luaState, int stackPos1, int stackPos2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_setfenv(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setfield(IntPtr luaState, int stackPos, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_callmeta(IntPtr luaState, int stackPos, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_newstate(); /// <summary>DEPRECATED - use luaL_newstate() instead!</summary> public static IntPtr lua_open() { return LuaDLL.luaL_newstate(); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_close(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_openlibs(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadstring(IntPtr luaState, string chunk); public static int luaL_dostring(IntPtr luaState, string chunk) { int result = LuaDLL.luaL_loadstring(luaState, chunk); if (result != 0) return result; return LuaDLL.lua_pcall(luaState, 0, -1, 0); } /// <summary>DEPRECATED - use luaL_dostring(IntPtr luaState, string chunk) instead!</summary> public static int lua_dostring(IntPtr luaState, string chunk) { return LuaDLL.luaL_dostring(luaState, chunk); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_createtable(IntPtr luaState, int narr, int nrec); public static void lua_newtable(IntPtr luaState) { LuaDLL.lua_createtable(luaState, 0, 0); } public static int luaL_dofile(IntPtr luaState, string fileName) { int result = LuaDLL.luaL_loadfile(luaState, fileName); if (result != 0) return result; return LuaDLL.lua_pcall(luaState, 0, -1, 0); } #if LUA_5_3 [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getglobal(IntPtr luaState, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setglobal(IntPtr luaState, string name); public static void lua_insert(IntPtr luaState, int newTop) { lua_rotate(luaState, newTop, 1); } public static void lua_pushglobaltable(IntPtr l) { lua_rawgeti(l, LuaIndexes.LUA_REGISTRYINDEX, 2); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rotate(IntPtr luaState, int index, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_rawlen(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadbufferx(IntPtr luaState, byte[] buff, int size, string name, IntPtr x); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_callk(IntPtr luaState, int nArgs, int nResults,int ctx,IntPtr k); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pcallk(IntPtr luaState, int nArgs, int nResults, int errfunc,int ctx,IntPtr k); public static int lua_call(IntPtr luaState, int nArgs, int nResults) { return lua_callk(luaState, nArgs, nResults, 0, IntPtr.Zero); } public static int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc) { return lua_pcallk(luaState, nArgs, nResults, errfunc, 0, IntPtr.Zero); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double lua_tonumberx(IntPtr luaState, int index, IntPtr x); public static double lua_tonumber(IntPtr luaState, int index) { return lua_tonumberx(luaState, index, IntPtr.Zero); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern Int64 lua_tointegerx(IntPtr luaState, int index,IntPtr x); public static int lua_tointeger(IntPtr luaState, int index) { return (int)lua_tointegerx(luaState, index, IntPtr.Zero); } public static int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name) { return luaL_loadbufferx(luaState, buff, size, name, IntPtr.Zero); } public static void lua_remove(IntPtr l, int idx) { lua_rotate(l, (idx), -1); lua_pop(l, 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, Int64 index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawseti(IntPtr luaState, int tableIndex, Int64 index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushinteger(IntPtr luaState, Int64 i); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern Int64 luaL_checkinteger(IntPtr luaState, int stackPos); #else public static void lua_getglobal(IntPtr luaState, string name) { LuaDLL.lua_pushstring(luaState, name); LuaDLL.lua_gettable(luaState, LuaIndexes.LUA_GLOBALSINDEX); } public static void lua_setglobal(IntPtr luaState, string name) { LuaDLL.lua_pushstring(luaState, name); LuaDLL.lua_insert(luaState, -2); LuaDLL.lua_settable(luaState, LuaIndexes.LUA_GLOBALSINDEX); } public static void lua_pushglobaltable(IntPtr l) { LuaDLL.lua_pushvalue(l, LuaIndexes.LUA_GLOBALSINDEX); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_insert(IntPtr luaState, int newTop); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_objlen(IntPtr luaState, int stackPos); public static int lua_rawlen(IntPtr luaState, int stackPos) { return lua_objlen(luaState, stackPos); } public static int lua_strlen(IntPtr luaState, int stackPos) { return lua_rawlen(luaState, stackPos); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_call(IntPtr luaState, int nArgs, int nResults); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double lua_tonumber(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_tointeger(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_remove(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawseti(IntPtr luaState, int tableIndex, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushinteger(IntPtr luaState, int i); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_checkinteger(IntPtr luaState, int stackPos); #endif [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settop(IntPtr luaState, int newTop); public static void lua_pop(IntPtr luaState, int amount) { LuaDLL.lua_settop(luaState, -(amount) - 1); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_gettable(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawget(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_settable(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_rawset(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_setmetatable(IntPtr luaState, int objIndex); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_getmetatable(IntPtr luaState, int objIndex); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_equal(IntPtr luaState, int index1, int index2); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushvalue(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_replace(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_gettop(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern LuaTypes lua_type(IntPtr luaState, int index); public static bool lua_isnil(IntPtr luaState, int index) { return (LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TNIL); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_isnumber(IntPtr luaState, int index); public static bool lua_isboolean(IntPtr luaState, int index) { return LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TBOOLEAN; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_ref(IntPtr luaState, int registryIndex); public static void lua_getref(IntPtr luaState, int reference) { LuaDLL.lua_rawgeti(luaState,LuaIndexes.LUA_REGISTRYINDEX, reference); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_unref(IntPtr luaState, int registryIndex, int reference); public static void lua_unref(IntPtr luaState, int reference) { LuaDLL.luaL_unref(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_isstring(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_iscfunction(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnil(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushstdcallcfunction(IntPtr luaState, IntPtr wrapper); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_checktype(IntPtr luaState, int p, LuaTypes t); public static void lua_pushstdcallcfunction(IntPtr luaState, LuaCSFunction function) { IntPtr fn = Marshal.GetFunctionPointerForDelegate(function); lua_pushstdcallcfunction(luaState, fn); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_tocfunction(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_toboolean(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr lua_tolstring(IntPtr luaState, int index, out int strLen); public static string lua_tostring(IntPtr luaState, int index) { int strlen; IntPtr str = lua_tolstring(luaState, index, out strlen); if (str != IntPtr.Zero) { return Marshal.PtrToStringAnsi(str, strlen); } return null; } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_atpanic(IntPtr luaState, LuaCSFunction panicf); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushnumber(IntPtr luaState, double number); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushboolean(IntPtr luaState, bool value); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushlstring(IntPtr luaState, string str, int size); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushstring(IntPtr luaState, string str); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_newmetatable(IntPtr luaState, string meta); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_getfield(IntPtr luaState, int stackPos, string meta); public static void luaL_getmetatable(IntPtr luaState, string meta) { LuaDLL.lua_getfield(luaState, LuaIndexes.LUA_REGISTRYINDEX, meta); } [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr luaL_checkudata(IntPtr luaState, int stackPos, string meta); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool luaL_getmetafield(IntPtr luaState, int stackPos, string field); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_load(IntPtr luaState, LuaChunkReader chunkReader, ref ReaderInfo data, string chunkName); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaL_loadfile(IntPtr luaState, string filename); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_error(IntPtr luaState); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern bool lua_checkstack(IntPtr luaState, int extra); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int lua_next(IntPtr luaState, int index); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_pushlightuserdata(IntPtr luaState, IntPtr udata); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void luaL_where(IntPtr luaState, int level); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern double luaL_checknumber(IntPtr luaState, int stackPos); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern void lua_concat(IntPtr luaState, int n); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_newuserdata(IntPtr luaState, int val); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_rawnetobj(IntPtr luaState, int obj); [DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] public static extern int luaS_checkcallback(IntPtr luaState, int index); } }
using System; using System.Collections.Generic; using Penneo.Connector; using Penneo.Mapping; using RestSharp; namespace Penneo { /// <summary> /// Base class for all Penneo business entities /// </summary> public abstract class Entity { protected Entity() { InternalIdentifier = Guid.NewGuid(); } /// <summary> /// The relative url (rest resource) of the entity type /// </summary> internal virtual string GetRelativeUrl(PenneoConnector con) { return con.ServiceLocator.GetInstance<RestResources>().GetResource(GetType(), Parent); } /// <summary> /// The entity type mapping /// </summary> internal IMapping GetMapping(PenneoConnector con) { return con.ServiceLocator.GetInstance<Mappings>().GetMapping(GetType()); } /// <summary> /// The parent of the entity (if any) /// </summary> internal virtual Entity Parent { get { return null; } } /// <summary> /// Internal guid of the entity /// </summary> internal Guid InternalIdentifier { get; set; } /// <summary> /// The Id of the entity /// </summary> public int? Id { get; set; } /// <summary> /// Denotes if the entity is new (i.e. still unknown to Penneo) /// </summary> public bool IsNew { get { return !Id.HasValue; } } /// <summary> /// Get request data from the entity as a property->value dictionary /// </summary> public Dictionary<string, object> GetRequestData(PenneoConnector con) { var values = IsNew ? GetMapping(con).GetCreateValues(this) : GetMapping(con).GetUpdateValues(this); return values; } /// <summary> /// Persist the entity to the storage /// </summary> public bool Persist(PenneoConnector con) { con.Log((IsNew ? "Creating" : "Updating") + " " + GetType().Name + " (" + (Id.HasValue ? Id.ToString() : "new") + ")", LogSeverity.Information); var success = con.ApiConnector.WriteObject(this); if (!success) { con.Log((IsNew ? "Creating" : "Updating") + " " + GetType().Name + " (" + (Id.HasValue ? Id.ToString() : "new") + ") failed", LogSeverity.Information); } return success; } /// <summary> /// Delete the entity from the storage /// </summary> public void Delete(PenneoConnector con) { con.Log("Deleting " + GetType().Name + " (" + (Id.HasValue ? Id.ToString() : "new") + ")", LogSeverity.Information); if (!con.ApiConnector.DeleteObject(this)) { throw new Exception("Penneo: Could not delete the " + GetType().Name); } Id = null; } /// <summary> /// Get the latest server result for the entity /// </summary> public ServerResult GetLatestServerResult(PenneoConnector con) { return con.ApiConnector.GetLatestEntityServerResult(this); } /// <summary> /// Link this entity with the given child in the storage /// </summary> protected bool LinkEntity(PenneoConnector con, Entity child) { con.Log("Linking " + GetType().Name + " (" + (Id.HasValue ? Id.ToString() : "new") + ") TO " + child.GetType().Name + " (" + (child.Id.HasValue ? Id.ToString() : "new") + ")", LogSeverity.Information); return con.ApiConnector.LinkEntity(this, child); } /// <summary> /// Unlink this entity with the given child in the storage /// </summary> protected bool UnlinkEntity(PenneoConnector con, Entity child) { con.Log("Unlinking " + GetType().Name + " (" + (Id.HasValue ? Id.ToString() : "new") + ") TO " + child.GetType().Name + " (" + (child.Id.HasValue ? Id.ToString() : "new") + ")", LogSeverity.Information); return con.ApiConnector.UnlinkEntity(this, child); } /// <summary> /// Get all entities linked with this entity in the storage /// </summary> protected QueryResult<T> GetLinkedEntities<T>(PenneoConnector con, string url = null) where T: Entity { return con.ApiConnector.GetLinkedEntities<T>(this, url); } /// <summary> /// Get entity linked with this entity based on url /// </summary> protected QuerySingleObjectResult<T> GetLinkedEntity<T>(PenneoConnector con, string url = null) where T: Entity { return con.ApiConnector.GetLinkedEntity<T>(this, url); } /// <summary> /// Find a specific linked entity /// </summary> protected T FindLinkedEntity<T>(PenneoConnector con, int id) { return con.ApiConnector.FindLinkedEntity<T>(this, id); } /// <summary> /// Get file assets with the given name for this entity /// </summary> protected byte[] GetFileAssets(PenneoConnector con, string assetName) { return con.ApiConnector.GetFileAssets(this, assetName); } /// <summary> /// Get text assets with the given name for this entity /// </summary> protected string GetTextAssets(PenneoConnector con, string assetName) { return con.ApiConnector.GetTextAssets(this, assetName); } protected T GetAsset<T>(PenneoConnector con, string assetName) { return con.ApiConnector.GetAsset<T>(this, assetName); } /// <summary> /// Get list of string asset with the given name for this entity /// </summary> protected IEnumerable<string> GetStringListAsset(PenneoConnector con, string assetName) { return con.ApiConnector.GetStringListAsset(this, assetName); } /// <summary> /// Perform the given action on this entity /// </summary> protected ServerResult PerformAction(PenneoConnector con, string action) { return con.ApiConnector.PerformAction(this, action); } protected ServerResult PerformComplexAction( PenneoConnector con, Method method, string action, Dictionary<string, object> data ) { return con.ApiConnector.PerformComplexAction(this, method, action, data); } /// <summary> /// Do optional initialization when reading the entity from a source /// </summary> internal virtual void ReadInit() { } /// <summary> /// Return a string for debugging with both type and id /// </summary> public override string ToString() { return string.Format("{0} Id: {1}", GetType().Name, Id); } } }
/* See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Esri Inc. licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Security.Cryptography; using com.esri.gpt.security; namespace com.esri.gpt.csw { /// <summary> /// CswClient class is used to submit CSW search request. /// </summary> /// <remarks> /// CswClient is a wrapper class of .NET HttpWebRequest and HttpWebResponse. It basically submits /// a HTTP request then return a text response. /// </remarks> /// public class CswClient { private CredentialCache _credentialCache; static CookieContainer _cookieContainer; //use static variable to be thread safe private String downloadFileName = ""; private bool retryAttempt = true; #region Constructor /// <summary> /// Constructor /// </summary> public CswClient() { _credentialCache = new CredentialCache(); _cookieContainer = new CookieContainer(); } #endregion #region PublicMethods /// <summary> /// Submit HTTP Request /// </summary> /// <param name="method">HTTP Method. for example "POST", "GET"</param> /// <param name="URL">URL to send HTTP Request to</param> /// <param name="postdata">Data to be posted</param> /// <returns>Response in plain text</returns> public string SubmitHttpRequest(string method, string URL, string postdata) { return SubmitHttpRequest(method, URL, postdata, "", ""); } /// <summary> /// Submit HTTP Request /// </summary> /// <remarks> /// Submit an HTTP request. /// </remarks> /// <param name="method">HTTP Method. for example "POST", "GET"</param> /// <param name="URL">URL to send HTTP Request to</param> /// <param name="postdata">Data to be posted</param> /// <param name="usr">Username</param> /// <param name="pwd">Password</param> /// <returns>Response in plain text.</returns> public string SubmitHttpRequest(string method, string URL, string postdata, string usr, string pwd) { String responseText = ""; HttpWebRequest request; Uri uri = new Uri(URL); request = (HttpWebRequest)WebRequest.Create(uri); request.AllowAutoRedirect = true; ClientCertRequest.handleClientCert(request, URL); if(method.Equals("SOAP")){ request.Method = "POST"; request.Headers.Add("SOAPAction: Some-URI"); request.ContentType = "text/xml; charset=UTF-8"; } else if (method.Equals("DOWNLOAD")) { request.Method = "GET"; } else{ request.ContentType = "text/xml; charset=UTF-8"; request.Method = method; } // Credential and cookies request.CookieContainer = _cookieContainer; NetworkCredential nc = null; String authType = "Negotiate"; if (_credentialCache.GetCredential(uri, authType) == null && _credentialCache.GetCredential(uri, "Basic") == null) { if (!String.IsNullOrEmpty(usr) && !String.IsNullOrEmpty(pwd)) { nc = new NetworkCredential(usr, pwd); _credentialCache.Add(uri, "Basic", nc); _credentialCache.Add(uri, authType, nc); } else{ nc = System.Net.CredentialCache.DefaultNetworkCredentials; _credentialCache.Add(uri, authType, nc); } } request.Credentials = _credentialCache; // post data if (request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase)) { UTF8Encoding encoding = new UTF8Encoding(); Byte[] byteTemp = encoding.GetBytes(postdata); request.ContentLength = byteTemp.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(byteTemp, 0, byteTemp.Length); requestStream.Close(); } HttpWebResponse response = null; try{ response = (HttpWebResponse)request.GetResponse(); } catch (UnauthorizedAccessException ua) { /*if (ua is CryptographicException) { // handle client certificate ClientCertRequest.handleClientCert(request, URL); response = (HttpWebResponse)request.GetResponse(); retryAttempt = false; }*/ if (retryAttempt) { PromptCredentials pc = new PromptCredentials(); pc.ShowDialog(); retryAttempt = false; try { _credentialCache.Remove(uri, "Basic"); } catch (Exception) { }; _credentialCache.Remove(uri, authType); if (!String.IsNullOrEmpty(pc.Username) && !String.IsNullOrEmpty(pc.Password)) return SubmitHttpRequest(method, URL, postdata, pc.Username, pc.Password); else return null; } else { retryAttempt = true; throw ua; } } catch (WebException we) { /* if (we is CryptographicException) { // handle client certificate ClientCertRequest.handleClientCert(request, URL); response = (HttpWebResponse)request.GetResponse(); retryAttempt = false; }*/ if (we.Status == WebExceptionStatus.ProtocolError) { HttpStatusCode statusCode = ((HttpWebResponse)we.Response).StatusCode; if (statusCode == HttpStatusCode.BadRequest) { retryAttempt = false; throw we; } } if (retryAttempt) { PromptCredentials pc = new PromptCredentials(); pc.ShowDialog(); retryAttempt = false; try { _credentialCache.Remove(uri, "Basic"); }catch(Exception){}; _credentialCache.Remove(uri, authType); if (!String.IsNullOrEmpty(pc.Username) && !String.IsNullOrEmpty(pc.Password)) return SubmitHttpRequest(method, URL, postdata, pc.Username, pc.Password); else return null; } else { retryAttempt = true; throw we; } } if (_cookieContainer.GetCookies(uri) == null) { _cookieContainer.Add(uri, response.Cookies); } Stream responseStream = response.GetResponseStream(); if (method.Equals("DOWNLOAD")) { FileStream file = null; string fileName = response.GetResponseHeader("Content-Disposition"); string[] s = null; if (fileName.ToLower().EndsWith(".tif")) { s = URL.Split(new String[] { "coverage=" }, 100, StringSplitOptions.RemoveEmptyEntries); s[1] = s[1].Trim() + ".tif"; } else { s = fileName.Split('='); s[1] = s[1].Replace('\\', ' '); s[1] = s[1].Replace('"', ' '); s[1] = s[1].Trim(); } try { downloadFileName = System.IO.Path.Combine(Utils.GetSpecialFolderPath(SpecialFolder.ConfigurationFiles), s[1]); System.IO.File.Delete(downloadFileName); file = System.IO.File.Create(downloadFileName); // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000]; int length = 10000; int offset = 0; while (length > 0) { length = responseStream.Read(buffer, 0, length); offset += length; file.Write(buffer, 0, length); } } catch (Exception e) {} finally { if(file != null) file.Close(); if(responseStream != null) responseStream.Close(); retryAttempt = true; } return downloadFileName; } StreamReader reader = new StreamReader(responseStream); responseText = reader.ReadToEnd(); reader.Close(); responseStream.Close(); return responseText; } /// <summary> /// Encode PostBody /// </summary> /// <remarks> /// Encode special characters (such as %, space, <, >, \, and &) to percent values. /// </remarks> /// <param name="postbody">Text to be encoded</param> /// <returns>Encoded text.</returns> public string EncodePostbody(string postbody) { postbody = postbody.Replace(@"%", @"%25"); postbody = postbody.Replace(@" ", @"%20"); postbody = postbody.Replace(@"<", @"%3c"); postbody = postbody.Replace(@">", @"%3e"); postbody = postbody.Replace("\"", @"%22"); // double quote postbody = postbody.Replace(@"&", @"%26"); return postbody; } #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.Runtime.Serialization { using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Xml.Serialization; using System.Xml.Schema; using System.Security; using System.Linq; using System.Runtime.CompilerServices; internal delegate IXmlSerializable CreateXmlSerializableDelegate(); internal sealed class XmlDataContract : DataContract { private readonly XmlDataContractCriticalHelper _helper; public XmlDataContract() : base(new XmlDataContractCriticalHelper()) { _helper = base.Helper as XmlDataContractCriticalHelper; } internal XmlDataContract(Type type) : base(new XmlDataContractCriticalHelper(type)) { _helper = base.Helper as XmlDataContractCriticalHelper; } public override DataContractDictionary KnownDataContracts { get { return _helper.KnownDataContracts; } set { _helper.KnownDataContracts = value; } } internal XmlSchemaType XsdType { get { return _helper.XsdType; } set { _helper.XsdType = value; } } internal bool IsAnonymous { get { return _helper.IsAnonymous; } } public override bool HasRoot { get { return _helper.HasRoot; } set { _helper.HasRoot = value; } } public override XmlDictionaryString TopLevelElementName { get { return _helper.TopLevelElementName; } set { _helper.TopLevelElementName = value; } } public override XmlDictionaryString TopLevelElementNamespace { get { return _helper.TopLevelElementNamespace; } set { _helper.TopLevelElementNamespace = value; } } internal bool IsTopLevelElementNullable { get { return _helper.IsTopLevelElementNullable; } set { _helper.IsTopLevelElementNullable = value; } } internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate { get { // We create XmlSerializableDelegate via CodeGen when CodeGen is enabled; // otherwise, we would create the delegate via reflection. if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || DataContractSerializer.Option == SerializationOption.ReflectionAsBackup) { if (_helper.CreateXmlSerializableDelegate == null) { lock (this) { if (_helper.CreateXmlSerializableDelegate == null) { CreateXmlSerializableDelegate tempCreateXmlSerializable = GenerateCreateXmlSerializableDelegate(); Interlocked.MemoryBarrier(); _helper.CreateXmlSerializableDelegate = tempCreateXmlSerializable; } } } return _helper.CreateXmlSerializableDelegate; } return () => ReflectionCreateXmlSerializable(this.UnderlyingType); } } internal override bool CanContainReferences => false; public override bool IsBuiltInDataContract => UnderlyingType == Globals.TypeOfXmlElement || UnderlyingType == Globals.TypeOfXmlNodeArray; private class XmlDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private DataContractDictionary _knownDataContracts; private bool _isKnownTypeAttributeChecked; private XmlDictionaryString _topLevelElementName; private XmlDictionaryString _topLevelElementNamespace; private bool _isTopLevelElementNullable; private bool _hasRoot; private CreateXmlSerializableDelegate _createXmlSerializable; private XmlSchemaType _xsdType; internal XmlDataContractCriticalHelper() { } internal XmlDataContractCriticalHelper(Type type) : base(type) { if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type)))); if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type)))); XmlSchemaType xsdType; bool hasRoot; XmlQualifiedName stableName; SchemaExporter.GetXmlTypeInfo(type, out stableName, out xsdType, out hasRoot); this.StableName = stableName; this.HasRoot = hasRoot; XmlDictionary dictionary = new XmlDictionary(); this.Name = dictionary.Add(StableName.Name); this.Namespace = dictionary.Add(StableName.Namespace); object[] xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray(); if (xmlRootAttributes == null || xmlRootAttributes.Length == 0) { if (hasRoot) { _topLevelElementName = Name; _topLevelElementNamespace = (this.StableName.Namespace == Globals.SchemaNamespace) ? DictionaryGlobals.EmptyString : Namespace; _isTopLevelElementNullable = true; } } else { if (hasRoot) { XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)xmlRootAttributes[0]; _isTopLevelElementNullable = xmlRootAttribute.IsNullable; string elementName = xmlRootAttribute.ElementName; _topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName)); string elementNs = xmlRootAttribute.Namespace; _topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType)))); } } } internal override DataContractDictionary KnownDataContracts { get { if (!_isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!_isKnownTypeAttributeChecked) { _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Interlocked.MemoryBarrier(); _isKnownTypeAttributeChecked = true; } } } return _knownDataContracts; } set { _knownDataContracts = value; } } internal XmlSchemaType XsdType { get { return _xsdType; } set { _xsdType = value; } } internal bool IsAnonymous => _xsdType != null; internal override bool HasRoot { get { return _hasRoot; } set { _hasRoot = value; } } internal override XmlDictionaryString TopLevelElementName { get { return _topLevelElementName; } set { _topLevelElementName = value; } } internal override XmlDictionaryString TopLevelElementNamespace { get { return _topLevelElementNamespace; } set { _topLevelElementNamespace = value; } } internal bool IsTopLevelElementNullable { get { return _isTopLevelElementNullable; } set { _isTopLevelElementNullable = value; } } internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate { get { return _createXmlSerializable; } set { _createXmlSerializable = value; } } } private ConstructorInfo GetConstructor() { Type type = UnderlyingType; if (type.IsValueType) return null; ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty<Type>()); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); return ctor; } internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate() { Type type = this.UnderlyingType; CodeGenerator ilg = new CodeGenerator(); bool memberAccessFlag = RequiresMemberAccessForCreate(null) && !(type.FullName == "System.Xml.Linq.XElement"); try { ilg.BeginMethod("Create" + DataContract.GetClrTypeFullName(type), typeof(CreateXmlSerializableDelegate), memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { RequiresMemberAccessForCreate(securityException); } else { throw; } } if (type.IsValueType) { System.Reflection.Emit.LocalBuilder local = ilg.DeclareLocal(type, type.Name + "Value"); ilg.Ldloca(local); ilg.InitObj(type); ilg.Ldloc(local); } else { // Special case XElement // codegen the same as 'internal XElement : this("default") { }' ConstructorInfo ctor = GetConstructor(); if (!ctor.IsPublic && type.FullName == "System.Xml.Linq.XElement") { Type xName = type.Assembly.GetType("System.Xml.Linq.XName"); if (xName != null) { MethodInfo XName_op_Implicit = xName.GetMethod( "op_Implicit", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, new Type[] { typeof(string) } ); ConstructorInfo XElement_ctor = type.GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, new Type[] { xName } ); if (XName_op_Implicit != null && XElement_ctor != null) { ilg.Ldstr("default"); ilg.Call(XName_op_Implicit); ctor = XElement_ctor; } } } ilg.New(ctor); } ilg.ConvertValue(this.UnderlyingType, Globals.TypeOfIXmlSerializable); ilg.Ret(); return (CreateXmlSerializableDelegate)ilg.EndMethod(); } /// <SecurityNote> /// Review - calculates whether this Xml type requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> private bool RequiresMemberAccessForCreate(SecurityException securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format(SR.PartialTrustIXmlSerializableTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ConstructorRequiresMemberAccess(GetConstructor())) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format(SR.PartialTrustIXmlSerialzableNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } return false; } internal IXmlSerializable ReflectionCreateXmlSerializable(Type type) { if (type.IsValueType) { throw new NotImplementedException("ReflectionCreateXmlSerializable - value type"); } else { object o = null; if (type == typeof(System.Xml.Linq.XElement)) { o = new System.Xml.Linq.XElement("default"); } else { ConstructorInfo ctor = GetConstructor(); o = ctor.Invoke(Array.Empty<object>()); } return (IXmlSerializable)o; } } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (context == null) XmlObjectSerializerWriteContext.WriteRootIXmlSerializable(xmlWriter, obj); else context.WriteIXmlSerializable(xmlWriter, obj); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { object o; if (context == null) { o = XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, this, true /*isMemberType*/); } else { o = context.ReadIXmlSerializable(xmlReader, this, true /*isMemberType*/); context.AddNewObject(o); } xmlReader.ReadEndElement(); return o; } } }
using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Abp.Application.Features; using Abp.Authorization.Users; using Abp.Collections.Extensions; using Abp.Domain.Services; using Abp.Domain.Uow; using Abp.IdentityFramework; using Abp.Localization; using Abp.MultiTenancy; using Abp.Runtime.Caching; using Abp.Runtime.Session; using Abp.Zero; using Abp.Zero.Configuration; using Microsoft.AspNet.Identity; namespace Abp.Authorization.Roles { /// <summary> /// Extends <see cref="RoleManager{TRole,TKey}"/> of ASP.NET Identity Framework. /// Applications should derive this class with appropriate generic arguments. /// </summary> public abstract class AbpRoleManager<TRole, TUser> : RoleManager<TRole, int>, IDomainService where TRole : AbpRole<TUser>, new() where TUser : AbpUser<TUser> { public ILocalizationManager LocalizationManager { get; set; } protected string LocalizationSourceName { get; set; } public IAbpSession AbpSession { get; set; } public IRoleManagementConfig RoleManagementConfig { get; private set; } public FeatureDependencyContext FeatureDependencyContext { get; set; } private IRolePermissionStore<TRole> RolePermissionStore { get { if (!(Store is IRolePermissionStore<TRole>)) { throw new AbpException("Store is not IRolePermissionStore"); } return Store as IRolePermissionStore<TRole>; } } protected AbpRoleStore<TRole, TUser> AbpStore { get; private set; } protected IPermissionManager PermissionManager { get; } protected ICacheManager CacheManager { get; } protected IUnitOfWorkManager UnitOfWorkManager { get; } /// <summary> /// Constructor. /// </summary> protected AbpRoleManager( AbpRoleStore<TRole, TUser> store, IPermissionManager permissionManager, IRoleManagementConfig roleManagementConfig, ICacheManager cacheManager, IUnitOfWorkManager unitOfWorkManager) : base(store) { PermissionManager = permissionManager; CacheManager = cacheManager; UnitOfWorkManager = unitOfWorkManager; RoleManagementConfig = roleManagementConfig; AbpStore = store; AbpSession = NullAbpSession.Instance; LocalizationManager = NullLocalizationManager.Instance; LocalizationSourceName = AbpZeroConsts.LocalizationSourceName; } /// <summary> /// Checks if a role is granted for a permission. /// </summary> /// <param name="roleName">The role's name to check it's permission</param> /// <param name="permissionName">Name of the permission</param> /// <returns>True, if the role has the permission</returns> public virtual async Task<bool> IsGrantedAsync(string roleName, string permissionName) { return await IsGrantedAsync((await GetRoleByNameAsync(roleName)).Id, PermissionManager.GetPermission(permissionName)); } /// <summary> /// Checks if a role has a permission. /// </summary> /// <param name="roleId">The role's id to check it's permission</param> /// <param name="permissionName">Name of the permission</param> /// <returns>True, if the role has the permission</returns> public virtual async Task<bool> IsGrantedAsync(int roleId, string permissionName) { return await IsGrantedAsync(roleId, PermissionManager.GetPermission(permissionName)); } /// <summary> /// Checks if a role is granted for a permission. /// </summary> /// <param name="role">The role</param> /// <param name="permission">The permission</param> /// <returns>True, if the role has the permission</returns> public Task<bool> IsGrantedAsync(TRole role, Permission permission) { return IsGrantedAsync(role.Id, permission); } /// <summary> /// Checks if a role is granted for a permission. /// </summary> /// <param name="roleId">role id</param> /// <param name="permission">The permission</param> /// <returns>True, if the role has the permission</returns> public virtual async Task<bool> IsGrantedAsync(int roleId, Permission permission) { //Get cached role permissions var cacheItem = await GetRolePermissionCacheItemAsync(roleId); //Check the permission return cacheItem.GrantedPermissions.Contains(permission.Name); } /// <summary> /// Gets granted permission names for a role. /// </summary> /// <param name="roleId">Role id</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(int roleId) { return await GetGrantedPermissionsAsync(await GetRoleByIdAsync(roleId)); } /// <summary> /// Gets granted permission names for a role. /// </summary> /// <param name="roleName">Role name</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(string roleName) { return await GetGrantedPermissionsAsync(await GetRoleByNameAsync(roleName)); } /// <summary> /// Gets granted permissions for a role. /// </summary> /// <param name="role">Role</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TRole role) { var permissionList = new List<Permission>(); foreach (var permission in PermissionManager.GetAllPermissions()) { if (await IsGrantedAsync(role.Id, permission)) { permissionList.Add(permission); } } return permissionList; } /// <summary> /// Sets all granted permissions of a role at once. /// Prohibits all other permissions. /// </summary> /// <param name="roleId">Role id</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(int roleId, IEnumerable<Permission> permissions) { await SetGrantedPermissionsAsync(await GetRoleByIdAsync(roleId), permissions); } /// <summary> /// Sets all granted permissions of a role at once. /// Prohibits all other permissions. /// </summary> /// <param name="role">The role</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(TRole role, IEnumerable<Permission> permissions) { var oldPermissions = await GetGrantedPermissionsAsync(role); var newPermissions = permissions.ToArray(); foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p, PermissionEqualityComparer.Instance))) { await ProhibitPermissionAsync(role, permission); } foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p, PermissionEqualityComparer.Instance))) { await GrantPermissionAsync(role, permission); } } /// <summary> /// Grants a permission for a role. /// </summary> /// <param name="role">Role</param> /// <param name="permission">Permission</param> public async Task GrantPermissionAsync(TRole role, Permission permission) { if (await IsGrantedAsync(role.Id, permission)) { return; } await RolePermissionStore.RemovePermissionAsync(role, new PermissionGrantInfo(permission.Name, false)); await RolePermissionStore.AddPermissionAsync(role, new PermissionGrantInfo(permission.Name, true)); } /// <summary> /// Prohibits a permission for a role. /// </summary> /// <param name="role">Role</param> /// <param name="permission">Permission</param> public async Task ProhibitPermissionAsync(TRole role, Permission permission) { if (!await IsGrantedAsync(role.Id, permission)) { return; } await RolePermissionStore.RemovePermissionAsync(role, new PermissionGrantInfo(permission.Name, true)); await RolePermissionStore.AddPermissionAsync(role, new PermissionGrantInfo(permission.Name, false)); } /// <summary> /// Prohibits all permissions for a role. /// </summary> /// <param name="role">Role</param> public async Task ProhibitAllPermissionsAsync(TRole role) { foreach (var permission in PermissionManager.GetAllPermissions()) { await ProhibitPermissionAsync(role, permission); } } /// <summary> /// Resets all permission settings for a role. /// It removes all permission settings for the role. /// </summary> /// <param name="role">Role</param> public async Task ResetAllPermissionsAsync(TRole role) { await RolePermissionStore.RemoveAllPermissionSettingsAsync(role); } /// <summary> /// Creates a role. /// </summary> /// <param name="role">Role</param> public override async Task<IdentityResult> CreateAsync(TRole role) { var result = await CheckDuplicateRoleNameAsync(role.Id, role.Name, role.DisplayName); if (!result.Succeeded) { return result; } var tenantId = GetCurrentTenantId(); if (tenantId.HasValue && !role.TenantId.HasValue) { role.TenantId = tenantId.Value; } return await base.CreateAsync(role); } public override async Task<IdentityResult> UpdateAsync(TRole role) { var result = await CheckDuplicateRoleNameAsync(role.Id, role.Name, role.DisplayName); if (!result.Succeeded) { return result; } return await base.UpdateAsync(role); } /// <summary> /// Deletes a role. /// </summary> /// <param name="role">Role</param> public async override Task<IdentityResult> DeleteAsync(TRole role) { if (role.IsStatic) { return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteStaticRole"), role.Name)); } return await base.DeleteAsync(role); } /// <summary> /// Gets a role by given id. /// Throws exception if no role with given id. /// </summary> /// <param name="roleId">Role id</param> /// <returns>Role</returns> /// <exception cref="AbpException">Throws exception if no role with given id</exception> public virtual async Task<TRole> GetRoleByIdAsync(int roleId) { var role = await FindByIdAsync(roleId); if (role == null) { throw new AbpException("There is no role with id: " + roleId); } return role; } /// <summary> /// Gets a role by given name. /// Throws exception if no role with given roleName. /// </summary> /// <param name="roleName">Role name</param> /// <returns>Role</returns> /// <exception cref="AbpException">Throws exception if no role with given roleName</exception> public virtual async Task<TRole> GetRoleByNameAsync(string roleName) { var role = await FindByNameAsync(roleName); if (role == null) { throw new AbpException("There is no role with name: " + roleName); } return role; } public async Task GrantAllPermissionsAsync(TRole role) { FeatureDependencyContext.TenantId = role.TenantId; var permissions = PermissionManager.GetAllPermissions(role.GetMultiTenancySide()) .Where(permission => permission.FeatureDependency == null || permission.FeatureDependency.IsSatisfied(FeatureDependencyContext) ); await SetGrantedPermissionsAsync(role, permissions); } [UnitOfWork] public virtual async Task<IdentityResult> CreateStaticRoles(int tenantId) { var staticRoleDefinitions = RoleManagementConfig.StaticRoles.Where(sr => sr.Side == MultiTenancySides.Tenant); using (UnitOfWorkManager.Current.SetTenantId(tenantId)) { foreach (var staticRoleDefinition in staticRoleDefinitions) { var role = new TRole { TenantId = tenantId, Name = staticRoleDefinition.RoleName, DisplayName = staticRoleDefinition.RoleName, IsStatic = true }; var identityResult = await CreateAsync(role); if (!identityResult.Succeeded) { return identityResult; } } } return IdentityResult.Success; } public virtual async Task<IdentityResult> CheckDuplicateRoleNameAsync(int? expectedRoleId, string name, string displayName) { var role = await FindByNameAsync(name); if (role != null && role.Id != expectedRoleId) { return AbpIdentityResult.Failed(string.Format(L("RoleNameIsAlreadyTaken"), name)); } role = await FindByDisplayNameAsync(displayName); if (role != null && role.Id != expectedRoleId) { return AbpIdentityResult.Failed(string.Format(L("RoleDisplayNameIsAlreadyTaken"), displayName)); } return IdentityResult.Success; } private Task<TRole> FindByDisplayNameAsync(string displayName) { return AbpStore.FindByDisplayNameAsync(displayName); } private async Task<RolePermissionCacheItem> GetRolePermissionCacheItemAsync(int roleId) { var cacheKey = roleId + "@" + (GetCurrentTenantId() ?? 0); return await CacheManager.GetRolePermissionCache().GetAsync(cacheKey, async () => { var newCacheItem = new RolePermissionCacheItem(roleId); var role = await Store.FindByIdAsync(roleId); if (role == null) { throw new AbpException("There is no role with given id: " + roleId); } var staticRoleDefinition = RoleManagementConfig.StaticRoles.FirstOrDefault(r => r.RoleName == role.Name && r.Side == role.GetMultiTenancySide()); if (staticRoleDefinition != null) { foreach (var permission in PermissionManager.GetAllPermissions()) { if (staticRoleDefinition.IsGrantedByDefault(permission)) { newCacheItem.GrantedPermissions.Add(permission.Name); } } } foreach (var permissionInfo in await RolePermissionStore.GetPermissionsAsync(roleId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.AddIfNotContains(permissionInfo.Name); } else { newCacheItem.GrantedPermissions.Remove(permissionInfo.Name); } } return newCacheItem; }); } protected virtual string L(string name) { return LocalizationManager.GetString(LocalizationSourceName, name); } protected virtual string L(string name, CultureInfo cultureInfo) { return LocalizationManager.GetString(LocalizationSourceName, name, cultureInfo); } private int? GetCurrentTenantId() { if (UnitOfWorkManager.Current != null) { return UnitOfWorkManager.Current.GetTenantId(); } return AbpSession.TenantId; } } }
// Comment this out if you wish to use stock Unity input #define USE_INCONTROL using UnityEngine; using System.Collections; using MoreMountains.Tools; using UnityEngine.Events; using System.Collections.Generic; #if USE_INCONTROL using InControl; #endif namespace MoreMountains.CorgiEngine { public struct ControlsModeEvent { public bool Status; public InputManager.MovementControls MovementControl; /// <summary> /// Initializes a new instance of the <see cref="MoreMountains.MMInterface.MMFadeOutEvent"/> struct. /// </summary> /// <param name="duration">Duration.</param> public ControlsModeEvent(bool status, InputManager.MovementControls movementControl) { Status = status; MovementControl = movementControl; } static ControlsModeEvent e; public static void Trigger(bool status, InputManager.MovementControls movementControl) { e.Status = status; e.MovementControl = movementControl; MMEventManager.TriggerEvent(e); } } /// <summary> /// This persistent singleton handles the inputs and sends commands to the player. /// IMPORTANT : this script's Execution Order MUST be -100. /// You can define a script's execution order by clicking on the script's file and then clicking on the Execution Order button at the bottom right of the script's inspector. /// See https://docs.unity3d.com/Manual/class-ScriptExecution.html for more details /// </summary> [AddComponentMenu("Corgi Engine/Managers/Input Manager")] public class InputManager : MMSingleton<InputManager> { [Header("Status")] /// set this to false to prevent input to be detected [Tooltip("set this to false to prevent input to be detected")] public bool InputDetectionActive = true; [Header("Player binding")] [MMInformation("The first thing you need to set on your InputManager is the PlayerID. This ID will be used to bind the input manager to your character(s). You'll want to go with Player1, Player2, Player3 or Player4.",MMInformationAttribute.InformationType.Info,false)] /// a string identifying the target player(s). You'll need to set this exact same string on your Character, and set its type to Player [Tooltip("a string identifying the target player(s). You'll need to set this exact same string on your Character, and set its type to Player")] public string PlayerID = "Player1"; /// the possible modes for this input manager public enum InputForcedMode { None, Mobile, Desktop } /// the possible kinds of control used for movement public enum MovementControls { Joystick, Arrows } [Header("Mobile controls")] [MMInformation("If you check Auto Mobile Detection, the engine will automatically switch to mobile controls when your build target is Android or iOS. You can also force mobile or desktop (keyboard, gamepad) controls using the dropdown below.\nNote that if you don't need mobile controls and/or GUI this component can also work on its own, just put it on an empty GameObject instead.",MMInformationAttribute.InformationType.Info,false)] /// if this is set to true, the InputManager will try to detect what mode it should be in, based on the current target device [Tooltip("if this is set to true, the InputManager will try to detect what mode it should be in, based on the current target device")] public bool AutoMobileDetection = true; /// use this to force desktop (keyboard, pad) or mobile (touch) mode [Tooltip("use this to force desktop (keyboard, pad) or mobile (touch) mode")] public InputForcedMode ForcedMode; /// if this is true, mobile controls will be hidden in editor mode, regardless of the current build target or the forced mode [Tooltip("if this is true, mobile controls will be hidden in editor mode, regardless of the current build target or the forced mode")] public bool HideMobileControlsInEditor = false; /// use this to specify whether you want to use the default joystick or arrows to move your character [Tooltip("use this to specify whether you want to use the default joystick or arrows to move your character")] public MovementControls MovementControl = MovementControls.Joystick; /// if this is true, button state changes are offset by one frame (usually useful on Android) [Tooltip("if this is true, button state changes are offset by one frame (usually useful on Android)")] public bool DelayedButtonPresses = false; /// if this is true, we're currently in mobile mode public bool IsMobile { get; protected set; } [Header("Movement settings")] [MMInformation("Turn SmoothMovement on to have inertia in your controls (meaning there'll be a small delay between a press/release of a direction and your character moving/stopping). You can also define here the horizontal and vertical thresholds.",MMInformationAttribute.InformationType.Info,false)] /// If set to true, acceleration / deceleration will take place when moving / stopping [Tooltip("If set to true, acceleration / deceleration will take place when moving / stopping")] public bool SmoothMovement=true; /// the minimum horizontal and vertical value you need to reach to trigger movement on an analog controller (joystick for example) [Tooltip("the minimum horizontal and vertical value you need to reach to trigger movement on an analog controller (joystick for example)")] public Vector2 Threshold = new Vector2(0.1f, 0.4f); /// the jump button, used for jumps public MMInput.IMButton JumpButton { get; protected set; } /// the swim button, used to swim public MMInput.IMButton SwimButton { get; protected set; } /// the glide button, used to glide in the air public MMInput.IMButton GlideButton { get; protected set; } /// the activate button, used for interactions with zones public MMInput.IMButton InteractButton { get; protected set; } /// the jetpack button public MMInput.IMButton JetpackButton { get; protected set; } /// the fly button public MMInput.IMButton FlyButton { get; protected set; } /// the run button public MMInput.IMButton RunButton { get; protected set; } /// the dash button public MMInput.IMButton DashButton { get; protected set; } /// the roll button public MMInput.IMButton RollButton { get; protected set; } /// the dash button public MMInput.IMButton GrabButton { get; protected set; } /// the dash button public MMInput.IMButton ThrowButton { get; protected set; } /// the shoot button public MMInput.IMButton ShootButton { get; protected set; } /// the shoot button public MMInput.IMButton SecondaryShootButton { get; protected set; } /// the reload button public MMInput.IMButton ReloadButton { get; protected set; } /// the push button public MMInput.IMButton PushButton { get; protected set; } /// the pause button public MMInput.IMButton PauseButton { get; protected set; } /// the button used to switch character (either via model or prefab switch) public MMInput.IMButton SwitchCharacterButton { get; protected set; } /// the switch weapon button public MMInput.IMButton SwitchWeaponButton { get; protected set; } /// the time control button public MMInput.IMButton TimeControlButton { get; protected set; } /// the shoot axis, used as a button (non analogic) public MMInput.ButtonStates ShootAxis { get; protected set; } /// the shoot axis, used as a button (non analogic) public MMInput.ButtonStates SecondaryShootAxis { get; protected set; } /// the primary movement value (used to move the character around) public Vector2 PrimaryMovement {get { return _primaryMovement; } } /// the secondary movement (usually the right stick on a gamepad), used to aim public Vector2 SecondaryMovement {get { return _secondaryMovement; } } protected List<MMInput.IMButton> ButtonList; protected Vector2 _primaryMovement = Vector2.zero; protected Vector2 _secondaryMovement = Vector2.zero; protected string _axisHorizontal; protected string _axisVertical; protected string _axisSecondaryHorizontal; protected string _axisSecondaryVertical; protected string _axisShoot; protected string _axisShootSecondary; /// <summary> /// On Start we look for what mode to use, and initialize our axis and buttons /// </summary> protected virtual void Start() { Initialization(); } protected virtual void Initialization() { ControlsModeDetection(); InitializeButtons(); InitializeAxis(); } /// <summary> /// Turns mobile controls on or off depending on what's been defined in the inspector, and what target device we're on /// </summary> public virtual void ControlsModeDetection() { ControlsModeEvent.Trigger(false, MovementControls.Joystick); IsMobile=false; if (AutoMobileDetection) { #if UNITY_ANDROID || UNITY_IPHONE ControlsModeEvent.Trigger(true, MovementControl); IsMobile = true; #endif } if (ForcedMode==InputForcedMode.Mobile) { ControlsModeEvent.Trigger(true, MovementControl); IsMobile = true; } if (ForcedMode==InputForcedMode.Desktop) { ControlsModeEvent.Trigger(false, MovementControls.Joystick); IsMobile = false; } if (HideMobileControlsInEditor) { #if UNITY_EDITOR ControlsModeEvent.Trigger(false, MovementControls.Joystick); IsMobile = false; #endif } } /// <summary> /// Initializes the buttons. If you want to add more buttons, make sure to register them here. /// </summary> protected virtual void InitializeButtons() { ButtonList = new List<MMInput.IMButton> (); ButtonList.Add(JumpButton = new MMInput.IMButton(PlayerID, "Jump", JumpButtonDown, JumpButtonPressed, JumpButtonUp)); ButtonList.Add(SwimButton = new MMInput.IMButton(PlayerID, "Swim", SwimButtonDown, SwimButtonPressed, SwimButtonUp)); ButtonList.Add(GlideButton = new MMInput.IMButton(PlayerID, "Glide", GlideButtonDown, GlideButtonPressed, GlideButtonUp)); ButtonList.Add(InteractButton = new MMInput.IMButton (PlayerID, "Interact", InteractButtonDown, InteractButtonPressed, InteractButtonUp)); ButtonList.Add(JetpackButton = new MMInput.IMButton (PlayerID, "Jetpack", JetpackButtonDown, JetpackButtonPressed, JetpackButtonUp)); ButtonList.Add(RunButton = new MMInput.IMButton (PlayerID, "Run", RunButtonDown, RunButtonPressed, RunButtonUp)); ButtonList.Add(DashButton = new MMInput.IMButton(PlayerID, "Dash", DashButtonDown, DashButtonPressed, DashButtonUp)); ButtonList.Add(RollButton = new MMInput.IMButton(PlayerID, "Roll", RollButtonDown, RollButtonPressed, RollButtonUp)); ButtonList.Add(FlyButton = new MMInput.IMButton(PlayerID, "Fly", FlyButtonDown, FlyButtonPressed, FlyButtonUp)); ButtonList.Add(ShootButton = new MMInput.IMButton(PlayerID, "Shoot", ShootButtonDown, ShootButtonPressed, ShootButtonUp)); ButtonList.Add(SecondaryShootButton = new MMInput.IMButton(PlayerID, "SecondaryShoot", SecondaryShootButtonDown, SecondaryShootButtonPressed, SecondaryShootButtonUp)); ButtonList.Add(ReloadButton = new MMInput.IMButton (PlayerID, "Reload", ReloadButtonDown, ReloadButtonPressed, ReloadButtonUp)); ButtonList.Add(SwitchWeaponButton = new MMInput.IMButton (PlayerID, "SwitchWeapon", SwitchWeaponButtonDown, SwitchWeaponButtonPressed, SwitchWeaponButtonUp)); ButtonList.Add(PauseButton = new MMInput.IMButton (PlayerID, "Pause", PauseButtonDown, PauseButtonPressed, PauseButtonUp)); ButtonList.Add(PushButton = new MMInput.IMButton(PlayerID, "Push", PushButtonDown, PushButtonPressed, PushButtonUp)); ButtonList.Add(SwitchCharacterButton = new MMInput.IMButton(PlayerID, "SwitchCharacter", SwitchCharacterButtonDown, SwitchCharacterButtonPressed, SwitchCharacterButtonUp)); ButtonList.Add(TimeControlButton = new MMInput.IMButton(PlayerID, "TimeControl", TimeControlButtonDown, TimeControlButtonPressed, TimeControlButtonUp)); ButtonList.Add(GrabButton = new MMInput.IMButton(PlayerID, "Grab", GrabButtonDown, GrabButtonPressed, GrabButtonUp)); ButtonList.Add(ThrowButton = new MMInput.IMButton(PlayerID, "Throw", ThrowButtonDown, ThrowButtonPressed, ThrowButtonUp)); } /// <summary> /// Initializes the axis strings. /// </summary> protected virtual void InitializeAxis() { _axisHorizontal = PlayerID+"_Horizontal"; _axisVertical = PlayerID+"_Vertical"; _axisSecondaryHorizontal = PlayerID+"_SecondaryHorizontal"; _axisSecondaryVertical = PlayerID+"_SecondaryVertical"; _axisShoot = PlayerID + "_ShootAxis"; _axisShootSecondary = PlayerID + "_SecondaryShootAxis"; } /// <summary> /// On LateUpdate, we process our button states /// </summary> protected virtual void LateUpdate() { ProcessButtonStates(); } /// <summary> /// At update, we check the various commands and update our values and states accordingly. /// </summary> protected virtual void Update() { if (!IsMobile && InputDetectionActive) { SetMovement(); SetSecondaryMovement (); SetShootAxis(); GetInputButtons (); } } /// <summary> /// If we're not on mobile, watches for input changes, and updates our buttons states accordingly /// </summary> protected virtual void GetInputButtons() { foreach(MMInput.IMButton button in ButtonList) { #if USE_INCONTROL PlayerAction playerAction = MMInControl.Instance.playerActions.GetPlayerActionByName(button.ButtonID); if (playerAction == null) Debug.Log(button.ButtonID); if (playerAction.IsPressed) { button.TriggerButtonPressed(); } if (playerAction.IsPressed && playerAction.HasChanged) { button.TriggerButtonDown(); } if (playerAction.WasReleased) { button.TriggerButtonUp(); } #else if (Input.GetButton(button.ButtonID)) { button.TriggerButtonPressed (); } if (Input.GetButtonDown(button.ButtonID)) { button.TriggerButtonDown (); } if (Input.GetButtonUp(button.ButtonID)) { button.TriggerButtonUp (); } #endif } } /// <summary> /// Called at LateUpdate(), this method processes the button states of all registered buttons /// </summary> public virtual void ProcessButtonStates() { // for each button, if we were at ButtonDown this frame, we go to ButtonPressed. If we were at ButtonUp, we're now Off foreach (MMInput.IMButton button in ButtonList) { if (button.State.CurrentState == MMInput.ButtonStates.ButtonDown) { if (DelayedButtonPresses) { StartCoroutine(DelayButtonPress(button)); } else { button.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } } if (button.State.CurrentState == MMInput.ButtonStates.ButtonUp) { if (DelayedButtonPresses) { StartCoroutine(DelayButtonRelease(button)); } else { button.State.ChangeState(MMInput.ButtonStates.Off); } } } } /// <summary> /// A coroutine that changes the pressed state one frame later /// </summary> /// <param name="button"></param> /// <returns></returns> IEnumerator DelayButtonPress(MMInput.IMButton button) { yield return null; button.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } /// <summary> /// A coroutine that changes the pressed state one frame later /// </summary> /// <param name="button"></param> /// <returns></returns> IEnumerator DelayButtonRelease(MMInput.IMButton button) { yield return null; button.State.ChangeState(MMInput.ButtonStates.Off); } /// <summary> /// Called every frame, if not on mobile, gets primary movement values from input /// </summary> public virtual void SetMovement() { if (!IsMobile && InputDetectionActive) { #if USE_INCONTROL _primaryMovement.x = MMInControl.Instance.playerActions.MoveHorizontal.Value; _primaryMovement.y = MMInControl.Instance.playerActions.MoveVertical.Value; #else if (SmoothMovement) { _primaryMovement.x = Input.GetAxis(_axisHorizontal); _primaryMovement.y = Input.GetAxis(_axisVertical); } else { _primaryMovement.x = Input.GetAxisRaw(_axisHorizontal); _primaryMovement.y = Input.GetAxisRaw(_axisVertical); } #endif } } /// <summary> /// Called every frame, if not on mobile, gets secondary movement values from input /// </summary> public virtual void SetSecondaryMovement() { if (!IsMobile && InputDetectionActive) { #if USE_INCONTROL _secondaryMovement.x = MMInControl.Instance.playerActions.MoveHorizontalSecondary.Value; _secondaryMovement.y = MMInControl.Instance.playerActions.MoveVerticalSecondary.Value; #else if (SmoothMovement) { _secondaryMovement.x = Input.GetAxis(_axisSecondaryHorizontal); _secondaryMovement.y = Input.GetAxis(_axisSecondaryVertical); } else { _secondaryMovement.x = Input.GetAxisRaw(_axisSecondaryHorizontal); _secondaryMovement.y = Input.GetAxisRaw(_axisSecondaryVertical); } #endif } } /// <summary> /// Called every frame, if not on mobile, gets shoot axis values from input /// </summary> protected virtual void SetShootAxis() { if (!IsMobile && InputDetectionActive) { #if USE_INCONTROL ShootAxis = MMInput.ProcessAxisAsButton(_axisShoot, Threshold.y, ShootAxis, MMInput.AxisTypes.Positive); SecondaryShootAxis = MMInput.ProcessAxisAsButton(_axisShootSecondary, -Threshold.y, SecondaryShootAxis, MMInput.AxisTypes.Negative); #else ShootAxis = MMInput.ProcessAxisAsButton(_axisShoot, Threshold.y, ShootAxis, MMInput.AxisTypes.Positive); SecondaryShootAxis = MMInput.ProcessAxisAsButton(_axisShootSecondary, -Threshold.y, SecondaryShootAxis, MMInput.AxisTypes.Negative); #endif } } /// <summary> /// If you're using a touch joystick, bind your main joystick to this method /// </summary> /// <param name="movement">Movement.</param> public virtual void SetMovement(Vector2 movement) { if (IsMobile && InputDetectionActive) { _primaryMovement.x = movement.x; _primaryMovement.y = movement.y; } } /// <summary> /// If you're using a touch joystick, bind your secondary joystick to this method /// </summary> /// <param name="movement">Movement.</param> public virtual void SetSecondaryMovement(Vector2 movement) { if (IsMobile && InputDetectionActive) { _secondaryMovement.x = movement.x; _secondaryMovement.y = movement.y; } } /// <summary> /// If you're using touch arrows, bind your left/right arrows to this method /// </summary> /// <param name="">.</param> public virtual void SetHorizontalMovement(float horizontalInput) { if (IsMobile && InputDetectionActive) { _primaryMovement.x = horizontalInput; } } /// <summary> /// If you're using touch arrows, bind your secondary down/up arrows to this method /// </summary> /// <param name="">.</param> public virtual void SetVerticalMovement(float verticalInput) { if (IsMobile && InputDetectionActive) { _primaryMovement.y = verticalInput; } } /// <summary> /// If you're using touch arrows, bind your secondary left/right arrows to this method /// </summary> /// <param name="">.</param> public virtual void SetSecondaryHorizontalMovement(float horizontalInput) { if (IsMobile && InputDetectionActive) { _secondaryMovement.x = horizontalInput; } } /// <summary> /// If you're using touch arrows, bind your down/up arrows to this method /// </summary> /// <param name="">.</param> public virtual void SetSecondaryVerticalMovement(float verticalInput) { if (IsMobile && InputDetectionActive) { _secondaryMovement.y = verticalInput; } } public virtual void JumpButtonDown() { JumpButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void JumpButtonPressed() { JumpButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void JumpButtonUp() { JumpButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void SwimButtonDown() { SwimButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void SwimButtonPressed() { SwimButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void SwimButtonUp() { SwimButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void GlideButtonDown() { GlideButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void GlideButtonPressed() { GlideButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void GlideButtonUp() { GlideButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void InteractButtonDown() { InteractButton.State.ChangeState (MMInput.ButtonStates.ButtonDown); } public virtual void InteractButtonPressed() { InteractButton.State.ChangeState (MMInput.ButtonStates.ButtonPressed); } public virtual void InteractButtonUp() { InteractButton.State.ChangeState (MMInput.ButtonStates.ButtonUp); } public virtual void DashButtonDown() { DashButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void DashButtonPressed() { DashButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void DashButtonUp() { DashButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void RollButtonDown() { RollButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void RollButtonPressed() { RollButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void RollButtonUp() { RollButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void FlyButtonDown() { FlyButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void FlyButtonPressed() { FlyButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void FlyButtonUp() { FlyButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void RunButtonDown() { RunButton.State.ChangeState (MMInput.ButtonStates.ButtonDown); } public virtual void RunButtonPressed() { RunButton.State.ChangeState (MMInput.ButtonStates.ButtonPressed); } public virtual void RunButtonUp() { RunButton.State.ChangeState (MMInput.ButtonStates.ButtonUp); } public virtual void JetpackButtonDown() { JetpackButton.State.ChangeState (MMInput.ButtonStates.ButtonDown); } public virtual void JetpackButtonPressed() { JetpackButton.State.ChangeState (MMInput.ButtonStates.ButtonPressed); } public virtual void JetpackButtonUp() { JetpackButton.State.ChangeState (MMInput.ButtonStates.ButtonUp); } public virtual void ReloadButtonDown() { ReloadButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void ReloadButtonPressed() { ReloadButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void ReloadButtonUp() { ReloadButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void PushButtonDown() { PushButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void PushButtonPressed() { PushButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void PushButtonUp() { PushButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void ShootButtonDown() { ShootButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void ShootButtonPressed() { ShootButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void ShootButtonUp() { ShootButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void SecondaryShootButtonDown() { SecondaryShootButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void SecondaryShootButtonPressed() { SecondaryShootButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void SecondaryShootButtonUp() { SecondaryShootButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void PauseButtonDown() { PauseButton.State.ChangeState (MMInput.ButtonStates.ButtonDown); } public virtual void PauseButtonPressed() { PauseButton.State.ChangeState (MMInput.ButtonStates.ButtonPressed); } public virtual void PauseButtonUp() { PauseButton.State.ChangeState (MMInput.ButtonStates.ButtonUp); } public virtual void SwitchWeaponButtonDown() { SwitchWeaponButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void SwitchWeaponButtonPressed() { SwitchWeaponButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void SwitchWeaponButtonUp() { SwitchWeaponButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void SwitchCharacterButtonDown() { SwitchCharacterButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void SwitchCharacterButtonPressed() { SwitchCharacterButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void SwitchCharacterButtonUp() { SwitchCharacterButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void TimeControlButtonDown() { TimeControlButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void TimeControlButtonPressed() { TimeControlButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void TimeControlButtonUp() { TimeControlButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void GrabButtonDown() { GrabButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void GrabButtonPressed() { GrabButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void GrabButtonUp() { GrabButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } public virtual void ThrowButtonDown() { ThrowButton.State.ChangeState(MMInput.ButtonStates.ButtonDown); } public virtual void ThrowButtonPressed() { ThrowButton.State.ChangeState(MMInput.ButtonStates.ButtonPressed); } public virtual void ThrowButtonUp() { ThrowButton.State.ChangeState(MMInput.ButtonStates.ButtonUp); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp.Swizzle { /// <summary> /// Temporary vector of type bool with 3 components, used for implementing swizzling for bvec3. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct swizzle_bvec3 { #region Fields /// <summary> /// x-component /// </summary> internal readonly bool x; /// <summary> /// y-component /// </summary> internal readonly bool y; /// <summary> /// z-component /// </summary> internal readonly bool z; #endregion #region Constructors /// <summary> /// Constructor for swizzle_bvec3. /// </summary> internal swizzle_bvec3(bool x, bool y, bool z) { this.x = x; this.y = y; this.z = z; } #endregion #region Properties /// <summary> /// Returns bvec3.xx swizzling. /// </summary> public bvec2 xx => new bvec2(x, x); /// <summary> /// Returns bvec3.rr swizzling (equivalent to bvec3.xx). /// </summary> public bvec2 rr => new bvec2(x, x); /// <summary> /// Returns bvec3.xxx swizzling. /// </summary> public bvec3 xxx => new bvec3(x, x, x); /// <summary> /// Returns bvec3.rrr swizzling (equivalent to bvec3.xxx). /// </summary> public bvec3 rrr => new bvec3(x, x, x); /// <summary> /// Returns bvec3.xxxx swizzling. /// </summary> public bvec4 xxxx => new bvec4(x, x, x, x); /// <summary> /// Returns bvec3.rrrr swizzling (equivalent to bvec3.xxxx). /// </summary> public bvec4 rrrr => new bvec4(x, x, x, x); /// <summary> /// Returns bvec3.xxxy swizzling. /// </summary> public bvec4 xxxy => new bvec4(x, x, x, y); /// <summary> /// Returns bvec3.rrrg swizzling (equivalent to bvec3.xxxy). /// </summary> public bvec4 rrrg => new bvec4(x, x, x, y); /// <summary> /// Returns bvec3.xxxz swizzling. /// </summary> public bvec4 xxxz => new bvec4(x, x, x, z); /// <summary> /// Returns bvec3.rrrb swizzling (equivalent to bvec3.xxxz). /// </summary> public bvec4 rrrb => new bvec4(x, x, x, z); /// <summary> /// Returns bvec3.xxy swizzling. /// </summary> public bvec3 xxy => new bvec3(x, x, y); /// <summary> /// Returns bvec3.rrg swizzling (equivalent to bvec3.xxy). /// </summary> public bvec3 rrg => new bvec3(x, x, y); /// <summary> /// Returns bvec3.xxyx swizzling. /// </summary> public bvec4 xxyx => new bvec4(x, x, y, x); /// <summary> /// Returns bvec3.rrgr swizzling (equivalent to bvec3.xxyx). /// </summary> public bvec4 rrgr => new bvec4(x, x, y, x); /// <summary> /// Returns bvec3.xxyy swizzling. /// </summary> public bvec4 xxyy => new bvec4(x, x, y, y); /// <summary> /// Returns bvec3.rrgg swizzling (equivalent to bvec3.xxyy). /// </summary> public bvec4 rrgg => new bvec4(x, x, y, y); /// <summary> /// Returns bvec3.xxyz swizzling. /// </summary> public bvec4 xxyz => new bvec4(x, x, y, z); /// <summary> /// Returns bvec3.rrgb swizzling (equivalent to bvec3.xxyz). /// </summary> public bvec4 rrgb => new bvec4(x, x, y, z); /// <summary> /// Returns bvec3.xxz swizzling. /// </summary> public bvec3 xxz => new bvec3(x, x, z); /// <summary> /// Returns bvec3.rrb swizzling (equivalent to bvec3.xxz). /// </summary> public bvec3 rrb => new bvec3(x, x, z); /// <summary> /// Returns bvec3.xxzx swizzling. /// </summary> public bvec4 xxzx => new bvec4(x, x, z, x); /// <summary> /// Returns bvec3.rrbr swizzling (equivalent to bvec3.xxzx). /// </summary> public bvec4 rrbr => new bvec4(x, x, z, x); /// <summary> /// Returns bvec3.xxzy swizzling. /// </summary> public bvec4 xxzy => new bvec4(x, x, z, y); /// <summary> /// Returns bvec3.rrbg swizzling (equivalent to bvec3.xxzy). /// </summary> public bvec4 rrbg => new bvec4(x, x, z, y); /// <summary> /// Returns bvec3.xxzz swizzling. /// </summary> public bvec4 xxzz => new bvec4(x, x, z, z); /// <summary> /// Returns bvec3.rrbb swizzling (equivalent to bvec3.xxzz). /// </summary> public bvec4 rrbb => new bvec4(x, x, z, z); /// <summary> /// Returns bvec3.xy swizzling. /// </summary> public bvec2 xy => new bvec2(x, y); /// <summary> /// Returns bvec3.rg swizzling (equivalent to bvec3.xy). /// </summary> public bvec2 rg => new bvec2(x, y); /// <summary> /// Returns bvec3.xyx swizzling. /// </summary> public bvec3 xyx => new bvec3(x, y, x); /// <summary> /// Returns bvec3.rgr swizzling (equivalent to bvec3.xyx). /// </summary> public bvec3 rgr => new bvec3(x, y, x); /// <summary> /// Returns bvec3.xyxx swizzling. /// </summary> public bvec4 xyxx => new bvec4(x, y, x, x); /// <summary> /// Returns bvec3.rgrr swizzling (equivalent to bvec3.xyxx). /// </summary> public bvec4 rgrr => new bvec4(x, y, x, x); /// <summary> /// Returns bvec3.xyxy swizzling. /// </summary> public bvec4 xyxy => new bvec4(x, y, x, y); /// <summary> /// Returns bvec3.rgrg swizzling (equivalent to bvec3.xyxy). /// </summary> public bvec4 rgrg => new bvec4(x, y, x, y); /// <summary> /// Returns bvec3.xyxz swizzling. /// </summary> public bvec4 xyxz => new bvec4(x, y, x, z); /// <summary> /// Returns bvec3.rgrb swizzling (equivalent to bvec3.xyxz). /// </summary> public bvec4 rgrb => new bvec4(x, y, x, z); /// <summary> /// Returns bvec3.xyy swizzling. /// </summary> public bvec3 xyy => new bvec3(x, y, y); /// <summary> /// Returns bvec3.rgg swizzling (equivalent to bvec3.xyy). /// </summary> public bvec3 rgg => new bvec3(x, y, y); /// <summary> /// Returns bvec3.xyyx swizzling. /// </summary> public bvec4 xyyx => new bvec4(x, y, y, x); /// <summary> /// Returns bvec3.rggr swizzling (equivalent to bvec3.xyyx). /// </summary> public bvec4 rggr => new bvec4(x, y, y, x); /// <summary> /// Returns bvec3.xyyy swizzling. /// </summary> public bvec4 xyyy => new bvec4(x, y, y, y); /// <summary> /// Returns bvec3.rggg swizzling (equivalent to bvec3.xyyy). /// </summary> public bvec4 rggg => new bvec4(x, y, y, y); /// <summary> /// Returns bvec3.xyyz swizzling. /// </summary> public bvec4 xyyz => new bvec4(x, y, y, z); /// <summary> /// Returns bvec3.rggb swizzling (equivalent to bvec3.xyyz). /// </summary> public bvec4 rggb => new bvec4(x, y, y, z); /// <summary> /// Returns bvec3.xyz swizzling. /// </summary> public bvec3 xyz => new bvec3(x, y, z); /// <summary> /// Returns bvec3.rgb swizzling (equivalent to bvec3.xyz). /// </summary> public bvec3 rgb => new bvec3(x, y, z); /// <summary> /// Returns bvec3.xyzx swizzling. /// </summary> public bvec4 xyzx => new bvec4(x, y, z, x); /// <summary> /// Returns bvec3.rgbr swizzling (equivalent to bvec3.xyzx). /// </summary> public bvec4 rgbr => new bvec4(x, y, z, x); /// <summary> /// Returns bvec3.xyzy swizzling. /// </summary> public bvec4 xyzy => new bvec4(x, y, z, y); /// <summary> /// Returns bvec3.rgbg swizzling (equivalent to bvec3.xyzy). /// </summary> public bvec4 rgbg => new bvec4(x, y, z, y); /// <summary> /// Returns bvec3.xyzz swizzling. /// </summary> public bvec4 xyzz => new bvec4(x, y, z, z); /// <summary> /// Returns bvec3.rgbb swizzling (equivalent to bvec3.xyzz). /// </summary> public bvec4 rgbb => new bvec4(x, y, z, z); /// <summary> /// Returns bvec3.xz swizzling. /// </summary> public bvec2 xz => new bvec2(x, z); /// <summary> /// Returns bvec3.rb swizzling (equivalent to bvec3.xz). /// </summary> public bvec2 rb => new bvec2(x, z); /// <summary> /// Returns bvec3.xzx swizzling. /// </summary> public bvec3 xzx => new bvec3(x, z, x); /// <summary> /// Returns bvec3.rbr swizzling (equivalent to bvec3.xzx). /// </summary> public bvec3 rbr => new bvec3(x, z, x); /// <summary> /// Returns bvec3.xzxx swizzling. /// </summary> public bvec4 xzxx => new bvec4(x, z, x, x); /// <summary> /// Returns bvec3.rbrr swizzling (equivalent to bvec3.xzxx). /// </summary> public bvec4 rbrr => new bvec4(x, z, x, x); /// <summary> /// Returns bvec3.xzxy swizzling. /// </summary> public bvec4 xzxy => new bvec4(x, z, x, y); /// <summary> /// Returns bvec3.rbrg swizzling (equivalent to bvec3.xzxy). /// </summary> public bvec4 rbrg => new bvec4(x, z, x, y); /// <summary> /// Returns bvec3.xzxz swizzling. /// </summary> public bvec4 xzxz => new bvec4(x, z, x, z); /// <summary> /// Returns bvec3.rbrb swizzling (equivalent to bvec3.xzxz). /// </summary> public bvec4 rbrb => new bvec4(x, z, x, z); /// <summary> /// Returns bvec3.xzy swizzling. /// </summary> public bvec3 xzy => new bvec3(x, z, y); /// <summary> /// Returns bvec3.rbg swizzling (equivalent to bvec3.xzy). /// </summary> public bvec3 rbg => new bvec3(x, z, y); /// <summary> /// Returns bvec3.xzyx swizzling. /// </summary> public bvec4 xzyx => new bvec4(x, z, y, x); /// <summary> /// Returns bvec3.rbgr swizzling (equivalent to bvec3.xzyx). /// </summary> public bvec4 rbgr => new bvec4(x, z, y, x); /// <summary> /// Returns bvec3.xzyy swizzling. /// </summary> public bvec4 xzyy => new bvec4(x, z, y, y); /// <summary> /// Returns bvec3.rbgg swizzling (equivalent to bvec3.xzyy). /// </summary> public bvec4 rbgg => new bvec4(x, z, y, y); /// <summary> /// Returns bvec3.xzyz swizzling. /// </summary> public bvec4 xzyz => new bvec4(x, z, y, z); /// <summary> /// Returns bvec3.rbgb swizzling (equivalent to bvec3.xzyz). /// </summary> public bvec4 rbgb => new bvec4(x, z, y, z); /// <summary> /// Returns bvec3.xzz swizzling. /// </summary> public bvec3 xzz => new bvec3(x, z, z); /// <summary> /// Returns bvec3.rbb swizzling (equivalent to bvec3.xzz). /// </summary> public bvec3 rbb => new bvec3(x, z, z); /// <summary> /// Returns bvec3.xzzx swizzling. /// </summary> public bvec4 xzzx => new bvec4(x, z, z, x); /// <summary> /// Returns bvec3.rbbr swizzling (equivalent to bvec3.xzzx). /// </summary> public bvec4 rbbr => new bvec4(x, z, z, x); /// <summary> /// Returns bvec3.xzzy swizzling. /// </summary> public bvec4 xzzy => new bvec4(x, z, z, y); /// <summary> /// Returns bvec3.rbbg swizzling (equivalent to bvec3.xzzy). /// </summary> public bvec4 rbbg => new bvec4(x, z, z, y); /// <summary> /// Returns bvec3.xzzz swizzling. /// </summary> public bvec4 xzzz => new bvec4(x, z, z, z); /// <summary> /// Returns bvec3.rbbb swizzling (equivalent to bvec3.xzzz). /// </summary> public bvec4 rbbb => new bvec4(x, z, z, z); /// <summary> /// Returns bvec3.yx swizzling. /// </summary> public bvec2 yx => new bvec2(y, x); /// <summary> /// Returns bvec3.gr swizzling (equivalent to bvec3.yx). /// </summary> public bvec2 gr => new bvec2(y, x); /// <summary> /// Returns bvec3.yxx swizzling. /// </summary> public bvec3 yxx => new bvec3(y, x, x); /// <summary> /// Returns bvec3.grr swizzling (equivalent to bvec3.yxx). /// </summary> public bvec3 grr => new bvec3(y, x, x); /// <summary> /// Returns bvec3.yxxx swizzling. /// </summary> public bvec4 yxxx => new bvec4(y, x, x, x); /// <summary> /// Returns bvec3.grrr swizzling (equivalent to bvec3.yxxx). /// </summary> public bvec4 grrr => new bvec4(y, x, x, x); /// <summary> /// Returns bvec3.yxxy swizzling. /// </summary> public bvec4 yxxy => new bvec4(y, x, x, y); /// <summary> /// Returns bvec3.grrg swizzling (equivalent to bvec3.yxxy). /// </summary> public bvec4 grrg => new bvec4(y, x, x, y); /// <summary> /// Returns bvec3.yxxz swizzling. /// </summary> public bvec4 yxxz => new bvec4(y, x, x, z); /// <summary> /// Returns bvec3.grrb swizzling (equivalent to bvec3.yxxz). /// </summary> public bvec4 grrb => new bvec4(y, x, x, z); /// <summary> /// Returns bvec3.yxy swizzling. /// </summary> public bvec3 yxy => new bvec3(y, x, y); /// <summary> /// Returns bvec3.grg swizzling (equivalent to bvec3.yxy). /// </summary> public bvec3 grg => new bvec3(y, x, y); /// <summary> /// Returns bvec3.yxyx swizzling. /// </summary> public bvec4 yxyx => new bvec4(y, x, y, x); /// <summary> /// Returns bvec3.grgr swizzling (equivalent to bvec3.yxyx). /// </summary> public bvec4 grgr => new bvec4(y, x, y, x); /// <summary> /// Returns bvec3.yxyy swizzling. /// </summary> public bvec4 yxyy => new bvec4(y, x, y, y); /// <summary> /// Returns bvec3.grgg swizzling (equivalent to bvec3.yxyy). /// </summary> public bvec4 grgg => new bvec4(y, x, y, y); /// <summary> /// Returns bvec3.yxyz swizzling. /// </summary> public bvec4 yxyz => new bvec4(y, x, y, z); /// <summary> /// Returns bvec3.grgb swizzling (equivalent to bvec3.yxyz). /// </summary> public bvec4 grgb => new bvec4(y, x, y, z); /// <summary> /// Returns bvec3.yxz swizzling. /// </summary> public bvec3 yxz => new bvec3(y, x, z); /// <summary> /// Returns bvec3.grb swizzling (equivalent to bvec3.yxz). /// </summary> public bvec3 grb => new bvec3(y, x, z); /// <summary> /// Returns bvec3.yxzx swizzling. /// </summary> public bvec4 yxzx => new bvec4(y, x, z, x); /// <summary> /// Returns bvec3.grbr swizzling (equivalent to bvec3.yxzx). /// </summary> public bvec4 grbr => new bvec4(y, x, z, x); /// <summary> /// Returns bvec3.yxzy swizzling. /// </summary> public bvec4 yxzy => new bvec4(y, x, z, y); /// <summary> /// Returns bvec3.grbg swizzling (equivalent to bvec3.yxzy). /// </summary> public bvec4 grbg => new bvec4(y, x, z, y); /// <summary> /// Returns bvec3.yxzz swizzling. /// </summary> public bvec4 yxzz => new bvec4(y, x, z, z); /// <summary> /// Returns bvec3.grbb swizzling (equivalent to bvec3.yxzz). /// </summary> public bvec4 grbb => new bvec4(y, x, z, z); /// <summary> /// Returns bvec3.yy swizzling. /// </summary> public bvec2 yy => new bvec2(y, y); /// <summary> /// Returns bvec3.gg swizzling (equivalent to bvec3.yy). /// </summary> public bvec2 gg => new bvec2(y, y); /// <summary> /// Returns bvec3.yyx swizzling. /// </summary> public bvec3 yyx => new bvec3(y, y, x); /// <summary> /// Returns bvec3.ggr swizzling (equivalent to bvec3.yyx). /// </summary> public bvec3 ggr => new bvec3(y, y, x); /// <summary> /// Returns bvec3.yyxx swizzling. /// </summary> public bvec4 yyxx => new bvec4(y, y, x, x); /// <summary> /// Returns bvec3.ggrr swizzling (equivalent to bvec3.yyxx). /// </summary> public bvec4 ggrr => new bvec4(y, y, x, x); /// <summary> /// Returns bvec3.yyxy swizzling. /// </summary> public bvec4 yyxy => new bvec4(y, y, x, y); /// <summary> /// Returns bvec3.ggrg swizzling (equivalent to bvec3.yyxy). /// </summary> public bvec4 ggrg => new bvec4(y, y, x, y); /// <summary> /// Returns bvec3.yyxz swizzling. /// </summary> public bvec4 yyxz => new bvec4(y, y, x, z); /// <summary> /// Returns bvec3.ggrb swizzling (equivalent to bvec3.yyxz). /// </summary> public bvec4 ggrb => new bvec4(y, y, x, z); /// <summary> /// Returns bvec3.yyy swizzling. /// </summary> public bvec3 yyy => new bvec3(y, y, y); /// <summary> /// Returns bvec3.ggg swizzling (equivalent to bvec3.yyy). /// </summary> public bvec3 ggg => new bvec3(y, y, y); /// <summary> /// Returns bvec3.yyyx swizzling. /// </summary> public bvec4 yyyx => new bvec4(y, y, y, x); /// <summary> /// Returns bvec3.gggr swizzling (equivalent to bvec3.yyyx). /// </summary> public bvec4 gggr => new bvec4(y, y, y, x); /// <summary> /// Returns bvec3.yyyy swizzling. /// </summary> public bvec4 yyyy => new bvec4(y, y, y, y); /// <summary> /// Returns bvec3.gggg swizzling (equivalent to bvec3.yyyy). /// </summary> public bvec4 gggg => new bvec4(y, y, y, y); /// <summary> /// Returns bvec3.yyyz swizzling. /// </summary> public bvec4 yyyz => new bvec4(y, y, y, z); /// <summary> /// Returns bvec3.gggb swizzling (equivalent to bvec3.yyyz). /// </summary> public bvec4 gggb => new bvec4(y, y, y, z); /// <summary> /// Returns bvec3.yyz swizzling. /// </summary> public bvec3 yyz => new bvec3(y, y, z); /// <summary> /// Returns bvec3.ggb swizzling (equivalent to bvec3.yyz). /// </summary> public bvec3 ggb => new bvec3(y, y, z); /// <summary> /// Returns bvec3.yyzx swizzling. /// </summary> public bvec4 yyzx => new bvec4(y, y, z, x); /// <summary> /// Returns bvec3.ggbr swizzling (equivalent to bvec3.yyzx). /// </summary> public bvec4 ggbr => new bvec4(y, y, z, x); /// <summary> /// Returns bvec3.yyzy swizzling. /// </summary> public bvec4 yyzy => new bvec4(y, y, z, y); /// <summary> /// Returns bvec3.ggbg swizzling (equivalent to bvec3.yyzy). /// </summary> public bvec4 ggbg => new bvec4(y, y, z, y); /// <summary> /// Returns bvec3.yyzz swizzling. /// </summary> public bvec4 yyzz => new bvec4(y, y, z, z); /// <summary> /// Returns bvec3.ggbb swizzling (equivalent to bvec3.yyzz). /// </summary> public bvec4 ggbb => new bvec4(y, y, z, z); /// <summary> /// Returns bvec3.yz swizzling. /// </summary> public bvec2 yz => new bvec2(y, z); /// <summary> /// Returns bvec3.gb swizzling (equivalent to bvec3.yz). /// </summary> public bvec2 gb => new bvec2(y, z); /// <summary> /// Returns bvec3.yzx swizzling. /// </summary> public bvec3 yzx => new bvec3(y, z, x); /// <summary> /// Returns bvec3.gbr swizzling (equivalent to bvec3.yzx). /// </summary> public bvec3 gbr => new bvec3(y, z, x); /// <summary> /// Returns bvec3.yzxx swizzling. /// </summary> public bvec4 yzxx => new bvec4(y, z, x, x); /// <summary> /// Returns bvec3.gbrr swizzling (equivalent to bvec3.yzxx). /// </summary> public bvec4 gbrr => new bvec4(y, z, x, x); /// <summary> /// Returns bvec3.yzxy swizzling. /// </summary> public bvec4 yzxy => new bvec4(y, z, x, y); /// <summary> /// Returns bvec3.gbrg swizzling (equivalent to bvec3.yzxy). /// </summary> public bvec4 gbrg => new bvec4(y, z, x, y); /// <summary> /// Returns bvec3.yzxz swizzling. /// </summary> public bvec4 yzxz => new bvec4(y, z, x, z); /// <summary> /// Returns bvec3.gbrb swizzling (equivalent to bvec3.yzxz). /// </summary> public bvec4 gbrb => new bvec4(y, z, x, z); /// <summary> /// Returns bvec3.yzy swizzling. /// </summary> public bvec3 yzy => new bvec3(y, z, y); /// <summary> /// Returns bvec3.gbg swizzling (equivalent to bvec3.yzy). /// </summary> public bvec3 gbg => new bvec3(y, z, y); /// <summary> /// Returns bvec3.yzyx swizzling. /// </summary> public bvec4 yzyx => new bvec4(y, z, y, x); /// <summary> /// Returns bvec3.gbgr swizzling (equivalent to bvec3.yzyx). /// </summary> public bvec4 gbgr => new bvec4(y, z, y, x); /// <summary> /// Returns bvec3.yzyy swizzling. /// </summary> public bvec4 yzyy => new bvec4(y, z, y, y); /// <summary> /// Returns bvec3.gbgg swizzling (equivalent to bvec3.yzyy). /// </summary> public bvec4 gbgg => new bvec4(y, z, y, y); /// <summary> /// Returns bvec3.yzyz swizzling. /// </summary> public bvec4 yzyz => new bvec4(y, z, y, z); /// <summary> /// Returns bvec3.gbgb swizzling (equivalent to bvec3.yzyz). /// </summary> public bvec4 gbgb => new bvec4(y, z, y, z); /// <summary> /// Returns bvec3.yzz swizzling. /// </summary> public bvec3 yzz => new bvec3(y, z, z); /// <summary> /// Returns bvec3.gbb swizzling (equivalent to bvec3.yzz). /// </summary> public bvec3 gbb => new bvec3(y, z, z); /// <summary> /// Returns bvec3.yzzx swizzling. /// </summary> public bvec4 yzzx => new bvec4(y, z, z, x); /// <summary> /// Returns bvec3.gbbr swizzling (equivalent to bvec3.yzzx). /// </summary> public bvec4 gbbr => new bvec4(y, z, z, x); /// <summary> /// Returns bvec3.yzzy swizzling. /// </summary> public bvec4 yzzy => new bvec4(y, z, z, y); /// <summary> /// Returns bvec3.gbbg swizzling (equivalent to bvec3.yzzy). /// </summary> public bvec4 gbbg => new bvec4(y, z, z, y); /// <summary> /// Returns bvec3.yzzz swizzling. /// </summary> public bvec4 yzzz => new bvec4(y, z, z, z); /// <summary> /// Returns bvec3.gbbb swizzling (equivalent to bvec3.yzzz). /// </summary> public bvec4 gbbb => new bvec4(y, z, z, z); /// <summary> /// Returns bvec3.zx swizzling. /// </summary> public bvec2 zx => new bvec2(z, x); /// <summary> /// Returns bvec3.br swizzling (equivalent to bvec3.zx). /// </summary> public bvec2 br => new bvec2(z, x); /// <summary> /// Returns bvec3.zxx swizzling. /// </summary> public bvec3 zxx => new bvec3(z, x, x); /// <summary> /// Returns bvec3.brr swizzling (equivalent to bvec3.zxx). /// </summary> public bvec3 brr => new bvec3(z, x, x); /// <summary> /// Returns bvec3.zxxx swizzling. /// </summary> public bvec4 zxxx => new bvec4(z, x, x, x); /// <summary> /// Returns bvec3.brrr swizzling (equivalent to bvec3.zxxx). /// </summary> public bvec4 brrr => new bvec4(z, x, x, x); /// <summary> /// Returns bvec3.zxxy swizzling. /// </summary> public bvec4 zxxy => new bvec4(z, x, x, y); /// <summary> /// Returns bvec3.brrg swizzling (equivalent to bvec3.zxxy). /// </summary> public bvec4 brrg => new bvec4(z, x, x, y); /// <summary> /// Returns bvec3.zxxz swizzling. /// </summary> public bvec4 zxxz => new bvec4(z, x, x, z); /// <summary> /// Returns bvec3.brrb swizzling (equivalent to bvec3.zxxz). /// </summary> public bvec4 brrb => new bvec4(z, x, x, z); /// <summary> /// Returns bvec3.zxy swizzling. /// </summary> public bvec3 zxy => new bvec3(z, x, y); /// <summary> /// Returns bvec3.brg swizzling (equivalent to bvec3.zxy). /// </summary> public bvec3 brg => new bvec3(z, x, y); /// <summary> /// Returns bvec3.zxyx swizzling. /// </summary> public bvec4 zxyx => new bvec4(z, x, y, x); /// <summary> /// Returns bvec3.brgr swizzling (equivalent to bvec3.zxyx). /// </summary> public bvec4 brgr => new bvec4(z, x, y, x); /// <summary> /// Returns bvec3.zxyy swizzling. /// </summary> public bvec4 zxyy => new bvec4(z, x, y, y); /// <summary> /// Returns bvec3.brgg swizzling (equivalent to bvec3.zxyy). /// </summary> public bvec4 brgg => new bvec4(z, x, y, y); /// <summary> /// Returns bvec3.zxyz swizzling. /// </summary> public bvec4 zxyz => new bvec4(z, x, y, z); /// <summary> /// Returns bvec3.brgb swizzling (equivalent to bvec3.zxyz). /// </summary> public bvec4 brgb => new bvec4(z, x, y, z); /// <summary> /// Returns bvec3.zxz swizzling. /// </summary> public bvec3 zxz => new bvec3(z, x, z); /// <summary> /// Returns bvec3.brb swizzling (equivalent to bvec3.zxz). /// </summary> public bvec3 brb => new bvec3(z, x, z); /// <summary> /// Returns bvec3.zxzx swizzling. /// </summary> public bvec4 zxzx => new bvec4(z, x, z, x); /// <summary> /// Returns bvec3.brbr swizzling (equivalent to bvec3.zxzx). /// </summary> public bvec4 brbr => new bvec4(z, x, z, x); /// <summary> /// Returns bvec3.zxzy swizzling. /// </summary> public bvec4 zxzy => new bvec4(z, x, z, y); /// <summary> /// Returns bvec3.brbg swizzling (equivalent to bvec3.zxzy). /// </summary> public bvec4 brbg => new bvec4(z, x, z, y); /// <summary> /// Returns bvec3.zxzz swizzling. /// </summary> public bvec4 zxzz => new bvec4(z, x, z, z); /// <summary> /// Returns bvec3.brbb swizzling (equivalent to bvec3.zxzz). /// </summary> public bvec4 brbb => new bvec4(z, x, z, z); /// <summary> /// Returns bvec3.zy swizzling. /// </summary> public bvec2 zy => new bvec2(z, y); /// <summary> /// Returns bvec3.bg swizzling (equivalent to bvec3.zy). /// </summary> public bvec2 bg => new bvec2(z, y); /// <summary> /// Returns bvec3.zyx swizzling. /// </summary> public bvec3 zyx => new bvec3(z, y, x); /// <summary> /// Returns bvec3.bgr swizzling (equivalent to bvec3.zyx). /// </summary> public bvec3 bgr => new bvec3(z, y, x); /// <summary> /// Returns bvec3.zyxx swizzling. /// </summary> public bvec4 zyxx => new bvec4(z, y, x, x); /// <summary> /// Returns bvec3.bgrr swizzling (equivalent to bvec3.zyxx). /// </summary> public bvec4 bgrr => new bvec4(z, y, x, x); /// <summary> /// Returns bvec3.zyxy swizzling. /// </summary> public bvec4 zyxy => new bvec4(z, y, x, y); /// <summary> /// Returns bvec3.bgrg swizzling (equivalent to bvec3.zyxy). /// </summary> public bvec4 bgrg => new bvec4(z, y, x, y); /// <summary> /// Returns bvec3.zyxz swizzling. /// </summary> public bvec4 zyxz => new bvec4(z, y, x, z); /// <summary> /// Returns bvec3.bgrb swizzling (equivalent to bvec3.zyxz). /// </summary> public bvec4 bgrb => new bvec4(z, y, x, z); /// <summary> /// Returns bvec3.zyy swizzling. /// </summary> public bvec3 zyy => new bvec3(z, y, y); /// <summary> /// Returns bvec3.bgg swizzling (equivalent to bvec3.zyy). /// </summary> public bvec3 bgg => new bvec3(z, y, y); /// <summary> /// Returns bvec3.zyyx swizzling. /// </summary> public bvec4 zyyx => new bvec4(z, y, y, x); /// <summary> /// Returns bvec3.bggr swizzling (equivalent to bvec3.zyyx). /// </summary> public bvec4 bggr => new bvec4(z, y, y, x); /// <summary> /// Returns bvec3.zyyy swizzling. /// </summary> public bvec4 zyyy => new bvec4(z, y, y, y); /// <summary> /// Returns bvec3.bggg swizzling (equivalent to bvec3.zyyy). /// </summary> public bvec4 bggg => new bvec4(z, y, y, y); /// <summary> /// Returns bvec3.zyyz swizzling. /// </summary> public bvec4 zyyz => new bvec4(z, y, y, z); /// <summary> /// Returns bvec3.bggb swizzling (equivalent to bvec3.zyyz). /// </summary> public bvec4 bggb => new bvec4(z, y, y, z); /// <summary> /// Returns bvec3.zyz swizzling. /// </summary> public bvec3 zyz => new bvec3(z, y, z); /// <summary> /// Returns bvec3.bgb swizzling (equivalent to bvec3.zyz). /// </summary> public bvec3 bgb => new bvec3(z, y, z); /// <summary> /// Returns bvec3.zyzx swizzling. /// </summary> public bvec4 zyzx => new bvec4(z, y, z, x); /// <summary> /// Returns bvec3.bgbr swizzling (equivalent to bvec3.zyzx). /// </summary> public bvec4 bgbr => new bvec4(z, y, z, x); /// <summary> /// Returns bvec3.zyzy swizzling. /// </summary> public bvec4 zyzy => new bvec4(z, y, z, y); /// <summary> /// Returns bvec3.bgbg swizzling (equivalent to bvec3.zyzy). /// </summary> public bvec4 bgbg => new bvec4(z, y, z, y); /// <summary> /// Returns bvec3.zyzz swizzling. /// </summary> public bvec4 zyzz => new bvec4(z, y, z, z); /// <summary> /// Returns bvec3.bgbb swizzling (equivalent to bvec3.zyzz). /// </summary> public bvec4 bgbb => new bvec4(z, y, z, z); /// <summary> /// Returns bvec3.zz swizzling. /// </summary> public bvec2 zz => new bvec2(z, z); /// <summary> /// Returns bvec3.bb swizzling (equivalent to bvec3.zz). /// </summary> public bvec2 bb => new bvec2(z, z); /// <summary> /// Returns bvec3.zzx swizzling. /// </summary> public bvec3 zzx => new bvec3(z, z, x); /// <summary> /// Returns bvec3.bbr swizzling (equivalent to bvec3.zzx). /// </summary> public bvec3 bbr => new bvec3(z, z, x); /// <summary> /// Returns bvec3.zzxx swizzling. /// </summary> public bvec4 zzxx => new bvec4(z, z, x, x); /// <summary> /// Returns bvec3.bbrr swizzling (equivalent to bvec3.zzxx). /// </summary> public bvec4 bbrr => new bvec4(z, z, x, x); /// <summary> /// Returns bvec3.zzxy swizzling. /// </summary> public bvec4 zzxy => new bvec4(z, z, x, y); /// <summary> /// Returns bvec3.bbrg swizzling (equivalent to bvec3.zzxy). /// </summary> public bvec4 bbrg => new bvec4(z, z, x, y); /// <summary> /// Returns bvec3.zzxz swizzling. /// </summary> public bvec4 zzxz => new bvec4(z, z, x, z); /// <summary> /// Returns bvec3.bbrb swizzling (equivalent to bvec3.zzxz). /// </summary> public bvec4 bbrb => new bvec4(z, z, x, z); /// <summary> /// Returns bvec3.zzy swizzling. /// </summary> public bvec3 zzy => new bvec3(z, z, y); /// <summary> /// Returns bvec3.bbg swizzling (equivalent to bvec3.zzy). /// </summary> public bvec3 bbg => new bvec3(z, z, y); /// <summary> /// Returns bvec3.zzyx swizzling. /// </summary> public bvec4 zzyx => new bvec4(z, z, y, x); /// <summary> /// Returns bvec3.bbgr swizzling (equivalent to bvec3.zzyx). /// </summary> public bvec4 bbgr => new bvec4(z, z, y, x); /// <summary> /// Returns bvec3.zzyy swizzling. /// </summary> public bvec4 zzyy => new bvec4(z, z, y, y); /// <summary> /// Returns bvec3.bbgg swizzling (equivalent to bvec3.zzyy). /// </summary> public bvec4 bbgg => new bvec4(z, z, y, y); /// <summary> /// Returns bvec3.zzyz swizzling. /// </summary> public bvec4 zzyz => new bvec4(z, z, y, z); /// <summary> /// Returns bvec3.bbgb swizzling (equivalent to bvec3.zzyz). /// </summary> public bvec4 bbgb => new bvec4(z, z, y, z); /// <summary> /// Returns bvec3.zzz swizzling. /// </summary> public bvec3 zzz => new bvec3(z, z, z); /// <summary> /// Returns bvec3.bbb swizzling (equivalent to bvec3.zzz). /// </summary> public bvec3 bbb => new bvec3(z, z, z); /// <summary> /// Returns bvec3.zzzx swizzling. /// </summary> public bvec4 zzzx => new bvec4(z, z, z, x); /// <summary> /// Returns bvec3.bbbr swizzling (equivalent to bvec3.zzzx). /// </summary> public bvec4 bbbr => new bvec4(z, z, z, x); /// <summary> /// Returns bvec3.zzzy swizzling. /// </summary> public bvec4 zzzy => new bvec4(z, z, z, y); /// <summary> /// Returns bvec3.bbbg swizzling (equivalent to bvec3.zzzy). /// </summary> public bvec4 bbbg => new bvec4(z, z, z, y); /// <summary> /// Returns bvec3.zzzz swizzling. /// </summary> public bvec4 zzzz => new bvec4(z, z, z, z); /// <summary> /// Returns bvec3.bbbb swizzling (equivalent to bvec3.zzzz). /// </summary> public bvec4 bbbb => new bvec4(z, z, z, z); #endregion } }
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace erl.Oracle.TnsNames.Antlr4.Runtime.Misc { /// <summary> /// This class implements the /// <see cref="IIntSet"/> /// backed by a sorted array of /// non-overlapping intervals. It is particularly efficient for representing /// large collections of numbers, where the majority of elements appear as part /// of a sequential range of numbers that are all part of the set. For example, /// the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }. /// <p> /// This class is able to represent sets containing any combination of values in /// the range /// <see cref="int.MinValue"/> /// to /// <see cref="int.MaxValue"/> /// (inclusive).</p> /// </summary> public class IntervalSet : IIntSet { public static readonly erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet CompleteCharSet = erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet.Of(Lexer.MinCharValue, Lexer.MaxCharValue); public static readonly erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet EmptySet = new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); static IntervalSet() { CompleteCharSet.SetReadonly(true); EmptySet.SetReadonly(true); } /// <summary>The list of sorted, disjoint intervals.</summary> /// <remarks>The list of sorted, disjoint intervals.</remarks> protected internal IList<Interval> intervals; protected internal bool @readonly; public IntervalSet(IList<Interval> intervals) { this.intervals = intervals; } public IntervalSet(erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet set) : this() { AddAll(set); } public IntervalSet(params int[] els) { if (els == null) { intervals = new ArrayList<Interval>(2); } else { // most sets are 1 or 2 elements intervals = new ArrayList<Interval>(els.Length); foreach (int e in els) { Add(e); } } } /// <summary>Create a set with a single element, el.</summary> /// <remarks>Create a set with a single element, el.</remarks> [return: NotNull] public static erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet Of(int a) { erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet s = new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); s.Add(a); return s; } /// <summary>Create a set with all ints within range [a..b] (inclusive)</summary> public static erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet Of(int a, int b) { erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet s = new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); s.Add(a, b); return s; } public virtual void Clear() { if (@readonly) { throw new InvalidOperationException("can't alter readonly IntervalSet"); } intervals.Clear(); } /// <summary>Add a single element to the set.</summary> /// <remarks> /// Add a single element to the set. An isolated element is stored /// as a range el..el. /// </remarks> public virtual void Add(int el) { if (@readonly) { throw new InvalidOperationException("can't alter readonly IntervalSet"); } Add(el, el); } /// <summary>Add interval; i.e., add all integers from a to b to set.</summary> /// <remarks> /// Add interval; i.e., add all integers from a to b to set. /// If b&lt;a, do nothing. /// Keep list in sorted order (by left range value). /// If overlap, combine ranges. For example, /// If this is {1..5, 10..20}, adding 6..7 yields /// {1..5, 6..7, 10..20}. Adding 4..8 yields {1..8, 10..20}. /// </remarks> public virtual void Add(int a, int b) { Add(Interval.Of(a, b)); } // copy on write so we can cache a..a intervals and sets of that protected internal virtual void Add(Interval addition) { if (@readonly) { throw new InvalidOperationException("can't alter readonly IntervalSet"); } //System.out.println("add "+addition+" to "+intervals.toString()); if (addition.b < addition.a) { return; } // find position in list // Use iterators as we modify list in place for (int i = 0; i < intervals.Count; i++) { Interval r = intervals[i]; if (addition.Equals(r)) { return; } if (addition.Adjacent(r) || !addition.Disjoint(r)) { // next to each other, make a single larger interval Interval bigger = addition.Union(r); intervals[i] = bigger; // make sure we didn't just create an interval that // should be merged with next interval in list while (i < intervals.Count - 1) { i++; Interval next = intervals[i]; if (!bigger.Adjacent(next) && bigger.Disjoint(next)) { break; } // if we bump up against or overlap next, merge intervals.RemoveAt(i); // remove this one i--; // move backwards to what we just set intervals[i] = bigger.Union(next); // set to 3 merged ones } // first call to next after previous duplicates the result return; } if (addition.StartsBeforeDisjoint(r)) { // insert before r intervals.Insert(i, addition); return; } } // if disjoint and after r, a future iteration will handle it // ok, must be after last interval (and disjoint from last interval) // just add it intervals.Add(addition); } /// <summary>combine all sets in the array returned the or'd value</summary> public static erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet Or(erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet[] sets) { erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet r = new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); foreach (erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet s in sets) { r.AddAll(s); } return r; } public virtual erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet AddAll(IIntSet set) { if (set == null) { return this; } if (set is erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet) { erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet other = (erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet)set; // walk set and add each interval int n = other.intervals.Count; for (int i = 0; i < n; i++) { Interval I = other.intervals[i]; this.Add(I.a, I.b); } } else { foreach (int value in set.ToList()) { Add(value); } } return this; } public virtual erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet Complement(int minElement, int maxElement) { return this.Complement(erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet.Of(minElement, maxElement)); } /// <summary> /// <inheritDoc/> /// /// </summary> public virtual erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet Complement(IIntSet vocabulary) { if (vocabulary == null || vocabulary.IsNil) { return null; } // nothing in common with null set erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet vocabularyIS; if (vocabulary is erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet) { vocabularyIS = (erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet)vocabulary; } else { vocabularyIS = new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); vocabularyIS.AddAll(vocabulary); } return vocabularyIS.Subtract(this); } public virtual erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet Subtract(IIntSet a) { if (a == null || a.IsNil) { return new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(this); } if (a is erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet) { return Subtract(this, (erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet)a); } erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet other = new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); other.AddAll(a); return Subtract(this, other); } /// <summary>Compute the set difference between two interval sets.</summary> /// <remarks> /// Compute the set difference between two interval sets. The specific /// operation is /// <c>left - right</c> /// . If either of the input sets is /// <see langword="null"/> /// , it is treated as though it was an empty set. /// </remarks> [return: NotNull] public static erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet Subtract(erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet left, erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet right) { if (left == null || left.IsNil) { return new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); } erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet result = new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(left); if (right == null || right.IsNil) { // right set has no elements; just return the copy of the current set return result; } int resultI = 0; int rightI = 0; while (resultI < result.intervals.Count && rightI < right.intervals.Count) { Interval resultInterval = result.intervals[resultI]; Interval rightInterval = right.intervals[rightI]; // operation: (resultInterval - rightInterval) and update indexes if (rightInterval.b < resultInterval.a) { rightI++; continue; } if (rightInterval.a > resultInterval.b) { resultI++; continue; } Interval? beforeCurrent = null; Interval? afterCurrent = null; if (rightInterval.a > resultInterval.a) { beforeCurrent = new Interval(resultInterval.a, rightInterval.a - 1); } if (rightInterval.b < resultInterval.b) { afterCurrent = new Interval(rightInterval.b + 1, resultInterval.b); } if (beforeCurrent != null) { if (afterCurrent != null) { // split the current interval into two result.intervals[resultI] = beforeCurrent.Value; result.intervals.Insert(resultI + 1, afterCurrent.Value); resultI++; rightI++; continue; } else { // replace the current interval result.intervals[resultI] = beforeCurrent.Value; resultI++; continue; } } else { if (afterCurrent != null) { // replace the current interval result.intervals[resultI] = afterCurrent.Value; rightI++; continue; } else { // remove the current interval (thus no need to increment resultI) result.intervals.RemoveAt(resultI); continue; } } } // If rightI reached right.intervals.size(), no more intervals to subtract from result. // If resultI reached result.intervals.size(), we would be subtracting from an empty set. // Either way, we are done. return result; } public virtual erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet Or(IIntSet a) { erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet o = new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); o.AddAll(this); o.AddAll(a); return o; } /// <summary> /// <inheritDoc/> /// /// </summary> public virtual erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet And(IIntSet other) { if (other == null) { //|| !(other instanceof IntervalSet) ) { return null; } // nothing in common with null set IList<Interval> myIntervals = this.intervals; IList<Interval> theirIntervals = ((erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet)other).intervals; erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet intersection = null; int mySize = myIntervals.Count; int theirSize = theirIntervals.Count; int i = 0; int j = 0; // iterate down both interval lists looking for nondisjoint intervals while (i < mySize && j < theirSize) { Interval mine = myIntervals[i]; Interval theirs = theirIntervals[j]; //System.out.println("mine="+mine+" and theirs="+theirs); if (mine.StartsBeforeDisjoint(theirs)) { // move this iterator looking for interval that might overlap i++; } else { if (theirs.StartsBeforeDisjoint(mine)) { // move other iterator looking for interval that might overlap j++; } else { if (mine.ProperlyContains(theirs)) { // overlap, add intersection, get next theirs if (intersection == null) { intersection = new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); } intersection.Add(mine.Intersection(theirs)); j++; } else { if (theirs.ProperlyContains(mine)) { // overlap, add intersection, get next mine if (intersection == null) { intersection = new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); } intersection.Add(mine.Intersection(theirs)); i++; } else { if (!mine.Disjoint(theirs)) { // overlap, add intersection if (intersection == null) { intersection = new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); } intersection.Add(mine.Intersection(theirs)); // Move the iterator of lower range [a..b], but not // the upper range as it may contain elements that will collide // with the next iterator. So, if mine=[0..115] and // theirs=[115..200], then intersection is 115 and move mine // but not theirs as theirs may collide with the next range // in thisIter. // move both iterators to next ranges if (mine.StartsAfterNonDisjoint(theirs)) { j++; } else { if (theirs.StartsAfterNonDisjoint(mine)) { i++; } } } } } } } } if (intersection == null) { return new erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet(); } return intersection; } /// <summary> /// <inheritDoc/> /// /// </summary> public virtual bool Contains(int el) { int n = intervals.Count; for (int i = 0; i < n; i++) { Interval I = intervals[i]; int a = I.a; int b = I.b; if (el < a) { break; } // list is sorted and el is before this interval; not here if (el >= a && el <= b) { return true; } } // found in this interval return false; } /// <summary> /// <inheritDoc/> /// /// </summary> public virtual bool IsNil { get { return intervals == null || intervals.Count == 0; } } /// <summary> /// <inheritDoc/> /// /// </summary> public virtual int SingleElement { get { if (intervals != null && intervals.Count == 1) { Interval I = intervals[0]; if (I.a == I.b) { return I.a; } } return TokenConstants.InvalidType; } } /// <summary>Returns the maximum value contained in the set.</summary> /// <remarks>Returns the maximum value contained in the set.</remarks> /// <returns> /// the maximum value contained in the set. If the set is empty, this /// method returns /// <see cref="TokenConstants.InvalidType"/> /// . /// </returns> public virtual int MaxElement { get { if (IsNil) { return TokenConstants.InvalidType; } Interval last = intervals[intervals.Count - 1]; return last.b; } } /// <summary>Returns the minimum value contained in the set.</summary> /// <remarks>Returns the minimum value contained in the set.</remarks> /// <returns> /// the minimum value contained in the set. If the set is empty, this /// method returns /// <see cref="TokenConstants.InvalidType"/> /// . /// </returns> public virtual int MinElement { get { if (IsNil) { return TokenConstants.InvalidType; } return intervals[0].a; } } /// <summary>Return a list of Interval objects.</summary> /// <remarks>Return a list of Interval objects.</remarks> public virtual IList<Interval> GetIntervals() { return intervals; } public override int GetHashCode() { int hash = MurmurHash.Initialize(); foreach (Interval I in intervals) { hash = MurmurHash.Update(hash, I.a); hash = MurmurHash.Update(hash, I.b); } hash = MurmurHash.Finish(hash, intervals.Count * 2); return hash; } /// <summary> /// Are two IntervalSets equal? Because all intervals are sorted /// and disjoint, equals is a simple linear walk over both lists /// to make sure they are the same. /// </summary> /// <remarks> /// Are two IntervalSets equal? Because all intervals are sorted /// and disjoint, equals is a simple linear walk over both lists /// to make sure they are the same. Interval.equals() is used /// by the List.equals() method to check the ranges. /// </remarks> public override bool Equals(object obj) { if (obj == null || !(obj is erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet)) { return false; } erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet other = (erl.Oracle.TnsNames.Antlr4.Runtime.Misc.IntervalSet)obj; return this.intervals.SequenceEqual(other.intervals); } public override string ToString() { return ToString(false); } public virtual string ToString(bool elemAreChar) { StringBuilder buf = new StringBuilder(); if (this.intervals == null || this.intervals.Count == 0) { return "{}"; } if (this.Count > 1) { buf.Append("{"); } bool first = true; foreach (Interval I in intervals) { if (!first) buf.Append(", "); first = false; int a = I.a; int b = I.b; if (a == b) { if (a == TokenConstants.EOF) { buf.Append("<EOF>"); } else { if (elemAreChar) { buf.Append("'").Append((char)a).Append("'"); } else { buf.Append(a); } } } else { if (elemAreChar) { buf.Append("'").Append((char)a).Append("'..'").Append((char)b).Append("'"); } else { buf.Append(a).Append("..").Append(b); } } } if (this.Count > 1) { buf.Append("}"); } return buf.ToString(); } public virtual string ToString(IVocabulary vocabulary) { StringBuilder buf = new StringBuilder(); if (this.intervals == null || this.intervals.Count == 0) { return "{}"; } if (this.Count > 1) { buf.Append("{"); } bool first = true; foreach (Interval I in intervals) { if (!first) buf.Append(", "); first = false; int a = I.a; int b = I.b; if (a == b) { buf.Append(ElementName(vocabulary, a)); } else { for (int i = a; i <= b; i++) { if (i > a) { buf.Append(", "); } buf.Append(ElementName(vocabulary, i)); } } } if (this.Count > 1) { buf.Append("}"); } return buf.ToString(); } [return: NotNull] protected internal virtual string ElementName(IVocabulary vocabulary, int a) { if (a == TokenConstants.EOF) { return "<EOF>"; } else { if (a == TokenConstants.EPSILON) { return "<EPSILON>"; } else { return vocabulary.GetDisplayName(a); } } } public virtual int Count { get { int n = 0; int numIntervals = intervals.Count; if (numIntervals == 1) { Interval firstInterval = this.intervals[0]; return firstInterval.b - firstInterval.a + 1; } for (int i = 0; i < numIntervals; i++) { Interval I = intervals[i]; n += (I.b - I.a + 1); } return n; } } public virtual ArrayList<int> ToIntegerList() { ArrayList<int> values = new ArrayList<int>(Count); int n = intervals.Count; for (int i = 0; i < n; i++) { Interval I = intervals[i]; int a = I.a; int b = I.b; for (int v = a; v <= b; v++) { values.Add(v); } } return values; } public virtual IList<int> ToList() { IList<int> values = new ArrayList<int>(); int n = intervals.Count; for (int i = 0; i < n; i++) { Interval I = intervals[i]; int a = I.a; int b = I.b; for (int v = a; v <= b; v++) { values.Add(v); } } return values; } public virtual HashSet<int> ToSet() { HashSet<int> s = new HashSet<int>(); foreach (Interval I in intervals) { int a = I.a; int b = I.b; for (int v = a; v <= b; v++) { s.Add(v); } } return s; } public virtual int[] ToArray() { return ToIntegerList().ToArray(); } public virtual void Remove(int el) { if (@readonly) { throw new InvalidOperationException("can't alter readonly IntervalSet"); } int n = intervals.Count; for (int i = 0; i < n; i++) { Interval I = intervals[i]; int a = I.a; int b = I.b; if (el < a) { break; } // list is sorted and el is before this interval; not here // if whole interval x..x, rm if (el == a && el == b) { intervals.RemoveAt(i); break; } // if on left edge x..b, adjust left if (el == a) { intervals[i] = Interval.Of(I.a + 1, I.b); break; } // if on right edge a..x, adjust right if (el == b) { intervals[i] = Interval.Of(I.a, I.b - 1); break; } // if in middle a..x..b, split interval if (el > a && el < b) { // found in this interval int oldb = I.b; intervals[i] = Interval.Of(I.a, el - 1); // [a..x-1] Add(el + 1, oldb); } } } public virtual bool IsReadOnly { get { // add [x+1..b] return @readonly; } } public virtual void SetReadonly(bool @readonly) { if (this.@readonly && !@readonly) { throw new InvalidOperationException("can't alter readonly IntervalSet"); } this.@readonly = @readonly; } IIntSet IIntSet.AddAll(IIntSet set) { return AddAll(set); } IIntSet IIntSet.And(IIntSet a) { return And(a); } IIntSet IIntSet.Complement(IIntSet elements) { return Complement(elements); } IIntSet IIntSet.Or(IIntSet a) { return Or(a); } IIntSet IIntSet.Subtract(IIntSet a) { return Subtract(a); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ParallelForTest.cs // // This file contains functional tests for Parallel.For and Parallel.ForEach // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Threading.Tasks.Tests { public sealed class ParallelForTest { #region Private Fields private readonly TestParameters _parameters; private IList<int> _collection = null; // the collection used in Foreach private readonly double[] _results; // global place to store the workload result for verication // data structure used with ParallelLoopState<TLocal> // each row is the sequence of loop "index" finished in the same thread private int _threadCount; private readonly List<int>[] _sequences; // @TODO: remove if ConcurrentDictionary can be used private readonly ThreadLocal<Random> _random = new ThreadLocal<Random>(() => new Random(unchecked((int)(DateTime.Now.Ticks)))); // Random generator for WorkloadPattern == Random private static readonly int s_zetaSeedOffset = 10000; // offset to the zeta seed to ensure result converge to the expected private OrderablePartitioner<int> _partitioner = null; private OrderablePartitioner<Tuple<int, int>> _rangePartitioner = null; private ParallelOptions _parallelOption; #endregion public ParallelForTest(TestParameters parameters) { _parameters = parameters; _results = new double[parameters.Count]; if (parameters.LocalOption != ActionWithLocal.None) { _sequences = new List<int>[1024]; _threadCount = 0; } } #region Test Methods internal void RealRun() { if (_parameters.Api == API.For64) RunParallelFor64Test(); else if (_parameters.Api == API.For) RunParallelForTest(); else RunParallelForeachTest(); // verify result for (int i = 0; i < _parameters.Count; i++) Verify(i); // verify unique index sequences if run WithLocal if (_parameters.LocalOption != ActionWithLocal.None) VerifySequences(); } // Tests Parallel.For version that takes 'long' from and to parameters private void RunParallelFor64Test() { if (_parameters.ParallelOption != WithParallelOption.None) { ParallelOptions option = GetParallelOptions(); if (_parameters.LocalOption == ActionWithLocal.None) { if (_parameters.StateOption == ActionWithState.None) { // call Parallel.For with ParallelOptions Parallel.For(_parameters.StartIndex64, _parameters.StartIndex64 + _parameters.Count, option, Work); } else if (_parameters.StateOption == ActionWithState.Stop) { // call Parallel.For with ParallelLoopState and ParallelOptions Parallel.For(_parameters.StartIndex64, _parameters.StartIndex64 + _parameters.Count, option, WorkWithStop); } } else if (_parameters.LocalOption == ActionWithLocal.HasFinally) { // call Parallel.For with ParallelLoopState<TLocal>, plus threadLocalFinally, plus ParallelOptions Parallel.For<List<int>>(_parameters.StartIndex64, _parameters.StartIndex64 + _parameters.Count, option, ThreadLocalInit, WorkWithLocal, ThreadLocalFinally); } } else { if (_parameters.LocalOption == ActionWithLocal.None) { if (_parameters.StateOption == ActionWithState.None) { // call Parallel.For Parallel.For(_parameters.StartIndex64, _parameters.StartIndex64 + _parameters.Count, Work); } else if (_parameters.StateOption == ActionWithState.Stop) { // call Parallel.For with ParallelLoopState Parallel.For(_parameters.StartIndex64, _parameters.StartIndex64 + _parameters.Count, WorkWithStop); } } else if (_parameters.LocalOption == ActionWithLocal.HasFinally) { // call Parallel.For with ParallelLoopState<TLocal>, plus threadLocalFinally Parallel.For<List<int>>(_parameters.StartIndex64, _parameters.StartIndex64 + _parameters.Count, ThreadLocalInit, WorkWithLocal, ThreadLocalFinally); } } } // Tests Parallel.ForEach private void RunParallelForeachTest() { int length = _parameters.Count; if (length < 0) length = 0; int[] arrayCollection = new int[length]; for (int i = 0; i < length; i++) arrayCollection[i] = _parameters.StartIndex + i; if (_parameters.Api == API.ForeachOnArray) _collection = arrayCollection; else if (_parameters.Api == API.ForeachOnList) _collection = new List<int>(arrayCollection); else _collection = arrayCollection; //if source is partitioner if (_parameters.PartitionerType == PartitionerType.RangePartitioner) _rangePartitioner = PartitionerFactory<Tuple<int, int>>.Create(_parameters.PartitionerType, _parameters.StartIndex, _parameters.StartIndex + _parameters.Count, _parameters.ChunkSize); else _partitioner = PartitionerFactory<int>.Create(_parameters.PartitionerType, _collection); if (_parameters.ParallelOption != WithParallelOption.None) { _parallelOption = GetParallelOptions(); if (_parameters.LocalOption == ActionWithLocal.None) { if (_parameters.StateOption == ActionWithState.None) { // call Parallel.Foreach with ParallelOptions ParallelForEachWithOptions(); } else if (_parameters.StateOption == ActionWithState.Stop) { // call Parallel.Foreach with ParallelLoopState and ParallelOptions if (_parameters.Api == API.Foreach) ParallelForEachWithOptionsAndState(); else // call indexed version for array / list overloads - to avoid calling too many combinations ParallelForEachWithOptionsAndIndexAndState(); } } else if (_parameters.LocalOption == ActionWithLocal.HasFinally) { // call Parallel.Foreach and ParallelLoopState<TLocal>, plus threadLocalFinally, plus ParallelOptions if (_parameters.Api == API.Foreach) ParallelForEachWithOptionsAndLocal(); else // call indexed version for array / list overloads - to avoid calling too many combinations ParallelForEachWithOptionsAndLocalAndIndex(); } } else { if (_parameters.LocalOption == ActionWithLocal.None) { if (_parameters.StateOption == ActionWithState.None) { // call Parallel.Foreach ParallelForEach(); } else if (_parameters.StateOption == ActionWithState.Stop) { // call Parallel.Foreach with ParallelLoopState if (_parameters.Api == API.Foreach) ParallelForEachWithState(); else // call indexed version for array / list overloads - to avoid calling too many combinations ParallelForEachWithIndexAndState(); } } else if (_parameters.LocalOption == ActionWithLocal.HasFinally) { // call Parallel.Foreach and ParallelLoopState<TLocal>, plus threadLocalFinally if (_parameters.Api == API.Foreach) ParallelForeachWithLocal(); else // call indexed version for array / list overloads - to avoid calling too many combinations ParallelForeachWithLocalAndIndex(); } } } // Tests Parallel.For version that takes 'int' from and to parameters private void RunParallelForTest() { if (_parameters.ParallelOption != WithParallelOption.None) { ParallelOptions option = GetParallelOptions(); if (_parameters.LocalOption == ActionWithLocal.None) { if (_parameters.StateOption == ActionWithState.None) { // call Parallel.For with ParallelOptions Parallel.For(_parameters.StartIndex, _parameters.StartIndex + _parameters.Count, option, Work); } else if (_parameters.StateOption == ActionWithState.Stop) { // call Parallel.For with ParallelLoopState and ParallelOptions Parallel.For(_parameters.StartIndex, _parameters.StartIndex + _parameters.Count, option, WorkWithStop); } } else if (_parameters.LocalOption == ActionWithLocal.HasFinally) { // call Parallel.For with ParallelLoopState<TLocal>, plus threadLocalFinally, plus ParallelOptions Parallel.For<List<int>>(_parameters.StartIndex, _parameters.StartIndex + _parameters.Count, option, ThreadLocalInit, WorkWithLocal, ThreadLocalFinally); } } else { if (_parameters.LocalOption == ActionWithLocal.None) { if (_parameters.StateOption == ActionWithState.None) { // call Parallel.For Parallel.For(_parameters.StartIndex, _parameters.StartIndex + _parameters.Count, Work); } else if (_parameters.StateOption == ActionWithState.Stop) { // call Parallel.For with ParallelLoopState Parallel.For(_parameters.StartIndex, _parameters.StartIndex + _parameters.Count, WorkWithStop); } } else if (_parameters.LocalOption == ActionWithLocal.HasFinally) { // call Parallel.For with ParallelLoopState<TLocal>, plus threadLocalFinally Parallel.For<List<int>>(_parameters.StartIndex, _parameters.StartIndex + _parameters.Count, ThreadLocalInit, WorkWithLocal, ThreadLocalFinally); } } } #endregion #region ParallelForeach Overloads - with partitioner and without /// <summary> /// ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source,Action<TSource> body) /// </summary> private void ParallelForEach() { if (_parameters.ParallelForeachDataSourceType == DataSourceType.Partitioner) { if (_parameters.PartitionerType == PartitionerType.RangePartitioner) Parallel.ForEach<Tuple<int, int>>(_rangePartitioner, Work); else Parallel.ForEach<int>(_partitioner, Work); } else { Parallel.ForEach<int>(_collection, Work); } } /// <summary> /// ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source,Action<T, ParallelLoopState> body) /// </summary> private void ParallelForEachWithState() { if (_parameters.ParallelForeachDataSourceType == DataSourceType.Partitioner) { if (_parameters.PartitionerType == PartitionerType.RangePartitioner) Parallel.ForEach<Tuple<int, int>>(_rangePartitioner, WorkWithStop); else Parallel.ForEach<int>(_partitioner, WorkWithStop); } else { Parallel.ForEach<int>(_collection, WorkWithStop); } } /// <summary> /// ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source,Action<TSource, ParallelLoopState, Int64> body) /// </summary> private void ParallelForEachWithIndexAndState() { if (_parameters.ParallelForeachDataSourceType == DataSourceType.Partitioner) { if (_parameters.PartitionerType == PartitionerType.RangePartitioner) Parallel.ForEach<Tuple<int, int>>(_rangePartitioner, WorkWithIndexAndStopPartitioner); else Parallel.ForEach<int>(_partitioner, WorkWithIndexAndStopPartitioner); } else { Parallel.ForEach<int>(_collection, WorkWithIndexAndStop); } } /// <summary> /// public static ParallelLoopResult ForEach<TSource, TLocal>(IEnumerable<TSource> source, /// Func<TLocal> threadLocalInitlocalInit, /// Func<TSource, ParallelLoopState, TLocal, TLocal> body, /// Action<TLocal> threadLocalFinallylocalFinally) /// </summary> private void ParallelForeachWithLocal() { if (_parameters.ParallelForeachDataSourceType == DataSourceType.Partitioner) { if (_parameters.PartitionerType == PartitionerType.RangePartitioner) Parallel.ForEach<Tuple<int, int>, List<int>>(_rangePartitioner, ThreadLocalInit, WorkWithLocal, ThreadLocalFinally); else Parallel.ForEach<int, List<int>>(_partitioner, ThreadLocalInit, WorkWithLocal, ThreadLocalFinally); } else { Parallel.ForEach<int, List<int>>(_collection, ThreadLocalInit, WorkWithLocal, ThreadLocalFinally); } } /// <summary> /// public static ParallelLoopResult ForEach<TSource, TLocal>(IEnumerable<TSource> source, /// Func<TLocal> threadLocalInitlocalInit, /// Func<TSource, ParallelLoopState, Int64, TLocal, TLocal> body, /// Action<TLocal> threadLocalFinallylocalFinally) /// </summary> private void ParallelForeachWithLocalAndIndex() { if (_parameters.ParallelForeachDataSourceType == DataSourceType.Partitioner) { if (_parameters.PartitionerType == PartitionerType.RangePartitioner) Parallel.ForEach<Tuple<int, int>, List<int>>(_rangePartitioner, ThreadLocalInit, WorkWithLocalAndIndexPartitioner, ThreadLocalFinally); else Parallel.ForEach<int, List<int>>(_partitioner, ThreadLocalInit, WorkWithLocalAndIndexPartitioner, ThreadLocalFinally); } else { Parallel.ForEach<int, List<int>>(_collection, ThreadLocalInit, WorkWithIndexAndLocal, ThreadLocalFinally); } } /// <summary> /// ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source,ParallelOptions parallelOptions, Action<TSource> body) /// </summary> private void ParallelForEachWithOptions() { if (_parameters.ParallelForeachDataSourceType == DataSourceType.Partitioner) { if (_parameters.PartitionerType == PartitionerType.RangePartitioner) Parallel.ForEach<Tuple<int, int>>(_rangePartitioner, _parallelOption, Work); else Parallel.ForEach<int>(_partitioner, _parallelOption, Work); } else { Parallel.ForEach<int>(_collection, _parallelOption, Work); } } /// <summary> /// ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source, ParallelOptions parallelOptions, Action<T, ParallelLoopState> body) /// </summary> private void ParallelForEachWithOptionsAndState() { if (_parameters.ParallelForeachDataSourceType == DataSourceType.Partitioner) { if (_parameters.PartitionerType == PartitionerType.RangePartitioner) Parallel.ForEach<Tuple<int, int>>(_rangePartitioner, _parallelOption, WorkWithStop); else Parallel.ForEach<int>(_partitioner, _parallelOption, WorkWithStop); } else { Parallel.ForEach<int>(_collection, _parallelOption, WorkWithStop); } } /// <summary> /// ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source, ParallelOptions parallelOptions,, Action<TSource, ParallelLoopState, Int64> body) /// </summary> private void ParallelForEachWithOptionsAndIndexAndState() { if (_parameters.ParallelForeachDataSourceType == DataSourceType.Partitioner) { if (_parameters.PartitionerType == PartitionerType.RangePartitioner) Parallel.ForEach<Tuple<int, int>>(_rangePartitioner, _parallelOption, WorkWithIndexAndStopPartitioner); else Parallel.ForEach<int>(_partitioner, _parallelOption, WorkWithIndexAndStopPartitioner); } else { Parallel.ForEach<int>(_collection, _parallelOption, WorkWithIndexAndStop); } } /// <summary> /// public static ParallelLoopResult ForEach<TSource, TLocal>(IEnumerable<TSource> source, /// ParallelOptions parallelOptions, /// Func<TLocal> threadLocalInitlocalInit, /// Func<TSource, ParallelLoopState, TLocal, TLocal> body, /// Action<TLocal> threadLocalFinallylocalFinally) /// </summary> private void ParallelForEachWithOptionsAndLocal() { if (_parameters.ParallelForeachDataSourceType == DataSourceType.Partitioner) { if (_parameters.PartitionerType == PartitionerType.RangePartitioner) Parallel.ForEach<Tuple<int, int>, List<int>>(_rangePartitioner, _parallelOption, ThreadLocalInit, WorkWithLocal, ThreadLocalFinally); else Parallel.ForEach<int, List<int>>(_partitioner, _parallelOption, ThreadLocalInit, WorkWithLocal, ThreadLocalFinally); } else { Parallel.ForEach<int, List<int>>(_collection, _parallelOption, ThreadLocalInit, WorkWithLocal, ThreadLocalFinally); } } /// <summary> /// public static ParallelLoopResult ForEach<TSource, TLocal>(IEnumerable<TSource> source, /// ParallelOptions parallelOptions, /// Func<TLocal> threadLocalInitlocalInit, /// Func<TSource, ParallelLoopState, Int64, TLocal, TLocal> body, /// Action<TLocal> threadLocalFinallylocalFinally) /// </summary> private void ParallelForEachWithOptionsAndLocalAndIndex() { if (_parameters.ParallelForeachDataSourceType == DataSourceType.Partitioner) { if (_parameters.PartitionerType == PartitionerType.RangePartitioner) Parallel.ForEach<Tuple<int, int>, List<int>>(_rangePartitioner, _parallelOption, ThreadLocalInit, WorkWithLocalAndIndexPartitioner, ThreadLocalFinally); else Parallel.ForEach<int, List<int>>(_partitioner, _parallelOption, ThreadLocalInit, WorkWithLocalAndIndexPartitioner, ThreadLocalFinally); } else { Parallel.ForEach<int, List<int>>(_collection, _parallelOption, ThreadLocalInit, WorkWithIndexAndLocal, ThreadLocalFinally); } } #endregion #region Workloads private void InvokeZetaWorkload(int i) { if (_results[i] == 0) { int zetaIndex = s_zetaSeedOffset; switch (_parameters.WorkloadPattern) { case WorkloadPattern.Similar: zetaIndex += i; break; case WorkloadPattern.Increasing: zetaIndex += i * s_zetaSeedOffset; break; case WorkloadPattern.Decreasing: zetaIndex += (_parameters.Count - i) * s_zetaSeedOffset; break; case WorkloadPattern.Random: zetaIndex += _random.Value.Next(0, _parameters.Count) * s_zetaSeedOffset; break; } _results[i] = ZetaSequence(zetaIndex); } else { //same index should not be processed twice _results[i] = double.MinValue; } } // workload for normal For private void Work(int i) { InvokeZetaWorkload(i - _parameters.StartIndex); } // workload for Foreach overload that takes a range partitioner private void Work(Tuple<int, int> tuple) { for (int i = tuple.Item1; i < tuple.Item2; i++) { Work(i); } } // workload for Foreach overload that takes a range partitioner private void Work(Tuple<long, long> tuple) { for (long i = tuple.Item1; i < tuple.Item2; i++) { Work(i); } } // workload for 64-bit For private void Work(long i) { InvokeZetaWorkload((int)(i - _parameters.StartIndex64)); } // workload for normal For which will possibly invoke ParallelLoopState.Stop private void WorkWithStop(int i, ParallelLoopState state) { Work(i); if (i > (_parameters.StartIndex + _parameters.Count / 2)) state.Stop(); // if the current index is in the second half range, try stop all } // workload for Foreach overload that takes a range partitioner private void WorkWithStop(Tuple<int, int> tuple, ParallelLoopState state) { for (int i = tuple.Item1; i < tuple.Item2; i++) { WorkWithStop(i, state); } } // workload for Foreach overload that takes a range partitioner private void WorkWithStop(Tuple<long, long> tuple, ParallelLoopState state) { for (long i = tuple.Item1; i < tuple.Item2; i++) { WorkWithStop(i, state); } } // workload for Foreach overload that takes a range partitioner private void WorkWithIndexAndStop(Tuple<int, int> tuple, ParallelLoopState state, long index) { for (int i = tuple.Item1; i < tuple.Item2; i++) { WorkWithIndexAndStop(i, state, index); } } // workload for Foreach overload that takes a range partitioner private void WorkWithIndexAndStopPartitioner(Tuple<int, int> tuple, ParallelLoopState state, long index) { WorkWithIndexAndStop(tuple, state, index); } // workload for Foreach overload that takes a range partitioner private List<int> WorkWithLocal(Tuple<int, int> tuple, ParallelLoopState state, List<int> threadLocalValue) { for (int i = tuple.Item1; i < tuple.Item2; i++) { WorkWithLocal(i, state, threadLocalValue); } return threadLocalValue; } // workload for 64-bit For which will possibly invoke ParallelLoopState.Stop private void WorkWithStop(long i, ParallelLoopState state) { Work(i); if (i > (_parameters.StartIndex64 + _parameters.Count / 2)) state.Stop(); } // workload for Parallel.Foreach which will possibly invoke ParallelLoopState.Stop private void WorkWithIndexAndStop(int i, ParallelLoopState state, long index) { Work(i); if (index > (_parameters.Count / 2)) state.Stop(); } // workload for Parallel.Foreach which will possibly invoke ParallelLoopState.Stop private void WorkWithIndexAndStopPartitioner(int i, ParallelLoopState state, long index) { //index verification if (_parameters.PartitionerType == PartitionerType.IEnumerableOOB) { int itemAtIndex = _collection[(int)index]; Assert.Equal(i, itemAtIndex); } WorkWithIndexAndStop(i, state, index); } // workload for normal For which uses the ThreadLocalState accessible from ParallelLoopState private List<int> WorkWithLocal(int i, ParallelLoopState state, List<int> threadLocalValue) { Work(i); threadLocalValue.Add(i - _parameters.StartIndex); if (_parameters.StateOption == ActionWithState.Stop) { if (i > (_parameters.StartIndex + _parameters.Count / 2)) state.Stop(); } return threadLocalValue; } // workload for 64-bit For which invokes both Stop and ThreadLocalState from ParallelLoopState private List<int> WorkWithLocal(long i, ParallelLoopState state, List<int> threadLocalValue) { Work(i); threadLocalValue.Add((int)(i - _parameters.StartIndex64)); if (_parameters.StateOption == ActionWithState.Stop) { if (i > (_parameters.StartIndex64 + _parameters.Count / 2)) state.Stop(); } return threadLocalValue; } // workload for Foreach overload that takes a range partitioner private List<int> WorkWithLocal(Tuple<long, long> tuple, ParallelLoopState state, List<int> threadLocalValue) { for (long i = tuple.Item1; i < tuple.Item2; i++) { Work(i); threadLocalValue.Add((int)(i - _parameters.StartIndex64)); if (_parameters.StateOption == ActionWithState.Stop) { if (i > (_parameters.StartIndex64 + _parameters.Count / 2)) state.Stop(); } } return threadLocalValue; } // workload for Foreach overload that takes a range partitioner private List<int> WorkWithIndexAndLocal(Tuple<int, int> tuple, ParallelLoopState state, long index, List<int> threadLocalValue) { for (int i = tuple.Item1; i < tuple.Item2; i++) { Work(i); threadLocalValue.Add((int)index); if (_parameters.StateOption == ActionWithState.Stop) { if (index > (_parameters.StartIndex + _parameters.Count / 2)) state.Stop(); } } return threadLocalValue; } // workload for Foreach overload that takes a range partitioner private List<int> WorkWithLocalAndIndexPartitioner(Tuple<int, int> tuple, ParallelLoopState state, long index, List<int> threadLocalValue) { for (int i = tuple.Item1; i < tuple.Item2; i++) { //index verification - only for enumerable if (_parameters.PartitionerType == PartitionerType.IEnumerableOOB) { int itemAtIndex = _collection[(int)index]; Assert.Equal(i, itemAtIndex); } } return WorkWithIndexAndLocal(tuple, state, index, threadLocalValue); } // workload for Foreach which invokes both Stop and ThreadLocalState from ParallelLoopState private List<int> WorkWithIndexAndLocal(int i, ParallelLoopState state, long index, List<int> threadLocalValue) { Work(i); threadLocalValue.Add((int)index); if (_parameters.StateOption == ActionWithState.Stop) { if (index > (_parameters.StartIndex + _parameters.Count / 2)) state.Stop(); } return threadLocalValue; } // workload for Foreach overload that takes a range partitioner private List<int> WorkWithLocalAndIndexPartitioner(int i, ParallelLoopState state, long index, List<int> threadLocalValue) { //index verification - only for enumerable if (_parameters.PartitionerType == PartitionerType.IEnumerableOOB) { int itemAtIndex = _collection[(int)index]; Assert.Equal(i, itemAtIndex); } return WorkWithIndexAndLocal(i, state, index, threadLocalValue); } #endregion #region Helper Methods public static double ZetaSequence(int n) { double result = 0; for (int i = 1; i < n; i++) { result += 1.0 / ((double)i * (double)i); } return result; } private List<int> ThreadLocalInit() { return new List<int>(); } private void ThreadLocalFinally(List<int> local) { //add this row to the global sequences int index = Interlocked.Increment(ref _threadCount) - 1; _sequences[index] = local; } // consolidate all the indexes of the global sequences into one list private List<int> Consolidate(out List<int> duplicates) { duplicates = new List<int>(); List<int> processedIndexes = new List<int>(); //foreach (List<int> perThreadSequences in sequences) for (int thread = 0; thread < _threadCount; thread++) { List<int> perThreadSequences = _sequences[thread]; foreach (int i in perThreadSequences) { if (processedIndexes.Contains(i)) { duplicates.Add(i); } else { processedIndexes.Add(i); } } } return processedIndexes; } // Creates an instance of ParallelOptions with an non-default DOP private ParallelOptions GetParallelOptions() { switch (_parameters.ParallelOption) { case WithParallelOption.WithDOP: return new ParallelOptions() { TaskScheduler = TaskScheduler.Current, MaxDegreeOfParallelism = _parameters.Count }; default: throw new ArgumentOutOfRangeException("Test error: Invalid option of " + _parameters.ParallelOption); } } /// <summary> /// Each Parallel.For loop stores the result of its compuatation in the 'result' array. /// This function checks if result[i] for each i from 0 to _parameters.Count is correct /// A result[i] == double[i] means that the body for index i was run more than once /// </summary> /// <param name="i">index to check</param> /// <returns>true if result[i] contains the expected value</returns> private void Verify(int i) { //Function point comparison cant be done by rounding off to nearest decimal points since //1.64 could be represented as 1.63999999 or as 1.6499999999. To perform floating point comparisons, //a range has to be defined and check to ensure that the result obtained is within the specified range double minLimit = 1.63; double maxLimit = 1.65; if (_results[i] < minLimit || _results[i] > maxLimit) { Assert.False(double.MinValue == _results[i], String.Format("results[{0}] has been revisisted", i)); Assert.True(_parameters.StateOption == ActionWithState.Stop && 0 == _results[i], String.Format("Incorrect results[{0}]. Expected result to lie between {1} and {2} but got {3})", i, minLimit, maxLimit, _results[i])); } } /// <summary> /// Checks if the ThreadLocal Functions - Init and Locally were run correctly /// Init creates a new List. Each body, pushes in a unique index and Finally consolidates /// the lists into 'sequences' array /// /// Expected: The consolidated list contains all indices that were executed. /// Duplicates indicate that the body for a certain index was executed more than once /// </summary> /// <returns>true if consolidated list contains indices for all executed loops</returns> private void VerifySequences() { List<int> duplicates; List<int> processedIndexes = Consolidate(out duplicates); Assert.Empty(duplicates); // If result[i] != 0 then the body for that index was executed. // We expect the threadlocal list to also contain the same index Assert.All(Enumerable.Range(0, _parameters.Count), idx => Assert.Equal(processedIndexes.Contains(idx), _results[idx] != 0)); } #endregion } #region Helper Classes / Enums public class TestParameters { public const int DEFAULT_STARTINDEXOFFSET = 1000; public TestParameters(API api, StartIndexBase startIndexBase, int? startIndexOffset = null) { Api = api; StartIndexBase = startIndexBase; StartIndexOffset = startIndexOffset.HasValue ? startIndexOffset.Value : DEFAULT_STARTINDEXOFFSET; if (api == API.For64) { // StartIndexBase.Int64 was set to -1 since Enum can't take a Int64.MaxValue. Fixing this below. long indexBase64 = (startIndexBase == StartIndexBase.Int64) ? Int64.MaxValue : (long)startIndexBase; StartIndex64 = indexBase64 + StartIndexOffset; } else { // startIndexBase must not be StartIndexBase.Int64 StartIndex = (int)startIndexBase + StartIndexOffset; } WorkloadPattern = WorkloadPattern.Similar; // setting defaults. Count = 0; ChunkSize = -1; StateOption = ActionWithState.None; LocalOption = ActionWithLocal.None; ParallelOption = WithParallelOption.None; //partitioner options ParallelForeachDataSourceType = DataSourceType.Collection; PartitionerType = PartitionerType.IListBalancedOOB; } public readonly API Api; // the api to be tested public int StartIndex; // the real start index (base + offset) for the loop public long StartIndex64; // the real start index (base + offset) for the 64 version loop public readonly StartIndexBase StartIndexBase; // the base of the _parameters.StartIndex for boundary testing public int StartIndexOffset; // the offset to be added to the base public int Count; // the _parameters.Count of loop range public int ChunkSize; // the chunk size to use for the range Partitioner public ActionWithState StateOption; // the ParallelLoopState option of the action body public ActionWithLocal LocalOption; // the ParallelLoopState<TLocal> option of the action body public WithParallelOption ParallelOption; // the ParallelOptions used in P.For/Foreach public WorkloadPattern WorkloadPattern; // the workload pattern used by each workload //partitioner public PartitionerType PartitionerType; //the partitioner type of the partitioner used - used for Partitioner tests public DataSourceType ParallelForeachDataSourceType; } /// <summary> /// used for partitioner creation /// </summary> /// <typeparam name="T"></typeparam> public class PartitionerFactory<T> { public static OrderablePartitioner<T> Create(PartitionerType partitionerName, IEnumerable<T> dataSource) { switch (partitionerName) { case PartitionerType.IListBalancedOOB: return Partitioner.Create(new List<T>(dataSource), true); case PartitionerType.ArrayBalancedOOB: return Partitioner.Create(new List<T>(dataSource).ToArray(), true); case PartitionerType.IEnumerableOOB: return Partitioner.Create(dataSource); case PartitionerType.IEnumerable1Chunk: return Partitioner.Create<T>(dataSource, EnumerablePartitionerOptions.NoBuffering); default: break; } return null; } public static OrderablePartitioner<Tuple<int, int>> Create(PartitionerType partitionerName, int from, int to, int chunkSize = -1) { switch (partitionerName) { case PartitionerType.RangePartitioner: return (chunkSize == -1) ? Partitioner.Create(from, to) : Partitioner.Create(from, to, chunkSize); default: break; } return null; } } /// <summary> /// Partitioner types used for ParallelForeach with partioners /// </summary> [Flags] public enum PartitionerType { IListBalancedOOB = 0, // Out of the box List Partitioner ArrayBalancedOOB = 1, // Out of the box Array partitioner IEnumerableOOB = 2, // Out of the box Enumerable partitioner RangePartitioner = 3, // out of the box range partitioner IEnumerable1Chunk = 4 // partitioner one chunk } public enum DataSourceType { Partitioner, Collection } // List of APIs being tested public enum API { For, For64, ForeachOnArray, ForeachOnList, Foreach } public enum ActionWithState { None, // no ParallelLoopState Stop, // need ParallelLoopState and will do Stop //Break, // need ParallelLoopState and will do Break, which is covered in ..\ParallelStateTests } public enum ActionWithLocal { None, // no ParallelLoopState<TLocal> HasFinally, // need ParallelLoopState<TLocal> and Action<TLocal> threadLocalFinally } public enum WithParallelOption { None, // no ParallelOptions WithDOP, // ParallelOptions created with DOP } public enum StartIndexBase { Zero = 0, Int16 = System.Int16.MaxValue, Int32 = System.Int32.MaxValue, Int64 = -1, // Enum can't take a Int64.MaxValue } public enum WorkloadPattern { Similar, Increasing, Decreasing, Random, } #endregion }
using System; using System.Runtime.InteropServices; namespace Torshify.Core.Native { internal partial class Spotify { /// <summary> /// Get load status for the specified track. If the track is not loaded yet, all other functions operating on the track return default values. /// </summary> /// <param name="albumPtr">The track whose load status you are interested in.</param> /// <returns>True if track is loaded, otherwise false.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_track_is_loaded(IntPtr trackPtr); /// <summary> /// Return an error code associated with a track. For example if it could not load. /// </summary> /// <param name="trackPtr"></param> /// <returns>Error code.</returns> [DllImport("libspotify")] internal static extern Error sp_track_error(IntPtr trackPtr); /// <summary> /// Return availability for a track /// </summary> /// <param name="sessionPtr"></param> /// <param name="trackPtr"></param> /// <returns></returns> [DllImport("libspotify")] internal static extern TrackAvailablity sp_track_get_availability(IntPtr sessionPtr, IntPtr trackPtr); /// <summary> /// Return offline status for a track. sp_session_callbacks::metadata_updated() will be invoked when /// offline status of a track changes /// </summary> /// <param name="trackPtr"></param> /// <returns></returns> [DllImport("libspotify")] internal static extern TrackOfflineStatus sp_track_offline_get_status(IntPtr trackPtr); /// <summary> /// Return true if the track is a placeholder. Placeholder tracks are used /// to store other objects than tracks in the playlist. Currently this is /// used in the inbox to store artists, albums and playlists. /// /// Use sp_link_create_from_track() to get a link object that points /// to the real object this "track" points to. /// /// Contrary to most functions the track does not have to be /// loaded for this function to return correct value /// </summary> /// <param name="trackPtr"></param> /// <returns>True if track is a placeholder</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_track_is_placeholder(IntPtr trackPtr); /// <summary> /// Return true if the track is a local file. /// </summary> /// <param name="sessionPtr">Session object returned from <c>sp_session_create</c>.</param> /// <param name="trackPtr">The track.</param> /// <remarks>The track must be loaded or this function will always return false. /// <seealso cref="Spotify.sp_track_is_loaded"/> /// </remarks> /// <returns>True if track is a local file, otherwise false.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_track_is_local(IntPtr sessionPtr, IntPtr trackPtr); /// <summary> /// Return true if the track is autolinked to another track. /// </summary> /// <param name="sessionPtr">Session object returned from <c>sp_session_create</c>.</param> /// <param name="albumPtr">The track.</param> /// <remarks>The track must be loaded or this function will always return false. /// </remarks> /// <returns>True if track is autolinked, otherwise false.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_track_is_autolinked(IntPtr sessionPtr, IntPtr trackPtr); /// <summary> /// Return true if the track is starred by the currently logged in user. /// </summary> /// <param name="sessionPtr">Session object returned from <c>sp_session_create</c>.</param> /// <param name="albumPtr">The track.</param> /// <remarks>The track must be loaded or this function will always return false. /// </remarks> /// <returns>True if track is a starred file, otherwise false.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_track_is_starred(IntPtr sessionPtr, IntPtr trackPtr); /// <summary> /// Star/Unstar the specified tracks. /// </summary> /// <param name="sessionPtr">Session object returned from <c>sp_session_create</c>.</param> /// <param name="trackArrayPtr">An array of pointer to tracks.</param> /// <param name="num_tracks">Count of <c>trackArray</c>.</param> /// <param name="star">Starred status of the track.</param> [DllImport("libspotify")] internal static extern Error sp_track_set_starred(IntPtr sessionPtr, IntPtr trackArrayPtr, int num_tracks, bool star); /// <summary> /// The number of artists performing on the specified track. /// </summary> /// <param name="albumPtr">The track whose number of participating artists you are interested in.</param> /// <returns>The number of artists performing on the specified track. If no metadata is available for the track yet, this function returns 0.</returns> [DllImport("libspotify")] internal static extern int sp_track_num_artists(IntPtr trackPtr); /// <summary> /// The artist matching the specified index performing on the current track. /// </summary> /// <param name="albumPtr">The track whose participating artist you are interested in.</param> /// <param name="index">The index for the participating artist. Should be in the interval [0, <c>sp_track_num_artists()</c> - 1]</param> /// <returns>The participating artist, or NULL if invalid index.</returns> [DllImport("libspotify")] internal static extern IntPtr sp_track_artist(IntPtr trackPtr, int index); /// <summary> /// The album of the specified track. /// </summary> /// <param name="albumPtr">A track object.</param> /// <returns>The album of the given track. You need to increase the refcount if you want to keep the pointer around. If no metadata is available for the track yet, this function returns 0.</returns> [DllImport("libspotify")] internal static extern IntPtr sp_track_album(IntPtr trackPtr); /// <summary> /// The string representation of the specified track's name. /// </summary> /// <param name="albumPtr">A track object.</param> /// <returns>The string representation of the specified track's name. /// Returned string is valid as long as the album object stays allocated and /// no longer than the next call to <c>sp_session_process_events()</c>. /// If no metadata is available for the track yet, this function returns empty string. </returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalPtrToUtf8))] internal static extern string sp_track_name(IntPtr trackPtr); /// <summary> /// The duration, in milliseconds, of the specified track. /// </summary> /// <param name="albumPtr">A track object.</param> /// <returns>The duration of the specified track, in milliseconds If no metadata is available for the track yet, this function returns 0.</returns> [DllImport("libspotify")] internal static extern int sp_track_duration(IntPtr trackPtr); /// <summary> /// Returns popularity for track. /// </summary> /// <param name="albumPtr">A track object.</param> /// <returns>Popularity in range 0 to 100, 0 if undefined. /// If no metadata is available for the track yet, this function returns 0.</returns> [DllImport("libspotify")] internal static extern int sp_track_popularity(IntPtr trackPtr); /// <summary> /// Returns the disc number for a track. /// </summary> /// <param name="albumPtr">A track object.</param> /// <returns>Disc index. Possible values are [1, total number of discs on album]. /// This function returns valid data only for tracks appearing in a browse artist or browse album result (otherwise returns 0).</returns> [DllImport("libspotify")] internal static extern int sp_track_disc(IntPtr trackPtr); /// <summary> /// Returns the position of a track on its disc. /// </summary> /// <param name="albumPtr">A track object.</param> /// <returns>Track position, starts at 1 (relative the corresponding disc). /// This function returns valid data only for tracks appearing in a browse artist or browse album result (otherwise returns 0).</returns> [DllImport("libspotify")] internal static extern int sp_track_index(IntPtr trackPtr); /// <summary> /// Returns the newly created local track. /// </summary> /// <param name="artist">Name of the artist.</param> /// <param name="title">Song title.</param> /// <param name="album">Name of the album, or an empty string if not available.</param> /// <param name="length">Count in MS, or -1 if not available.</param> /// <returns>A track.</returns> [DllImport("libspotify")] internal static extern IntPtr sp_localtrack_create(string artist, string title, string album, int length); /// <summary> /// Increase the reference count of a track. /// </summary> /// <param name="albumPtr">The track object.</param> [DllImport("libspotify")] internal static extern Error sp_track_add_ref(IntPtr trackPtr); /// <summary> /// Decrease the reference count of a track. /// </summary> /// <param name="albumPtr">The track object.</param> [DllImport("libspotify")] internal static extern Error sp_track_release(IntPtr trackPtr); /// <summary> /// Return the actual track that will be played if the given track is played /// </summary> /// <returns>A track.</returns> [DllImport("libspotify")] internal static extern IntPtr sp_track_get_playable(IntPtr sessionPtr, IntPtr trackPtr); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using CommonComponent; namespace GameResource { public class ResourcePoolManager : ResourceSingleton<ResourcePoolManager> { #region public public GameObject Spawn(ulong pathHash) { ResourcePool resourcePool = _GetResourcePool(pathHash); if (resourcePool == null) { Object asset = ResourceDataManager.Instance.Load(pathHash, typeof(GameObject)); if (asset != null) { resourcePool = new ResourcePool(pathHash, asset); resourcePool = _AddResourcePool(resourcePool); } } GameObject gameObject = null; if (resourcePool != null) { if (resourcePool.Spawn(out gameObject)) { --m_deSpawnCount; } } if (gameObject != null) _UpdateGameObjectState(gameObject, pathHash); return gameObject; } public void Despawn(GameObject gameObject, DespawnType despawnType) { if (gameObject == null) return; int spawnID = gameObject.GetInstanceID(); ulong pathHash = 0; if (!m_spawnID2PathHash.TryGetValue(spawnID, out pathHash)) { if (Application.isPlaying) GameObject.Destroy(gameObject); else GameObject.DestroyImmediate(gameObject); Log.ErrorFormat("[ResourcePoolManager]Failed to despawn unkown gameObject({0})", gameObject.name); return; } m_spawnID2PathHash.Remove(spawnID); ResourcePool resourcePool = _GetResourcePool(pathHash); if (resourcePool == null) { if (Application.isPlaying) GameObject.Destroy(gameObject); else GameObject.DestroyImmediate(gameObject); Log.ErrorFormat("[ResourcePoolManager]Failed to find resource pool for gameObject({0})", gameObject.name); return; } _OnCacheFull(); if (despawnType != DespawnType.Destroy) { Transform parent = despawnType == DespawnType.Invisible ? m_invisibleParent : m_inactiveParent; gameObject.transform.SetParent(parent, false); } if (resourcePool.Despawn(gameObject, despawnType)) { ++m_deSpawnCount; _AddCacheValue(resourcePool); } } public ResourceSpawnHandle SpawnAsync(ulong pathHash, int priority) { ResourceSpawnHandle spawnHandle = new ResourceSpawnHandle(); ResourceSpawnRequest request = m_loader.TryGetRequest(pathHash); if (request == null) { request = new ResourceSpawnRequest(pathHash, priority); request.OnLoadDone += _OnRequestDone; m_loader.PushRequst(request); } request.AddSpawnHandle(spawnHandle); return spawnHandle; } public void UnloadUnusedPool() { foreach (var iterator in m_pathHash2Pool) { ResourcePool resourcePool = iterator.Value; if (resourcePool == null || resourcePool.IsRefZero()) { m_clearList.Add(iterator.Key); } } for (int i = 0; i < m_clearList.Count; ++i) { _ClearResourcePool(m_clearList[i]); } m_clearList.Clear(); } public void ClearPool() { foreach (var iterator in m_pathHash2Pool) { m_clearList.Add(iterator.Key); } for (int i = 0; i < m_clearList.Count; ++i) _ClearResourcePool(m_clearList[i]); m_clearList.Clear(); } #endregion #region init protected override bool Init() { GameObject inactiveGameObj = new GameObject("UnityComponent-InactivePool"); inactiveGameObj.SetActive(false); m_inactiveParent = inactiveGameObj.transform; Object.DontDestroyOnLoad(inactiveGameObj); GameObject invisibleGameObj = new GameObject("UnityComponent-InvisiblePool"); invisibleGameObj.transform.position = new Vector3(-6666, -88888, -6666); m_invisibleParent = invisibleGameObj.transform; Object.DontDestroyOnLoad(invisibleGameObj); m_loader = new RequestLoader<ResourceSpawnRequest, ResourcePool>(); ResourceUpdater.Instance.RegisterUpdater(m_loader.Update); return base.Init(); } protected override bool UnInit() { ResourceUpdater.Instance.UnRegisterUpdater(m_loader.Update); if (Application.isPlaying) { GameObject.Destroy(m_inactiveParent); GameObject.Destroy(m_invisibleParent); } else { GameObject.DestroyImmediate(m_invisibleParent); GameObject.DestroyImmediate(m_inactiveParent); } return base.UnInit(); } #endregion #region private private void _UpdateGameObjectState(GameObject gameObject, ulong pathHash) { int spawnID = gameObject.GetInstanceID(); m_spawnID2PathHash[spawnID] = pathHash; gameObject.transform.parent = null; } private ResourcePool _GetResourcePool(ulong pathHash) { ResourcePool resourcePool = null; if (!m_pathHash2Pool.TryGetValue(pathHash, out resourcePool)) return null; return resourcePool; } private ResourcePool _AddResourcePool(ResourcePool resourcePool) { ResourcePool existedPool = null; if (m_pathHash2Pool.TryGetValue(resourcePool.Id, out existedPool)) { m_deSpawnCount += resourcePool.GetObjectCount(); existedPool.Merge(resourcePool); return existedPool; } m_pathHash2Pool.Add(resourcePool.Id, resourcePool); return resourcePool; } private void _ClearResourcePool(ulong pathHash) { ResourcePool resourcePool = null; if (!m_pathHash2Pool.TryGetValue(pathHash, out resourcePool)) { return; } m_pathHash2Pool.Remove(pathHash); if (resourcePool != null) { int count = resourcePool.GetObjectCount(); if (count > 0) { m_deSpawnCount -= count; _RemoveCacheValue(resourcePool.Id); } resourcePool.Clear(true); } } private void _OnRequestDone(RequestBase<ResourcePool> requestBase) { ResourceSpawnRequest request = requestBase as ResourceSpawnRequest; if (request == null) { Log.Error("[ResourcePoolManager]Invalid request."); return; } ResourcePool resourcePool = request.asset as ResourcePool; if (resourcePool == null) { Log.Error("[ResourcePoolManager]Invalid resource pool."); return; } _AddResourcePool(resourcePool); foreach (var spawnHandle in request.spawnHandleList) { if (!spawnHandle.success) continue; int spawnID = spawnHandle.spawnID; if (m_spawnID2PathHash.ContainsKey(spawnID)) { GameObject gameObject = spawnHandle.gameObject; string gameObjectName = gameObject != null ? gameObject.name : "Unknown"; Log.ErrorFormat("[ResourcePoolManager]Duplicated spawn id for gameObject({0})", gameObjectName); if (Application.isPlaying) GameObject.Destroy(gameObject); else GameObject.DestroyImmediate(gameObject); continue; } m_spawnID2PathHash[spawnID] = resourcePool.Id; } } private Transform m_inactiveParent = null; private Transform m_invisibleParent = null; private List<ulong> m_clearList = new List<ulong>(); private Dictionary<int, ulong> m_spawnID2PathHash = new Dictionary<int, ulong>(); private Dictionary<ulong, ResourcePool> m_pathHash2Pool = new Dictionary<ulong, ResourcePool>(); private RequestLoader<ResourceSpawnRequest, ResourcePool> m_loader = null; #endregion #region lru cache private void _AddCacheValue(ResourcePool resourcePool) { LinkedListNode<ResourcePool> lnode; if (m_cacheMap.TryGetValue(resourcePool.Id, out lnode)) { m_lruList.Remove(lnode); m_cacheMap.Remove(resourcePool.Id); } LinkedListNode<ResourcePool> node = new LinkedListNode<ResourcePool>(resourcePool); m_lruList.AddLast(node); m_cacheMap.Add(resourcePool.Id, node); } private void _RemoveCacheValue(ulong pathHash) { LinkedListNode<ResourcePool> lnode; if (m_cacheMap.TryGetValue(pathHash, out lnode)) { m_lruList.Remove(lnode); m_cacheMap.Remove(pathHash); } } private ResourcePool _GetCacheFirst() { if (m_lruList.Count > 0) { return m_lruList.First.Value; } else { return null; } } private void _OnCacheFull() { if (m_deSpawnCount > ResourceConfig.MAX_POOL_COUNT) { ResourcePool first = _GetCacheFirst(); if (first != null) { m_deSpawnCount -= first.GetObjectCount(); first.Clear(false); _RemoveCacheValue(first.Id); } } } private Dictionary<ulong, LinkedListNode<ResourcePool>> m_cacheMap = new Dictionary<ulong, LinkedListNode<ResourcePool>>(); private LinkedList<ResourcePool> m_lruList = new LinkedList<ResourcePool>(); private int m_deSpawnCount = 0; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Reflection.Metadata.Ecma335 { /// <summary> /// Encodes instructions. /// </summary> public struct InstructionEncoder { /// <summary> /// Underlying builder where encoded instructions are written to. /// </summary> public BlobBuilder CodeBuilder { get; } /// <summary> /// Builder tracking labels, branches and exception handlers. /// </summary> /// <remarks> /// If null the encoder doesn't support construction of control flow. /// </remarks> public ControlFlowBuilder ControlFlowBuilder { get; } /// <summary> /// Creates an encoder backed by code and control-flow builders. /// </summary> /// <param name="codeBuilder">Builder to write encoded instructions to.</param> /// <param name="controlFlowBuilder"> /// Builder tracking labels, branches and exception handlers. /// Must be specified to be able to use some of the control-flow factory methods of <see cref="InstructionEncoder"/>, /// such as <see cref="Branch(ILOpCode, LabelHandle)"/>, <see cref="DefineLabel"/>, <see cref="MarkLabel(LabelHandle)"/> etc. /// </param> public InstructionEncoder(BlobBuilder codeBuilder, ControlFlowBuilder controlFlowBuilder = null) { if (codeBuilder == null) { Throw.BuilderArgumentNull(); } CodeBuilder = codeBuilder; ControlFlowBuilder = controlFlowBuilder; } /// <summary> /// Offset of the next encoded instruction. /// </summary> public int Offset => CodeBuilder.Count; /// <summary> /// Encodes specified op-code. /// </summary> public void OpCode(ILOpCode code) { if (unchecked((byte)code) == (ushort)code) { CodeBuilder.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. CodeBuilder.WriteUInt16BE((ushort)code); } } /// <summary> /// Encodes a token. /// </summary> public void Token(EntityHandle handle) { Token(MetadataTokens.GetToken(handle)); } /// <summary> /// Encodes a token. /// </summary> public void Token(int token) { CodeBuilder.WriteInt32(token); } /// <summary> /// Encodes <code>ldstr</code> instruction and its operand. /// </summary> public void LoadString(UserStringHandle handle) { OpCode(ILOpCode.Ldstr); Token(MetadataTokens.GetToken(handle)); } /// <summary> /// Encodes <code>call</code> instruction and its operand. /// </summary> public void Call(EntityHandle methodHandle) { if (methodHandle.Kind != HandleKind.MethodDefinition && methodHandle.Kind != HandleKind.MethodSpecification && methodHandle.Kind != HandleKind.MemberReference) { Throw.InvalidArgument_Handle(nameof(methodHandle)); } OpCode(ILOpCode.Call); Token(methodHandle); } /// <summary> /// Encodes <code>call</code> instruction and its operand. /// </summary> public void Call(MethodDefinitionHandle methodHandle) { OpCode(ILOpCode.Call); Token(methodHandle); } /// <summary> /// Encodes <code>call</code> instruction and its operand. /// </summary> public void Call(MethodSpecificationHandle methodHandle) { OpCode(ILOpCode.Call); Token(methodHandle); } /// <summary> /// Encodes <code>call</code> instruction and its operand. /// </summary> public void Call(MemberReferenceHandle methodHandle) { OpCode(ILOpCode.Call); Token(methodHandle); } /// <summary> /// Encodes <code>calli</code> instruction and its operand. /// </summary> public void CallIndirect(StandaloneSignatureHandle signature) { OpCode(ILOpCode.Calli); Token(signature); } /// <summary> /// Encodes <see cref="int"/> constant load instruction. /// </summary> 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); CodeBuilder.WriteSByte((sbyte)value); } else { OpCode(ILOpCode.Ldc_i4); CodeBuilder.WriteInt32(value); } return; } OpCode(code); } /// <summary> /// Encodes <see cref="long"/> constant load instruction. /// </summary> public void LoadConstantI8(long value) { OpCode(ILOpCode.Ldc_i8); CodeBuilder.WriteInt64(value); } /// <summary> /// Encodes <see cref="float"/> constant load instruction. /// </summary> public void LoadConstantR4(float value) { OpCode(ILOpCode.Ldc_r4); CodeBuilder.WriteSingle(value); } /// <summary> /// Encodes <see cref="double"/> constant load instruction. /// </summary> public void LoadConstantR8(double value) { OpCode(ILOpCode.Ldc_r8); CodeBuilder.WriteDouble(value); } /// <summary> /// Encodes local variable load instruction. /// </summary> /// <param name="slotIndex">Index of the local variable slot.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="slotIndex"/> is negative.</exception> 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 (unchecked((uint)slotIndex) <= byte.MaxValue) { OpCode(ILOpCode.Ldloc_s); CodeBuilder.WriteByte((byte)slotIndex); } else if (slotIndex > 0) { OpCode(ILOpCode.Ldloc); CodeBuilder.WriteInt32(slotIndex); } else { Throw.ArgumentOutOfRange(nameof(slotIndex)); } break; } } /// <summary> /// Encodes local variable store instruction. /// </summary> /// <param name="slotIndex">Index of the local variable slot.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="slotIndex"/> is negative.</exception> 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 (unchecked((uint)slotIndex) <= byte.MaxValue) { OpCode(ILOpCode.Stloc_s); CodeBuilder.WriteByte((byte)slotIndex); } else if (slotIndex > 0) { OpCode(ILOpCode.Stloc); CodeBuilder.WriteInt32(slotIndex); } else { Throw.ArgumentOutOfRange(nameof(slotIndex)); } break; } } /// <summary> /// Encodes local variable address load instruction. /// </summary> /// <param name="slotIndex">Index of the local variable slot.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="slotIndex"/> is negative.</exception> public void LoadLocalAddress(int slotIndex) { if (unchecked((uint)slotIndex) <= byte.MaxValue) { OpCode(ILOpCode.Ldloca_s); CodeBuilder.WriteByte((byte)slotIndex); } else if (slotIndex > 0) { OpCode(ILOpCode.Ldloca); CodeBuilder.WriteInt32(slotIndex); } else { Throw.ArgumentOutOfRange(nameof(slotIndex)); } } /// <summary> /// Encodes argument load instruction. /// </summary> /// <param name="argumentIndex">Index of the argument.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="argumentIndex"/> is negative.</exception> 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 (unchecked((uint)argumentIndex) <= byte.MaxValue) { OpCode(ILOpCode.Ldarg_s); CodeBuilder.WriteByte((byte)argumentIndex); } else if (argumentIndex > 0) { OpCode(ILOpCode.Ldarg); CodeBuilder.WriteInt32(argumentIndex); } else { Throw.ArgumentOutOfRange(nameof(argumentIndex)); } break; } } /// <summary> /// Encodes argument address load instruction. /// </summary> /// <param name="argumentIndex">Index of the argument.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="argumentIndex"/> is negative.</exception> public void LoadArgumentAddress(int argumentIndex) { if (unchecked((uint)argumentIndex) <= byte.MaxValue) { OpCode(ILOpCode.Ldarga_s); CodeBuilder.WriteByte((byte)argumentIndex); } else if (argumentIndex > 0) { OpCode(ILOpCode.Ldarga); CodeBuilder.WriteInt32(argumentIndex); } else { Throw.ArgumentOutOfRange(nameof(argumentIndex)); } } /// <summary> /// Encodes argument store instruction. /// </summary> /// <param name="argumentIndex">Index of the argument.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="argumentIndex"/> is negative.</exception> public void StoreArgument(int argumentIndex) { if (unchecked((uint)argumentIndex) <= byte.MaxValue) { OpCode(ILOpCode.Starg_s); CodeBuilder.WriteByte((byte)argumentIndex); } else if (argumentIndex > 0) { OpCode(ILOpCode.Starg); CodeBuilder.WriteInt32(argumentIndex); } else { Throw.ArgumentOutOfRange(nameof(argumentIndex)); } } /// <summary> /// Defines a label that can later be used to mark and refer to a location in the instruction stream. /// </summary> /// <returns>Label handle.</returns> /// <exception cref="InvalidOperationException"><see cref="ControlFlowBuilder"/> is null.</exception> public LabelHandle DefineLabel() { return GetBranchBuilder().AddLabel(); } /// <summary> /// Encodes a branch instruction. /// </summary> /// <param name="code">Branch instruction to encode.</param> /// <param name="label">Label of the target location in instruction stream.</param> /// <exception cref="ArgumentException"><paramref name="code"/> is not a branch instruction.</exception> /// <exception cref="ArgumentException"><paramref name="label"/> was not defined by this encoder.</exception> /// <exception cref="InvalidOperationException"><see cref="ControlFlowBuilder"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="label"/> has default value.</exception> public void Branch(ILOpCode code, LabelHandle label) { // throws if code is not a branch: int size = code.GetBranchOperandSize(); GetBranchBuilder().AddBranch(Offset, label, code); OpCode(code); // -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. if (size == 1) { CodeBuilder.WriteSByte(-1); } else { Debug.Assert(size == 4); CodeBuilder.WriteInt32(-1); } } /// <summary> /// Associates specified label with the current IL offset. /// </summary> /// <param name="label">Label to mark.</param> /// <remarks> /// A single label may be marked multiple times, the last offset wins. /// </remarks> /// <exception cref="InvalidOperationException"><see cref="ControlFlowBuilder"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="label"/> was not defined by this encoder.</exception> /// <exception cref="ArgumentNullException"><paramref name="label"/> has default value.</exception> public void MarkLabel(LabelHandle label) { GetBranchBuilder().MarkLabel(Offset, label); } private ControlFlowBuilder GetBranchBuilder() { if (ControlFlowBuilder == null) { Throw.ControlFlowBuilderNotAvailable(); } return ControlFlowBuilder; } } }
using System; using System.Data; using Aranasoft.Cobweb.FluentMigrator.Extensions; using FluentMigrator; using FluentMigrator.SqlServer; namespace Aranasoft.Cobweb.EntityFrameworkCore.Validation.Tests.Support.Migrations { [Migration(12345, "Add Identity Tables")] public class MigrationsMissingViews : Migration { public override void Up() { Create.Table("AspNetRoles") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_AspNetRoles")) .WithColumn("ConcurrencyStamp", col => col.AsStringMax().Nullable()) .WithColumn("Name", col => col.AsString(256).Nullable()) .WithColumn("NormalizedName", col => col.AsString(256).Nullable()) ; Create.Index("RoleNameIndex") .OnTable("AspNetRoles") .OnColumn("NormalizedName", col => col.Unique().NullsNotDistinct()) ; IfDatabase(dbType => string.Equals(dbType, "SQLite-Test", StringComparison.InvariantCultureIgnoreCase)) .Delegate(() => Create.Table("AspNetUsers") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_AspNetUsers")) .WithColumn("AccessFailedCount", col => col.AsInt32().NotNullable()) .WithColumn("ConcurrencyStamp", col => col.AsStringMax().Nullable()) .WithColumn("Email", col => col.AsString(256).Nullable()) .WithColumn("EmailConfirmed", col => col.AsBoolean().NotNullable()) .WithColumn("LockoutEnabled", col => col.AsBoolean().NotNullable()) .WithColumn("LockoutEnd", col => col.AsString().Nullable()) .WithColumn("NormalizedEmail", col => col.AsString(256).Nullable().Indexed("EmailIndex")) .WithColumn("NormalizedUserName", col => col.AsString(256).Nullable()) .WithColumn("PasswordHash", col => col.AsStringMax().Nullable()) .WithColumn("PhoneNumber", col => col.AsStringMax().Nullable()) .WithColumn("PhoneNumberConfirmed", col => col.AsBoolean().NotNullable()) .WithColumn("SecurityStamp", col => col.AsStringMax().Nullable()) .WithColumn("TwoFactorEnabled", col => col.AsBoolean().NotNullable()) .WithColumn("UserName", col => col.AsString(256).Nullable()) ); IfDatabase(dbType => !string.Equals(dbType, "SQLite-Test", StringComparison.InvariantCultureIgnoreCase)) .Delegate(() => Create.Table("AspNetUsers") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_AspNetUsers")) .WithColumn("AccessFailedCount", col => col.AsInt32().NotNullable()) .WithColumn("ConcurrencyStamp", col => col.AsStringMax().Nullable()) .WithColumn("Email", col => col.AsString(256).Nullable()) .WithColumn("EmailConfirmed", col => col.AsBoolean().NotNullable()) .WithColumn("LockoutEnabled", col => col.AsBoolean().NotNullable()) .WithColumn("LockoutEnd", col => col.AsDateTimeOffset().Nullable()) .WithColumn("NormalizedEmail", col => col.AsString(256).Nullable().Indexed("EmailIndex")) .WithColumn("NormalizedUserName", col => col.AsString(256).Nullable()) .WithColumn("PasswordHash", col => col.AsStringMax().Nullable()) .WithColumn("PhoneNumber", col => col.AsStringMax().Nullable()) .WithColumn("PhoneNumberConfirmed", col => col.AsBoolean().NotNullable()) .WithColumn("SecurityStamp", col => col.AsStringMax().Nullable()) .WithColumn("TwoFactorEnabled", col => col.AsBoolean().NotNullable()) .WithColumn("UserName", col => col.AsString(256).Nullable()) ); Create.Index("UserNameIndex") .OnTable("AspNetUsers") .OnColumn("NormalizedUserName", col => col.Unique().NullsNotDistinct()) ; Create.Table("AspNetRoleClaims") .WithColumn("Id", col => col.AsInt32().NotNullable().Identity().PrimaryKey("PK_AspNetRoleClaims")) .WithColumn("ClaimType", col => col.AsStringMax().Nullable()) .WithColumn("ClaimValue", col => col.AsStringMax().Nullable()) .WithColumn("RoleId", col => col.AsInt32() .NotNullable() .Indexed("IX_AspNetRoleClaims_RoleId") .ForeignKey("FK_AspNetRoleClaims_AspNetRoles_RoleId", "AspNetRoles", "Id") .OnDelete(Rule.Cascade)) ; Create.Table("AspNetUserClaims") .WithColumn("Id", col => col.AsInt32().NotNullable().Identity().PrimaryKey("PK_AspNetUserClaims")) .WithColumn("ClaimType", col => col.AsStringMax().Nullable()) .WithColumn("ClaimValue", col => col.AsStringMax().Nullable()) .WithColumn("UserId", col => col.AsInt32() .NotNullable() .Indexed("IX_AspNetUserClaims_UserId") .ForeignKey("FK_AspNetUserClaims_AspNetUsers_UserId", "AspNetUsers", "Id") .OnDelete(Rule.Cascade)) ; Create.Table("AspNetUserLogins") .WithColumn("LoginProvider", col => col.AsString(450).NotNullable().PrimaryKey("PK_AspNetUserLogins")) .WithColumn("ProviderKey", col => col.AsString(450).NotNullable().PrimaryKey("PK_AspNetUserLogins")) .WithColumn("ProviderDisplayName", col => col.AsStringMax().Nullable()) .WithColumn("UserId", col => col.AsInt32() .NotNullable() .Indexed("IX_AspNetUserLogins_UserId") .ForeignKey("FK_AspNetUserLogins_AspNetUsers_UserId", "AspNetUsers", "Id") .OnDelete(Rule.Cascade)) ; Create.Table("AspNetUserRoles") .WithColumn("UserId", col => col.AsInt32() .NotNullable() .PrimaryKey("PK_AspNetUserRoles") .ForeignKey("FK_AspNetUserRoles_AspNetUsers_UserId", "AspNetUsers", "Id") .OnDelete(Rule.Cascade)) .WithColumn("RoleId", col => col.AsInt32() .NotNullable() .PrimaryKey("PK_AspNetUserRoles") .Indexed("IX_AspNetUserRoles_RoleId") .ForeignKey("FK_AspNetUserRoles_AspNetRoles_RoleId", "AspNetRoles", "Id") .OnDelete(Rule.Cascade)) ; Create.Table("AspNetUserTokens") .WithColumn("UserId", col => col.AsInt32() .NotNullable() .PrimaryKey("PK_AspNetUserTokens") .ForeignKey("FK_AspNetUserTokens_AspNetUsers_UserId", "AspNetUsers", "Id") .OnDelete(Rule.Cascade)) .WithColumn("LoginProvider", col => col.AsString(450).NotNullable().PrimaryKey("PK_AspNetUserTokens")) .WithColumn("Name", col => col.AsString(450).NotNullable().PrimaryKey("PK_AspNetUserTokens")) .WithColumn("Value", col => col.AsStringMax().Nullable()) ; IfDatabase(dbType => string.Equals(dbType, "SQLite-Test", StringComparison.InvariantCultureIgnoreCase)) .Delegate(() => { Create.Table("TableBasedEntity") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_TableBasedEntity")) .WithColumn("Field", col => col.AsString(256).Nullable()) .WithColumn("NumberValue", col => col.AsString(20000).NotNullable()) .WithColumn("RoleId", col => col.AsInt32() .NotNullable() .Indexed("IX_TableBasedEntity_RoleId") .ForeignKey("FK_TableBasedEntity_AspNetRoles_RoleId", "AspNetRoles", "Id") .OnDelete(Rule.Cascade)) ; }); IfDatabase(dbType => !string.Equals(dbType, "SQLite-Test", StringComparison.InvariantCultureIgnoreCase)) .Delegate(() => { Create.Table("TableBasedEntity") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_TableBasedEntity")) .WithColumn("Field", col => col.AsString(256).Nullable()) .WithColumn("NumberValue", col => col.AsDecimal(18, 2).NotNullable()) .WithColumn("RoleId", col => col.AsInt32() .NotNullable() .Indexed("IX_TableBasedEntity_RoleId") .ForeignKey("FK_TableBasedEntity_AspNetRoles_RoleId", "AspNetRoles", "Id") .OnDelete(Rule.Cascade)) ; }); Create.Table("TableBasedChildEntity") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_TableBasedChildEntity")) .WithColumn("Name", col => col.AsString(20000).Nullable()) .WithColumn("ViewEntityId", col => col.AsInt32() .NotNullable() .Indexed("IX_TableBasedChildEntity_ViewEntityId")) ; } public override void Down() { if (Schema.Table("TableBasedChildEntity").Exists()) { Delete.Table("TableBasedChildEntity"); } if (Schema.Table("TableBasedEntity").Exists()) { Delete.Table("TableBasedEntity"); } if (Schema.Table("AspNetRoleClaims").Exists()) { Delete.Table("AspNetRoleClaims"); } if (Schema.Table("AspNetUserClaims").Exists()) { Delete.Table("AspNetUserClaims"); } if (Schema.Table("AspNetUserLogins").Exists()) { Delete.Table("AspNetUserLogins"); } if (Schema.Table("AspNetUserRoles").Exists()) { Delete.Table("AspNetUserRoles"); } if (Schema.Table("AspNetUserTokens").Exists()) { Delete.Table("AspNetUserTokens"); } if (Schema.Table("AspNetRoles").Exists()) { Delete.Table("AspNetRoles"); } if (Schema.Table("AspNetUsers").Exists()) { Delete.Table("AspNetUsers"); } } } }
using System; using System.Collections.Generic; using System.Text; using SpeechLib; using System.Diagnostics; using SimplePatientDocumentation.CommonObjects; using SimplePatientDocumentation.BL; namespace SimplePatientDocumentation.VoiceInfo { public enum State { init, cognitied, master, lastOperation, allOperation, lastVisit, allVisit } class VoiceInfoAutomat { private State state; private const int grammarId = 10; //private ISpeechGrammarRule ruleTopLevel; //private ISpeechGrammarRule ruleListItemsNames; //private ISpeechGrammarRule ruleListItemsIDs; //private ISpeechGrammarRule ruleListItemsDefault; List<string> patientenNameList; List<long> patientIDList; IList<PatientData> patientList; private PatientData currentPatient; private PatientDocumentationComponent patientComponent; public VoiceInfoAutomat(List<string> patientenNameList, List<long> patientIDList) { state = State.init; this.patientenNameList = patientenNameList; this.currentPatient = null; patientComponent = new PatientDocumentationComponent(); this.patientenNameList = patientenNameList; this.patientIDList = patientIDList; patientList = patientComponent.GetAllPatients(); } public State Status { get { return this.state; } } public State EnterCommand(string command) { Debug.WriteLine("EnterCommand " + this.state); command.Trim(); switch(this.state){ case State.init: if (command.StartsWith("name")) { string patientName = command.Remove(0, 4).Trim(); foreach (PatientData patient in patientList) { if (patientName.Equals(patient.FirstName + " " + patient.SurName)) { this.state = State.cognitied; this.currentPatient = patient; } } } else if (command.StartsWith("id")) { long patientID = 0; if (command.Length <= 2) { return this.state; } try { patientID = Int64.Parse(command.Remove(0, 2).Trim()); } catch (FormatException) { this.currentPatient = null; return this.state; } foreach (PatientData patient in patientList) { if (patientID == patient.Id) { this.state = State.cognitied; this.currentPatient = patient; } } } break; case State.cognitied: if (command.Equals("master")) { this.state = State.master; } else if (command.Equals("operation")) { this.state = State.lastOperation; } else if (command.Equals("visit")) { this.state = State.lastVisit; } else if (command.Equals("reset")) { this.state = State.init; } break; case State.master: if (command.Equals("repeat")) { this.state = State.master; } else if (command.Equals("back")) { this.state = State.cognitied; } else if (command.Equals("reset")) { this.state = State.init; } else if (command.Equals("repeat")) { this.state = State.master; } break; case State.lastOperation: if (command.Equals("more")) { this.state = State.allOperation; } else if (command.Equals("back")) { this.state = State.cognitied; } else if (command.Equals("reset")) { this.state = State.init; } else if (command.Equals("repeat")) { this.state = State.lastOperation; } break; case State.lastVisit: if (command.Equals("more")) { this.state = State.allVisit; } else if (command.Equals("back")) { this.state = State.cognitied; } else if (command.Equals("reset")) { this.state = State.init; } else if (command.Equals("repeat")) { this.state = State.lastVisit; } break; case State.allOperation: if (command.Equals("back")) { this.state = State.cognitied; } else if (command.Equals("reset")) { this.state = State.init; } else if (command.Equals("repeat")) { this.state = State.allOperation; } break; case State.allVisit: if (command.Equals("back")) { this.state = State.cognitied; } else if (command.Equals("reset")) { this.state = State.init; } else if (command.Equals("repeat")) { this.state = State.allVisit; } break; default: break; } return this.state; } public bool RebuildGrammar(ISpeechRecoGrammar grammar, bool speechEnabled, SpSharedRecoContext objRecoContext, ISpeechGrammarRule ruleListItemsDefault) { Debug.WriteLine("RebuildGrammar " + this.state.ToString()); if (!speechEnabled) { return false; } //grammar = objRecoContext.CreateGrammar(grammarId); ////ruleTopLevel = grammar.Rules.Add("TopLevelRule", SpeechRuleAttributes.SRATopLevel | SpeechRuleAttributes.SRADynamic, 1); object PropValue = ""; switch (this.state) { case State.init: //ruleListItemsNames = grammar.Rules.Add("ListItemsNameRule", SpeechRuleAttributes.SRADynamic, 2); //ruleListItemsIDs = grammar.Rules.Add("ListItemsIDRule", SpeechRuleAttributes.SRADynamic, 3); //ruleListItemsDefault = grammar.Rules.Add("ListItemsDefaultRule", SpeechRuleAttributes.SRADynamic, 2); //SpeechLib.ISpeechGrammarRuleState stateName; //SpeechLib.ISpeechGrammarRuleState stateID; ////SpeechLib.ISpeechGrammarRuleState stateDefault; //stateName = ruleTopLevel.AddState(); //stateID = ruleTopLevel.AddState(); ////stateDefault = ruleListItemsDefault.AddState(); //object PropValue1 = ""; //object PropValue2 = ""; ////PropValue = ""; //ruleTopLevel.InitialState.AddWordTransition(stateName, "name", " ", SpeechGrammarWordType.SGLexical, "", 0, ref PropValue1, 1.0F); //ruleTopLevel.InitialState.AddWordTransition(stateID, "id", " ", SpeechGrammarWordType.SGLexical, "", 0, ref PropValue2, 1.0F); ////ruleTopLevel.InitialState.AddWordTransition(stateDefault, " ", " ", SpeechGrammarWordType.SGLexical, "", 0, ref PropValue, 1.0F); //PropValue1 = ""; //PropValue2 = ""; ////PropValue = ""; //stateName.AddRuleTransition(null, ruleListItemsNames, "", 1, ref PropValue1, 0F); //stateID.AddRuleTransition(null, ruleListItemsIDs, "", 1, ref PropValue2, 0F); ////stateDefault.AddRuleTransition(null, ruleListItemsDefault, "", 1, ref PropValue, 0F); try { //ruleListItemsNames.Clear(); //ruleListItemsIDs.Clear(); ruleListItemsDefault.Clear(); //int i = 0; //foreach (string patientName in patientenNameList) { // string word = patientName; // ruleListItemsNames.InitialState.AddWordTransition(null, word, " ", SpeechGrammarWordType.SGLexical, word, i, ref PropValue1, 1F); // i++; //} //i = 0; //foreach (long patientID in patientIDList) { // long ID = patientID; // ruleListItemsIDs.InitialState.AddWordTransition(null, ID.ToString(), " ", SpeechGrammarWordType.SGLexical, ID.ToString(), i, ref PropValue2, 1F); // i++; //} int i = 0; foreach (string patientName in patientenNameList) { string word = "name " + patientName; ruleListItemsDefault.InitialState.AddWordTransition(null, word, " ", SpeechGrammarWordType.SGLexical, word, i, ref PropValue, 1F); i++; } foreach (long patientID in patientIDList) { string word = "id " + patientID.ToString(); ruleListItemsDefault.InitialState.AddWordTransition(null, word, " ", SpeechGrammarWordType.SGLexical, word, i, ref PropValue, 1F); i++; } grammar.Rules.Commit(); ////grammar.CmdSetRuleState("TopLevelRule", SpeechRuleState.SGDSActive); } catch (Exception e) { System.Windows.Forms.MessageBox.Show( "Exception caught when rebuilding dynamic listbox rule.\r\n\r\n" + e.ToString(), "Error"); } break; case State.cognitied: //ruleListItemsDefault = grammar.Rules.Add("ListItemsDefaultRule", SpeechRuleAttributes.SRADynamic, 2); //SpeechLib.ISpeechGrammarRuleState stateCognitied; //stateCognitied = ruleTopLevel.AddState(); //PropValue = ""; //ruleTopLevel.InitialState.AddWordTransition(stateCognitied, "", " ", SpeechGrammarWordType.SGLexical, "", 0, ref PropValue, 1.0F); //PropValue = ""; //stateCognitied.AddRuleTransition(null, ruleListItemsDefault, "", 1, ref PropValue, 0F); try { ruleListItemsDefault.Clear(); ruleListItemsDefault.InitialState.AddWordTransition(null, "master", " ", SpeechGrammarWordType.SGLexical, "master", 0, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "operation", " ", SpeechGrammarWordType.SGLexical, "operation", 1, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "visit", " ", SpeechGrammarWordType.SGLexical, "visit", 2, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "reset", " ", SpeechGrammarWordType.SGLexical, "reset", 3, ref PropValue, 1F); grammar.Rules.Commit(); //grammar.CmdSetRuleState("TopLevelRule", SpeechRuleState.SGDSActive); } catch (Exception e) { System.Windows.Forms.MessageBox.Show( "Exception caught when rebuilding dynamic listbox rule.\r\n\r\n" + e.ToString(), "Error"); } break; case State.master: try { ruleListItemsDefault.Clear(); ruleListItemsDefault.InitialState.AddWordTransition(null, "repeat", " ", SpeechGrammarWordType.SGLexical, "master", 0, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "back", " ", SpeechGrammarWordType.SGLexical, "operation", 1, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "reset", " ", SpeechGrammarWordType.SGLexical, "reset", 2, ref PropValue, 1F); grammar.Rules.Commit(); //grammar.CmdSetRuleState("TopLevelRule", SpeechRuleState.SGDSActive); } catch (Exception e) { System.Windows.Forms.MessageBox.Show( "Exception caught when rebuilding dynamic listbox rule.\r\n\r\n" + e.ToString(), "Error"); } break; case State.lastOperation: try { ruleListItemsDefault.Clear(); ruleListItemsDefault.InitialState.AddWordTransition(null, "repeat", " ", SpeechGrammarWordType.SGLexical, "master", 0, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "back", " ", SpeechGrammarWordType.SGLexical, "operation", 1, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "reset", " ", SpeechGrammarWordType.SGLexical, "reset", 2, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "more", " ", SpeechGrammarWordType.SGLexical, "reset", 3, ref PropValue, 1F); grammar.Rules.Commit(); //grammar.CmdSetRuleState("TopLevelRule", SpeechRuleState.SGDSActive); } catch (Exception e) { System.Windows.Forms.MessageBox.Show( "Exception caught when rebuilding dynamic listbox rule.\r\n\r\n" + e.ToString(), "Error"); } break; case State.lastVisit: try { ruleListItemsDefault.Clear(); ruleListItemsDefault.InitialState.AddWordTransition(null, "repeat", " ", SpeechGrammarWordType.SGLexical, "master", 0, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "back", " ", SpeechGrammarWordType.SGLexical, "operation", 1, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "reset", " ", SpeechGrammarWordType.SGLexical, "reset", 2, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "more", " ", SpeechGrammarWordType.SGLexical, "reset", 3, ref PropValue, 1F); grammar.Rules.Commit(); } catch (Exception e) { System.Windows.Forms.MessageBox.Show( "Exception caught when rebuilding dynamic listbox rule.\r\n\r\n" + e.ToString(), "Error"); } break; case State.allOperation: try { ruleListItemsDefault.Clear(); ruleListItemsDefault.InitialState.AddWordTransition(null, "repeat", " ", SpeechGrammarWordType.SGLexical, "master", 0, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "back", " ", SpeechGrammarWordType.SGLexical, "operation", 1, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "reset", " ", SpeechGrammarWordType.SGLexical, "reset", 2, ref PropValue, 1F); grammar.Rules.Commit(); } catch (Exception e) { System.Windows.Forms.MessageBox.Show( "Exception caught when rebuilding dynamic listbox rule.\r\n\r\n" + e.ToString(), "Error"); } break; case State.allVisit: try { ruleListItemsDefault.Clear(); ruleListItemsDefault.InitialState.AddWordTransition(null, "repeat", " ", SpeechGrammarWordType.SGLexical, "master", 0, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "back", " ", SpeechGrammarWordType.SGLexical, "operation", 1, ref PropValue, 1F); ruleListItemsDefault.InitialState.AddWordTransition(null, "reset", " ", SpeechGrammarWordType.SGLexical, "reset", 2, ref PropValue, 1F); grammar.Rules.Commit(); } catch (Exception e) { System.Windows.Forms.MessageBox.Show( "Exception caught when rebuilding dynamic listbox rule.\r\n\r\n" + e.ToString(), "Error"); } break; default: break; } return true; } public PatientData CurrentPatient{ get { return this.currentPatient; } } } }
// =========================================================== // Copyright (c) 2014-2015, Enrico Da Ros/kendar.org // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // =========================================================== using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using ConcurrencyHelpers.Containers; using ConcurrencyHelpers.Utils; namespace ConcurrencyHelpers.Coroutines { [Obsolete] [ExcludeFromCodeCoverage] public class CoroutineThread : IValuesCollection, IDisposable { private CounterInt64 _status; private readonly List<CoroutineStatus> _coroutines; private readonly LockFreeQueue<ICoroutine> _coroutinesQueue; private readonly Thread _thread; private readonly ManualResetEvent _pauseVerifier; private CounterInt64 _cycleMaxMs; private readonly int _affinity; private readonly Dictionary<string, object> _values; private readonly CounterInt64 _startedCoroutines; private readonly CounterInt64 _terminatedCoroutines; private readonly CultureInfo _currentCulture; public CoroutineThread(int cycleMaxMs = 10, int affinity = -1) { _startedCoroutines = new CounterInt64(); _terminatedCoroutines = new CounterInt64(); Status = (int)CoroutineThreadStatus.Stopped; _values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); _cycleMaxMs = cycleMaxMs; _affinity = affinity; _coroutines = new List<CoroutineStatus>(); _coroutinesQueue = new LockFreeQueue<ICoroutine>(); _thread = new Thread(StartThread); _pauseVerifier = new ManualResetEvent(false); _currentCulture = Thread.CurrentThread.CurrentCulture; } public virtual void AddCoroutine(params ICoroutine[] coroutines) { foreach (var coroutine in coroutines) { _coroutinesQueue.Enqueue(coroutine); } } public int CycleMaxMs { get { return (int)_cycleMaxMs; } set { _cycleMaxMs = value; } } public CoroutineThreadStatus Status { get { return (CoroutineThreadStatus)(int)_status; } protected set { _status = (int)value; } } public void Stop() { Status = CoroutineThreadStatus.Stopped; } public void Pause() { Status = CoroutineThreadStatus.Paused; } public void Start() { if (Status == CoroutineThreadStatus.Paused) { _pauseVerifier.Set(); } else { if (_thread.ThreadState != System.Threading.ThreadState.Running) { _thread.Start(); } } } public Action<Exception, ICoroutine> HandleError { get; set; } public long StartedCoroutines { get { return _startedCoroutines.Value; } } public long TerminatedCoroutines { get { return _terminatedCoroutines.Value; } } [DllImport("kernel32.dll")] public static extern int GetCurrentThreadId(); [DllImport("kernel32.dll")] public static extern int GetCurrentProcessorNumber(); private ProcessThread CurrentThread { get { int id = GetCurrentThreadId(); return (from ProcessThread th in Process.GetCurrentProcess().Threads where th.Id == id select th).Single(); } } private void StartThread() { Thread.BeginThreadAffinity(); try { if ( _affinity >= 0 ) { CurrentThread.ProcessorAffinity = new IntPtr ( _affinity ); } // ReSharper disable once TooWideLocalVariableScope Status = CoroutineThreadStatus.Running; var stopWatch = new Stopwatch(); while (Status != CoroutineThreadStatus.Stopped) { RunStep(stopWatch); } } finally { // reset affinity CurrentThread.ProcessorAffinity =new IntPtr(0xFFFF); Thread.EndThreadAffinity(); } } protected void RunStep(Stopwatch stopWatch) { Thread.CurrentThread.CurrentCulture = _currentCulture; PauseWait(); if (Status == CoroutineThreadStatus.Stopped) return; stopWatch.Reset(); stopWatch.Start(); foreach (var coroutineToAdd in _coroutinesQueue.Dequeue()) { coroutineToAdd.Thread = this; coroutineToAdd.ShouldTerminate = false; _coroutines.Add(new CoroutineStatus { Instance = coroutineToAdd }); _startedCoroutines.Increment(); } for (int i = (_coroutines.Count - 1); i >= 0; i--) { PauseWait(); var coroutineStatus = _coroutines[i]; var coroutine = coroutineStatus.Instance; try { // ReSharper disable PossibleMultipleEnumeration if (coroutineStatus.Enumerator == null) { coroutineStatus.Enumerator = new CoroutineStack(coroutine.Run().GetEnumerator(), coroutine); } if (!coroutineStatus.Enumerator.MoveNext()) { coroutine.ShouldTerminate = true; } // ReSharper restore PossibleMultipleEnumeration } catch (Exception ex) { if (HandleError != null) { try { HandleError(ex, coroutine); } catch (Exception) { } } coroutine.OnError(ex); if (coroutineStatus.Enumerator != null) { coroutineStatus.Enumerator.Reset(); } coroutineStatus.Enumerator = null; } if (coroutine.ShouldTerminate) { _terminatedCoroutines.Increment(); _coroutines.RemoveAt(i); // ReSharper disable once RedundantAssignment coroutine = null; } } stopWatch.Stop(); var wait = (int)(CycleMaxMs - stopWatch.ElapsedMilliseconds); Thread.Sleep(wait > 1 ? wait : 0); } private void PauseWait() { if (Status == CoroutineThreadStatus.Paused) { _pauseVerifier.Reset(); while (false == _pauseVerifier.WaitOne(1000)) { if (Status == CoroutineThreadStatus.Stopped) { _pauseVerifier.Reset(); return; } } Status = CoroutineThreadStatus.Running; } } ~CoroutineThread() { // Finalizer calls Dispose(false) Dispose(false); } public virtual void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // free managed resources Status = CoroutineThreadStatus.Stopped; _pauseVerifier.Reset(); } } public void ClearValues() { _values.Clear(); } public object this[string index] { get { return _values[index]; } set { _values[index] = value; } } public void RemoveValueAt(string index) { if (ContainsKey(index)) { _values.Remove(index); } } public bool ContainsKey(string index) { return _values.ContainsKey(index); } } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace UnityTest { public interface ITestComponent : IComparable<ITestComponent> { void EnableTest (bool enable); bool IsTestGroup (); GameObject gameObject { get; } string Name { get; } ITestComponent GetTestGroup (); bool IsExceptionExpected (string exceptionType); bool ShouldSucceedOnException (); double GetTimeout (); bool IsIgnored (); bool ShouldSucceedOnAssertions (); bool IsExludedOnThisPlatform (); } public class TestComponent : MonoBehaviour, ITestComponent { public static ITestComponent NullTestComponent = new NullTestComponentImpl (); public float timeout = 5; public bool ignored = false; public bool succeedAfterAllAssertionsAreExecuted = false; public bool expectException = false; public string expectedExceptionList = ""; public bool succeedWhenExceptionIsThrown = false; public IncludedPlatforms includedPlatforms = (IncludedPlatforms) ~0L; public string[] platformsToIgnore = null; public bool dynamic; public string dynamicTypeName; public bool IsExludedOnThisPlatform () { return platformsToIgnore != null && platformsToIgnore.Any (platform => platform == Application.platform.ToString ()); } static bool IsAssignableFrom(Type a, Type b) { #if !UNITY_METRO return a.IsAssignableFrom(b); #else return false; #endif } public bool IsExceptionExpected (string exception) { if (!expectException) return false; exception = exception.Trim (); foreach (var expectedException in expectedExceptionList.Split (',').Select (e => e.Trim ())) { if (exception == expectedException) return true; var exceptionType = Type.GetType (exception) ?? GetTypeByName (exception); var expectedExceptionType = Type.GetType (expectedException) ?? GetTypeByName (expectedException); if (exceptionType != null && expectedExceptionType != null && IsAssignableFrom(expectedExceptionType,exceptionType)) return true; } return false; } public bool ShouldSucceedOnException () { return succeedWhenExceptionIsThrown; } public double GetTimeout () { return timeout; } public bool IsIgnored () { return ignored; } public bool ShouldSucceedOnAssertions () { return succeedAfterAllAssertionsAreExecuted; } private static Type GetTypeByName (string className) { #if !UNITY_METRO return AppDomain.CurrentDomain.GetAssemblies ().SelectMany (a => a.GetTypes ()).FirstOrDefault (type => type.Name == className); #else return null; #endif } public void OnValidate () { if (timeout < 0.01f) timeout = 0.01f; } //Legacy [Flags] public enum IncludedPlatforms { WindowsEditor = 1 << 0, OSXEditor = 1 << 1, WindowsPlayer = 1 << 2, OSXPlayer = 1 << 3, LinuxPlayer = 1 << 4, MetroPlayerX86 = 1 << 5, MetroPlayerX64 = 1 << 6, MetroPlayerARM = 1 << 7, WindowsWebPlayer = 1 << 8, OSXWebPlayer = 1 << 9, Android = 1 << 10, IPhonePlayer = 1 << 11, TizenPlayer = 1 << 12, WP8Player = 1 << 13, BB10Player = 1 << 14, NaCl = 1 << 15, PS3 = 1 << 16, XBOX360 = 1 << 17, WiiPlayer = 1 << 18, PSP2 = 1 << 19, PS4 = 1 << 20, PSMPlayer = 1 << 21, XboxOne = 1 << 22, } #region ITestComponent implementation public void EnableTest (bool enable) { if (enable && dynamic) { Type t = Type.GetType (dynamicTypeName); var s = gameObject.GetComponent(t) as MonoBehaviour; if(s!=null) DestroyImmediate (s); gameObject.AddComponent (t); } if(gameObject.activeSelf!=enable) gameObject.SetActive (enable); } public int CompareTo (ITestComponent obj) { if (obj == NullTestComponent) return 1; var result = gameObject.name.CompareTo (obj.gameObject.name); if (result == 0) result = gameObject.GetInstanceID ().CompareTo (obj.gameObject.GetInstanceID ()); return result; } public bool IsTestGroup () { for (int i = 0; i < gameObject.transform.childCount; i++) { var childTC = gameObject.transform.GetChild (i).GetComponent (typeof (TestComponent)); if (childTC != null) return true; } return false; } public string Name { get { return gameObject == null ? "" : gameObject.name; } } public ITestComponent GetTestGroup () { var parent = gameObject.transform.parent; if (parent == null) return NullTestComponent; return parent.GetComponent<TestComponent> (); } public override bool Equals ( object o ) { if (o is TestComponent) return this == (o as TestComponent); return false; } public override int GetHashCode () { return base.GetHashCode (); } public static bool operator == ( TestComponent a, TestComponent b ) { if (ReferenceEquals (a, b)) return true; if (((object)a == null) || ((object)b == null)) return false; if(a.dynamic && b.dynamic) return a.dynamicTypeName == b.dynamicTypeName; if(a.dynamic || b.dynamic) return false; return a.gameObject == b.gameObject; } public static bool operator != ( TestComponent a, TestComponent b ) { return !(a == b); } #endregion #region Static helpers public static TestComponent CreateDynamicTest (Type type) { var go = CreateTest (type.Name); go.hideFlags |= HideFlags.DontSave; go.SetActive (false); var tc = go.GetComponent<TestComponent> (); tc.dynamic = true; tc.dynamicTypeName = type.AssemblyQualifiedName; #if !UNITY_METRO foreach (var typeAttribute in type.GetCustomAttributes (false)) { if (typeAttribute is IntegrationTest.TimeoutAttribute) tc.timeout = (typeAttribute as IntegrationTest.TimeoutAttribute).timeout; else if (typeAttribute is IntegrationTest.IgnoreAttribute) tc.ignored = true; else if (typeAttribute is IntegrationTest.SucceedWithAssertions) tc.succeedAfterAllAssertionsAreExecuted = true; else if (typeAttribute is IntegrationTest.ExcludePlatformAttribute) tc.platformsToIgnore = (typeAttribute as IntegrationTest.ExcludePlatformAttribute).platformsToExclude; else if (typeAttribute is IntegrationTest.ExpectExceptions) { var attribute = (typeAttribute as IntegrationTest.ExpectExceptions); tc.expectException = true; tc.expectedExceptionList = string.Join (",", attribute.exceptionTypeNames); tc.succeedWhenExceptionIsThrown = attribute.succeedOnException; } } go.AddComponent(type); #endif return tc; } public static GameObject CreateTest () { return CreateTest ("New Test"); } private static GameObject CreateTest (string name) { var go = new GameObject (name); go.AddComponent<TestComponent> (); go.transform.hideFlags |= HideFlags.HideInInspector; return go; } public static List<TestComponent> FindAllTestsOnScene () { return Resources.FindObjectsOfTypeAll (typeof (TestComponent)).Cast<TestComponent> ().ToList (); } public static List<TestComponent> FindAllTopTestsOnScene () { return FindAllTestsOnScene ().Where (component => component.gameObject.transform.parent == null).ToList (); } public static List<TestComponent> FindAllDynamicTestsOnScene () { return FindAllTestsOnScene ().Where (t => t.dynamic).ToList (); } public static void DestroyAllDynamicTests () { foreach (var dynamicTestComponent in FindAllDynamicTestsOnScene ()) DestroyImmediate (dynamicTestComponent.gameObject); } public static void DisableAllTests () { foreach (var t in FindAllTestsOnScene ()) t.EnableTest (false); } public static bool AnyTestsOnScene () { return FindAllTestsOnScene().Any(); } #endregion private sealed class NullTestComponentImpl : ITestComponent { public int CompareTo (ITestComponent other) { if (other == this) return 0; return -1; } public void EnableTest (bool enable) { } public ITestComponent GetParentTestComponent () { throw new NotImplementedException (); } public bool IsTestGroup () { throw new NotImplementedException (); } public GameObject gameObject { get; private set; } public string Name { get { return ""; } } public ITestComponent GetTestGroup () { return null; } public bool IsExceptionExpected (string exceptionType) { throw new NotImplementedException (); } public bool ShouldSucceedOnException () { throw new NotImplementedException (); } public double GetTimeout () { throw new NotImplementedException (); } public bool IsIgnored () { throw new NotImplementedException (); } public bool ShouldSucceedOnAssertions () { throw new NotImplementedException (); } public bool IsExludedOnThisPlatform () { throw new NotImplementedException (); } } public static IEnumerable<Type> GetTypesWithHelpAttribute (string sceneName) { #if !UNITY_METRO foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies ()) { foreach (Type type in assembly.GetTypes ()) { var attributes = type.GetCustomAttributes (typeof (IntegrationTest.DynamicTestAttribute), true); if (attributes.Length == 1) { var a = attributes.Single () as IntegrationTest.DynamicTestAttribute; if (a.IncludeOnScene (sceneName)) yield return type; } } } #else yield break; #endif } } }
/******************************************************************** * * PropertyBag.cs * -------------- * Derived from PropertyBag.cs by Tony Allowatt * CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp * Last Update: 04/05/2005 * ********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing.Design; using System.Reflection; using CslaGenerator.Attributes; using CslaGenerator.CodeGen; using CslaGenerator.Metadata; namespace CslaGenerator.Util.PropertyBags { /// <summary> /// Represents a collection of custom properties that can be selected into a /// PropertyGrid to provide functionality beyond that of the simple reflection /// normally used to query an object's properties. /// </summary> public class AssociativeEntityPropertyBag : ICustomTypeDescriptor { #region PropertySpecCollection class definition /// <summary> /// Encapsulates a collection of PropertySpec objects. /// </summary> [Serializable] public class PropertySpecCollection : IList { private readonly ArrayList _innerArray; /// <summary> /// Initializes a new instance of the PropertySpecCollection class. /// </summary> public PropertySpecCollection() { _innerArray = new ArrayList(); } /// <summary> /// Gets or sets the element at the specified index. /// In C#, this property is the indexer for the PropertySpecCollection class. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <value> /// The element at the specified index. /// </value> public PropertySpec this[int index] { get { return (PropertySpec) _innerArray[index]; } set { _innerArray[index] = value; } } #region IList Members /// <summary> /// Gets the number of elements in the PropertySpecCollection. /// </summary> /// <value> /// The number of elements contained in the PropertySpecCollection. /// </value> public int Count { get { return _innerArray.Count; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection has a fixed size. /// </summary> /// <value> /// true if the PropertySpecCollection has a fixed size; otherwise, false. /// </value> public bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection is read-only. /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <value> /// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false. /// </value> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> /// <value> /// An object that can be used to synchronize access to the collection. /// </value> object ICollection.SyncRoot { get { return null; } } /// <summary> /// Removes all elements from the PropertySpecCollection. /// </summary> public void Clear() { _innerArray.Clear(); } /// <summary> /// Returns an enumerator that can iterate through the PropertySpecCollection. /// </summary> /// <returns>An IEnumerator for the entire PropertySpecCollection.</returns> public IEnumerator GetEnumerator() { return _innerArray.GetEnumerator(); } /// <summary> /// Removes the object at the specified index of the PropertySpecCollection. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> public void RemoveAt(int index) { _innerArray.RemoveAt(index); } #endregion /// <summary> /// Adds a PropertySpec to the end of the PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param> /// <returns>The PropertySpecCollection index at which the value has been added.</returns> public int Add(PropertySpec value) { int index = _innerArray.Add(value); return index; } /// <summary> /// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection. /// </summary> /// <param name="array">The PropertySpec array whose elements should be added to the end of the /// PropertySpecCollection.</param> public void AddRange(PropertySpec[] array) { _innerArray.AddRange(array); } /// <summary> /// Determines whether a PropertySpec is in the PropertySpecCollection. /// </summary> /// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate /// can be a null reference (Nothing in Visual Basic).</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(PropertySpec item) { return _innerArray.Contains(item); } /// <summary> /// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(string name) { foreach (PropertySpec spec in _innerArray) if (spec.Name == name) return true; return false; } /// <summary> /// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the /// beginning of the target array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from PropertySpecCollection. The Array must have zero-based indexing.</param> public void CopyTo(PropertySpec[] array) { _innerArray.CopyTo(array); } /// <summary> /// Copies the PropertySpecCollection or a portion of it to a one-dimensional array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from the collection.</param> /// <param name="index">The zero-based index in array at which copying begins.</param> public void CopyTo(PropertySpec[] array, int index) { _innerArray.CopyTo(array, index); } /// <summary> /// Searches for the specified PropertySpec and returns the zero-based index of the first /// occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(PropertySpec value) { return _innerArray.IndexOf(value); } /// <summary> /// Searches for the PropertySpec with the specified name and returns the zero-based index of /// the first occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(string name) { int i = 0; foreach (PropertySpec spec in _innerArray) { //if (spec.Name == name) if (spec.TargetProperty == name) return i; i++; } return -1; } /// <summary> /// Inserts a PropertySpec object into the PropertySpecCollection at the specified index. /// </summary> /// <param name="index">The zero-based index at which value should be inserted.</param> /// <param name="value">The PropertySpec to insert.</param> public void Insert(int index, PropertySpec value) { _innerArray.Insert(index, value); } /// <summary> /// Removes the first occurrence of a specific object from the PropertySpecCollection. /// </summary> /// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(PropertySpec obj) { _innerArray.Remove(obj); } /// <summary> /// Removes the property with the specified name from the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(string name) { int index = IndexOf(name); RemoveAt(index); } /// <summary> /// Copies the elements of the PropertySpecCollection to a new PropertySpec array. /// </summary> /// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns> public PropertySpec[] ToArray() { return (PropertySpec[]) _innerArray.ToArray(typeof (PropertySpec)); } #region Explicit interface implementations for ICollection and IList /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void ICollection.CopyTo(Array array, int index) { CopyTo((PropertySpec[]) array, index); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.Add(object value) { return Add((PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> bool IList.Contains(object obj) { return Contains((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (PropertySpec) value; } } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.IndexOf(object obj) { return IndexOf((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Insert(int index, object value) { Insert(index, (PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Remove(object value) { Remove((PropertySpec) value); } #endregion } #endregion #region PropertySpecDescriptor class definition private class PropertySpecDescriptor : PropertyDescriptor { private readonly AssociativeEntityPropertyBag _bag; private readonly PropertySpec _item; public PropertySpecDescriptor(PropertySpec item, AssociativeEntityPropertyBag bag, string name, Attribute[] attrs) : base(name, attrs) { _bag = bag; _item = item; } public override Type ComponentType { get { return _item.GetType(); } } public override bool IsReadOnly { get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); } } public override Type PropertyType { get { return Type.GetType(_item.TypeName); } } public override bool CanResetValue(object component) { if (_item.DefaultValue == null) return false; return !GetValue(component).Equals(_item.DefaultValue); } public override object GetValue(object component) { // Have the property bag raise an event to get the current value // of the property. var e = new PropertySpecEventArgs(_item, null); _bag.OnGetValue(e); return e.Value; } public override void ResetValue(object component) { SetValue(component, _item.DefaultValue); } public override void SetValue(object component, object value) { // Have the property bag raise an event to set the current value // of the property. var e = new PropertySpecEventArgs(_item, value); _bag.OnSetValue(e); } public override bool ShouldSerializeValue(object component) { object val = GetValue(component); if (_item.DefaultValue == null && val == null) return false; return !val.Equals(_item.DefaultValue); } } #endregion #region Properties and Events private readonly PropertySpecCollection _properties; private string _defaultProperty; private AssociativeEntity[] _selectedObject; /// <summary> /// Initializes a new instance of the AssociativeEntityPropertyBag class. /// </summary> public AssociativeEntityPropertyBag() { _defaultProperty = null; _properties = new PropertySpecCollection(); } public AssociativeEntityPropertyBag(AssociativeEntity obj) : this(new[] {obj}) { } public AssociativeEntityPropertyBag(AssociativeEntity[] obj) { _defaultProperty = "ObjectName"; _properties = new PropertySpecCollection(); _selectedObject = obj; InitPropertyBag(); } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public string DefaultProperty { get { return _defaultProperty; } set { _defaultProperty = value; } } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public AssociativeEntity[] SelectedObject { get { return _selectedObject; } set { _selectedObject = value; InitPropertyBag(); } } /// <summary> /// Gets the collection of properties contained within this AssociativeEntityPropertyBag. /// </summary> public PropertySpecCollection Properties { get { return _properties; } } /// <summary> /// Occurs when a PropertyGrid requests the value of a property. /// </summary> public event PropertySpecEventHandler GetValue; /// <summary> /// Occurs when the user changes the value of a property in a PropertyGrid. /// </summary> public event PropertySpecEventHandler SetValue; /// <summary> /// Raises the GetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnGetValue(PropertySpecEventArgs e) { if (e.Value != null) GetValue(this, e); e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue); } /// <summary> /// Raises the SetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnSetValue(PropertySpecEventArgs e) { if (SetValue != null) SetValue(this, e); SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value); } #endregion #region Initialize Propertybag private void InitPropertyBag() { PropertyInfo pi; Type t = typeof (AssociativeEntity); // _selectedObject.GetType(); PropertyInfo[] props = t.GetProperties(); // Display information for all properties. for (int i = 0; i < props.Length; i++) { pi = props[i]; object[] myAttributes = pi.GetCustomAttributes(true); string category = ""; string description = ""; bool isreadonly = false; bool isbrowsable = true; object defaultvalue = null; string userfriendlyname = ""; string typeconverter = ""; string designertypename = ""; string helptopic = ""; bool bindable = true; string editor = ""; for (int n = 0; n < myAttributes.Length; n++) { var a = (Attribute) myAttributes[n]; switch (a.GetType().ToString()) { case "System.ComponentModel.CategoryAttribute": category = ((CategoryAttribute) a).Category; break; case "System.ComponentModel.DescriptionAttribute": description = ((DescriptionAttribute) a).Description; break; case "System.ComponentModel.ReadOnlyAttribute": isreadonly = ((ReadOnlyAttribute) a).IsReadOnly; break; case "System.ComponentModel.BrowsableAttribute": isbrowsable = ((BrowsableAttribute) a).Browsable; break; case "System.ComponentModel.DefaultValueAttribute": defaultvalue = ((DefaultValueAttribute) a).Value; break; case "CslaGenerator.Attributes.UserFriendlyNameAttribute": userfriendlyname = ((UserFriendlyNameAttribute) a).UserFriendlyName; break; case "CslaGenerator.Attributes.HelpTopicAttribute": helptopic = ((HelpTopicAttribute) a).HelpTopic; break; case "System.ComponentModel.TypeConverterAttribute": typeconverter = ((TypeConverterAttribute) a).ConverterTypeName; break; case "System.ComponentModel.DesignerAttribute": designertypename = ((DesignerAttribute) a).DesignerTypeName; break; case "System.ComponentModel.BindableAttribute": bindable = ((BindableAttribute) a).Bindable; break; case "System.ComponentModel.EditorAttribute": editor = ((EditorAttribute) a).EditorTypeName; break; } } userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : pi.Name; var types = new List<string>(); foreach (AssociativeEntity obj in _selectedObject) { // if (!types.Contains(obj.RelationType.ToString())) types.Add(obj.RelationType.ToString()); // if (!types.Contains(obj.MainLoadingScheme.ToString())) types.Add(obj.MainLoadingScheme.ToString()); // if (!types.Contains(obj.SecondaryLoadingScheme.ToString())) types.Add(obj.SecondaryLoadingScheme.ToString()); } // here get rid of ComponentName and Parent bool isValidProperty = (pi.Name != "Properties" && pi.Name != "ComponentName" && pi.Name != "Parent"); if (isValidProperty && IsBrowsable(types.ToArray(), pi.Name)) { // CR added missing parameters //this.Properties.Add(new PropertySpec(userfriendlyname,pi.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, pi.Name,helptopic)); Properties.Add(new PropertySpec(userfriendlyname, pi.PropertyType.AssemblyQualifiedName, category, description, defaultvalue, editor, typeconverter, _selectedObject, pi.Name, helptopic, isreadonly, isbrowsable, designertypename, bindable)); } } } #endregion private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>(); private PropertyInfo GetPropertyInfoCache(string propertyName) { if (!propertyInfoCache.ContainsKey(propertyName)) { propertyInfoCache.Add(propertyName, typeof (AssociativeEntity).GetProperty(propertyName)); } return propertyInfoCache[propertyName]; } private bool IsEnumerable(PropertyInfo prop) { if (prop.PropertyType == typeof (string)) return false; Type[] interfaces = prop.PropertyType.GetInterfaces(); foreach (Type typ in interfaces) if (typ.Name.Contains("IEnumerable")) return true; return false; } #region IsBrowsable map objectType:propertyName -> true | false private bool IsBrowsable(string[] objectType, string propertyName) { try { // is it non-root? var mainCslaObject = GeneratorController.Current.CurrentUnit.CslaObjects.Find(SelectedObject[0].MainObject); if (CslaTemplateHelperCS.IsNotRootType(mainCslaObject)) if (propertyName == "MainLoadParameters" || propertyName == "SecondaryLoadParameters") return false; if (objectType[0] == "OneToMultiple" && (propertyName == "SecondaryObject" || propertyName == "SecondaryPropertyName" || propertyName == "SecondaryCollectionTypeName" || propertyName == "SecondaryItemTypeName" || propertyName == "SecondaryLazyLoad" || propertyName == "SecondaryLoadingScheme" || propertyName == "SecondaryLoadProperties" || propertyName == "SecondaryLoadParameters")) return false; if (objectType[1] == "ParentLoad" && (propertyName == "MainLoadProperties" || propertyName == "MainLazyLoad")) return false; if (objectType[2] == "ParentLoad" && (propertyName == "SecondaryLoadProperties" || propertyName == "SecondaryLazyLoad")) return false; if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName))) return false; return true; } catch //(Exception e) { Debug.WriteLine(objectType + ":" + propertyName); return true; } } #endregion #region Reflection functions private object GetField(Type t, string name, object target) { object obj = null; Type tx; FieldInfo[] fields; //fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); fields = target.GetType().GetFields(BindingFlags.Public); tx = target.GetType(); obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] {}); return obj; } private object SetField(Type t, string name, object value, object target) { object obj; obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] {value}); return obj; } private bool SetProperty(object obj, string propertyName, object val) { try { // get a reference to the PropertyInfo, exit if no property with that // name PropertyInfo pi = typeof (AssociativeEntity).GetProperty(propertyName); if (pi == null) return false; // convert the value to the expected type val = Convert.ChangeType(val, pi.PropertyType); // attempt the assignment foreach (AssociativeEntity bo in (AssociativeEntity[]) obj) pi.SetValue(bo, val, null); return true; } catch { return false; } } private object GetProperty(object obj, string propertyName, object defaultValue) { try { PropertyInfo pi = GetPropertyInfoCache(propertyName); if (!(pi == null)) { var objs = (AssociativeEntity[]) obj; var valueList = new ArrayList(); foreach (AssociativeEntity bo in objs) { object value = pi.GetValue(bo, null); if (!valueList.Contains(value)) { valueList.Add(value); } } switch (valueList.Count) { case 1: return valueList[0]; default: return string.Empty; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } // if property doesn't exist or throws return defaultValue; } #endregion #region ICustomTypeDescriptor explicit interface definitions // Most of the functions required by the ICustomTypeDescriptor are // merely pssed on to the default TypeDescriptor for this type, // which will do something appropriate. The exceptions are noted // below. AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(this, true); } string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(this, true); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { // This function searches the property list for the property // with the same name as the DefaultProperty specified, and // returns a property descriptor for it. If no property is // found that matches DefaultProperty, a null reference is // returned instead. PropertySpec propertySpec = null; if (_defaultProperty != null) { int index = _properties.IndexOf(_defaultProperty); propertySpec = _properties[index]; } if (propertySpec != null) return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null); return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor) this).GetProperties(new Attribute[0]); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { // Rather than passing this function on to the default TypeDescriptor, // which would return the actual properties of AssociativeEntityPropertyBag, I construct // a list here that contains property descriptors for the elements of the // Properties list in the bag. var props = new ArrayList(); foreach (PropertySpec property in _properties) { var attrs = new ArrayList(); // If a category, description, editor, or type converter are specified // in the PropertySpec, create attributes to define that relationship. if (property.Category != null) attrs.Add(new CategoryAttribute(property.Category)); if (property.Description != null) attrs.Add(new DescriptionAttribute(property.Description)); if (property.EditorTypeName != null) attrs.Add(new EditorAttribute(property.EditorTypeName, typeof (UITypeEditor))); if (property.ConverterTypeName != null) attrs.Add(new TypeConverterAttribute(property.ConverterTypeName)); // Additionally, append the custom attributes associated with the // PropertySpec, if any. if (property.Attributes != null) attrs.AddRange(property.Attributes); if (property.DefaultValue != null) attrs.Add(new DefaultValueAttribute(property.DefaultValue)); attrs.Add(new BrowsableAttribute(property.Browsable)); attrs.Add(new ReadOnlyAttribute(property.ReadOnly)); attrs.Add(new BindableAttribute(property.Bindable)); var attrArray = (Attribute[]) attrs.ToArray(typeof (Attribute)); // Create a new property descriptor for the property item, and add // it to the list. var pd = new PropertySpecDescriptor(property, this, property.Name, attrArray); props.Add(pd); } // Convert the list of PropertyDescriptors to a collection that the // ICustomTypeDescriptor can use, and return it. var propArray = (PropertyDescriptor[]) props.ToArray( typeof (PropertyDescriptor)); return new PropertyDescriptorCollection(propArray); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion } }
/* * The MIT License (MIT) * * Copyright (c) 2014 Alistair Leslie-Hughes * * 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.Net; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Microsoft.DirectX.DirectPlay { public class Address : MarshalByRefObject, IDisposable, ICloneable { public const int DpnServerPort = 6073; public const int IndexInvalid = -1; public const int TraversalModeNone = 0; public const int TraversalModePortRequired = 1; public const int TraversalModePortRecommended = 2; public static string SeparatorKeyValue; public static string SeparatorUserdata; public static string SeparatorComponent; public static string EscapeChar; public static string Header; public static string KeyNatResolver; public static string KeyNatResolverUserString; public static string KeyApplicationInstance; public static string KeyTraversalMode; public static string KeyDevice; public static string KeyHostname; public static string KeyPort; public static string KeyProcessor; public static string KeyProgram; public static string KeyProvider; public static string KeyScope; public static string KeyBaud; public static string KeyFlowControl; public static string KeyParity; public static string KeyPhoneNumber; public static string KeyStopBits; public const int BaudRate9600 = 9600; public const int BaudRate14400 = 14400; public const int BaudRate19200 = 19200; public const int BaudRate38400 = 38400; public const int BaudRate56000 = 56000; public const int BaudRate57600 = 57600; public const int BaudRate115200 = 115200; public static string StopBitsOne; public static string StopBitsOneFive; public static string StopBitsTwo; public static string ParityNone; public static string ParityEven; public static string ParityOdd; public static string ParityMark; public static string ParitySpace; public static string FlowControlNone; public static string FlowControlXonXoff; public static string FlowControlControlRts; public static string FlowControlDtr; public static string FlowControlRtsDtr; public static string TcpIpProvider; public static string IpxProvider; public static string ModemProvider; public static string SerialProvider; public static readonly Guid ServiceProviderIpx; public static readonly Guid ServiceProviderModem; public static readonly Guid ServiceProviderSerial; public static readonly Guid ServiceProviderTcpIp; public static readonly Guid ServiceProviderBlueTooth; internal bool m_bDisposed; public event EventHandler Disposing { [MethodImpl(32)] add { throw new NotImplementedException (); } [MethodImpl(32)] remove { throw new NotImplementedException (); } } public bool Disposed { [return: MarshalAs(4)] get { throw new NotImplementedException (); } } public int NumberComponents { get { throw new NotImplementedException (); } } public IntPtr UserData { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public string Url { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Guid Device { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } public Guid ServiceProvider { get { throw new NotImplementedException (); } set { throw new NotImplementedException (); } } static Address () { } [return: MarshalAs(4)] public bool Equals (Address address) { throw new NotImplementedException (); } [return: MarshalAs(4)] public override bool Equals (object compare) { throw new NotImplementedException (); } [return: MarshalAs(4)] public static bool operator == (Address left, Address right) { throw new NotImplementedException (); } [return: MarshalAs(4)] public static bool operator != (Address left, Address right) { throw new NotImplementedException (); } public override int GetHashCode () { throw new NotImplementedException (); } public void Dispose () { throw new NotImplementedException (); } public Address (IPEndPoint address) { throw new NotImplementedException (); } public Address (IPAddress address) { throw new NotImplementedException (); } public Address (string hostname, int port) { throw new NotImplementedException (); } public Address () { } public void SetEqual (Address address) { throw new NotImplementedException (); } public void AddComponent (string keyName, byte[] value) { throw new NotImplementedException (); } public void AddComponent (string keyName, Guid value) { throw new NotImplementedException (); } public void AddComponent (string keyName, string value) { throw new NotImplementedException (); } public void AddComponent (string keyName, int iValue) { throw new NotImplementedException (); } public int GetComponentInteger (string keyName) { throw new NotImplementedException (); } public string GetComponentString (string keyName) { throw new NotImplementedException (); } public Guid GetComponentGuid (string keyName) { throw new NotImplementedException (); } public byte[] GetComponentBinary (string keyName) { throw new NotImplementedException (); } public void Clear () { throw new NotImplementedException (); } public object Clone () { throw new NotImplementedException (); } [MethodImpl(32)] protected void raise_Disposing (object i1, EventArgs i2) { } } }
namespace AutoMapper { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Configuration; using Execution; /// <summary> /// Main configuration object holding all mapping configuration for a source and destination type /// </summary> [DebuggerDisplay("{SourceType.Name} -> {DestinationType.Name}")] public class TypeMap { private readonly List<LambdaExpression> _afterMapActions = new List<LambdaExpression>(); private readonly List<LambdaExpression> _beforeMapActions = new List<LambdaExpression>(); private readonly HashSet<TypePair> _includedDerivedTypes = new HashSet<TypePair>(); private readonly HashSet<TypePair> _includedBaseTypes = new HashSet<TypePair>(); private readonly ConcurrentBag<PropertyMap> _propertyMaps = new ConcurrentBag<PropertyMap>(); private readonly ConcurrentBag<SourceMemberConfig> _sourceMemberConfigs = new ConcurrentBag<SourceMemberConfig>(); private readonly IList<PropertyMap> _inheritedMaps = new List<PropertyMap>(); private PropertyMap[] _orderedPropertyMaps; private bool _sealed; public bool Sealed => _sealed; private readonly IList<TypeMap> _inheritedTypeMaps = new List<TypeMap>(); public TypeMap(TypeDetails sourceType, TypeDetails destinationType, MemberList memberList, IProfileConfiguration profile) { SourceTypeDetails = sourceType; DestinationTypeDetails = destinationType; Types = new TypePair(sourceType.Type, destinationType.Type); Profile = profile; ConfiguredMemberList = memberList; IgnorePropertiesStartingWith = profile.GlobalIgnores; } public LambdaExpression MapExpression { get; private set; } public TypePair Types { get; } public ConstructorMap ConstructorMap { get; set; } public TypeDetails SourceTypeDetails { get; } public TypeDetails DestinationTypeDetails { get; } public Type SourceType => SourceTypeDetails.Type; public Type DestinationType => DestinationTypeDetails.Type; public IProfileConfiguration Profile { get; } public LambdaExpression CustomMapper { get; set; } public LambdaExpression CustomProjection { get; set; } public LambdaExpression DestinationCtor { get; set; } public IEnumerable<string> IgnorePropertiesStartingWith { get; set; } public Type DestinationTypeOverride { get; set; } public Type DestinationTypeToUse => DestinationTypeOverride ?? DestinationType; public bool ConstructDestinationUsingServiceLocator { get; set; } public MemberList ConfiguredMemberList { get; } public IEnumerable<TypePair> IncludedDerivedTypes => _includedDerivedTypes; public IEnumerable<TypePair> IncludedBaseTypes => _includedBaseTypes; public IEnumerable<LambdaExpression> BeforeMapActions => _beforeMapActions; public IEnumerable<LambdaExpression> AfterMapActions => _afterMapActions; public bool PreserveReferences { get; set; } public LambdaExpression Condition { get; set; } public int MaxDepth { get; set; } public LambdaExpression Substitution { get; set; } public LambdaExpression ConstructExpression { get; set; } public Type TypeConverterType { get; set; } public PropertyMap[] GetPropertyMaps() { return _orderedPropertyMaps ?? _propertyMaps.Concat(_inheritedMaps).ToArray(); } public void AddPropertyMap(IMemberAccessor destProperty, IEnumerable<IMemberGetter> resolvers) { var propertyMap = new PropertyMap(destProperty, this); propertyMap.ChainMembers(resolvers); _propertyMaps.Add(propertyMap); } public string[] GetUnmappedPropertyNames() { Func<PropertyMap, string> getFunc = pm => ConfiguredMemberList == MemberList.Destination ? pm.DestinationProperty.Name : pm.CustomExpression == null && pm.SourceMember != null ? pm.SourceMember.Name : pm.DestinationProperty.Name; var autoMappedProperties = _propertyMaps.Where(pm => pm.IsMapped()) .Select(getFunc).ToList(); var inheritedProperties = _inheritedMaps.Where(pm => pm.IsMapped()) .Select(getFunc).ToList(); IEnumerable<string> properties; if (ConfiguredMemberList == MemberList.Destination) { properties = DestinationTypeDetails.PublicWriteAccessors .Select(p => p.Name) .Except(autoMappedProperties) .Except(inheritedProperties); } else { var redirectedSourceMembers = _propertyMaps .Where(pm => pm.IsMapped() && pm.SourceMember != null && pm.SourceMember.Name != pm.DestinationProperty.Name) .Select(pm => pm.SourceMember.Name); var ignoredSourceMembers = _sourceMemberConfigs .Where(smc => smc.IsIgnored()) .Select(pm => pm.SourceMember.Name).ToList(); properties = SourceTypeDetails.PublicReadAccessors .Select(p => p.Name) .Except(autoMappedProperties) .Except(inheritedProperties) .Except(redirectedSourceMembers) .Except(ignoredSourceMembers); } return properties.Where(memberName => !IgnorePropertiesStartingWith.Any(memberName.StartsWith)).ToArray(); } public PropertyMap FindOrCreatePropertyMapFor(IMemberAccessor destinationProperty) { var propertyMap = GetExistingPropertyMapFor(destinationProperty); if (propertyMap != null) return propertyMap; propertyMap = new PropertyMap(destinationProperty, this); _propertyMaps.Add(propertyMap); return propertyMap; } public void IncludeDerivedTypes(Type derivedSourceType, Type derivedDestinationType) { var derivedTypes = new TypePair(derivedSourceType, derivedDestinationType); if (derivedTypes.Equals(Types)) { throw new InvalidOperationException("You cannot include a type map into itself."); } _includedDerivedTypes.Add(derivedTypes); } public void IncludeBaseTypes(Type baseSourceType, Type baseDestinationType) { var baseTypes = new TypePair(baseSourceType, baseDestinationType); if (baseTypes.Equals(Types)) { throw new InvalidOperationException("You cannot include a type map into itself."); } _includedBaseTypes.Add(baseTypes); } public Type GetDerivedTypeFor(Type derivedSourceType) { if (DestinationTypeOverride != null) { return DestinationTypeOverride; } // This might need to be fixed for multiple derived source types to different dest types var match = _includedDerivedTypes.FirstOrDefault(tp => tp.SourceType == derivedSourceType); return match.DestinationType ?? DestinationType; } public bool TypeHasBeenIncluded(TypePair derivedTypes) { return _includedDerivedTypes.Contains(derivedTypes); } public bool HasDerivedTypesToInclude() { return _includedDerivedTypes.Any() || DestinationTypeOverride != null; } public void AddBeforeMapAction(LambdaExpression beforeMap) { _beforeMapActions.Add(beforeMap); } public void AddAfterMapAction(LambdaExpression afterMap) { _afterMapActions.Add(afterMap); } public void Seal(TypeMapRegistry typeMapRegistry, IConfigurationProvider configurationProvider) { if (_sealed) return; foreach (var inheritedTypeMap in _inheritedTypeMaps) { ApplyInheritedTypeMap(inheritedTypeMap); } _orderedPropertyMaps = _propertyMaps .Union(_inheritedMaps) .OrderBy(map => map.MappingOrder).ToArray(); MapExpression = TypeMapPlanBuilder.BuildMapperFunc(this, configurationProvider, typeMapRegistry); _sealed = true; } public PropertyMap GetExistingPropertyMapFor(IMemberAccessor destinationProperty) { var propertyMap = _propertyMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name)); if (propertyMap != null) return propertyMap; propertyMap = _inheritedMaps.FirstOrDefault(pm => pm.DestinationProperty.Name.Equals(destinationProperty.Name)); if (propertyMap == null) return null; var propertyInfo = propertyMap.DestinationProperty.MemberInfo as PropertyInfo; if (propertyInfo == null) return propertyMap; var baseAccessor = propertyInfo.GetMethod; if (baseAccessor.IsAbstract || baseAccessor.IsVirtual) return propertyMap; var accessor = ((PropertyInfo)destinationProperty.MemberInfo).GetMethod; if (baseAccessor.DeclaringType == accessor.DeclaringType) return propertyMap; return null; } public void InheritTypes(TypeMap inheritedTypeMap) { foreach (var includedDerivedType in inheritedTypeMap._includedDerivedTypes .Where(includedDerivedType => !_includedDerivedTypes.Contains(includedDerivedType))) { _includedDerivedTypes.Add(includedDerivedType); } } public SourceMemberConfig FindOrCreateSourceMemberConfigFor(MemberInfo sourceMember) { var config = _sourceMemberConfigs.FirstOrDefault(smc => Equals(smc.SourceMember, sourceMember)); if (config != null) return config; config = new SourceMemberConfig(sourceMember); _sourceMemberConfigs.Add(config); return config; } public void ApplyInheritedMap(TypeMap inheritedTypeMap) { _inheritedTypeMaps.Add(inheritedTypeMap); } public bool ShouldCheckForValid() { return CustomMapper == null && CustomProjection == null && TypeConverterType == null && DestinationTypeOverride == null; } private void ApplyInheritedTypeMap(TypeMap inheritedTypeMap) { foreach (var inheritedMappedProperty in inheritedTypeMap.GetPropertyMaps().Where(m => m.IsMapped())) { var conventionPropertyMap = GetPropertyMaps() .SingleOrDefault(m => m.DestinationProperty.Name == inheritedMappedProperty.DestinationProperty.Name); if (conventionPropertyMap != null) { conventionPropertyMap.ApplyInheritedPropertyMap(inheritedMappedProperty); } else { var propertyMap = new PropertyMap(inheritedMappedProperty, this); _inheritedMaps.Add(propertyMap); } } //Include BeforeMap foreach (var beforeMapAction in inheritedTypeMap._beforeMapActions) { AddBeforeMapAction(beforeMapAction); } //Include AfterMap foreach (var afterMapAction in inheritedTypeMap._afterMapActions) { AddAfterMapAction(afterMapAction); } } } }
/* * Yeppp! library implementation * * This file is part of Yeppp! library and licensed under the New BSD license. * See LICENSE.txt for the full text of the license. */ namespace Yeppp { /// <summary>Type of processor microarchitecture.</summary> /// <remarks>Low-level instruction performance characteristics, such as latency and throughput, are constant within microarchitecture.</remarks> /// <remarks>Processors of the same microarchitecture can differ in supported instruction sets and other extensions.</remarks> /// <seealso cref="Library.GetCpuMicroarchitecture" /> public struct CpuMicroarchitecture { /// <summary>Microarchitecture is unknown, or the library failed to get information about the microarchitecture from OS</summary> public static readonly CpuMicroarchitecture Unknown = new CpuMicroarchitecture(0); /// <summary>Pentium and Pentium MMX microarchitecture.</summary> public static readonly CpuMicroarchitecture P5 = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0001); /// <summary>Pentium Pro, Pentium II, and Pentium III.</summary> public static readonly CpuMicroarchitecture P6 = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0002); /// <summary>Pentium 4 with Willamette, Northwood, or Foster cores.</summary> public static readonly CpuMicroarchitecture Willamette = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0003); /// <summary>Pentium 4 with Prescott and later cores.</summary> public static readonly CpuMicroarchitecture Prescott = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0004); /// <summary>Pentium M.</summary> public static readonly CpuMicroarchitecture Dothan = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0005); /// <summary>Intel Core microarchitecture.</summary> public static readonly CpuMicroarchitecture Yonah = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0006); /// <summary>Intel Core 2 microarchitecture on 65 nm process.</summary> public static readonly CpuMicroarchitecture Conroe = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0007); /// <summary>Intel Core 2 microarchitecture on 45 nm process.</summary> public static readonly CpuMicroarchitecture Penryn = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0008); /// <summary>Intel Atom on 45 nm process.</summary> public static readonly CpuMicroarchitecture Bonnell = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0009); /// <summary>Intel Nehalem and Westmere microarchitectures (Core i3/i5/i7 1st gen).</summary> public static readonly CpuMicroarchitecture Nehalem = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x000A); /// <summary>Intel Sandy Bridge microarchitecture (Core i3/i5/i7 2nd gen).</summary> public static readonly CpuMicroarchitecture SandyBridge = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x000B); /// <summary>Intel Atom on 32 nm process.</summary> public static readonly CpuMicroarchitecture Saltwell = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x000C); /// <summary>Intel Ivy Bridge microarchitecture (Core i3/i5/i7 3rd gen).</summary> public static readonly CpuMicroarchitecture IvyBridge = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x000D); /// <summary>Intel Haswell microarchitecture (Core i3/i5/i7 4th gen).</summary> public static readonly CpuMicroarchitecture Haswell = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x000E); /// <summary> Intel Silvermont microarchitecture (22 nm out-of-order Atom).</summary> public static readonly CpuMicroarchitecture Silvermont = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x000F); /// <summary>Intel Knights Ferry HPC boards.</summary> public static readonly CpuMicroarchitecture KnightsFerry = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0100); /// <summary>Intel Knights Corner HPC boards (aka Xeon Phi).</summary> public static readonly CpuMicroarchitecture KnightsCorner = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0101); /// <summary>AMD K5.</summary> public static readonly CpuMicroarchitecture K5 = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.AMD.Id << 16) + 0x0001); /// <summary>AMD K6 and alike.</summary> public static readonly CpuMicroarchitecture K6 = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.AMD.Id << 16) + 0x0002); /// <summary>AMD Athlon and Duron.</summary> public static readonly CpuMicroarchitecture K7 = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.AMD.Id << 16) + 0x0003); /// <summary>AMD Geode GX and LX.</summary> public static readonly CpuMicroarchitecture Geode = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.AMD.Id << 16) + 0x0004); /// <summary>AMD Athlon 64, Opteron 64.</summary> public static readonly CpuMicroarchitecture K8 = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.AMD.Id << 16) + 0x0005); /// <summary>AMD K10 (Barcelona, Istambul, Magny-Cours).</summary> public static readonly CpuMicroarchitecture K10 = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.AMD.Id << 16) + 0x0006); /// <summary>AMD Bobcat mobile microarchitecture.</summary> public static readonly CpuMicroarchitecture Bobcat = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.AMD.Id << 16) + 0x0007); /// <summary>AMD Bulldozer microarchitecture (1st gen K15).</summary> public static readonly CpuMicroarchitecture Bulldozer = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.AMD.Id << 16) + 0x0008); /// <summary>AMD Piledriver microarchitecture (2nd gen K15).</summary> public static readonly CpuMicroarchitecture Piledriver = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.AMD.Id << 16) + 0x0009); /// <summary>AMD Jaguar mobile microarchitecture.</summary> public static readonly CpuMicroarchitecture Jaguar = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.AMD.Id << 16) + 0x000A); /// <summary>AMD Steamroller microarchitecture (3rd gen K15).</summary> public static readonly CpuMicroarchitecture Steamroller = new CpuMicroarchitecture((CpuArchitecture.X86.Id << 24) + (CpuVendor.AMD.Id << 16) + 0x000B); /// <summary>DEC/Intel StrongARM processors.</summary> public static readonly CpuMicroarchitecture StrongARM = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0001); /// <summary>Intel/Marvell XScale processors.</summary> public static readonly CpuMicroarchitecture XScale = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0002); /// <summary>ARM7 series.</summary> public static readonly CpuMicroarchitecture ARM7 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.ARM.Id << 16) + 0x0001); /// <summary>ARM9 series.</summary> public static readonly CpuMicroarchitecture ARM9 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.ARM.Id << 16) + 0x0002); /// <summary>ARM 1136, ARM 1156, ARM 1176, or ARM 11MPCore.</summary> public static readonly CpuMicroarchitecture ARM11 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.ARM.Id << 16) + 0x0003); /// <summary>ARM Cortex-A5.</summary> public static readonly CpuMicroarchitecture CortexA5 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.ARM.Id << 16) + 0x0004); /// <summary>ARM Cortex-A7.</summary> public static readonly CpuMicroarchitecture CortexA7 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.ARM.Id << 16) + 0x0005); /// <summary>ARM Cortex-A8.</summary> public static readonly CpuMicroarchitecture CortexA8 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.ARM.Id << 16) + 0x0006); /// <summary>ARM Cortex-A9.</summary> public static readonly CpuMicroarchitecture CortexA9 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.ARM.Id << 16) + 0x0007); /// <summary>ARM Cortex-A15.</summary> public static readonly CpuMicroarchitecture CortexA15 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.ARM.Id << 16) + 0x0008); /// <summary>ARM Cortex-A12.</summary> public static readonly CpuMicroarchitecture CortexA12 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.ARM.Id << 16) + 0x0009); /// <summary>ARM Cortex-A53.</summary> public static readonly CpuMicroarchitecture CortexA53 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.ARM.Id << 16) + 0x000A); /// <summary>ARM Cortex-A57.</summary> public static readonly CpuMicroarchitecture CortexA57 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.ARM.Id << 16) + 0x000B); /// <summary>Qualcomm Scorpion.</summary> public static readonly CpuMicroarchitecture Scorpion = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.Qualcomm.Id << 16) + 0x0001); /// <summary>Qualcomm Krait.</summary> public static readonly CpuMicroarchitecture Krait = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.Qualcomm.Id << 16) + 0x0002); /// <summary>Marvell Sheeva PJ1.</summary> public static readonly CpuMicroarchitecture PJ1 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.Marvell.Id << 16) + 0x0001); /// <summary>Marvell Sheeva PJ4.</summary> public static readonly CpuMicroarchitecture PJ4 = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.Marvell.Id << 16) + 0x0002); /// <summary>Apple A6 and A6X processors.</summary> public static readonly CpuMicroarchitecture Swift = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.Apple.Id << 16) + 0x0001); /// <summary>Apple A7 processor.</summary> public static readonly CpuMicroarchitecture Cyclone = new CpuMicroarchitecture((CpuArchitecture.ARM.Id << 24) + (CpuVendor.Apple.Id << 16) + 0x0002); /// <summary>Intel Itanium.</summary> public static readonly CpuMicroarchitecture Itanium = new CpuMicroarchitecture((CpuArchitecture.IA64.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0001); /// <summary>Intel Itanium 2.</summary> public static readonly CpuMicroarchitecture Itanium2 = new CpuMicroarchitecture((CpuArchitecture.IA64.Id << 24) + (CpuVendor.Intel.Id << 16) + 0x0002); /// <summary>MIPS 24K.</summary> public static readonly CpuMicroarchitecture MIPS24K = new CpuMicroarchitecture((CpuArchitecture.MIPS.Id << 24) + (CpuVendor.MIPS.Id << 16) + 0x0001); /// <summary>MIPS 34K.</summary> public static readonly CpuMicroarchitecture MIPS34K = new CpuMicroarchitecture((CpuArchitecture.MIPS.Id << 24) + (CpuVendor.MIPS.Id << 16) + 0x0002); /// <summary>MIPS 74K.</summary> public static readonly CpuMicroarchitecture MIPS74K = new CpuMicroarchitecture((CpuArchitecture.MIPS.Id << 24) + (CpuVendor.MIPS.Id << 16) + 0x0003); /// <summary>Ingenic XBurst.</summary> public static readonly CpuMicroarchitecture XBurst = new CpuMicroarchitecture((CpuArchitecture.MIPS.Id << 24) + (CpuVendor.Ingenic.Id << 16) + 0x0001); /// <summary>Ingenic XBurst 2.</summary> public static readonly CpuMicroarchitecture XBurst2 = new CpuMicroarchitecture((CpuArchitecture.MIPS.Id << 24) + (CpuVendor.Ingenic.Id << 16) + 0x0002); /// <summary>IBM PowerPC 970 (PowerPC G5).</summary> public static readonly CpuMicroarchitecture PowerPC970 = new CpuMicroarchitecture((CpuArchitecture.PowerPC.Id << 24) + (CpuVendor.IBM.Id << 16) + 0x0021); /// <summary>IBM POWER 4.</summary> public static readonly CpuMicroarchitecture POWER4 = new CpuMicroarchitecture((CpuArchitecture.PowerPC.Id << 24) + (CpuVendor.IBM.Id << 16) + 0x011F); /// <summary>IBM POWER 5.</summary> public static readonly CpuMicroarchitecture POWER5 = new CpuMicroarchitecture((CpuArchitecture.PowerPC.Id << 24) + (CpuVendor.IBM.Id << 16) + 0x0120); /// <summary>IBM POWER 6.</summary> public static readonly CpuMicroarchitecture POWER6 = new CpuMicroarchitecture((CpuArchitecture.PowerPC.Id << 24) + (CpuVendor.IBM.Id << 16) + 0x0121); /// <summary>IBM POWER 7.</summary> public static readonly CpuMicroarchitecture POWER7 = new CpuMicroarchitecture((CpuArchitecture.PowerPC.Id << 24) + (CpuVendor.IBM.Id << 16) + 0x0122); /// <summary>IBM POWER 8.</summary> public static readonly CpuMicroarchitecture POWER8 = new CpuMicroarchitecture((CpuArchitecture.PowerPC.Id << 24) + (CpuVendor.IBM.Id << 16) + 0x0123); /// <summary>IBM PowerPC 440 (Blue Gene/L processor).</summary> public static readonly CpuMicroarchitecture PowerPC440 = new CpuMicroarchitecture((CpuArchitecture.PowerPC.Id << 24) + (CpuVendor.IBM.Id << 16) + 0x0200); /// <summary>IBM PowerPC 450 (Blue Gene/P processor).</summary> public static readonly CpuMicroarchitecture PowerPC450 = new CpuMicroarchitecture((CpuArchitecture.PowerPC.Id << 24) + (CpuVendor.IBM.Id << 16) + 0x0201); /// <summary>IBM PowerPC A2 (Blue Gene/Q processor).</summary> public static readonly CpuMicroarchitecture PowerPCA2 = new CpuMicroarchitecture((CpuArchitecture.PowerPC.Id << 24) + (CpuVendor.IBM.Id << 16) + 0x0202); /// <summary>P.A.Semi PWRficient.</summary> public static readonly CpuMicroarchitecture PWRficient = new CpuMicroarchitecture((CpuArchitecture.PowerPC.Id << 24) + (CpuVendor.PASemi.Id << 16) + 0x0001); private readonly uint id; internal CpuMicroarchitecture(uint id) { this.id = id; } internal uint Id { get { return this.id; } } /// <summary>Compares for equality with another <see cref="CpuMicroarchitecture" /> object.</summary> /// <remarks>Comparison is performed by value.</remarks> public bool Equals(CpuMicroarchitecture other) { return this.id == other.id; } /// <summary>Compares for equality with another object.</summary> /// <remarks>Comparison is performed by value.</remarks> public override bool Equals(System.Object other) { if (other == null || GetType() != other.GetType()) return false; return this.Equals((CpuMicroarchitecture)other); } /// <summary>Provides a hash for the object.</summary> /// <remarks>Non-equal <see cref="CpuMicroarchitecture" /> objects are guaranteed to have different hashes.</remarks> public override int GetHashCode() { return unchecked((int)this.id); } /// <summary>Provides a string ID for the object.</summary> /// <remarks>The string ID starts with a Latin letter and contains only Latin letters, digits, and underscore symbol.</remarks> /// <seealso cref="Description" /> public override string ToString() { return Library.GetString(Enumeration.CpuMicroarchitecture, this.id, StringType.ID); } /// <summary>Provides a description for the object.</summary> /// <remarks>The description can contain spaces and non-ASCII characters.</remarks> /// <seealso cref="ToString()" /> public string Description { get { return Library.GetString(Enumeration.CpuMicroarchitecture, this.id, StringType.Description); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Notification; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal class SymbolSpecificationViewModel : AbstractNotifyPropertyChanged { public Guid ID { get; set; } public List<SymbolKindViewModel> SymbolKindList { get; set; } public List<AccessibilityViewModel> AccessibilityList { get; set; } public List<ModifierViewModel> ModifierList { get; set; } public List<CustomTagViewModel> CustomTagList { get; set; } private string _symbolSpecName; public string SymbolSpecName { get { return _symbolSpecName; } set { SetProperty(ref _symbolSpecName, value); } } private readonly INotificationService _notificationService; public SymbolSpecificationViewModel(string languageName, ImmutableArray<string> categories, INotificationService notificationService) : this(languageName, categories, new SymbolSpecification(), notificationService) { } public SymbolSpecificationViewModel(string languageName, ImmutableArray<string> categories, SymbolSpecification specification, INotificationService notificationService) { _notificationService = notificationService; SymbolSpecName = specification.Name; ID = specification.ID; CustomTagList = new List<CustomTagViewModel>(); foreach (var category in categories) { CustomTagList.Add(new CustomTagViewModel(category, specification)); } // The list of supported SymbolKinds is limited due to https://github.com/dotnet/roslyn/issues/8753. if (languageName == LanguageNames.CSharp) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(TypeKind.Class, "class", specification), new SymbolKindViewModel(TypeKind.Struct, "struct", specification), new SymbolKindViewModel(TypeKind.Interface, "interface", specification), new SymbolKindViewModel(TypeKind.Enum, "enum", specification), new SymbolKindViewModel(SymbolKind.Property, "property", specification), new SymbolKindViewModel(SymbolKind.Method, "method", specification), new SymbolKindViewModel(SymbolKind.Field, "field", specification), new SymbolKindViewModel(SymbolKind.Event, "event", specification), new SymbolKindViewModel(SymbolKind.Namespace, "namespace", specification), new SymbolKindViewModel(TypeKind.Delegate, "delegate", specification), new SymbolKindViewModel(TypeKind.TypeParameter, "type parameter", specification), }; AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "public", specification), new AccessibilityViewModel(Accessibility.Internal, "internal", specification), new AccessibilityViewModel(Accessibility.Private, "private", specification), new AccessibilityViewModel(Accessibility.Protected, "protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "protected internal", specification), }; ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "abstract", specification), new ModifierViewModel(DeclarationModifiers.Async, "async", specification), new ModifierViewModel(DeclarationModifiers.Const, "const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "readonly", specification), new ModifierViewModel(DeclarationModifiers.Static, "static", specification) }; } else if (languageName == LanguageNames.VisualBasic) { SymbolKindList = new List<SymbolKindViewModel> { new SymbolKindViewModel(TypeKind.Class, "Class", specification), new SymbolKindViewModel(TypeKind.Struct, "Structure", specification), new SymbolKindViewModel(TypeKind.Interface, "Interface", specification), new SymbolKindViewModel(TypeKind.Enum, "Enum", specification), new SymbolKindViewModel(TypeKind.Module, "Module", specification), new SymbolKindViewModel(SymbolKind.Property, "Property", specification), new SymbolKindViewModel(SymbolKind.Method, "Method", specification), new SymbolKindViewModel(SymbolKind.Field, "Field", specification), new SymbolKindViewModel(SymbolKind.Event, "Event", specification), new SymbolKindViewModel(SymbolKind.Namespace, "Namespace", specification), new SymbolKindViewModel(TypeKind.Delegate, "Delegate", specification), new SymbolKindViewModel(TypeKind.TypeParameter, "Type Parameter", specification), }; AccessibilityList = new List<AccessibilityViewModel> { new AccessibilityViewModel(Accessibility.Public, "Public", specification), new AccessibilityViewModel(Accessibility.Friend, "Friend", specification), new AccessibilityViewModel(Accessibility.Private, "Private", specification), new AccessibilityViewModel(Accessibility.Protected , "Protected", specification), new AccessibilityViewModel(Accessibility.ProtectedOrInternal, "Protected Friend", specification), }; ModifierList = new List<ModifierViewModel> { new ModifierViewModel(DeclarationModifiers.Abstract, "MustInherit", specification), new ModifierViewModel(DeclarationModifiers.Async, "Async", specification), new ModifierViewModel(DeclarationModifiers.Const, "Const", specification), new ModifierViewModel(DeclarationModifiers.ReadOnly, "ReadOnly", specification), new ModifierViewModel(DeclarationModifiers.Static, "Shared", specification) }; } else { throw new ArgumentException(string.Format("Unexpected language name: {0}", languageName), nameof(languageName)); } } internal SymbolSpecification GetSymbolSpecification() { return new SymbolSpecification( ID, SymbolSpecName, SymbolKindList.Where(s => s.IsChecked).Select(s => s.CreateSymbolKindOrTypeKind()).ToList(), AccessibilityList.Where(a => a.IsChecked).Select(a => new SymbolSpecification.AccessibilityKind(a._accessibility)).ToList(), ModifierList.Where(m => m.IsChecked).Select(m => new SymbolSpecification.ModifierKind(m._modifier)).ToList(), CustomTagList.Where(t => t.IsChecked).Select(t => t.Name).ToList()); } internal interface ISymbolSpecificationViewModelPart { bool IsChecked { get; set; } } public class SymbolKindViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } private readonly SymbolKind? _symbolKind; private readonly TypeKind? _typeKind; private bool _isChecked; public SymbolKindViewModel(SymbolKind symbolKind, string name, SymbolSpecification specification) { this._symbolKind = symbolKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.SymbolKind == symbolKind); } public SymbolKindViewModel(TypeKind typeKind, string name, SymbolSpecification specification) { this._typeKind = typeKind; Name = name; IsChecked = specification.ApplicableSymbolKindList.Any(k => k.TypeKind == typeKind); } internal SymbolSpecification.SymbolKindOrTypeKind CreateSymbolKindOrTypeKind() { if (_symbolKind.HasValue) { return new SymbolSpecification.SymbolKindOrTypeKind(_symbolKind.Value); } else { return new SymbolSpecification.SymbolKindOrTypeKind(_typeKind.Value); } } } public class AccessibilityViewModel: AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { internal readonly Accessibility _accessibility; public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } public AccessibilityViewModel(Accessibility accessibility, string name, SymbolSpecification specification) { _accessibility = accessibility; Name = name; IsChecked = specification.ApplicableAccessibilityList.Any(a => a.Accessibility == accessibility); } } public class ModifierViewModel: AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } internal readonly DeclarationModifiers _modifier; public ModifierViewModel(DeclarationModifiers modifier, string name, SymbolSpecification specification) { this._modifier = modifier; Name = name; IsChecked = specification.RequiredModifierList.Any(m => m.Modifier == modifier); } } public class CustomTagViewModel : AbstractNotifyPropertyChanged, ISymbolSpecificationViewModelPart { public string Name { get; set; } private bool _isChecked; public bool IsChecked { get { return _isChecked; } set { SetProperty(ref _isChecked, value); } } public CustomTagViewModel(string name, SymbolSpecification specification) { Name = name; IsChecked = specification.RequiredCustomTagList.Contains(name); } } internal bool TrySubmit() { if (string.IsNullOrWhiteSpace(SymbolSpecName)) { _notificationService.SendNotification(ServicesVSResources.Enter_a_title_for_this_Symbol_Specification); return false; } return true; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: pbx_connector/mitel_call_ended.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.PBXConnector { /// <summary>Holder for reflection information generated from pbx_connector/mitel_call_ended.proto</summary> public static partial class MitelCallEndedReflection { #region Descriptor /// <summary>File descriptor for pbx_connector/mitel_call_ended.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static MitelCallEndedReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiRwYnhfY29ubmVjdG9yL21pdGVsX2NhbGxfZW5kZWQucHJvdG8SGWhvbG1z", "LnR5cGVzLnBieF9jb25uZWN0b3IaHmdvb2dsZS9wcm90b2J1Zi9kdXJhdGlv", "bi5wcm90bxofZ29vZ2xlL3Byb3RvYnVmL3RpbWVzdGFtcC5wcm90byJ3ChFN", "aXRlbFBob25lQ2lyY3VpdBJGCgxjaXJjdWl0X3R5cGUYASABKA4yMC5ob2xt", "cy50eXBlcy5wYnhfY29ubmVjdG9yLk1pdGVsUGhvbmVDaXJjdWl0VHlwZRIa", "ChJjaXJjdWl0X2lkZW50aWZpZXIYAiABKAkiswIKDk1pdGVsQ2FsbEVuZGVk", "Ei4KCnN0YXJ0X3RpbWUYASABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0", "YW1wEisKCGR1cmF0aW9uGAIgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0", "aW9uEkEKC2NhbGxfb3JpZ2luGAMgASgLMiwuaG9sbXMudHlwZXMucGJ4X2Nv", "bm5lY3Rvci5NaXRlbFBob25lQ2lyY3VpdBIdChVsZWFkaW5nX2RpZ2l0c19k", "aWFsZWQYBCABKAkSGgoSbWFpbl9kaWdpdHNfZGlhbGVkGAUgASgJEkYKEGNh", "bGxfZGVzdGluYXRpb24YBiABKAsyLC5ob2xtcy50eXBlcy5wYnhfY29ubmVj", "dG9yLk1pdGVsUGhvbmVDaXJjdWl0KqgBChVNaXRlbFBob25lQ2lyY3VpdFR5", "cGUSLworTUlURUxfUEhPTkVfQ0lSQ1VJVF9UWVBFX0lOVEVSTkFMX0VYVEVO", "U0lPThAAEiwKKE1JVEVMX1BIT05FX0NJUkNVSVRfVFlQRV9DT19UUlVOS19O", "VU1CRVIQARIwCixNSVRFTF9QSE9ORV9DSVJDVUlUX1RZUEVfTk9OX0NPX1RS", "VU5LX05VTUJFUhACQilaDHBieGNvbm5lY3RvcqoCGEhPTE1TLlR5cGVzLlBC", "WENvbm5lY3RvcmIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.PBXConnector.MitelPhoneCircuitType), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.PBXConnector.MitelPhoneCircuit), global::HOLMS.Types.PBXConnector.MitelPhoneCircuit.Parser, new[]{ "CircuitType", "CircuitIdentifier" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.PBXConnector.MitelCallEnded), global::HOLMS.Types.PBXConnector.MitelCallEnded.Parser, new[]{ "StartTime", "Duration", "CallOrigin", "LeadingDigitsDialed", "MainDigitsDialed", "CallDestination" }, null, null, null) })); } #endregion } #region Enums public enum MitelPhoneCircuitType { [pbr::OriginalName("MITEL_PHONE_CIRCUIT_TYPE_INTERNAL_EXTENSION")] InternalExtension = 0, [pbr::OriginalName("MITEL_PHONE_CIRCUIT_TYPE_CO_TRUNK_NUMBER")] CoTrunkNumber = 1, [pbr::OriginalName("MITEL_PHONE_CIRCUIT_TYPE_NON_CO_TRUNK_NUMBER")] NonCoTrunkNumber = 2, } #endregion #region Messages public sealed partial class MitelPhoneCircuit : pb::IMessage<MitelPhoneCircuit> { private static readonly pb::MessageParser<MitelPhoneCircuit> _parser = new pb::MessageParser<MitelPhoneCircuit>(() => new MitelPhoneCircuit()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MitelPhoneCircuit> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.PBXConnector.MitelCallEndedReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MitelPhoneCircuit() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MitelPhoneCircuit(MitelPhoneCircuit other) : this() { circuitType_ = other.circuitType_; circuitIdentifier_ = other.circuitIdentifier_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MitelPhoneCircuit Clone() { return new MitelPhoneCircuit(this); } /// <summary>Field number for the "circuit_type" field.</summary> public const int CircuitTypeFieldNumber = 1; private global::HOLMS.Types.PBXConnector.MitelPhoneCircuitType circuitType_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.PBXConnector.MitelPhoneCircuitType CircuitType { get { return circuitType_; } set { circuitType_ = value; } } /// <summary>Field number for the "circuit_identifier" field.</summary> public const int CircuitIdentifierFieldNumber = 2; private string circuitIdentifier_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CircuitIdentifier { get { return circuitIdentifier_; } set { circuitIdentifier_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MitelPhoneCircuit); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MitelPhoneCircuit other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (CircuitType != other.CircuitType) return false; if (CircuitIdentifier != other.CircuitIdentifier) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (CircuitType != 0) hash ^= CircuitType.GetHashCode(); if (CircuitIdentifier.Length != 0) hash ^= CircuitIdentifier.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (CircuitType != 0) { output.WriteRawTag(8); output.WriteEnum((int) CircuitType); } if (CircuitIdentifier.Length != 0) { output.WriteRawTag(18); output.WriteString(CircuitIdentifier); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (CircuitType != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) CircuitType); } if (CircuitIdentifier.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CircuitIdentifier); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MitelPhoneCircuit other) { if (other == null) { return; } if (other.CircuitType != 0) { CircuitType = other.CircuitType; } if (other.CircuitIdentifier.Length != 0) { CircuitIdentifier = other.CircuitIdentifier; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { circuitType_ = (global::HOLMS.Types.PBXConnector.MitelPhoneCircuitType) input.ReadEnum(); break; } case 18: { CircuitIdentifier = input.ReadString(); break; } } } } } public sealed partial class MitelCallEnded : pb::IMessage<MitelCallEnded> { private static readonly pb::MessageParser<MitelCallEnded> _parser = new pb::MessageParser<MitelCallEnded>(() => new MitelCallEnded()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MitelCallEnded> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.PBXConnector.MitelCallEndedReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MitelCallEnded() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MitelCallEnded(MitelCallEnded other) : this() { StartTime = other.startTime_ != null ? other.StartTime.Clone() : null; Duration = other.duration_ != null ? other.Duration.Clone() : null; CallOrigin = other.callOrigin_ != null ? other.CallOrigin.Clone() : null; leadingDigitsDialed_ = other.leadingDigitsDialed_; mainDigitsDialed_ = other.mainDigitsDialed_; CallDestination = other.callDestination_ != null ? other.CallDestination.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MitelCallEnded Clone() { return new MitelCallEnded(this); } /// <summary>Field number for the "start_time" field.</summary> public const int StartTimeFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Timestamp startTime_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp StartTime { get { return startTime_; } set { startTime_ = value; } } /// <summary>Field number for the "duration" field.</summary> public const int DurationFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Duration duration_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration Duration { get { return duration_; } set { duration_ = value; } } /// <summary>Field number for the "call_origin" field.</summary> public const int CallOriginFieldNumber = 3; private global::HOLMS.Types.PBXConnector.MitelPhoneCircuit callOrigin_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.PBXConnector.MitelPhoneCircuit CallOrigin { get { return callOrigin_; } set { callOrigin_ = value; } } /// <summary>Field number for the "leading_digits_dialed" field.</summary> public const int LeadingDigitsDialedFieldNumber = 4; private string leadingDigitsDialed_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string LeadingDigitsDialed { get { return leadingDigitsDialed_; } set { leadingDigitsDialed_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "main_digits_dialed" field.</summary> public const int MainDigitsDialedFieldNumber = 5; private string mainDigitsDialed_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MainDigitsDialed { get { return mainDigitsDialed_; } set { mainDigitsDialed_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "call_destination" field.</summary> public const int CallDestinationFieldNumber = 6; private global::HOLMS.Types.PBXConnector.MitelPhoneCircuit callDestination_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.PBXConnector.MitelPhoneCircuit CallDestination { get { return callDestination_; } set { callDestination_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MitelCallEnded); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MitelCallEnded other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(StartTime, other.StartTime)) return false; if (!object.Equals(Duration, other.Duration)) return false; if (!object.Equals(CallOrigin, other.CallOrigin)) return false; if (LeadingDigitsDialed != other.LeadingDigitsDialed) return false; if (MainDigitsDialed != other.MainDigitsDialed) return false; if (!object.Equals(CallDestination, other.CallDestination)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (startTime_ != null) hash ^= StartTime.GetHashCode(); if (duration_ != null) hash ^= Duration.GetHashCode(); if (callOrigin_ != null) hash ^= CallOrigin.GetHashCode(); if (LeadingDigitsDialed.Length != 0) hash ^= LeadingDigitsDialed.GetHashCode(); if (MainDigitsDialed.Length != 0) hash ^= MainDigitsDialed.GetHashCode(); if (callDestination_ != null) hash ^= CallDestination.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (startTime_ != null) { output.WriteRawTag(10); output.WriteMessage(StartTime); } if (duration_ != null) { output.WriteRawTag(18); output.WriteMessage(Duration); } if (callOrigin_ != null) { output.WriteRawTag(26); output.WriteMessage(CallOrigin); } if (LeadingDigitsDialed.Length != 0) { output.WriteRawTag(34); output.WriteString(LeadingDigitsDialed); } if (MainDigitsDialed.Length != 0) { output.WriteRawTag(42); output.WriteString(MainDigitsDialed); } if (callDestination_ != null) { output.WriteRawTag(50); output.WriteMessage(CallDestination); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (startTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime); } if (duration_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Duration); } if (callOrigin_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CallOrigin); } if (LeadingDigitsDialed.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(LeadingDigitsDialed); } if (MainDigitsDialed.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MainDigitsDialed); } if (callDestination_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CallDestination); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MitelCallEnded other) { if (other == null) { return; } if (other.startTime_ != null) { if (startTime_ == null) { startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } StartTime.MergeFrom(other.StartTime); } if (other.duration_ != null) { if (duration_ == null) { duration_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } Duration.MergeFrom(other.Duration); } if (other.callOrigin_ != null) { if (callOrigin_ == null) { callOrigin_ = new global::HOLMS.Types.PBXConnector.MitelPhoneCircuit(); } CallOrigin.MergeFrom(other.CallOrigin); } if (other.LeadingDigitsDialed.Length != 0) { LeadingDigitsDialed = other.LeadingDigitsDialed; } if (other.MainDigitsDialed.Length != 0) { MainDigitsDialed = other.MainDigitsDialed; } if (other.callDestination_ != null) { if (callDestination_ == null) { callDestination_ = new global::HOLMS.Types.PBXConnector.MitelPhoneCircuit(); } CallDestination.MergeFrom(other.CallDestination); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (startTime_ == null) { startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(startTime_); break; } case 18: { if (duration_ == null) { duration_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(duration_); break; } case 26: { if (callOrigin_ == null) { callOrigin_ = new global::HOLMS.Types.PBXConnector.MitelPhoneCircuit(); } input.ReadMessage(callOrigin_); break; } case 34: { LeadingDigitsDialed = input.ReadString(); break; } case 42: { MainDigitsDialed = input.ReadString(); break; } case 50: { if (callDestination_ == null) { callDestination_ = new global::HOLMS.Types.PBXConnector.MitelPhoneCircuit(); } input.ReadMessage(callDestination_); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Reflection.Emit; using System.Reflection; namespace ClrTest.Reflection { public abstract class ILInstruction { protected Int32 m_offset; protected OpCode m_opCode; internal ILInstruction(Int32 offset, OpCode opCode) { this.m_offset = offset; this.m_opCode = opCode; } public Int32 Offset { get { return m_offset; } } public OpCode OpCode { get { return m_opCode; } } public abstract void Accept(ILInstructionVisitor vistor); } public class InlineNoneInstruction : ILInstruction { internal InlineNoneInstruction(Int32 offset, OpCode opCode) : base(offset, opCode) { } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineNoneInstruction(this); } } public class InlineBrTargetInstruction : ILInstruction { private Int32 m_delta; internal InlineBrTargetInstruction(Int32 offset, OpCode opCode, Int32 delta) : base(offset, opCode) { this.m_delta = delta; } public Int32 Delta { get { return m_delta; } } public Int32 TargetOffset { get { return m_offset + m_delta + 1 + 4; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineBrTargetInstruction(this); } } public class ShortInlineBrTargetInstruction : ILInstruction { private SByte m_delta; internal ShortInlineBrTargetInstruction(Int32 offset, OpCode opCode, SByte delta) : base(offset, opCode) { this.m_delta = delta; } public SByte Delta { get { return m_delta; } } public Int32 TargetOffset { get { return m_offset + m_delta + 1 + 1; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitShortInlineBrTargetInstruction(this); } } public class InlineSwitchInstruction : ILInstruction { private Int32[] m_deltas; private Int32[] m_targetOffsets; internal InlineSwitchInstruction(Int32 offset, OpCode opCode, Int32[] deltas) : base(offset, opCode) { this.m_deltas = deltas; } public Int32[] Deltas { get { return (Int32[])m_deltas.Clone(); } } public Int32[] TargetOffsets { get { if (m_targetOffsets == null) { int cases = m_deltas.Length; int itself = 1 + 4 + 4 * cases; m_targetOffsets = new Int32[cases]; for (Int32 i = 0; i < cases; i++) m_targetOffsets[i] = m_offset + m_deltas[i] + itself; } return m_targetOffsets; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineSwitchInstruction(this); } } public class InlineIInstruction : ILInstruction { private Int32 m_int32; internal InlineIInstruction(Int32 offset, OpCode opCode, Int32 value) : base(offset, opCode) { this.m_int32 = value; } public Int32 Int32 { get { return m_int32; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineIInstruction(this); } } public class InlineI8Instruction : ILInstruction { private Int64 m_int64; internal InlineI8Instruction(Int32 offset, OpCode opCode, Int64 value) : base(offset, opCode) { this.m_int64 = value; } public Int64 Int64 { get { return m_int64; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineI8Instruction(this); } } public class ShortInlineIInstruction : ILInstruction { private Byte m_int8; internal ShortInlineIInstruction(Int32 offset, OpCode opCode, Byte value) : base(offset, opCode) { this.m_int8 = value; } public Byte Byte { get { return m_int8; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitShortInlineIInstruction(this); } } public class InlineRInstruction : ILInstruction { private Double m_value; internal InlineRInstruction(Int32 offset, OpCode opCode, Double value) : base(offset, opCode) { this.m_value = value; } public Double Double { get { return m_value; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineRInstruction(this); } } public class ShortInlineRInstruction : ILInstruction { private Single m_value; internal ShortInlineRInstruction(Int32 offset, OpCode opCode, Single value) : base(offset, opCode) { this.m_value = value; } public Single Single { get { return m_value; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitShortInlineRInstruction(this); } } public class InlineFieldInstruction : ILInstruction { ITokenResolver m_resolver; Int32 m_token; FieldInfo m_field; internal InlineFieldInstruction(ITokenResolver resolver, Int32 offset, OpCode opCode, Int32 token) : base(offset, opCode) { this.m_resolver = resolver; this.m_token = token; } public FieldInfo Field { get { if (m_field == null) { m_field = m_resolver.AsField(m_token); } return m_field; } } public Int32 Token { get { return m_token; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineFieldInstruction(this); } } public class InlineMethodInstruction : ILInstruction { private ITokenResolver m_resolver; private Int32 m_token; private MethodBase m_method; internal InlineMethodInstruction(Int32 offset, OpCode opCode, Int32 token, ITokenResolver resolver) : base(offset, opCode) { this.m_resolver = resolver; this.m_token = token; } public MethodBase Method { get { if (m_method == null) { m_method = m_resolver.AsMethod(m_token); } return m_method; } } public Int32 Token { get { return m_token; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineMethodInstruction(this); } } public class InlineTypeInstruction : ILInstruction { private ITokenResolver m_resolver; private Int32 m_token; private Type m_type; internal InlineTypeInstruction(Int32 offset, OpCode opCode, Int32 token, ITokenResolver resolver) : base(offset, opCode) { this.m_resolver = resolver; this.m_token = token; } public Type Type { get { if (m_type == null) { m_type = m_resolver.AsType(m_token); } return m_type; } } public Int32 Token { get { return m_token; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineTypeInstruction(this); } } public class InlineSigInstruction : ILInstruction { private ITokenResolver m_resolver; private Int32 m_token; private byte[] m_signature; internal InlineSigInstruction(Int32 offset, OpCode opCode, Int32 token, ITokenResolver resolver) : base(offset, opCode) { this.m_resolver = resolver; this.m_token = token; } public byte[] Signature { get { if (m_signature == null) { m_signature = m_resolver.AsSignature(m_token); } return m_signature; } } public Int32 Token { get { return m_token; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineSigInstruction(this); } } public class InlineTokInstruction : ILInstruction { private ITokenResolver m_resolver; private Int32 m_token; private MemberInfo m_member; internal InlineTokInstruction(Int32 offset, OpCode opCode, Int32 token, ITokenResolver resolver) : base(offset, opCode) { this.m_resolver = resolver; this.m_token = token; } public MemberInfo Member { get { if (m_member == null) { m_member = m_resolver.AsMember(Token); } return m_member; } } public Int32 Token { get { return m_token; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineTokInstruction(this); } } public class InlineStringInstruction : ILInstruction { private ITokenResolver m_resolver; private Int32 m_token; private String m_string; internal InlineStringInstruction(Int32 offset, OpCode opCode, Int32 token, ITokenResolver resolver) : base(offset, opCode) { this.m_resolver = resolver; this.m_token = token; } public String String { get { if (m_string == null) m_string = m_resolver.AsString(Token); return m_string; } } public Int32 Token { get { return m_token; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineStringInstruction(this); } } public class InlineVarInstruction : ILInstruction { private UInt16 m_ordinal; internal InlineVarInstruction(Int32 offset, OpCode opCode, UInt16 ordinal) : base(offset, opCode) { this.m_ordinal = ordinal; } public UInt16 Ordinal { get { return m_ordinal; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitInlineVarInstruction(this); } } public class ShortInlineVarInstruction : ILInstruction { private Byte m_ordinal; internal ShortInlineVarInstruction(Int32 offset, OpCode opCode, Byte ordinal) : base(offset, opCode) { this.m_ordinal = ordinal; } public Byte Ordinal { get { return m_ordinal; } } public override void Accept(ILInstructionVisitor vistor) { vistor.VisitShortInlineVarInstruction(this); } } }
using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security.Principal; using System.Text; namespace Ansible.AccessToken { internal class NativeHelpers { [StructLayout(LayoutKind.Sequential)] public struct LUID_AND_ATTRIBUTES { public Luid Luid; public UInt32 Attributes; } [StructLayout(LayoutKind.Sequential)] public struct SID_AND_ATTRIBUTES { public IntPtr Sid; public int Attributes; } [StructLayout(LayoutKind.Sequential)] public struct TOKEN_PRIVILEGES { public UInt32 PrivilegeCount; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] public LUID_AND_ATTRIBUTES[] Privileges; } [StructLayout(LayoutKind.Sequential)] public struct TOKEN_USER { public SID_AND_ATTRIBUTES User; } public enum TokenInformationClass : uint { TokenUser = 1, TokenPrivileges = 3, TokenStatistics = 10, TokenElevationType = 18, TokenLinkedToken = 19, } } internal class NativeMethods { [DllImport("kernel32.dll", SetLastError = true)] public static extern bool CloseHandle( IntPtr hObject); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool DuplicateTokenEx( SafeNativeHandle hExistingToken, TokenAccessLevels dwDesiredAccess, IntPtr lpTokenAttributes, SecurityImpersonationLevel ImpersonationLevel, TokenType TokenType, out SafeNativeHandle phNewToken); [DllImport("kernel32.dll")] public static extern SafeNativeHandle GetCurrentProcess(); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool GetTokenInformation( SafeNativeHandle TokenHandle, NativeHelpers.TokenInformationClass TokenInformationClass, SafeMemoryBuffer TokenInformation, UInt32 TokenInformationLength, out UInt32 ReturnLength); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool ImpersonateLoggedOnUser( SafeNativeHandle hToken); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool LogonUserW( string lpszUsername, string lpszDomain, string lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out SafeNativeHandle phToken); [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool LookupPrivilegeNameW( string lpSystemName, ref Luid lpLuid, StringBuilder lpName, ref UInt32 cchName); [DllImport("kernel32.dll", SetLastError = true)] public static extern SafeNativeHandle OpenProcess( ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, UInt32 dwProcessId); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool OpenProcessToken( SafeNativeHandle ProcessHandle, TokenAccessLevels DesiredAccess, out SafeNativeHandle TokenHandle); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool RevertToSelf(); } internal class SafeMemoryBuffer : SafeHandleZeroOrMinusOneIsInvalid { public SafeMemoryBuffer() : base(true) { } public SafeMemoryBuffer(int cb) : base(true) { base.SetHandle(Marshal.AllocHGlobal(cb)); } public SafeMemoryBuffer(IntPtr handle) : base(true) { base.SetHandle(handle); } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] protected override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); return true; } } public enum LogonProvider { Default, } public enum LogonType { Interactive = 2, Network = 3, Batch = 4, Service = 5, Unlock = 7, NetworkCleartext = 8, NewCredentials = 9, } [Flags] public enum PrivilegeAttributes : uint { Disabled = 0x00000000, EnabledByDefault = 0x00000001, Enabled = 0x00000002, Removed = 0x00000004, UsedForAccess = 0x80000000, } [Flags] public enum ProcessAccessFlags : uint { Terminate = 0x00000001, CreateThread = 0x00000002, VmOperation = 0x00000008, VmRead = 0x00000010, VmWrite = 0x00000020, DupHandle = 0x00000040, CreateProcess = 0x00000080, SetQuota = 0x00000100, SetInformation = 0x00000200, QueryInformation = 0x00000400, SuspendResume = 0x00000800, QueryLimitedInformation = 0x00001000, Delete = 0x00010000, ReadControl = 0x00020000, WriteDac = 0x00040000, WriteOwner = 0x00080000, Synchronize = 0x00100000, } public enum SecurityImpersonationLevel { Anonymous, Identification, Impersonation, Delegation, } public enum TokenElevationType { Default = 1, Full, Limited, } public enum TokenType { Primary = 1, Impersonation, } [StructLayout(LayoutKind.Sequential)] public struct Luid { public UInt32 LowPart; public Int32 HighPart; public static explicit operator UInt64(Luid l) { return (UInt64)((UInt64)l.HighPart << 32) | (UInt64)l.LowPart; } } [StructLayout(LayoutKind.Sequential)] public struct TokenStatistics { public Luid TokenId; public Luid AuthenticationId; public Int64 ExpirationTime; public TokenType TokenType; public SecurityImpersonationLevel ImpersonationLevel; public UInt32 DynamicCharged; public UInt32 DynamicAvailable; public UInt32 GroupCount; public UInt32 PrivilegeCount; public Luid ModifiedId; } public class PrivilegeInfo { public string Name; public PrivilegeAttributes Attributes; internal PrivilegeInfo(NativeHelpers.LUID_AND_ATTRIBUTES la) { Name = TokenUtil.GetPrivilegeName(la.Luid); Attributes = (PrivilegeAttributes)la.Attributes; } } public class SafeNativeHandle : SafeHandleZeroOrMinusOneIsInvalid { public SafeNativeHandle() : base(true) { } public SafeNativeHandle(IntPtr handle) : base(true) { this.handle = handle; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] protected override bool ReleaseHandle() { return NativeMethods.CloseHandle(handle); } } public class Win32Exception : System.ComponentModel.Win32Exception { private string _msg; public Win32Exception(string message) : this(Marshal.GetLastWin32Error(), message) { } public Win32Exception(int errorCode, string message) : base(errorCode) { _msg = String.Format("{0} ({1}, Win32ErrorCode {2} - 0x{2:X8})", message, base.Message, errorCode); } public override string Message { get { return _msg; } } public static explicit operator Win32Exception(string message) { return new Win32Exception(message); } } public class TokenUtil { public static SafeNativeHandle DuplicateToken(SafeNativeHandle hToken, TokenAccessLevels access, SecurityImpersonationLevel impersonationLevel, TokenType tokenType) { SafeNativeHandle dupToken; if (!NativeMethods.DuplicateTokenEx(hToken, access, IntPtr.Zero, impersonationLevel, tokenType, out dupToken)) throw new Win32Exception("Failed to duplicate token"); return dupToken; } public static SecurityIdentifier GetTokenUser(SafeNativeHandle hToken) { using (SafeMemoryBuffer tokenInfo = GetTokenInformation(hToken, NativeHelpers.TokenInformationClass.TokenUser)) { NativeHelpers.TOKEN_USER tokenUser = (NativeHelpers.TOKEN_USER)Marshal.PtrToStructure( tokenInfo.DangerousGetHandle(), typeof(NativeHelpers.TOKEN_USER)); return new SecurityIdentifier(tokenUser.User.Sid); } } public static List<PrivilegeInfo> GetTokenPrivileges(SafeNativeHandle hToken) { using (SafeMemoryBuffer tokenInfo = GetTokenInformation(hToken, NativeHelpers.TokenInformationClass.TokenPrivileges)) { NativeHelpers.TOKEN_PRIVILEGES tokenPrivs = (NativeHelpers.TOKEN_PRIVILEGES)Marshal.PtrToStructure( tokenInfo.DangerousGetHandle(), typeof(NativeHelpers.TOKEN_PRIVILEGES)); NativeHelpers.LUID_AND_ATTRIBUTES[] luidAttrs = new NativeHelpers.LUID_AND_ATTRIBUTES[tokenPrivs.PrivilegeCount]; PtrToStructureArray(luidAttrs, IntPtr.Add(tokenInfo.DangerousGetHandle(), Marshal.SizeOf(tokenPrivs.PrivilegeCount))); return luidAttrs.Select(la => new PrivilegeInfo(la)).ToList(); } } public static TokenStatistics GetTokenStatistics(SafeNativeHandle hToken) { using (SafeMemoryBuffer tokenInfo = GetTokenInformation(hToken, NativeHelpers.TokenInformationClass.TokenStatistics)) { TokenStatistics tokenStats = (TokenStatistics)Marshal.PtrToStructure( tokenInfo.DangerousGetHandle(), typeof(TokenStatistics)); return tokenStats; } } public static TokenElevationType GetTokenElevationType(SafeNativeHandle hToken) { using (SafeMemoryBuffer tokenInfo = GetTokenInformation(hToken, NativeHelpers.TokenInformationClass.TokenElevationType)) { return (TokenElevationType)Marshal.ReadInt32(tokenInfo.DangerousGetHandle()); } } public static SafeNativeHandle GetTokenLinkedToken(SafeNativeHandle hToken) { using (SafeMemoryBuffer tokenInfo = GetTokenInformation(hToken, NativeHelpers.TokenInformationClass.TokenLinkedToken)) { return new SafeNativeHandle(Marshal.ReadIntPtr(tokenInfo.DangerousGetHandle())); } } public static IEnumerable<SafeNativeHandle> EnumerateUserTokens(SecurityIdentifier sid, TokenAccessLevels access = TokenAccessLevels.Query) { foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcesses()) { // We always need the Query access level so we can query the TokenUser using (process) using (SafeNativeHandle hToken = TryOpenAccessToken(process, access | TokenAccessLevels.Query)) { if (hToken == null) continue; if (!sid.Equals(GetTokenUser(hToken))) continue; yield return hToken; } } } public static void ImpersonateToken(SafeNativeHandle hToken) { if (!NativeMethods.ImpersonateLoggedOnUser(hToken)) throw new Win32Exception("Failed to impersonate token"); } public static SafeNativeHandle LogonUser(string username, string domain, string password, LogonType logonType, LogonProvider logonProvider) { SafeNativeHandle hToken; if (!NativeMethods.LogonUserW(username, domain, password, logonType, logonProvider, out hToken)) throw new Win32Exception(String.Format("Failed to logon {0}", String.IsNullOrEmpty(domain) ? username : domain + "\\" + username)); return hToken; } public static SafeNativeHandle OpenProcess() { return NativeMethods.GetCurrentProcess(); } public static SafeNativeHandle OpenProcess(Int32 pid, ProcessAccessFlags access, bool inherit) { SafeNativeHandle hProcess = NativeMethods.OpenProcess(access, inherit, (UInt32)pid); if (hProcess.IsInvalid) throw new Win32Exception(String.Format("Failed to open process {0} with access {1}", pid, access.ToString())); return hProcess; } public static SafeNativeHandle OpenProcessToken(SafeNativeHandle hProcess, TokenAccessLevels access) { SafeNativeHandle hToken; if (!NativeMethods.OpenProcessToken(hProcess, access, out hToken)) throw new Win32Exception(String.Format("Failed to open proces token with access {0}", access.ToString())); return hToken; } public static void RevertToSelf() { if (!NativeMethods.RevertToSelf()) throw new Win32Exception("Failed to revert thread impersonation"); } internal static string GetPrivilegeName(Luid luid) { UInt32 nameLen = 0; NativeMethods.LookupPrivilegeNameW(null, ref luid, null, ref nameLen); StringBuilder name = new StringBuilder((int)(nameLen + 1)); if (!NativeMethods.LookupPrivilegeNameW(null, ref luid, name, ref nameLen)) throw new Win32Exception("LookupPrivilegeName() failed"); return name.ToString(); } private static SafeMemoryBuffer GetTokenInformation(SafeNativeHandle hToken, NativeHelpers.TokenInformationClass infoClass) { UInt32 tokenLength; bool res = NativeMethods.GetTokenInformation(hToken, infoClass, new SafeMemoryBuffer(IntPtr.Zero), 0, out tokenLength); int errCode = Marshal.GetLastWin32Error(); if (!res && errCode != 24 && errCode != 122) // ERROR_INSUFFICIENT_BUFFER, ERROR_BAD_LENGTH throw new Win32Exception(errCode, String.Format("GetTokenInformation({0}) failed to get buffer length", infoClass.ToString())); SafeMemoryBuffer tokenInfo = new SafeMemoryBuffer((int)tokenLength); if (!NativeMethods.GetTokenInformation(hToken, infoClass, tokenInfo, tokenLength, out tokenLength)) throw new Win32Exception(String.Format("GetTokenInformation({0}) failed", infoClass.ToString())); return tokenInfo; } private static void PtrToStructureArray<T>(T[] array, IntPtr ptr) { IntPtr ptrOffset = ptr; for (int i = 0; i < array.Length; i++, ptrOffset = IntPtr.Add(ptrOffset, Marshal.SizeOf(typeof(T)))) array[i] = (T)Marshal.PtrToStructure(ptrOffset, typeof(T)); } private static SafeNativeHandle TryOpenAccessToken(System.Diagnostics.Process process, TokenAccessLevels access) { try { using (SafeNativeHandle hProcess = OpenProcess(process.Id, ProcessAccessFlags.QueryInformation, false)) return OpenProcessToken(hProcess, access); } catch (Win32Exception) { return null; } } } }
//----------------------------------------------------------------------------- // Filename: RTCPPacket.cs // // Description: Encapsulation of an RTCP (Real Time Control Protocol) packet. // // RTCP Packet // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ //header |V=2|P| RC | PT=SR=200 | length | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | SSRC of sender | // +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ //sender | NTP timestamp, most significant word | //info +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | NTP timestamp, least significant word | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | RTP timestamp | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | sender's packet count | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | sender's octet count | // +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ //report | SSRC_1 (SSRC of first source) | //block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // 1 | fraction lost | cumulative number of packets lost | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | extended highest sequence number received | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | interarrival jitter | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | last SR (LSR) | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | delay since last SR (DLSR) | // +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ //report | SSRC_2 (SSRC of second source) | //block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // 2 : ... : // +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // | profile-specific extensions | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // // History: // 22 Feb 2007 Aaron Clauson Created. // // License: // Aaron Clauson //----------------------------------------------------------------------------- using System; using SIPSorcery.Sys; #if UNITTEST using NUnit.Framework; #endif namespace SIPSorcery.Net { public class RTCPPacket { public const int SENDERINFO_BYTES_LENGTH = 24; public RTCPHeader Header; // 32 bits. public uint SenderSyncSource; // 32 bits. public UInt64 NTPTimestamp; // 64 bits. public uint RTPTimestamp; // 32 bits. public uint SenderPacketCount; // 32 bits. public uint SenderOctetCount; // 32 bits. public byte[] Reports; public RTCPPacket(uint senderSyncSource, ulong ntpTimestamp, uint rtpTimestamp, uint senderPacketCount, uint senderOctetCount) { Header = new RTCPHeader(); SenderSyncSource = senderSyncSource; NTPTimestamp = ntpTimestamp; RTPTimestamp = rtpTimestamp; SenderPacketCount = senderPacketCount; SenderOctetCount = senderOctetCount; } public RTCPPacket(byte[] packet) { Header = new RTCPHeader(packet); if (BitConverter.IsLittleEndian) { SenderSyncSource = NetConvert.DoReverseEndian(BitConverter.ToUInt32(packet, 4)); NTPTimestamp = NetConvert.DoReverseEndian(BitConverter.ToUInt64(packet, 8)); RTPTimestamp = NetConvert.DoReverseEndian(BitConverter.ToUInt32(packet, 16)); SenderPacketCount = NetConvert.DoReverseEndian(BitConverter.ToUInt32(packet, 20)); SenderOctetCount = NetConvert.DoReverseEndian(BitConverter.ToUInt32(packet, 24)); } else { SenderSyncSource = BitConverter.ToUInt32(packet, 4); NTPTimestamp = BitConverter.ToUInt64(packet, 8); RTPTimestamp = BitConverter.ToUInt32(packet, 16); SenderPacketCount = BitConverter.ToUInt32(packet, 20); SenderOctetCount = BitConverter.ToUInt32(packet, 24); } Reports = new byte[packet.Length - RTCPHeader.HEADER_BYTES_LENGTH - SENDERINFO_BYTES_LENGTH]; Buffer.BlockCopy(packet, RTCPHeader.HEADER_BYTES_LENGTH + SENDERINFO_BYTES_LENGTH, Reports, 0, Reports.Length); } public byte[] GetBytes() { byte[] payload = new byte[SENDERINFO_BYTES_LENGTH]; if (BitConverter.IsLittleEndian) { Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SenderSyncSource)), 0, payload, 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(NTPTimestamp)), 0, payload, 4, 8); Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(RTPTimestamp)), 0, payload, 12, 4); Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SenderPacketCount)), 0, payload, 16, 4); Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SenderOctetCount)), 0, payload, 20, 4); } else { Buffer.BlockCopy(BitConverter.GetBytes(SenderSyncSource), 0, payload, 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(NTPTimestamp), 0, payload, 4, 8); Buffer.BlockCopy(BitConverter.GetBytes(RTPTimestamp), 0, payload, 12, 4); Buffer.BlockCopy(BitConverter.GetBytes(SenderPacketCount), 0, payload, 16, 4); Buffer.BlockCopy(BitConverter.GetBytes(SenderOctetCount), 0, payload, 20, 4); } Header.Length = Convert.ToUInt16(payload.Length / 4); byte[] header = Header.GetBytes(); byte[] packet = new byte[header.Length + payload.Length]; Array.Copy(header, packet, header.Length); Array.Copy(payload, 0, packet, header.Length, payload.Length); return packet; } public byte[] GetBytes(byte[] reports) { Reports = reports; byte[] payload = new byte[SENDERINFO_BYTES_LENGTH + reports.Length]; if (BitConverter.IsLittleEndian) { Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SenderSyncSource)), 0, payload, 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(NTPTimestamp)), 0, payload, 4, 8); Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(RTPTimestamp)), 0, payload, 12, 4); Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SenderPacketCount)), 0, payload, 16, 4); Buffer.BlockCopy(BitConverter.GetBytes(NetConvert.DoReverseEndian(SenderOctetCount)), 0, payload, 20, 4); } else { Buffer.BlockCopy(BitConverter.GetBytes(SenderSyncSource), 0, payload, 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(NTPTimestamp), 0, payload, 4, 8); Buffer.BlockCopy(BitConverter.GetBytes(RTPTimestamp), 0, payload, 12, 4); Buffer.BlockCopy(BitConverter.GetBytes(SenderPacketCount), 0, payload, 16, 4); Buffer.BlockCopy(BitConverter.GetBytes(SenderOctetCount), 0, payload, 20, 4); } Buffer.BlockCopy(reports, 0, payload, 24, reports.Length); Header.Length = Convert.ToUInt16(payload.Length / 4); byte[] header = Header.GetBytes(); byte[] packet = new byte[header.Length + payload.Length]; Array.Copy(header, packet, header.Length); Array.Copy(payload, 0, packet, header.Length, payload.Length); return packet; } #region Unit testing. #if UNITTEST [TestFixture] public class RTPCPacketUnitTest { [TestFixtureSetUp] public void Init() { } [TestFixtureTearDown] public void Dispose() { } [Test] public void SampleTest() { Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); Assert.IsTrue(true, "True was false."); } [Test] public void GetRTCPPacketTest() { Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); RTCPPacket rtcpPacket = new RTCPPacket(1, 1, 1, 1, 1); byte[] reports = new byte[84]; byte[] packetBuffer = rtcpPacket.GetBytes(reports); int byteNum = 1; foreach (byte packetByte in packetBuffer) { Console.WriteLine(byteNum + ": " + packetByte.ToString("x")); byteNum++; } } [Test] public void RTCPHeaderRoundTripTest() { Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); RTCPPacket src = new RTCPPacket(12, 122, 561, 6756, 56434); byte[] reports = new byte[84]; byte[] packetBuffer = src.GetBytes(reports); RTCPPacket dst = new RTCPPacket(packetBuffer); Console.WriteLine("SenderSyncSource: " + src.SenderSyncSource + ", " + dst.SenderSyncSource); Console.WriteLine("NTPTimestamp: " + src.NTPTimestamp + ", " + dst.NTPTimestamp); Console.WriteLine("RTPTimestamp: " + src.RTPTimestamp + ", " + dst.RTPTimestamp); Console.WriteLine("SenderPacketCount: " + src.SenderPacketCount + ", " + dst.SenderPacketCount); Console.WriteLine("SenderOctetCount: " + src.SenderOctetCount + ", " + dst.SenderOctetCount); Console.WriteLine("Reports Length: " + src.Reports.Length + ", " + dst.Reports.Length); //Console.WriteLine("Raw Header: " + System.Text.Encoding.ASCII.GetString(headerBuffer, 0, headerBuffer.Length)); Assert.IsTrue(src.SenderSyncSource == dst.SenderSyncSource, "SenderSyncSource was mismatched."); Assert.IsTrue(src.NTPTimestamp == dst.NTPTimestamp, "NTPTimestamp was mismatched."); Assert.IsTrue(src.RTPTimestamp == dst.RTPTimestamp, "RTPTimestamp was mismatched."); Assert.IsTrue(src.SenderPacketCount == dst.SenderPacketCount, "SenderPacketCount was mismatched."); Assert.IsTrue(src.SenderOctetCount == dst.SenderOctetCount, "SenderOctetCount was mismatched."); Assert.IsTrue(src.Reports.Length == dst.Reports.Length, "Reports length was mismatched."); } } #endif #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddSubtractDouble() { var test = new AlternatingBinaryOpTest__AddSubtractDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.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 (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class AlternatingBinaryOpTest__AddSubtractDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(AlternatingBinaryOpTest__AddSubtractDouble testClass) { var result = Sse3.AddSubtract(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(AlternatingBinaryOpTest__AddSubtractDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse3.AddSubtract( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static AlternatingBinaryOpTest__AddSubtractDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public AlternatingBinaryOpTest__AddSubtractDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse3.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse3.AddSubtract( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse3.AddSubtract( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse3.AddSubtract( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse3).GetMethod(nameof(Sse3.AddSubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse3).GetMethod(nameof(Sse3.AddSubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse3).GetMethod(nameof(Sse3.AddSubtract), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse3.AddSubtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse3.AddSubtract( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse3.AddSubtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse3.AddSubtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse3.AddSubtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new AlternatingBinaryOpTest__AddSubtractDouble(); var result = Sse3.AddSubtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new AlternatingBinaryOpTest__AddSubtractDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse3.AddSubtract( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse3.AddSubtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse3.AddSubtract( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse3.AddSubtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse3.AddSubtract( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i += 2) { if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(left[i] - right[i])) { succeeded = false; break; } if (BitConverter.DoubleToInt64Bits(result[i + 1]) != BitConverter.DoubleToInt64Bits(left[i + 1] + right[i + 1])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse3)}.{nameof(Sse3.AddSubtract)}<Double>(Vector128<Double>, Vector128<Double>): {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.IO; using System.Linq; using System.Web; using Nop.Core; using Nop.Core.Domain.Catalog; using Nop.Services.Catalog; using Nop.Services.Media; using Nop.Services.Seo; using OfficeOpenXml; namespace Nop.Services.ExportImport { /// <summary> /// Import manager /// </summary> public partial class ImportManager : IImportManager { #region Fields private readonly IProductService _productService; private readonly ICategoryService _categoryService; private readonly IManufacturerService _manufacturerService; private readonly IPictureService _pictureService; private readonly IUrlRecordService _urlRecordService; #endregion #region Ctor public ImportManager(IProductService productService, ICategoryService categoryService, IManufacturerService manufacturerService, IPictureService pictureService, IUrlRecordService urlRecordService) { this._productService = productService; this._categoryService = categoryService; this._manufacturerService = manufacturerService; this._pictureService = pictureService; this._urlRecordService = urlRecordService; } #endregion #region Utilities protected virtual int GetColumnIndex(string[] properties, string columnName) { if (properties == null) throw new ArgumentNullException("properties"); if (columnName == null) throw new ArgumentNullException("columnName"); for (int i = 0; i < properties.Length; i++) if (properties[i].Equals(columnName, StringComparison.InvariantCultureIgnoreCase)) return i + 1; //excel indexes start from 1 return 0; } protected virtual string ConvertColumnToString(object columnValue) { if (columnValue == null) return null; return Convert.ToString(columnValue); } protected virtual string GetMimeTypeFromFilePath(string filePath) { var mimeType = MimeMapping.GetMimeMapping(filePath); //little hack here because MimeMapping does not contain all mappings (e.g. PNG) if (mimeType == "application/octet-stream") mimeType = "image/jpeg"; return mimeType; } #endregion #region Methods /// <summary> /// Import products from XLSX file /// </summary> /// <param name="stream">Stream</param> public virtual void ImportProductsFromXlsx(Stream stream) { // ok, we can run the real code of the sample now using (var xlPackage = new ExcelPackage(stream)) { // get the first worksheet in the workbook var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault(); if (worksheet == null) throw new NopException("No worksheet found"); //the columns var properties = new string[] { "ProductTypeId", "ParentGroupedProductId", "VisibleIndividually", "Name", "ShortDescription", "FullDescription", "VendorId", "ProductTemplateId", "ShowOnHomePage", "MetaKeywords", "MetaDescription", "MetaTitle", "SeName", "AllowCustomerReviews", "Published", "SKU", "ManufacturerPartNumber", "Gtin", "IsGiftCard", "GiftCardTypeId", "RequireOtherProducts", "RequiredProductIds", "AutomaticallyAddRequiredProducts", "IsDownload", "DownloadId", "UnlimitedDownloads", "MaxNumberOfDownloads", "DownloadActivationTypeId", "HasSampleDownload", "SampleDownloadId", "HasUserAgreement", "UserAgreementText", "IsRecurring", "RecurringCycleLength", "RecurringCyclePeriodId", "RecurringTotalCycles", "IsShipEnabled", "IsFreeShipping", "AdditionalShippingCharge", "DeliveryDateId", "WarehouseId", "IsTaxExempt", "TaxCategoryId", "ManageInventoryMethodId", "StockQuantity", "DisplayStockAvailability", "DisplayStockQuantity", "MinStockQuantity", "LowStockActivityId", "NotifyAdminForQuantityBelow", "BackorderModeId", "AllowBackInStockSubscriptions", "OrderMinimumQuantity", "OrderMaximumQuantity", "AllowedQuantities", "AllowAddingOnlyExistingAttributeCombinations", "DisableBuyButton", "DisableWishlistButton", "AvailableForPreOrder", "PreOrderAvailabilityStartDateTimeUtc", "CallForPrice", "Price", "OldPrice", "ProductCost", "SpecialPrice", "SpecialPriceStartDateTimeUtc", "SpecialPriceEndDateTimeUtc", "CustomerEntersPrice", "MinimumCustomerEnteredPrice", "MaximumCustomerEnteredPrice", "Weight", "Length", "Width", "Height", "CreatedOnUtc", "CategoryIds", "ManufacturerIds", "Picture1", "Picture2", "Picture3", }; int iRow = 2; while (true) { bool allColumnsAreEmpty = true; for (var i = 1; i <= properties.Length; i++) if (worksheet.Cells[iRow, i].Value != null && !String.IsNullOrEmpty(worksheet.Cells[iRow, i].Value.ToString())) { allColumnsAreEmpty = false; break; } if (allColumnsAreEmpty) break; int productTypeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTypeId")].Value); int parentGroupedProductId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ParentGroupedProductId")].Value); bool visibleIndividually = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "VisibleIndividually")].Value); string name = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Name")].Value); string shortDescription = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ShortDescription")].Value); string fullDescription = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "FullDescription")].Value); int vendorId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "VendorId")].Value); int productTemplateId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTemplateId")].Value); bool showOnHomePage = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "ShowOnHomePage")].Value); string metaKeywords = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaKeywords")].Value); string metaDescription = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaDescription")].Value); string metaTitle = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaTitle")].Value); string seName = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "SeName")].Value); bool allowCustomerReviews = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowCustomerReviews")].Value); bool published = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "Published")].Value); string sku = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "SKU")].Value); string manufacturerPartNumber = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerPartNumber")].Value); string gtin = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Gtin")].Value); bool isGiftCard = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsGiftCard")].Value); int giftCardTypeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "GiftCardTypeId")].Value); bool requireOtherProducts = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "RequireOtherProducts")].Value); string requiredProductIds = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "RequiredProductIds")].Value); bool automaticallyAddRequiredProducts = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AutomaticallyAddRequiredProducts")].Value); bool isDownload = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsDownload")].Value); int downloadId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadId")].Value); bool unlimitedDownloads = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "UnlimitedDownloads")].Value); int maxNumberOfDownloads = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MaxNumberOfDownloads")].Value); int downloadActivationTypeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadActivationTypeId")].Value); bool hasSampleDownload = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasSampleDownload")].Value); int sampleDownloadId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "SampleDownloadId")].Value); bool hasUserAgreement = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasUserAgreement")].Value); string userAgreementText = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "UserAgreementText")].Value); bool isRecurring = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsRecurring")].Value); int recurringCycleLength = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCycleLength")].Value); int recurringCyclePeriodId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCyclePeriodId")].Value); int recurringTotalCycles = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringTotalCycles")].Value); bool isShipEnabled = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsShipEnabled")].Value); bool isFreeShipping = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsFreeShipping")].Value); decimal additionalShippingCharge = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "AdditionalShippingCharge")].Value); int deliveryDateId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DeliveryDateId")].Value); int warehouseId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "WarehouseId")].Value); bool isTaxExempt = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsTaxExempt")].Value); int taxCategoryId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "TaxCategoryId")].Value); int manageInventoryMethodId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ManageInventoryMethodId")].Value); int stockQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "StockQuantity")].Value); bool displayStockAvailability = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockAvailability")].Value); bool displayStockQuantity = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockQuantity")].Value); int minStockQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MinStockQuantity")].Value); int lowStockActivityId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "LowStockActivityId")].Value); int notifyAdminForQuantityBelow = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "NotifyAdminForQuantityBelow")].Value); int backorderModeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BackorderModeId")].Value); bool allowBackInStockSubscriptions = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowBackInStockSubscriptions")].Value); int orderMinimumQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMinimumQuantity")].Value); int orderMaximumQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMaximumQuantity")].Value); string allowedQuantities = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowedQuantities")].Value); bool allowAddingOnlyExistingAttributeCombinations = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowAddingOnlyExistingAttributeCombinations")].Value); bool disableBuyButton = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableBuyButton")].Value); bool disableWishlistButton = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableWishlistButton")].Value); bool availableForPreOrder = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AvailableForPreOrder")].Value); DateTime? preOrderAvailabilityStartDateTimeUtc = null; var preOrderAvailabilityStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "PreOrderAvailabilityStartDateTimeUtc")].Value; if (preOrderAvailabilityStartDateTimeUtcExcel != null) preOrderAvailabilityStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(preOrderAvailabilityStartDateTimeUtcExcel)); bool callForPrice = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CallForPrice")].Value); decimal price = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Price")].Value); decimal oldPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "OldPrice")].Value); decimal productCost = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductCost")].Value); decimal? specialPrice = null; var specialPriceExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPrice")].Value; if (specialPriceExcel != null) specialPrice = Convert.ToDecimal(specialPriceExcel); DateTime? specialPriceStartDateTimeUtc = null; var specialPriceStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceStartDateTimeUtc")].Value; if (specialPriceStartDateTimeUtcExcel != null) specialPriceStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceStartDateTimeUtcExcel)); DateTime? specialPriceEndDateTimeUtc = null; var specialPriceEndDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceEndDateTimeUtc")].Value; if (specialPriceEndDateTimeUtcExcel != null) specialPriceEndDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceEndDateTimeUtcExcel)); bool customerEntersPrice = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CustomerEntersPrice")].Value); decimal minimumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MinimumCustomerEnteredPrice")].Value); decimal maximumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MaximumCustomerEnteredPrice")].Value); decimal weight = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Weight")].Value); decimal length = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Length")].Value); decimal width = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Width")].Value); decimal height = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Height")].Value); DateTime createdOnUtc = DateTime.FromOADate(Convert.ToDouble(worksheet.Cells[iRow, GetColumnIndex(properties, "CreatedOnUtc")].Value)); string categoryIds = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "CategoryIds")].Value); string manufacturerIds = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerIds")].Value); string picture1 = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture1")].Value); string picture2 = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture2")].Value); string picture3 = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture3")].Value); var product = _productService.GetProductBySku(sku); bool newProduct = false; if (product == null) { product = new Product(); newProduct = true; } product.ProductTypeId = productTypeId; product.ParentGroupedProductId = parentGroupedProductId; product.VisibleIndividually = visibleIndividually; product.Name = name; product.ShortDescription = shortDescription; product.FullDescription = fullDescription; product.VendorId = vendorId; product.ProductTemplateId = productTemplateId; product.ShowOnHomePage = showOnHomePage; product.MetaKeywords = metaKeywords; product.MetaDescription = metaDescription; product.MetaTitle = metaTitle; product.AllowCustomerReviews = allowCustomerReviews; product.Sku = sku; product.ManufacturerPartNumber = manufacturerPartNumber; product.Gtin = gtin; product.IsGiftCard = isGiftCard; product.GiftCardTypeId = giftCardTypeId; product.RequireOtherProducts = requireOtherProducts; product.RequiredProductIds = requiredProductIds; product.AutomaticallyAddRequiredProducts = automaticallyAddRequiredProducts; product.IsDownload = isDownload; product.DownloadId = downloadId; product.UnlimitedDownloads = unlimitedDownloads; product.MaxNumberOfDownloads = maxNumberOfDownloads; product.DownloadActivationTypeId = downloadActivationTypeId; product.HasSampleDownload = hasSampleDownload; product.SampleDownloadId = sampleDownloadId; product.HasUserAgreement = hasUserAgreement; product.UserAgreementText = userAgreementText; product.IsRecurring = isRecurring; product.RecurringCycleLength = recurringCycleLength; product.RecurringCyclePeriodId = recurringCyclePeriodId; product.RecurringTotalCycles = recurringTotalCycles; product.IsShipEnabled = isShipEnabled; product.IsFreeShipping = isFreeShipping; product.AdditionalShippingCharge = additionalShippingCharge; product.DeliveryDateId = deliveryDateId; product.WarehouseId = warehouseId; product.IsTaxExempt = isTaxExempt; product.TaxCategoryId = taxCategoryId; product.ManageInventoryMethodId = manageInventoryMethodId; product.StockQuantity = stockQuantity; product.DisplayStockAvailability = displayStockAvailability; product.DisplayStockQuantity = displayStockQuantity; product.MinStockQuantity = minStockQuantity; product.LowStockActivityId = lowStockActivityId; product.NotifyAdminForQuantityBelow = notifyAdminForQuantityBelow; product.BackorderModeId = backorderModeId; product.AllowBackInStockSubscriptions = allowBackInStockSubscriptions; product.OrderMinimumQuantity = orderMinimumQuantity; product.OrderMaximumQuantity = orderMaximumQuantity; product.AllowedQuantities = allowedQuantities; product.AllowAddingOnlyExistingAttributeCombinations = allowAddingOnlyExistingAttributeCombinations; product.DisableBuyButton = disableBuyButton; product.DisableWishlistButton = disableWishlistButton; product.AvailableForPreOrder = availableForPreOrder; product.PreOrderAvailabilityStartDateTimeUtc = preOrderAvailabilityStartDateTimeUtc; product.CallForPrice = callForPrice; product.Price = price; product.OldPrice = oldPrice; product.ProductCost = productCost; product.SpecialPrice = specialPrice; product.SpecialPriceStartDateTimeUtc = specialPriceStartDateTimeUtc; product.SpecialPriceEndDateTimeUtc = specialPriceEndDateTimeUtc; product.CustomerEntersPrice = customerEntersPrice; product.MinimumCustomerEnteredPrice = minimumCustomerEnteredPrice; product.MaximumCustomerEnteredPrice = maximumCustomerEnteredPrice; product.Weight = weight; product.Length = length; product.Width = width; product.Height = height; product.Published = published; product.CreatedOnUtc = createdOnUtc; product.UpdatedOnUtc = DateTime.UtcNow; if (newProduct) { _productService.InsertProduct(product); } else { _productService.UpdateProduct(product); } //search engine name _urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0); //category mappings if (!String.IsNullOrEmpty(categoryIds)) { foreach (var id in categoryIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) == null) { //ensure that category exists var category = _categoryService.GetCategoryById(id); if (category != null) { var productCategory = new ProductCategory() { ProductId = product.Id, CategoryId = category.Id, IsFeaturedProduct = false, DisplayOrder = 1 }; _categoryService.InsertProductCategory(productCategory); } } } } //manufacturer mappings if (!String.IsNullOrEmpty(manufacturerIds)) { foreach (var id in manufacturerIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim()))) { if (product.ProductManufacturers.FirstOrDefault(x => x.ManufacturerId == id) == null) { //ensure that manufacturer exists var manufacturer = _manufacturerService.GetManufacturerById(id); if (manufacturer != null) { var productManufacturer = new ProductManufacturer() { ProductId = product.Id, ManufacturerId = manufacturer.Id, IsFeaturedProduct = false, DisplayOrder = 1 }; _manufacturerService.InsertProductManufacturer(productManufacturer); } } } } //pictures foreach (var picturePath in new string[] { picture1, picture2, picture3 }) { if (String.IsNullOrEmpty(picturePath)) continue; var mimeType = GetMimeTypeFromFilePath(picturePath); var newPictureBinary = File.ReadAllBytes(picturePath); var pictureAlreadyExists = false; if (!newProduct) { //compare with existing product pictures var existingPictures = _pictureService.GetPicturesByProductId(product.Id); foreach (var existingPicture in existingPictures) { var existingBinary = _pictureService.LoadPictureBinary(existingPicture); //picture binary after validation (like in database) var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType); if (existingBinary.SequenceEqual(validatedPictureBinary)) { //the same picture content pictureAlreadyExists = true; break; } } } if (!pictureAlreadyExists) { product.ProductPictures.Add(new ProductPicture() { Picture = _pictureService.InsertPicture(newPictureBinary, mimeType , _pictureService.GetPictureSeName(name), true), DisplayOrder = 1, }); _productService.UpdateProduct(product); } } //update "HasTierPrices" and "HasDiscountsApplied" properties _productService.UpdateHasTierPricesProperty(product); _productService.UpdateHasDiscountsApplied(product); //next product iRow++; } } } #endregion } }
using BracketPipe.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Xml; namespace BracketPipe { public static partial class Html { /// <summary> /// Sanitizes the specified HTML, removing scripts, styles, and tags /// which might pose a security concern /// </summary> /// <param name="html">The HTML content to minify. A <see cref="string"/> or <see cref="Stream"/> can also be used.</param> /// <param name="settings">Settings controlling what CSS and HTML is permitted in the result</param> /// <returns>An <see cref="HtmlString"/> containing only the permitted elements</returns> /// <remarks> /// The goal of sanitization is to prevent XSS patterns /// described on <a href="https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet">XSS Filter Evasion Cheat Sheet</a> /// </remarks> public static HtmlString Sanitize(TextSource html, HtmlSanitizeSettings settings = null) { var sb = new StringBuilder(html.Length); using (var reader = new HtmlReader(html, false)) using (var sw = new StringWriter(sb)) { reader.Sanitize(settings).ToHtml(sw, new HtmlWriterSettings()); return new HtmlString(sw.ToString()); } } /// <summary> /// Sanitizes the specified HTML, removing scripts, styles, and tags /// which might pose a security concern /// </summary> /// <param name="html">The HTML content to minify. A <see cref="string"/> or <see cref="Stream"/> can also be used.</param> /// <param name="writer">Writer to which the sanitized HTML is written</param> /// <param name="settings">Settings controlling what CSS and HTML is permitted in the result</param> /// <remarks> /// The goal of sanitization is to prevent XSS patterns /// described on <a href="https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet">XSS Filter Evasion Cheat Sheet</a> /// </remarks> public static void Sanitize(TextSource html, XmlWriter writer, HtmlSanitizeSettings settings = null) { using (var reader = new HtmlReader(html, false)) { reader.Sanitize(settings).ToHtml(writer); } } /// <summary> /// Sanitizes the specified HTML, removing scripts, styles, and tags /// which might pose a security concern /// </summary> /// <param name="reader">A stream of <see cref="HtmlNode"/></param> /// <returns>A stream of sanitized <see cref="HtmlNode"/></returns> /// <remarks> /// The goal of sanitization is to prevent XSS patterns /// described on <a href="https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet">XSS Filter Evasion Cheat Sheet</a> /// </remarks> public static IEnumerable<HtmlNode> Sanitize(this IEnumerable<HtmlNode> reader) { return Sanitize(reader, HtmlSanitizeSettings.ReadOnlyDefault); } /// <summary> /// Sanitizes the specified HTML, removing scripts, styles, and tags /// which might pose a security concern /// </summary> /// <param name="reader">A stream of <see cref="HtmlNode"/></param> /// <param name="settings">Settings controlling what CSS and HTML is permitted in the result</param> /// <returns>A stream of sanitized <see cref="HtmlNode"/></returns> /// <remarks> /// The goal of sanitization is to prevent XSS patterns /// described on <a href="https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet">XSS Filter Evasion Cheat Sheet</a> /// </remarks> public static IEnumerable<HtmlNode> Sanitize(this IEnumerable<HtmlNode> reader, HtmlSanitizeSettings settings) { var removeDepth = -1; var inStyle = false; settings = settings ?? HtmlSanitizeSettings.ReadOnlyDefault; foreach (var origToken in reader) { var token = origToken; if ((token.Type == HtmlTokenType.StartTag || token.Type == HtmlTokenType.EndTag) && IsLinkPsuedoTag(token.Value)) { if (settings.EmailLinkPseudoTags == SanitizeBehavior.Allow || settings.EmailLinkPseudoTags == SanitizeBehavior.Encode) { var builder = Pool.NewStringBuilder(); token.AddToDebugDisplay(builder); token = new HtmlText(token.Position, builder.ToPool()) { Encode = settings.EmailLinkPseudoTags == SanitizeBehavior.Encode }; } else { token = new HtmlText(""); } } switch (token.Type) { case HtmlTokenType.Text: if (removeDepth < 0) { if (inStyle) yield return new HtmlText(token.Position, SanitizeCss(token.Value, settings, true)); else yield return token; } break; case HtmlTokenType.Comment: // No need to risk weird comments that might be interpreted as content (e.g. in IE) break; case HtmlTokenType.Doctype: // Doctypes should not appear in snippets break; case HtmlTokenType.StartTag: var tag = (HtmlStartTag)token; if (removeDepth < 0) { if (settings.AllowedTags.Contains(token.Value)) { if (token.Value == "style") inStyle = true; var allowed = AllowedAttributes(tag, settings).ToArray(); if (tag.Value == "img" && !allowed.Any(k => k.Key == "src")) { if (!HtmlTextWriter.VoidElements.Contains(tag.Value) && !tag.IsSelfClosing) removeDepth = 0; } else { var newTag = new HtmlStartTag(tag.Position, tag.Value); newTag.IsSelfClosing = tag.IsSelfClosing; foreach (var attr in allowed) { newTag.Attributes.Add(attr); } yield return newTag; } } else if (!HtmlTextWriter.VoidElements.Contains(tag.Value) && !tag.IsSelfClosing) { removeDepth = 0; } } else { if (!HtmlTextWriter.VoidElements.Contains(tag.Value) && !tag.IsSelfClosing) removeDepth++; } break; case HtmlTokenType.EndTag: if (removeDepth < 0 && settings.AllowedTags.Contains(token.Value)) yield return token; else removeDepth--; if (token.Value == "style") inStyle = false; break; } } } private static bool IsValidTagName(string name) { if (name == null) return false; for (var i = 0; i < name.Length; i++) { if (!char.IsLetterOrDigit(name[i]) && name[i] != ':' && name[i] != '_' && name[i] != '-' && name[i] != '.' && name[i] > ' ' && name[i] < 127) return false; } return true; } private static bool IsLinkPsuedoTag(string name) { if (name.StartsWith("http:", StringComparison.OrdinalIgnoreCase) || name.StartsWith("https:", StringComparison.OrdinalIgnoreCase)) return true; var atIdx = name.IndexOf('@'); if (atIdx < 0) return false; return name.IndexOf('.', atIdx) > 0; } private static IEnumerable<KeyValuePair<string, string>> AllowedAttributes(HtmlStartTag tag, HtmlSanitizeSettings settings) { for (var i = 0; i < tag.Attributes.Count; i++) { if (!settings.AllowedAttributes.Contains(tag.Attributes[i].Key)) { // Do nothing } else if (string.Equals(tag.Attributes[i].Key, "style", StringComparison.OrdinalIgnoreCase)) { var style = SanitizeCss(tag.Attributes[i].Value, settings, false); if (!style.IsNullOrWhiteSpace()) yield return new KeyValuePair<string, string>(tag.Attributes[i].Key, style); } else if (settings.UriAttributes.Contains(tag.Attributes[i].Key)) { var url = SanitizeUrl(tag.Attributes[i].Value, settings); if (url != null) yield return new KeyValuePair<string, string>(tag.Attributes[i].Key, url); } else if (!tag.Attributes[i].Value.StartsWith("&{")) { yield return tag.Attributes[i]; } } } private static string SanitizeCss(string css, HtmlSanitizeSettings settings, bool styleTag) { using (var sw = new StringWriter()) using (var writer = new CssWriter(sw)) { foreach (var token in new CssTokenizer(css).Normalize()) { var prop = token as CssPropertyToken; var group = token as CssAtGroupToken; if (prop != null) { if (settings.AllowedCssProps.Contains(prop.Data)) { var removeProp = false; foreach (var arg in prop) { if (arg.Type == CssTokenType.Function && !settings.AllowedCssFunctions.Contains(arg.Data)) { removeProp = true; } else if (arg.Type == CssTokenType.Url) { var url = SanitizeUrl(arg.Data, settings); if (url == null) removeProp = true; } else if (arg.Data.IndexOf('<') >= 0 || arg.Data.IndexOf('>') >= 0) { removeProp = true; } } if (!removeProp) writer.Write(token); } } else if (group != null) { if (settings.AllowedCssAtRules.Contains(group.Data)) writer.Write(group); } else if (styleTag && (token.Type != CssTokenType.Function || settings.AllowedCssFunctions.Contains(token.Data))) { writer.Write(token); } } sw.Flush(); return sw.ToString(); } } /// <summary> /// Sanitizes a URL. /// </summary> /// <param name="url">The URL.</param> /// <param name="baseUrl">The base URL relative URLs are resolved against (empty or null for no resolution).</param> /// <returns>The sanitized URL or null if no safe URL can be created.</returns> private static string SanitizeUrl(string url, HtmlSanitizeSettings settings) { var uri = GetSafeUri(url, settings); if (uri == null) return null; try { return uri.IsAbsoluteUri ? uri.GetComponents(UriComponents.AbsoluteUri, settings.UriFormat) : uri.GetComponents(UriComponents.SerializationInfoString, settings.UriFormat); } catch (Exception) { return null; } } /// <summary> /// Tries to create a safe <see cref="Uri"/> object from a string. /// </summary> /// <param name="url">The URL.</param> /// <returns>The <see cref="Uri"/> object or null if no safe <see cref="Uri"/> can be created.</returns> private static Uri GetSafeUri(string url, HtmlSanitizeSettings settings) { Uri uri; if (!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri) || !uri.IsAbsoluteUri && !IsWellFormedRelativeUri(uri) || uri.IsAbsoluteUri && !settings.AllowedSchemes.Contains(uri.Scheme, StringComparer.OrdinalIgnoreCase)) return null; if (!uri.IsAbsoluteUri && uri.ToString().IndexOf(':') > 0) return null; return uri; } private static readonly Uri _exampleUri = new Uri("http://www.example.com/"); private static bool IsWellFormedRelativeUri(Uri uri) { Uri absoluteUri; return uri.OriginalString.IndexOf(':') < 0 && Uri.TryCreate(_exampleUri, uri, out absoluteUri); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Brokerages; using QuantConnect.Data; using QuantConnect.Data.Shortable; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Tests filtering in coarse selection by shortable quantity /// </summary> public class AllShortableSymbolsCoarseSelectionRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private static readonly DateTime _20140325 = new DateTime(2014, 3, 25); private static readonly DateTime _20140326 = new DateTime(2014, 3, 26); private static readonly DateTime _20140327 = new DateTime(2014, 3, 27); private static readonly DateTime _20140328 = new DateTime(2014, 3, 28); private static readonly DateTime _20140329 = new DateTime(2014, 3, 29); private static readonly Symbol _aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA); private static readonly Symbol _bac = QuantConnect.Symbol.Create("BAC", SecurityType.Equity, Market.USA); private static readonly Symbol _gme = QuantConnect.Symbol.Create("GME", SecurityType.Equity, Market.USA); private static readonly Symbol _goog = QuantConnect.Symbol.Create("GOOG", SecurityType.Equity, Market.USA); private static readonly Symbol _qqq = QuantConnect.Symbol.Create("QQQ", SecurityType.Equity, Market.USA); private static readonly Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA); private DateTime _lastTradeDate; private static readonly Dictionary<DateTime, bool> _coarseSelected = new Dictionary<DateTime, bool> { { _20140325, false }, { _20140326, false }, { _20140327, false }, { _20140328, false }, }; private static readonly Dictionary<DateTime, Symbol[]> _expectedSymbols = new Dictionary<DateTime, Symbol[]> { { _20140325, new[] { _bac, _qqq, _spy } }, { _20140326, new[] { _spy } }, { _20140327, new[] { _aapl, _bac, _gme, _qqq, _spy, } }, { _20140328, new[] { _goog } }, { _20140329, new Symbol[0] } }; public override void Initialize() { SetStartDate(2014, 3, 25); SetEndDate(2014, 3, 29); SetCash(10000000); AddUniverse(CoarseSelection); UniverseSettings.Resolution = Resolution.Daily; SetBrokerageModel(new AllShortableSymbolsRegressionAlgorithmBrokerageModel()); } public override void OnData(Slice data) { if (Time.Date == _lastTradeDate) { return; } foreach (var symbol in ActiveSecurities.Keys.OrderBy(symbol => symbol)) { if (!Portfolio.ContainsKey(symbol) || !Portfolio[symbol].Invested) { if (!Shortable(symbol)) { throw new Exception($"Expected {symbol} to be shortable on {Time:yyyy-MM-dd}"); } // Buy at least once into all Symbols. Since daily data will always use // MOO orders, it makes the testing of liquidating buying into Symbols difficult. MarketOrder(symbol, -(decimal)ShortableQuantity(symbol)); _lastTradeDate = Time.Date; } } } private IEnumerable<Symbol> CoarseSelection(IEnumerable<CoarseFundamental> coarse) { var shortableSymbols = AllShortableSymbols(); var selectedSymbols = coarse .Select(x => x.Symbol) .Where(s => shortableSymbols.ContainsKey(s) && shortableSymbols[s] >= 500) .OrderBy(s => s) .ToList(); var expectedMissing = 0; if (Time.Date == _20140327) { var gme = QuantConnect.Symbol.Create("GME", SecurityType.Equity, Market.USA); if (!shortableSymbols.ContainsKey(gme)) { throw new Exception("Expected unmapped GME in shortable symbols list on 2014-03-27"); } if (!coarse.Select(x => x.Symbol.Value).Contains("GME")) { throw new Exception("Expected mapped GME in coarse symbols on 2014-03-27"); } expectedMissing = 1; } var missing = _expectedSymbols[Time.Date].Except(selectedSymbols).ToList(); if (missing.Count != expectedMissing) { throw new Exception($"Expected Symbols selected on {Time.Date:yyyy-MM-dd} to match expected Symbols, but the following Symbols were missing: {string.Join(", ", missing.Select(s => s.ToString()))}"); } _coarseSelected[Time.Date] = true; return selectedSymbols; } public override void OnEndOfAlgorithm() { if (!_coarseSelected.Values.All(x => x)) { throw new AggregateException($"Expected coarse selection on all dates, but didn't run on: {string.Join(", ", _coarseSelected.Where(kvp => !kvp.Value).Select(kvp => kvp.Key.ToStringInvariant("yyyy-MM-dd")))}"); } } private class AllShortableSymbolsRegressionAlgorithmBrokerageModel : DefaultBrokerageModel { public AllShortableSymbolsRegressionAlgorithmBrokerageModel() : base() { ShortableProvider = new RegressionTestShortableProvider(); } } private class RegressionTestShortableProvider : LocalDiskShortableProvider { public RegressionTestShortableProvider() : base(SecurityType.Equity, "testbrokerage", Market.USA) { } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "5"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "19.147%"}, {"Drawdown", "0%"}, {"Expectancy", "0"}, {"Net Profit", "0.192%"}, {"Sharpe Ratio", "231.673"}, {"Probabilistic Sharpe Ratio", "0%"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.163"}, {"Beta", "-0.007"}, {"Annual Standard Deviation", "0.001"}, {"Annual Variance", "0"}, {"Information Ratio", "4.804"}, {"Tracking Error", "0.098"}, {"Treynor Ratio", "-22.526"}, {"Total Fees", "$307.50"}, {"Estimated Strategy Capacity", "$2600000.00"}, {"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"}, {"Fitness Score", "0.106"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "79228162514264337593543950335"}, {"Return Over Maximum Drawdown", "79228162514264337593543950335"}, {"Portfolio Turnover", "0.106"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "0069f402ffcd2d91b9018b81badfab81"} }; } }
/* Copyright (C) 2013-2015 MetaMorph Software, Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this data, including any software or models in source or binary form, as well as any drawings, specifications, and documentation (collectively "the Data"), to deal in the Data without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Data, and to permit persons to whom the Data 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 Data. THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA. */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; using GME.CSharp; using GME; using GME.MGA; using GME.MGA.Core; using System.Linq; using META; using CyPhyGUIs; using Tonka = ISIS.GME.Dsml.CyPhyML.Interfaces; using TonkaClasses = ISIS.GME.Dsml.CyPhyML.Classes; using System.Diagnostics; using System.Windows.Forms; using System.Reflection; namespace CyPhy2Schematic { /// <summary> /// This class implements the necessary COM interfaces for a GME interpreter component. /// </summary> [Guid(ComponentConfig.guid), ProgId(ComponentConfig.progID), ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] public class CyPhy2SchematicInterpreter : IMgaComponentEx, IGMEVersionInfo, ICyPhyInterpreter { /// <summary> /// Contains information about the GUI event that initiated the invocation. /// </summary> public enum ComponentStartMode { GME_MAIN_START = 0, // Not used by GME GME_BROWSER_START = 1, // Right click in the GME Tree Browser window GME_CONTEXT_START = 2, // Using the context menu by right clicking a model element in the GME modeling window GME_EMBEDDED_START = 3, // Not used by GME GME_MENU_START = 16, // Clicking on the toolbar icon, or using the main menu GME_BGCONTEXT_START = 18, // Using the context menu by right clicking the background of the GME modeling window GME_ICON_START = 32, // Not used by GME GME_SILENT_MODE = 128 // Not used by GME, available to testers not using GME } /// <summary> /// This function is called for each interpreter invocation before Main. /// Don't perform MGA operations here unless you open a transaction. /// </summary> /// <param name="project">The handle of the project opened in GME, for which the interpreter was called.</param> public void Initialize(MgaProject project) { if (Logger == null) Logger = new GMELogger(project, ComponentName); MgaGateway = new MgaGateway(project); project.CreateTerritoryWithoutSink(out MgaGateway.territory); } private CyPhy2Schematic_Settings InitializeSettingsFromWorkflow(CyPhy2Schematic_Settings settings) { // Seed with settings from workflow. String str_WorkflowParameters = ""; try { MgaGateway.PerformInTransaction(delegate { var testBench = TonkaClasses.TestBench.Cast(this.mainParameters.CurrentFCO); var workflowRef = testBench.Children.WorkflowRefCollection.FirstOrDefault(); var workflow = workflowRef.Referred.Workflow; var taskCollection = workflow.Children.TaskCollection; var myTask = taskCollection.FirstOrDefault(t => t.Attributes.COMName == this.ComponentProgID); str_WorkflowParameters = myTask.Attributes.Parameters; }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: true ); Dictionary<string, string> dict_WorkflowParameters = (Dictionary<string, string>) Newtonsoft.Json.JsonConvert.DeserializeObject(str_WorkflowParameters, typeof(Dictionary<string, string>)); if (dict_WorkflowParameters != null) { settings = new CyPhy2Schematic_Settings(); foreach (var property in settings.GetType().GetProperties() .Where(p => p.GetCustomAttributes(typeof(WorkflowConfigItemAttribute), false).Any()) .Where(p => dict_WorkflowParameters.ContainsKey(p.Name))) { property.SetValue(settings, dict_WorkflowParameters[property.Name], null); } } } catch (NullReferenceException) { Logger.WriteInfo("Could not find workflow object for CyPhy2Schematic interpreter."); } catch (Newtonsoft.Json.JsonReaderException) { Logger.WriteWarning("Workflow Parameter has invalid Json String: {0}", str_WorkflowParameters); } return settings; } #region IMgaComponentEx Members private MgaGateway MgaGateway { get; set; } private GMELogger Logger { get; set; } public void InvokeEx(MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param) { if (this.enabled == false) { return; } try { // Need to call this interpreter in the same way as the MasterInterpreter will call it. // initialize main parameters var parameters = new InterpreterMainParameters() { Project = project, CurrentFCO = currentobj, SelectedFCOs = selectedobjs, StartModeParam = param }; this.mainParameters = parameters; parameters.ProjectDirectory = project.GetRootDirectoryPath(); // set up the output directory MgaGateway.PerformInTransaction(delegate { string outputDirName = project.Name; if (currentobj != null) { outputDirName = currentobj.Name; } var outputDirAbsPath = Path.GetFullPath(Path.Combine( parameters.ProjectDirectory, "results", outputDirName)); parameters.OutputDirectory = outputDirAbsPath; if (Directory.Exists(outputDirAbsPath)) { Logger.WriteWarning("Output directory {0} already exists. Unexpected behavior may result.", outputDirAbsPath); } else { Directory.CreateDirectory(outputDirAbsPath); } //this.Parameters.PackageName = Schematic.Factory.GetModifiedName(currentobj.Name); }); PreConfigArgs preConfigArgs = new PreConfigArgs() { ProjectDirectory = parameters.ProjectDirectory, Project = parameters.Project }; // call the preconfiguration with no parameters and get preconfig var preConfig = this.PreConfig(preConfigArgs); // get previous GUI config var settings_ = META.ComComponent.DeserializeConfiguration(parameters.ProjectDirectory, typeof(CyPhy2Schematic_Settings), this.ComponentProgID); CyPhy2Schematic_Settings settings = (settings_ != null) ? settings_ as CyPhy2Schematic_Settings : new CyPhy2Schematic_Settings(); // Set configuration based on Workflow Parameters. This will override all [WorkflowConfigItem] members. settings = InitializeSettingsFromWorkflow(settings); // Don't skip GUI -- we've been invoked directly here. settings.skipGUI = null; // get interpreter config through GUI var config = this.DoGUIConfiguration(preConfig, settings); if (config == null) { Logger.WriteWarning("Operation canceled by the user."); return; } // if config is valid save it and update it on the file system META.ComComponent.SerializeConfiguration(parameters.ProjectDirectory, config, this.ComponentProgID); // assign the new configuration to mainParameters parameters.config = config; // call the main (ICyPhyComponent) function this.Main(parameters); } catch (Exception ex) { Logger.WriteError("Interpretation failed {0}<br>{1}", ex.Message, ex.StackTrace); } finally { if (MgaGateway != null && MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } DisposeLogger(); MgaGateway = null; project = null; currentobj = null; selectedobjs = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } } #region Component Information public string ComponentName { get { return GetType().Name; } } public string ComponentProgID { get { return ComponentConfig.progID; } } public componenttype_enum ComponentType { get { return ComponentConfig.componentType; } } public string Paradigm { get { return ComponentConfig.paradigmName; } } #endregion #region Enabling bool enabled = true; public void Enable(bool newval) { enabled = newval; } #endregion #region Interactive Mode protected bool interactiveMode = true; public bool InteractiveMode { get { return interactiveMode; } set { interactiveMode = value; } } #endregion #region Custom Parameters SortedDictionary<string, object> componentParameters = null; public object get_ComponentParameter(string Name) { if (Name == "type") return "csharp"; if (Name == "path") return GetType().Assembly.Location; if (Name == "fullname") return GetType().FullName; object value; if (componentParameters != null && componentParameters.TryGetValue(Name, out value)) { return value; } return null; } public void set_ComponentParameter(string Name, object pVal) { if (componentParameters == null) { componentParameters = new SortedDictionary<string, object>(); } componentParameters[Name] = pVal; } #endregion #region Unused Methods // Old interface, it is never called for MgaComponentEx interfaces public void Invoke(MgaProject Project, MgaFCOs selectedobjs, int param) { throw new NotImplementedException(); } // Not used by GME public void ObjectsInvokeEx(MgaProject Project, MgaObject currentobj, MgaObjects selectedobjs, int param) { throw new NotImplementedException(); } #endregion #endregion #region IMgaVersionInfo Members public GMEInterfaceVersion_enum version { get { return GMEInterfaceVersion_enum.GMEInterfaceVersion_Current; } } #endregion #region Registration Helpers [ComRegisterFunctionAttribute] public static void GMERegister(Type t) { Registrar.RegisterComponentsInGMERegistry(); } [ComUnregisterFunctionAttribute] public static void GMEUnRegister(Type t) { Registrar.UnregisterComponentsInGMERegistry(); } #endregion #region Dependent Interpreters private bool CallElaborator( MgaProject project, MgaFCO currentobj, MgaFCOs selectedobjs, int param, bool expand = true) { bool result = false; try { this.Logger.WriteDebug("Elaborating model..."); var elaborator = new CyPhyElaborateCS.CyPhyElaborateCSInterpreter(); elaborator.Initialize(project); int verbosity = 128; result = elaborator.RunInTransaction(project, currentobj, selectedobjs, verbosity); if (this.result.Traceability == null) { this.result.Traceability = new META.MgaTraceability(); } if (elaborator.Traceability != null) { elaborator.Traceability.CopyTo(this.result.Traceability); } this.Logger.WriteDebug("Elaboration is done."); } catch (Exception ex) { this.Logger.WriteError("Exception occurred in Elaborator : {0}", ex.ToString()); result = false; } return result; } #endregion #region CyPhyGUIs /// <summary> /// Result of the latest run of this interpreter. /// </summary> private InterpreterResult result = new InterpreterResult(); /// <summary> /// Parameter of this run. /// </summary> private IInterpreterMainParameters mainParameters { get; set; } /// <summary> /// Output directory where all files must be generated /// </summary> private string OutputDirectory { get { return this.mainParameters.OutputDirectory; } } private void UpdateSuccess(string message, bool success) { this.result.Success = this.result.Success && success; this.runtime.Enqueue(new Tuple<string, TimeSpan>(message, DateTime.Now - this.startTime)); if (success) { Logger.WriteInfo("{0} : OK", message); } else { Logger.WriteError("{0} : FAILED", message); } } /// <summary> /// Name of the log file. (It is not a full path) /// </summary> private string LogFileFilename { get; set; } /// <summary> /// ProgId of the configuration class of this interpreter. /// </summary> public string InterpreterConfigurationProgId { get { return (typeof(CyPhy2Schematic_Settings).GetCustomAttributes(typeof(ProgIdAttribute), false)[0] as ProgIdAttribute).Value; } } /// <summary> /// Preconfig gets called first. No transaction is open, but one may be opened. /// In this function model may be processed and some object ids get serialized /// and returned as preconfiguration (project-wise configuration). /// </summary> /// <param name="preConfigParameters"></param> /// <returns>Null if no configuration is required by the DoGUIConfig.</returns> public IInterpreterPreConfiguration PreConfig(IPreConfigParameters preConfigParameters) { //var preConfig = new CyPhy2Schematic_v2PreConfiguration() //{ // ProjectDirectory = preConfigParameters.ProjectDirectory //}; //return preConfig; return null; } /// <summary> /// Shows a form for the user to select/change settings through a GUI. All interactive /// GUI operations MUST happen within this function scope. /// </summary> /// <param name="preConfig">Result of PreConfig</param> /// <param name="previousConfig">Previous configuration to initialize the GUI.</param> /// <returns>Null if operation is canceled by the user. Otherwise returns with a new /// configuration object.</returns> public IInterpreterConfiguration DoGUIConfiguration( IInterpreterPreConfiguration preConfig, IInterpreterConfiguration previousConfig) { CyPhy2Schematic_Settings settings = (previousConfig as CyPhy2Schematic_Settings); // If none found, we should do GUI. // If available, seed the GUI with the previous settings. if (settings == null || settings.skipGUI == null) { // Do GUI var gui = new CyPhy2Schematic.GUI.CyPhy2Schematic_GUI(); gui.settings = settings; var result = gui.ShowDialog(); if (result == DialogResult.OK) { return gui.settings; } else { // USER CANCELED. return null; } } return settings; } private Queue<Tuple<string, TimeSpan>> runtime = new Queue<Tuple<string, TimeSpan>>(); private DateTime startTime = DateTime.Now; /// <summary> /// No GUI and interactive elements are allowed within this function. /// </summary> /// <param name="parameters">Main parameters for this run and GUI configuration.</param> /// <returns>Result of the run, which contains a success flag.</returns> public IInterpreterResult Main(IInterpreterMainParameters parameters) { if (Logger == null) Logger = new GMELogger(parameters.Project, ComponentName); this.runtime.Clear(); this.mainParameters = parameters; var configSuccess = this.mainParameters != null; this.UpdateSuccess("Configuration", configSuccess); this.result.Labels = "Schematic"; try { MgaGateway.PerformInTransaction(delegate { this.WorkInMainTransaction(); }, transactiontype_enum.TRANSACTION_NON_NESTED, abort: true ); this.PrintRuntimeStatistics(); if (this.result.Success) { Logger.WriteInfo("Generated files are here: <a href=\"file:///{0}\" target=\"_blank\">{0}</a>", this.mainParameters.OutputDirectory); Logger.WriteInfo("Schematic Interpreter has finished. [SUCCESS: {0}, Labels: {1}]", this.result.Success, this.result.Labels); } else { Logger.WriteError("Schematic Interpreter failed! See error messages above."); } } catch (Exception ex) { Logger.WriteError("Exception: {0}<br> {1}", ex.Message, ex.StackTrace); } finally { if (MgaGateway != null && MgaGateway.territory != null) { MgaGateway.territory.Destroy(); } DisposeLogger(); MgaGateway = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } META.Logger.RemoveFileListener(this.ComponentName); var SchematicSettings = this.mainParameters.config as CyPhy2Schematic_Settings; return this.result; } public void DisposeLogger() { if (Logger != null) Logger.Dispose(); Logger = null; } private void PrintRuntimeStatistics() { Logger.WriteDebug("======================================================"); Logger.WriteDebug("Start time: {0}", this.startTime); foreach (var time in this.runtime) { Logger.WriteDebug("{0} = {1}", time.Item1, time.Item2); } Logger.WriteDebug("======================================================"); } #endregion #region CyPhy2Schematic Specific code /// <summary> /// This function does the job. CyPhy2Schematic translation. /// </summary> private void WorkInMainTransaction() { var config = (this.mainParameters.config as CyPhy2Schematic_Settings); this.result.Success = true; Schematic.CodeGenerator.Mode mode = Schematic.CodeGenerator.Mode.EDA; if (config.doSpice != null) { this.result.RunCommand = "runspice.bat"; mode = Schematic.CodeGenerator.Mode.SPICE; } else if (config.doSpiceForSI != null) { this.result.RunCommand = "runspice.bat"; mode = Schematic.CodeGenerator.Mode.SPICE_SI; } else { mode = Schematic.CodeGenerator.Mode.EDA; if (config.doChipFit != null) { Boolean chipFitViz = false; if (Boolean.TryParse(config.showChipFitVisualizer, out chipFitViz) && chipFitViz) { this.result.RunCommand = "chipfit.bat chipfit_display"; } else { this.result.RunCommand = "chipFit.bat"; } } else if (config.doPlaceRoute != null) { this.result.RunCommand = "placement.bat"; } else if (config.doPlaceOnly != null) { this.result.RunCommand = "placeonly.bat"; } else { this.result.RunCommand = "dir"; } } // Call Elaborator var elaboratorSuccess = this.CallElaborator(this.mainParameters.Project, this.mainParameters.CurrentFCO, this.mainParameters.SelectedFCOs, this.mainParameters.StartModeParam); this.UpdateSuccess("Elaborator", elaboratorSuccess); bool successTranslation = true; try { Schematic.CodeGenerator.Logger = Logger; var schematicCodeGenerator = new Schematic.CodeGenerator(this.mainParameters, mode); var gcResult = schematicCodeGenerator.GenerateCode(); if (mode == Schematic.CodeGenerator.Mode.EDA && (config.doPlaceRoute != null || config.doPlaceOnly != null)) { this.result.RunCommand += gcResult.runCommandArgs; } successTranslation = true; } catch (Exception ex) { Logger.WriteError(ex.ToString()); successTranslation = false; } this.UpdateSuccess("Schematic translation", successTranslation); } #endregion } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ namespace NLog.Targets { using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Security; using Internal.Fakeables; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Writes log message to the Event Log. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/EventLog-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/EventLog/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/EventLog/Simple/Example.cs" /> /// </example> [Target("EventLog")] public class EventLogTarget : TargetWithLayout, IInstallable { private EventLog eventLogInstance; /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> public EventLogTarget() : this(AppDomainWrapper.CurrentDomain) { } /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> public EventLogTarget(IAppDomain appDomain) { this.Source = appDomain.FriendlyName; this.Log = "Application"; this.MachineName = "."; this.MaxMessageLength = 16384; } /// <summary> /// Gets or sets the name of the machine on which Event Log service is running. /// </summary> /// <docgen category='Event Log Options' order='10' /> [DefaultValue(".")] public string MachineName { get; set; } /// <summary> /// Gets or sets the layout that renders event ID. /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout EventId { get; set; } /// <summary> /// Gets or sets the layout that renders event Category. /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout Category { get; set; } /// <summary> /// Optional entrytype. When not set, or when not convertable to <see cref="LogLevel"/> then determined by <see cref="NLog.LogLevel"/> /// </summary> public Layout EntryType { get; set; } /// <summary> /// Gets or sets the value to be used as the event Source. /// </summary> /// <remarks> /// By default this is the friendly name of the current AppDomain. /// </remarks> /// <docgen category='Event Log Options' order='10' /> public Layout Source { get; set; } /// <summary> /// Gets or sets the name of the Event Log to write to. This can be System, Application or /// any user-defined name. /// </summary> /// <docgen category='Event Log Options' order='10' /> [DefaultValue("Application")] public string Log { get; set; } private int maxMessageLength; /// <summary> /// Gets or sets the message length limit to write to the Event Log. /// </summary> /// <remarks><value>MaxMessageLength</value> cannot be zero or negative</remarks> [DefaultValue(16384)] public int MaxMessageLength { get { return this.maxMessageLength; } set { if (value <= 0) throw new ArgumentException("MaxMessageLength cannot be zero or negative."); this.maxMessageLength = value; } } /// <summary> /// Gets or sets the action to take if the message is larger than the <see cref="MaxMessageLength"/> option. /// </summary> /// <docgen category='Event Log Overflow Action' order='10' /> [DefaultValue(EventLogTargetOverflowAction.Truncate)] public EventLogTargetOverflowAction OnOverflow { get; set; } /// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { var fixedSource = GetFixedSource(); //always throw error to keep backwardscomp behavior. CreateEventSourceIfNeeded(fixedSource, true); } /// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { var fixedSource = GetFixedSource(); if (string.IsNullOrEmpty(fixedSource)) { InternalLogger.Debug("Skipping removing of event source because it contains layout renderers"); } else { EventLog.DeleteEventSource(fixedSource, this.MachineName); } } /// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { var fixedSource = GetFixedSource(); if (!string.IsNullOrEmpty(fixedSource)) { return EventLog.SourceExists(fixedSource, this.MachineName); } InternalLogger.Debug("Unclear if event source exists because it contains layout renderers"); return null; //unclear! } /// <summary> /// Initializes the target. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); var fixedSource = GetFixedSource(); if (string.IsNullOrEmpty(fixedSource)) { InternalLogger.Debug("Skipping creation of event source because it contains layout renderers"); } else { var currentSourceName = EventLog.LogNameFromSourceName(fixedSource, this.MachineName); if (!currentSourceName.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase)) { this.CreateEventSourceIfNeeded(fixedSource, false); } } } /// <summary> /// Writes the specified logging event to the event log. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { string message = this.Layout.Render(logEvent); EventLogEntryType entryType = GetEntryType(logEvent); int eventId = 0; if (this.EventId != null) { eventId = Convert.ToInt32(this.EventId.Render(logEvent), CultureInfo.InvariantCulture); } short category = 0; if (this.Category != null) { category = Convert.ToInt16(this.Category.Render(logEvent), CultureInfo.InvariantCulture); } EventLog eventLog = GetEventLog(logEvent); // limitation of EventLog API if (message.Length > this.MaxMessageLength) { if (OnOverflow == EventLogTargetOverflowAction.Truncate) { message = message.Substring(0, this.MaxMessageLength); eventLog.WriteEntry(message, entryType, eventId, category); } else if (OnOverflow == EventLogTargetOverflowAction.Split) { for (int offset = 0; offset < message.Length; offset += this.MaxMessageLength) { string chunk = message.Substring(offset, Math.Min(this.MaxMessageLength, (message.Length - offset))); eventLog.WriteEntry(chunk, entryType, eventId, category); } } else if (OnOverflow == EventLogTargetOverflowAction.Discard) { //message will not be written return; } } else { eventLog.WriteEntry(message, entryType, eventId, category); } } /// <summary> /// Get the entry type for logging the message. /// </summary> /// <param name="logEvent">The logging event - for rendering the <see cref="EntryType"/></param> /// <returns></returns> private EventLogEntryType GetEntryType(LogEventInfo logEvent) { if (this.EntryType != null) { //try parse, if fail, determine auto var value = this.EntryType.Render(logEvent); EventLogEntryType eventLogEntryType; if (EnumHelpers.TryParse(value, true, out eventLogEntryType)) { return eventLogEntryType; } } // determine auto if (logEvent.Level >= LogLevel.Error) { return EventLogEntryType.Error; } if (logEvent.Level >= LogLevel.Warn) { return EventLogEntryType.Warning; } return EventLogEntryType.Information; } /// <summary> /// Get the source, if and only if the source is fixed. /// </summary> /// <returns><c>null</c> when not <see cref="SimpleLayout.IsFixedText"/></returns> /// <remarks>Internal for unit tests</remarks> internal string GetFixedSource() { if (this.Source == null) { return null; } var simpleLayout = Source as SimpleLayout; if (simpleLayout != null && simpleLayout.IsFixedText) { return simpleLayout.FixedText; } return null; } /// <summary> /// Get the eventlog to write to. /// </summary> /// <param name="logEvent">Event if the source needs to be rendered.</param> /// <returns></returns> private EventLog GetEventLog(LogEventInfo logEvent) { return eventLogInstance ?? (eventLogInstance = new EventLog(this.Log, this.MachineName, this.Source.Render(logEvent))); } /// <summary> /// (re-)create a event source, if it isn't there. Works only with fixed sourcenames. /// </summary> /// <param name="fixedSource">sourcenaam. If source is not fixed (see <see cref="SimpleLayout.IsFixedText"/>, then pass <c>null</c> or emptystring.</param> /// <param name="alwaysThrowError">always throw an Exception when there is an error</param> private void CreateEventSourceIfNeeded(string fixedSource, bool alwaysThrowError) { if (string.IsNullOrEmpty(fixedSource)) { InternalLogger.Debug("Skipping creation of event source because it contains layout renderers"); //we can only create event sources if the source is fixed (no layout) return; } // if we throw anywhere, we remain non-operational try { if (EventLog.SourceExists(fixedSource, this.MachineName)) { string currentLogName = EventLog.LogNameFromSourceName(fixedSource, this.MachineName); if (!currentLogName.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase)) { // re-create the association between Log and Source EventLog.DeleteEventSource(fixedSource, this.MachineName); var eventSourceCreationData = new EventSourceCreationData(fixedSource, this.Log) { MachineName = this.MachineName }; EventLog.CreateEventSource(eventSourceCreationData); } } else { var eventSourceCreationData = new EventSourceCreationData(fixedSource, this.Log) { MachineName = this.MachineName }; EventLog.CreateEventSource(eventSourceCreationData); } } catch (Exception exception) { InternalLogger.Error(exception, "Error when connecting to EventLog."); if (alwaysThrowError || exception.MustBeRethrown()) { throw; } } } } } #endif
/* * 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.Collections.Generic; using System.Data; using OpenSim.Framework; using OpenSim.Framework.Console; using log4net; using OpenMetaverse; using Npgsql; using NpgsqlTypes; namespace OpenSim.Data.PGSQL { public class PGSQLFSAssetData : IFSAssetDataPlugin { private const string _migrationStore = "FSAssetStore"; private static string m_Table = "fsassets"; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private long m_ticksToEpoch; private PGSQLManager m_database; private string m_connectionString; public PGSQLFSAssetData() { } public void Initialise(string connect, string realm, int UpdateAccessTime) { DaysBetweenAccessTimeUpdates = UpdateAccessTime; m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks; m_connectionString = connect; m_database = new PGSQLManager(m_connectionString); //New migration to check for DB changes m_database.CheckMigration(_migrationStore); } public void Initialise() { throw new NotImplementedException(); } /// <summary> /// Number of days that must pass before we update the access time on an asset when it has been fetched /// Config option to change this is "DaysBetweenAccessTimeUpdates" /// </summary> private int DaysBetweenAccessTimeUpdates = 0; protected virtual Assembly Assembly { get { return GetType().Assembly; } } #region IPlugin Members public string Version { get { return "1.0.0.0"; } } public void Dispose() { } public string Name { get { return "PGSQL FSAsset storage engine"; } } #endregion #region IFSAssetDataPlugin Members public AssetMetadata Get(string id, out string hash) { hash = String.Empty; AssetMetadata meta = null; string query = String.Format("select \"id\", \"type\", \"hash\", \"create_time\", \"access_time\", \"asset_flags\" from {0} where \"id\" = :id", m_Table); using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { dbcon.Open(); cmd.Parameters.Add(m_database.CreateParameter("id", new UUID(id))); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default)) { if (reader.Read()) { meta = new AssetMetadata(); hash = reader["hash"].ToString().Trim(); meta.ID = id; meta.FullID = new UUID(id); meta.Name = String.Empty; meta.Description = String.Empty; meta.Type = (sbyte)Convert.ToInt32(reader["type"]); meta.ContentType = SLUtil.SLAssetTypeToContentType(meta.Type); meta.CreationDate = Util.ToDateTime(Convert.ToInt32(reader["create_time"])); meta.Flags = (AssetFlags)Convert.ToInt32(reader["asset_flags"]); int atime = Convert.ToInt32(reader["access_time"]); UpdateAccessTime(atime, id); } } } return meta; } private void UpdateAccessTime(int AccessTime, string id) { // Reduce DB work by only updating access time if asset hasn't recently been accessed // 0 By Default, Config option is "DaysBetweenAccessTimeUpdates" if (DaysBetweenAccessTimeUpdates > 0 && (DateTime.UtcNow - Utils.UnixTimeToDateTime(AccessTime)).TotalDays < DaysBetweenAccessTimeUpdates) return; string query = String.Format("UPDATE {0} SET \"access_time\" = :access_time WHERE \"id\" = (:id)::uuid", m_Table); using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { dbcon.Open(); int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000); cmd.Parameters.Add(m_database.CreateParameter("id", id)); cmd.Parameters.Add(m_database.CreateParameter("access_time", now)); cmd.ExecuteNonQuery(); } } public bool Store(AssetMetadata meta, string hash) { try { bool found = false; string oldhash; AssetMetadata existingAsset = Get(meta.ID, out oldhash); string query = String.Format("UPDATE {0} SET \"access_time\" = :access_time WHERE \"id\" = (:id)::uuid", m_Table); if (existingAsset == null) { query = String.Format("insert into {0} (\"id\", \"type\", \"hash\", \"asset_flags\", \"create_time\", \"access_time\") values ( (:id)::uuid, :type, :hash, :asset_flags, :create_time, :access_time)", m_Table); found = true; } using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { dbcon.Open(); int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000); cmd.Parameters.Add(m_database.CreateParameter("id", meta.FullID)); cmd.Parameters.Add(m_database.CreateParameter("type", meta.Type)); cmd.Parameters.Add(m_database.CreateParameter("hash", hash)); cmd.Parameters.Add(m_database.CreateParameter("asset_flags", Convert.ToInt32(meta.Flags))); cmd.Parameters.Add(m_database.CreateParameter("create_time", now)); cmd.Parameters.Add(m_database.CreateParameter("access_time", now)); cmd.ExecuteNonQuery(); } return found; } catch(Exception e) { m_log.Error("[PGSQL FSASSETS] Failed to store asset with ID " + meta.ID); m_log.Error(e.ToString()); return false; } } /// <summary> /// Check if the assets exist in the database. /// </summary> /// <param name="uuids">The asset UUID's</param> /// <returns>For each asset: true if it exists, false otherwise</returns> public bool[] AssetsExist(UUID[] uuids) { if (uuids.Length == 0) return new bool[0]; HashSet<UUID> exists = new HashSet<UUID>(); string ids = "'" + string.Join("','", uuids) + "'"; string query = string.Format("select \"id\" from {1} where id in ({0})", ids, m_Table); using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { dbcon.Open(); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default)) { while (reader.Read()) { UUID id = DBGuid.FromDB(reader["id"]);; exists.Add(id); } } } bool[] results = new bool[uuids.Length]; for (int i = 0; i < uuids.Length; i++) results[i] = exists.Contains(uuids[i]); return results; } public int Count() { int count = 0; string query = String.Format("select count(*) as count from {0}", m_Table); using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { dbcon.Open(); IDataReader reader = cmd.ExecuteReader(); reader.Read(); count = Convert.ToInt32(reader["count"]); reader.Close(); } return count; } public bool Delete(string id) { string query = String.Format("delete from {0} where \"id\" = :id", m_Table); using (NpgsqlConnection dbcon = new NpgsqlConnection(m_connectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { dbcon.Open(); cmd.Parameters.Add(m_database.CreateParameter("id", new UUID(id))); cmd.ExecuteNonQuery(); } return true; } public void Import(string conn, string table, int start, int count, bool force, FSStoreDelegate store) { int imported = 0; string limit = String.Empty; if(count != -1) { limit = String.Format(" limit {0} offset {1}", start, count); } string query = String.Format("select * from {0}{1}", table, limit); try { using (NpgsqlConnection remote = new NpgsqlConnection(conn)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, remote)) { remote.Open(); MainConsole.Instance.Output("Querying database"); MainConsole.Instance.Output("Reading data"); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default)) { while (reader.Read()) { if ((imported % 100) == 0) { MainConsole.Instance.Output(String.Format("{0} assets imported so far", imported)); } AssetBase asset = new AssetBase(); AssetMetadata meta = new AssetMetadata(); meta.ID = reader["id"].ToString(); meta.FullID = new UUID(meta.ID); meta.Name = String.Empty; meta.Description = String.Empty; meta.Type = (sbyte)Convert.ToInt32(reader["assetType"]); meta.ContentType = SLUtil.SLAssetTypeToContentType(meta.Type); meta.CreationDate = Util.ToDateTime(Convert.ToInt32(reader["create_time"])); asset.Metadata = meta; asset.Data = (byte[])reader["data"]; store(asset, force); imported++; } } } } catch (Exception e) { m_log.ErrorFormat("[PGSQL FSASSETS]: Error importing assets: {0}", e.Message.ToString()); return; } MainConsole.Instance.Output(String.Format("Import done, {0} assets imported", imported)); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using GraphQL.Language.AST; using GraphQL.StarWars.Types; using GraphQL.Types; using Shouldly; using Xunit; namespace GraphQL.Tests.Utilities { public class SchemaBuilderTests { [Fact] public void should_set_query_by_name() { var definitions = @" type Query { id: String } "; var schema = Schema.For(definitions); schema.Initialize(); var query = schema.Query; query.ShouldNotBeNull(); query.Name.ShouldBe("Query"); query.Fields.Count.ShouldBe(1); query.Fields.Single().Name.ShouldBe("id"); } [Fact] public void should_set_mutation_by_name() { var definitions = @" type Mutation { mutate: String } "; var schema = Schema.For(definitions); schema.Initialize(); var mutation = schema.Mutation; mutation.ShouldNotBeNull(); mutation.Name.ShouldBe("Mutation"); mutation.Fields.Count.ShouldBe(1); mutation.Fields.Single().Name.ShouldBe("mutate"); } [Fact] public void should_set_subscription_by_name() { var definitions = @" type Subscription { subscribe: String } "; var schema = Schema.For(definitions); schema.Initialize(); var subscription = schema.Subscription; subscription.ShouldNotBeNull(); subscription.Name.ShouldBe("Subscription"); subscription.Fields.Count.ShouldBe(1); subscription.Fields.Single().Name.ShouldBe("subscribe"); } [Fact] public void configures_schema_from_schema_type() { var definitions = @" type MyQuery { id: String } type MyMutation { mutate: String } type MySubscription { subscribe: String } schema { query: MyQuery mutation: MyMutation subscription: MySubscription } "; var schema = Schema.For(definitions); schema.Initialize(); var query = schema.Query; query.ShouldNotBeNull(); query.Name.ShouldBe("MyQuery"); var mutation = schema.Mutation; mutation.ShouldNotBeNull(); mutation.Name.ShouldBe("MyMutation"); var subscription = schema.Subscription; subscription.ShouldNotBeNull(); subscription.Name.ShouldBe("MySubscription"); } private enum TestEnum { ASC, DESC } [Fact] public void configures_schema_from_schema_type_and_directives() { var definitions = @" type MyQuery { id: String } type MyMutation @requireAuth(role: ""Admin"") { mutate: String } type MySubscription @requireAuth { subscribe: String @traits(volatile: true, documented: false, enumerated: DESC) @some @some } schema @public { query: MyQuery mutation: MyMutation subscription: MySubscription } "; var schema = Schema.For(definitions); schema.Directives.Register(new DirectiveGraphType("public", DirectiveLocation.Schema)); schema.Directives.Register(new DirectiveGraphType("requireAuth", DirectiveLocation.Object) { Arguments = new QueryArguments(new QueryArgument<StringGraphType> { Name = "role" }) }); schema.Directives.Register(new DirectiveGraphType("traits", DirectiveLocation.FieldDefinition) { Arguments = new QueryArguments(new QueryArgument<NonNullGraphType<BooleanGraphType>> { Name = "volatile" }, new QueryArgument<BooleanGraphType> { Name = "documented" }, new QueryArgument<EnumerationGraphType<TestEnum>> { Name = "enumerated" }) }); schema.Directives.Register(new DirectiveGraphType("some", DirectiveLocation.FieldDefinition) { Repeatable = true }); schema.Initialized.ShouldBe(false); schema.Initialize(); schema.HasAppliedDirectives().ShouldBeTrue(); schema.GetAppliedDirectives().Count.ShouldBe(1); schema.GetAppliedDirectives().Find("public").ShouldNotBeNull(); schema.GetAppliedDirectives().Find("public").ArgumentsCount.ShouldBe(0); schema.GetAppliedDirectives().Find("public").List.ShouldBeNull(); var query = schema.Query; query.ShouldNotBeNull(); query.Name.ShouldBe("MyQuery"); query.HasAppliedDirectives().ShouldBeFalse(); query.GetAppliedDirectives().ShouldBeNull(); var mutation = schema.Mutation; mutation.ShouldNotBeNull(); mutation.Name.ShouldBe("MyMutation"); mutation.HasAppliedDirectives().ShouldBeTrue(); mutation.GetAppliedDirectives().Count.ShouldBe(1); mutation.GetAppliedDirectives().Find("requireAuth").ShouldNotBeNull(); mutation.GetAppliedDirectives().Find("requireAuth").List.Count.ShouldBe(1); mutation.GetAppliedDirectives().Find("requireAuth").List[0].Name.ShouldBe("role"); mutation.GetAppliedDirectives().Find("requireAuth").List[0].Value.ShouldBe("Admin"); var subscription = schema.Subscription; subscription.ShouldNotBeNull(); subscription.Name.ShouldBe("MySubscription"); subscription.GetAppliedDirectives().Count.ShouldBe(1); subscription.GetAppliedDirectives().Find("requireAuth").ShouldNotBeNull(); subscription.GetAppliedDirectives().Find("requireAuth").ArgumentsCount.ShouldBe(0); subscription.GetAppliedDirectives().Find("requireAuth").List.ShouldBeNull(); var field = subscription.Fields.Find("subscribe"); field.ShouldNotBeNull(); field.GetAppliedDirectives().Count.ShouldBe(3); field.GetAppliedDirectives().Find("traits").ShouldNotBeNull(); field.GetAppliedDirectives().Find("traits").List.Count.ShouldBe(3); field.GetAppliedDirectives().Find("traits").List[0].Name.ShouldBe("volatile"); field.GetAppliedDirectives().Find("traits").List[0].Value.ShouldBe(true); field.GetAppliedDirectives().Find("traits").List[1].Name.ShouldBe("documented"); field.GetAppliedDirectives().Find("traits").List[1].Value.ShouldBe(false); field.GetAppliedDirectives().Find("traits").List[2].Name.ShouldBe("enumerated"); field.GetAppliedDirectives().Find("traits").List[2].Value.ShouldBe("DESC"); field.GetAppliedDirectives().Find("some").ShouldNotBeNull(); field.GetAppliedDirectives().Find("some").ArgumentsCount.ShouldBe(0); } [Fact] public void builds_type_with_arguments() { var definitions = @" type Query { """""" Post description """""" post(""ID description"" id: ID = 1, ""Val description"" val: String): String } "; var schema = Schema.For(definitions, builder => builder.Types.For("Query").FieldFor("post").ArgumentFor("id").Description = "Some argument"); schema.Initialize(); var query = schema.Query; query.Fields.Count.ShouldBe(1); var field = query.Fields.Single(); field.Name.ShouldBe("post"); field.Arguments.Count.ShouldBe(2); field.ResolvedType.Name.ShouldBe("String"); field.Description.ShouldBe("Post description"); var arg = field.Arguments.First(); arg.Name.ShouldBe("id"); arg.DefaultValue.ShouldBe(1); arg.ResolvedType.Name.ShouldBe("ID"); arg.Description.ShouldBe("Some argument"); arg = field.Arguments.Last(); arg.Name.ShouldBe("val"); arg.ResolvedType.Name.ShouldBe("String"); arg.Description.ShouldBe("Val description"); } [Fact] public void builds_type_with_arguments_with_dependent_default_values() { var definitions = @" type Query { post(arg: [SomeInputType] = [{ name: ""John"" }]): String } input SomeInputType { id: ID! = 1 name: String! } "; var schema = Schema.For(definitions); schema.Initialize(); var query = schema.Query; query.Fields.Count.ShouldBe(1); var field = query.Fields.Single(); field.Name.ShouldBe("post"); field.Arguments.Count.ShouldBe(1); var arg = field.Arguments.First(); arg.Name.ShouldBe("arg"); var list = arg.DefaultValue.ShouldBeAssignableTo<IEnumerable<object>>(); list.Count().ShouldBe(1); var item = list.First().ShouldBeAssignableTo<IDictionary<string, object>>(); item.Count.ShouldBe(2); item["name"].ShouldBeOfType<string>().ShouldBe("John"); item["id"].ShouldBeOfType<int>().ShouldBe(1); } [Fact] public void builds_interface() { var definitions = @" """""" Example description """""" interface Pet { """""" ID description """""" id: ID } "; var schema = Schema.For(definitions); schema.Initialize(); var type = schema.AllTypes["Pet"] as InterfaceGraphType; type.ShouldNotBeNull(); type.Description.ShouldBe("Example description"); type.Fields.Count.ShouldBe(1); var field = type.Fields.Single(); field.Name.ShouldBe("id"); field.ResolvedType.Name.ShouldBe("ID"); field.Description.ShouldBe("ID description"); } [Fact] public void builds_enum() { var definitions = @" """""" Example description """""" enum PetKind { """""" Cat description """""" CAT DOG } "; var schema = Schema.For(definitions); schema.Initialize(); var type = schema.AllTypes["PetKind"] as EnumerationGraphType; type.ShouldNotBeNull(); type.Description.ShouldBe("Example description"); type.Values.Select(x => x.Name).ShouldBe(new[] { "CAT", "DOG" }); type.Values.Select(x => x.Value.ToString()).ShouldBe(new[] { "CAT", "DOG" }); type.Values.Select(x => x.Description).ShouldBe(new[] { "Cat description", null }); } private enum PetKind { Cat, Dog } [Fact] public void builds_case_insensitive_typed_enum() { var definitions = @" enum PetKind { CAT DOG } "; var schema = Schema.For(definitions, c => c.Types.Include<PetKind>()); schema.Initialize(); var type = schema.AllTypes["PetKind"] as EnumerationGraphType; type.ShouldNotBeNull(); type.Values.Select(x => x.Name).ShouldBe(new[] { "CAT", "DOG" }); type.Values.Select(x => (PetKind)x.Value).ShouldBe(new[] { PetKind.Cat, PetKind.Dog }); } [Fact] public void builds_scalars() { var definitions = @" scalar CustomScalar type Query { search: CustomScalar } "; var customScalar = new CustomScalarType(); var schema = Schema.For(definitions); schema.RegisterType(customScalar); schema.Initialize(); var type = schema.AllTypes["CustomScalar"] as ScalarGraphType; type.ShouldNotBeNull(); var query = schema.Query; query.ShouldNotBeNull(); var field = query.Fields.First(); field.ResolvedType.ShouldBeOfType<CustomScalarType>(); } [Fact] public void references_other_types() { var definitions = @" type Post { id: ID! title: String votes: Int } type Query { posts: [Post] post(id: ID = 1): Post } "; var schema = Schema.For(definitions, builder => builder.Types.For("Query").FieldFor("post").ArgumentFor("id").DefaultValue = 999); schema.Initialize(); var query = schema.Query; query.ShouldNotBeNull(); query.Name.ShouldBe("Query"); query.Fields.Count.ShouldBe(2); var posts = query.Fields.First(); posts.Name.ShouldBe("posts"); posts.ResolvedType.ToString().ShouldBe("[Post]"); query.Fields.Last().ResolvedType.Name.ShouldBe("Post"); var post = schema.AllTypes["Post"] as IObjectGraphType; post.ShouldNotBeNull(); post.Fields.Count.ShouldBe(3); var arg = query.Fields.Last().Arguments.Single(); arg.Name.ShouldBe("id"); arg.DefaultValue.ShouldBe(999); arg.Description.ShouldBeNull(); } [Fact] public void builds_unions() { var definitions = @" type Human { name: String } type Droid { name: String } """""" Example description """""" union SearchResult = Human | Droid"; var schema = Schema.For(definitions, _ => { _.Types.For("Human").IsTypeOf<Human>(); _.Types.For("Droid").IsTypeOf<Droid>(); }); schema.Initialize(); var searchResult = schema.AllTypes["SearchResult"] as UnionGraphType; searchResult.Description.ShouldBe("Example description"); searchResult.PossibleTypes.Select(x => x.Name).ShouldBe(new[] { "Human", "Droid" }); } [Fact] public void builds_input_types() { var definitions = @" """""" Example description """""" input ReviewInput { """""" Stars description """""" stars: Int! commentary: String } "; var schema = Schema.For(definitions); schema.Initialize(); var input = schema.AllTypes["ReviewInput"] as InputObjectGraphType; input.ShouldNotBeNull(); input.Description.ShouldBe("Example description"); input.Fields.Count.ShouldBe(2); input.Fields.First().Description.ShouldBe("Stars description"); } [Fact] public void builds_input_types_with_default_values() { var definitions = @" input ReviewInput { stars: Int! = 23 } "; var schema = Schema.For(definitions); schema.Initialize(); var input = schema.AllTypes["ReviewInput"] as InputObjectGraphType; input.ShouldNotBeNull(); input.Fields.Count.ShouldBe(1); input.Fields.First().DefaultValue.ShouldBe(23); } [Fact] public void builds_input_types_with_dependent_default_values() { var definitions = @" input SomeInputType1 { test: SomeInputType2! = { arg1: 22 } } input SomeInputType2 { arg1: Int arg2: Int = 30 } "; var schema = Schema.For(definitions); schema.Initialize(); var inputType1 = schema.AllTypes["SomeInputType1"] as InputObjectGraphType; inputType1.ShouldNotBeNull(); inputType1.Fields.Count.ShouldBe(1); inputType1.Fields.First().Name.ShouldBe("test"); var value1 = inputType1.Fields.First().DefaultValue.ShouldBeAssignableTo<IDictionary<string, object>>(); value1.ShouldContainKeyAndValue("arg1", 22); value1.ShouldContainKeyAndValue("arg2", 30); var inputType2 = schema.AllTypes["SomeInputType2"] as InputObjectGraphType; inputType2.ShouldNotBeNull(); inputType2.Fields.Count.ShouldBe(2); inputType2.Fields.Find("arg1").ShouldNotBeNull().DefaultValue.ShouldBeNull(); inputType2.Fields.Find("arg2").ShouldNotBeNull().DefaultValue.ShouldBe(30); } [Fact] public void input_types_default_value_loops_throw1() { var definitions = @" input SomeInputType1 { test: SomeInputType1 = { } } "; var schema = Schema.For(definitions); Should.Throw<InvalidOperationException>(() => schema.Initialize()).Message.ShouldBe("Default values in input types cannot contain a circular dependency loop. Please resolve dependency loop between the following types: 'SomeInputType1'."); } [Fact] public void input_types_default_value_loops_throw2() { var definitions = @" input SomeInputType1 { test: SomeInputType2 = { } } input SomeInputType2 { test: SomeInputType3 = { } } input SomeInputType3 { test: SomeInputType1 = { } } "; var schema = Schema.For(definitions); Should.Throw<InvalidOperationException>(() => schema.Initialize()).Message.ShouldBe("Default values in input types cannot contain a circular dependency loop. Please resolve dependency loop between the following types: 'SomeInputType3', 'SomeInputType2', 'SomeInputType1'."); } [Fact(Skip = "Not yet supported")] public void input_types_default_value_loops_pass() { // see: https://github.com/graphql-dotnet/graphql-dotnet/pull/2696#discussion_r764975585 var definitions = @" input SomeInputType1 { test: SomeInputType1 = { test: null } } "; var schema = Schema.For(definitions); schema.Initialize(); } [Fact] public void builds_directives() { var definitions = @" """""" Example description """""" directive @myDirective( if: Boolean! ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT "; var schema = Schema.For(definitions); schema.Initialize(); var directive = schema.Directives.Find("myDirective"); directive.ShouldNotBeNull(); directive.Description.ShouldBe("Example description"); directive.Arguments.Count.ShouldBe(1); var argument = directive.Arguments.Find("if"); argument.ResolvedType.ToString().ShouldBe("Boolean!"); directive.Locations.ShouldBe(new[] { DirectiveLocation.Field, DirectiveLocation.FragmentSpread, DirectiveLocation.InlineFragment }); } [Fact] public void custom_deprecation_on_type_field() { var definitions = @" type Query { stars: Int @deprecated(reason: ""a reason"") } "; var schema = Schema.For(definitions); schema.Initialize(); var type = schema.AllTypes["Query"] as IObjectGraphType; type.ShouldNotBeNull(); type.Fields.Count.ShouldBe(1); type.Fields.Single().DeprecationReason.ShouldBe("a reason"); } [Fact] public void default_deprecation_on_type_field() { var definitions = @" type Query { stars: Int @deprecated } "; var schema = Schema.For(definitions); schema.Initialize(); var type = schema.AllTypes["Query"] as IObjectGraphType; type.ShouldNotBeNull(); type.Fields.Count.ShouldBe(1); type.Fields.Single().DeprecationReason.ShouldBe("No longer supported"); } [Fact] public void deprecate_enum_value() { var definitions = @" enum PetKind { CAT @deprecated(reason: ""dogs rule"") DOG } "; var schema = Schema.For(definitions); schema.Initialize(); var type = schema.AllTypes["PetKind"] as EnumerationGraphType; type.ShouldNotBeNull(); var cat = type.Values.Single(x => x.Name == "CAT"); cat.DeprecationReason.ShouldBe("dogs rule"); } [Fact] public void deprecated_prefers_metadata_values() { var definitions = @" type Movie { movies: Int @deprecated } "; var schema = Schema.For(definitions, _ => _.Types.Include<Movie>()); schema.Initialize(); var type = schema.AllTypes["Movie"] as IObjectGraphType; type.ShouldNotBeNull(); type.Fields.Count.ShouldBe(1); type.Fields.Single().DeprecationReason.ShouldBe("my reason"); } [Fact] public void build_extension_type() { var definitions = @" type Query { author(id: Int): String } extend type Query { book(id: Int): String } "; var schema = Schema.For(definitions); schema.Initialize(); var type = schema.AllTypes["Query"] as IObjectGraphType; type.Fields.Count.ShouldBe(2); } [Fact] public void build_extension_type_out_of_order() { var definitions = @" extend type Query { author(id: Int): String } type Query { book(id: Int): String } "; var schema = Schema.For(definitions); schema.Initialize(); var type = (IObjectGraphType)schema.AllTypes["Query"]; type.Fields.Count.ShouldBe(2); } internal class Movie { [GraphQLMetadata("movies", DeprecationReason = "my reason")] public int Movies() => 0; } internal class CustomScalarType : ScalarGraphType { public CustomScalarType() { Name = "CustomScalar"; } public override object ParseValue(object value) => throw new System.NotImplementedException(); public override object ParseLiteral(IValue value) => throw new System.NotImplementedException(); } } }
// 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; using System; using System.Collections; using System.Collections.Specialized; namespace System.Collections.Specialized.Tests { public class OrderedDictionaryTests { // public OrderedDictionary(); [Fact] public void DefaultConstructorDoesNotThrow() { OrderedDictionary dictionary = new OrderedDictionary(); } // public OrderedDictionary(int capacity); [Fact] public void CreatingWithDifferentCapacityValues() { // exceptions are not thrown until you add an element var d1 = new OrderedDictionary(-1000); var d2 = new OrderedDictionary(-1); var d3 = new OrderedDictionary(0); var d4 = new OrderedDictionary(1); var d5 = new OrderedDictionary(1000); Assert.Throws<ArgumentOutOfRangeException>(() => d1.Add("foo", "bar")); Assert.Throws<ArgumentOutOfRangeException>(() => d2.Add("foo", "bar")); d3.Add("foo", "bar"); d4.Add("foo", "bar"); d5.Add("foo", "bar"); } // public OrderedDictionary(IEqualityComparer comparer); [Fact] public void PassingEqualityComparers() { var eqComp = new CaseInsensitiveEqualityComparer(); var d1 = new OrderedDictionary(eqComp); d1.Add("foo", "bar"); Assert.Throws<ArgumentException>(() => d1.Add("FOO", "bar")); // The equality comparer should also test for a non-existent key d1.Remove("foofoo"); Assert.True(d1.Contains("foo")); // Make sure we can change an existent key that passes the equality comparer d1["FOO"] = "barbar"; Assert.Equal("barbar", d1["foo"]); d1.Remove("FOO"); Assert.False(d1.Contains("foo")); } // public OrderedDictionary(int capacity, IEqualityComparer comparer); [Fact] public void PassingCapacityAndIEqualityComparer() { var eqComp = new CaseInsensitiveEqualityComparer(); var d1 = new OrderedDictionary(-1000, eqComp); var d2 = new OrderedDictionary(-1, eqComp); var d3 = new OrderedDictionary(0, eqComp); var d4 = new OrderedDictionary(1, eqComp); var d5 = new OrderedDictionary(1000, eqComp); Assert.Throws<ArgumentOutOfRangeException>(() => d1.Add("foo", "bar")); Assert.Throws<ArgumentOutOfRangeException>(() => d2.Add("foo", "bar")); d3.Add("foo", "bar"); d4.Add("foo", "bar"); d5.Add("foo", "bar"); } // public int Count { get; } [Fact] public void CountTests() { var d = new OrderedDictionary(); Assert.Equal(0, d.Count); for (int i = 0; i < 1000; i++) { d.Add(i, i); Assert.Equal(i + 1, d.Count); } for (int i = 0; i < 1000; i++) { d.Remove(i); Assert.Equal(1000 - i - 1, d.Count); } for (int i = 0; i < 1000; i++) { d[(object)i] = i; Assert.Equal(i + 1, d.Count); } for (int i = 0; i < 1000; i++) { d.RemoveAt(0); Assert.Equal(1000 - i - 1, d.Count); } } // public bool IsReadOnly { get; } [Fact] public void IsReadOnlyTests() { var d = new OrderedDictionary(); Assert.False(d.IsReadOnly); var d2 = d.AsReadOnly(); Assert.True(d2.IsReadOnly); } [Fact] public void AsReadOnly_AttemptingToModifyDictionary_Throws() { OrderedDictionary orderedDictionary = new OrderedDictionary().AsReadOnly(); Assert.Throws<NotSupportedException>(() => orderedDictionary[0] = "value"); Assert.Throws<NotSupportedException>(() => orderedDictionary["key"] = "value"); Assert.Throws<NotSupportedException>(() => orderedDictionary.Add("key", "value")); Assert.Throws<NotSupportedException>(() => orderedDictionary.Insert(0, "key", "value")); Assert.Throws<NotSupportedException>(() => orderedDictionary.Remove("key")); Assert.Throws<NotSupportedException>(() => orderedDictionary.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => orderedDictionary.Clear()); } // public ICollection Keys { get; } [Fact] public void KeysPropertyContainsAllKeys() { var d = new OrderedDictionary(); var alreadyChecked = new bool[1000]; for (int i = 0; i < 1000; i++) { d["test_" + i] = i; alreadyChecked[i] = false; } ICollection keys = d.Keys; Assert.False(keys.IsSynchronized); Assert.NotEqual(d, keys.SyncRoot); Assert.Equal(d.Count, keys.Count); foreach (var key in d.Keys) { string skey = (string)key; var p = skey.Split(new char[] { '_' }); Assert.Equal(2, p.Length); int number = int.Parse(p[1]); Assert.False(alreadyChecked[number]); Assert.True(number >= 0 && number < 1000); alreadyChecked[number] = true; } object[] array = new object[keys.Count + 50]; keys.CopyTo(array, 50); for (int i = 50; i < array.Length; i++) { Assert.True(d.Contains(array[i])); } Assert.Throws<ArgumentNullException>("array", () => keys.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>("index", () => keys.CopyTo(new object[keys.Count], -1)); } // bool System.Collections.ICollection.IsSynchronized { get; } [Fact] public void IsSynchronizedTests() { ICollection c = new OrderedDictionary(); Assert.False(c.IsSynchronized); } [Fact] public void SyncRootTests() { ICollection orderedDictionary1 = new OrderedDictionary(); ICollection orderedDictionary2 = new OrderedDictionary(); object sync1 = orderedDictionary1.SyncRoot; object sync2 = orderedDictionary2.SyncRoot; // Sync root does not refer to the dictionary Assert.NotEqual(sync1, orderedDictionary1); Assert.NotEqual(sync2, orderedDictionary2); // Sync root objects for the same dictionaries are equivilent Assert.Equal(orderedDictionary1.SyncRoot, orderedDictionary1.SyncRoot); Assert.Equal(orderedDictionary2.SyncRoot, orderedDictionary2.SyncRoot); // Sync root objects for different dictionaries are not equivilent Assert.NotEqual(sync1, sync2); } // bool System.Collections.IDictionary.IsFixedSize { get; } [Fact] public void IsFixedSizeTests() { var d = new OrderedDictionary(); IDictionary dic = d; IDictionary rodic = d.AsReadOnly(); Assert.False(dic.IsFixedSize); Assert.True(rodic.IsFixedSize); } // public object this[int index] { get; set; } [Fact] public void GettingByIndexTests() { var d = new OrderedDictionary(); for (int i = 0; i < 1000; i++) { d.Add("test" + i, i); } for (int i = 0; i < 1000; i++) { Assert.Equal(d[i], i); d[i] = (int)d[i] + 100; Assert.Equal(d[i], 100 + i); } Assert.Throws<ArgumentOutOfRangeException>(() => { int foo = (int)d[-1]; }); Assert.Throws<ArgumentOutOfRangeException>(() => { d[-1] = 5; }); Assert.Throws<ArgumentOutOfRangeException>(() => { int foo = (int)d[1000]; }); Assert.Throws<ArgumentOutOfRangeException>(() => { d[1000] = 5; }); } // public object this[object key] { get; set; } [Fact] public void GettingByKeyTests() { var d = new OrderedDictionary(); for (int i = 0; i < 1000; i++) { d.Add("test" + i, i); } for (int i = 0; i < 1000; i++) { Assert.Equal(d["test" + i], i); d["test" + i] = (int)d["test" + i] + 100; Assert.Equal(d["test" + i], 100 + i); } for (int i = 1000; i < 2000; i++) { d["test" + i] = 1337; } Assert.Equal(null, d["asdasd"]); Assert.Throws<ArgumentNullException>(() => { var a = d[null]; }); Assert.Throws<ArgumentNullException>(() => { d[null] = 1337; }); } // public ICollection Values { get; } [Fact] public void ValuesPropertyContainsAllValues() { var d = new OrderedDictionary(); var alreadyChecked = new bool[1000]; for (int i = 0; i < 1000; i++) { d["foo" + i] = "bar_" + i; alreadyChecked[i] = false; } ICollection values = d.Values; Assert.False(values.IsSynchronized); Assert.NotEqual(d, values.SyncRoot); Assert.Equal(d.Count, values.Count); foreach (var val in values) { string sval = (string)val; var p = sval.Split(new char[] { '_' }); Assert.Equal(2, p.Length); int number = int.Parse(p[1]); Assert.False(alreadyChecked[number]); Assert.True(number >= 0 && number < 1000); alreadyChecked[number] = true; } object[] array = new object[values.Count + 50]; values.CopyTo(array, 50); for (int i = 50; i < array.Length; i++) { Assert.Equal(array[i], "bar_" + (i - 50)); } Assert.Throws<ArgumentNullException>("array", () => values.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>("index", () => values.CopyTo(new object[values.Count], -1)); } // public void Add(object key, object value); [Fact] public void AddTests() { var d = new OrderedDictionary(); d.Add((int)5, "foo1"); Assert.Equal("foo1", d[(object)((int)5)]); d.Add((double)5, "foo2"); Assert.Equal("foo2", d[(object)((double)5)]); d.Add((long)5, "foo3"); Assert.Equal("foo3", d[(object)((long)5)]); d.Add((short)5, "foo4"); Assert.Equal("foo4", d[(object)((short)5)]); d.Add((uint)5, "foo5"); Assert.Equal("foo5", d[(object)((uint)5)]); d.Add("5", "foo6"); Assert.Equal("foo6", d["5"]); Assert.Throws<ArgumentException>(() => d.Add((int)5, "foo")); Assert.Throws<ArgumentException>(() => d.Add((double)5, "foo")); Assert.Throws<ArgumentException>(() => d.Add((long)5, "foo")); Assert.Throws<ArgumentException>(() => d.Add((short)5, "foo")); Assert.Throws<ArgumentException>(() => d.Add((uint)5, "foo")); Assert.Throws<ArgumentException>(() => d.Add("5", "foo")); Assert.Throws<ArgumentNullException>(() => d.Add(null, "foobar")); } // public OrderedDictionary AsReadOnly(); [Fact] public void AsReadOnlyTests() { var _d = new OrderedDictionary(); _d["foo"] = "bar"; _d[(object)13] = 37; var d = _d.AsReadOnly(); Assert.True(d.IsReadOnly); Assert.Equal("bar", d["foo"]); Assert.Equal(37, d[(object)13]); Assert.Throws<NotSupportedException>(() => { d["foo"] = "moooooooooaaah"; }); Assert.Throws<NotSupportedException>(() => { d["asdasd"] = "moooooooooaaah"; }); Assert.Equal(null, d["asdasd"]); Assert.Throws<ArgumentNullException>(() => { var a = d[null]; }); } // public void Clear(); [Fact] public void ClearTests() { var d = new OrderedDictionary(); d.Clear(); Assert.Equal(0, d.Count); for (int i = 0; i < 1000; i++) { d.Add(i, i); } d.Clear(); Assert.Equal(0, d.Count); d.Clear(); Assert.Equal(0, d.Count); for (int i = 0; i < 1000; i++) { d.Add("foo", "bar"); d.Clear(); Assert.Equal(0, d.Count); } } // public bool Contains(object key); [Fact] public void ContainsTests() { var d = new OrderedDictionary(); Assert.Throws<ArgumentNullException>(() => d.Contains(null)); Assert.False(d.Contains("foo")); for (int i = 0; i < 1000; i++) { var k = "test_" + i; d.Add(k, "asd"); Assert.True(d.Contains(k)); // different reference Assert.True(d.Contains("test_" + i)); } Assert.False(d.Contains("foo")); } // public void CopyTo(Array array, int index); [Fact] public void CopyToTests() { var d = new OrderedDictionary(); d["foo"] = "bar"; d[" "] = "asd"; DictionaryEntry[] arr = new DictionaryEntry[3]; Assert.Throws<ArgumentNullException>(() => d.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => d.CopyTo(arr, -1)); Assert.Throws<ArgumentException>(() => d.CopyTo(arr, 3)); d.CopyTo(arr, 0); for (int i = 0; i < 2; i++) { Assert.True(d.Contains(arr[i].Key)); Assert.Equal(d[arr[i].Key], arr[i].Value); } Assert.NotEqual(arr[0].Key, arr[1].Key); d.CopyTo(arr, 1); for (int i = 1; i < 3; i++) { Assert.True(d.Contains(arr[i].Key)); Assert.Equal(d[arr[i].Key], arr[i].Value); } Assert.NotEqual(arr[1].Key, arr[2].Key); } [Fact] public void GetDictionaryEnumeratorTests() { var d = new OrderedDictionary(); for (int i = 0; i < 10; i++) { d.Add("Key_" + i, "Value_" + i); } IDictionaryEnumerator e = d.GetEnumerator(); for (int i = 0; i < 2; i++) { int count = 0; while (e.MoveNext()) { DictionaryEntry entry1 = (DictionaryEntry)e.Current; DictionaryEntry entry2 = e.Entry; Assert.Equal(entry1.Key, entry2.Key); Assert.Equal(entry1.Value, entry1.Value); Assert.Equal(e.Key, entry1.Key); Assert.Equal(e.Value, entry1.Value); Assert.Equal(e.Value, d[e.Key]); count++; } Assert.Equal(count, d.Count); Assert.False(e.MoveNext()); e.Reset(); } e = d.GetEnumerator(); d["foo"] = "bar"; Assert.Throws<InvalidOperationException>(() => e.MoveNext()); } [Fact] public void GetEnumeratorTests() { var d = new OrderedDictionary(); for (int i = 0; i < 10; i++) { d.Add("Key_" + i, "Value_" + i); } IEnumerator e = ((ICollection)d).GetEnumerator(); for (int i = 0; i < 2; i++) { int count = 0; while (e.MoveNext()) { DictionaryEntry entry = (DictionaryEntry)e.Current; Assert.Equal(entry.Value, d[entry.Key]); count++; } Assert.Equal(count, d.Count); Assert.False(e.MoveNext()); e.Reset(); } } // public void Insert(int index, object key, object value); [Fact] public void InsertTests() { var d = new OrderedDictionary(); Assert.Throws<ArgumentOutOfRangeException>(() => d.Insert(-1, "foo", "bar")); Assert.Throws<ArgumentNullException>(() => d.Insert(0, null, "bar")); Assert.Throws<ArgumentOutOfRangeException>(() => d.Insert(1, "foo", "bar")); d.Insert(0, "foo", "bar"); Assert.Equal("bar", d["foo"]); Assert.Equal("bar", d[0]); Assert.Throws<ArgumentException>(() => d.Insert(0, "foo", "bar")); d.Insert(0, "aaa", "bbb"); Assert.Equal("bbb", d["aaa"]); Assert.Equal("bbb", d[0]); d.Insert(0, "zzz", "ccc"); Assert.Equal("ccc", d["zzz"]); Assert.Equal("ccc", d[0]); d.Insert(3, "13", "37"); Assert.Equal("37", d["13"]); Assert.Equal("37", d[3]); } // public void Remove(object key); [Fact] public void RemoveTests() { var d = new OrderedDictionary(); // should work d.Remove("asd"); Assert.Throws<ArgumentNullException>(() => d.Remove(null)); for (var i = 0; i < 1000; i++) { d.Add("foo_" + i, "bar_" + i); } for (var i = 0; i < 1000; i++) { Assert.True(d.Contains("foo_" + i)); d.Remove("foo_" + i); Assert.False(d.Contains("foo_" + i)); Assert.Equal(1000 - i - 1, d.Count); } } // public void RemoveAt(int index); [Fact] public void RemoveAtTests() { var d = new OrderedDictionary(); Assert.Throws<ArgumentOutOfRangeException>(() => d.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => d.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => d.RemoveAt(5)); Assert.Throws<ArgumentNullException>(() => d.Remove(null)); for (var i = 0; i < 1000; i++) { d.Add("foo_" + i, "bar_" + i); } for (var i = 0; i < 1000; i++) { d.RemoveAt(1000 - i - 1); Assert.Equal(1000 - i - 1, d.Count); } for (var i = 0; i < 1000; i++) { d.Add("foo_" + i, "bar_" + i); } for (var i = 0; i < 1000; i++) { Assert.Equal("bar_" + i, d[0]); d.RemoveAt(0); Assert.Equal(1000 - i - 1, d.Count); } } } }
//------------------------------------------------------------------------------ // // Copyright (c) Glympse Inc. All rights reserved. // //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; namespace Glympse { /** * Declares the list of all constants (enumerations) utilized by various API components. */ /*O*/public/**/ class GlympseConstants { /** * @name SMS Modes * * SMS mode defines party responsible for SMS delivery. */ /** * The default SMS send mode allows the Glympse API to query the device and determine * if an SMS invite should be sent locally from the device's SMS number or remotely * from the Glympse server SMS provider. * * You can call the IGlympse::canDeviceSendSms method to determine if the Glympse API * has detected that the device does support sending of SMS messages. */ public const int SMS_SEND_MODE_DEFAULT = 1; /** * The device SMS send mode forces the Glympse API to always send SMS invites from the device's SMS number. */ public const int SMS_SEND_MODE_DEVICE = 2; /** * The server SMS send mode forces the Glympse API to always send SMS invites through the Glympse server SMS provider. */ public const int SMS_SEND_MODE_SERVER = 3; /** * @name Device SMS Capabilities * * Constants for identifying device SMS capabilities. */ /** * The device is capable of sending SMS messages programmatically. */ public const int SMS_SEND_AUTO = 1; /** * The device is capable of sending SMS messages, but user confirmation is required. */ public const int SMS_SEND_MANUAL = 2; /** * The device is not capable of sending SMS messages. */ public const int SMS_SEND_NOT_SUPPORTED = 3; /** * @name ETA Modes * * Supported ETA modes. */ /** * In this mode ETA information should be provided externally. * Glympse API will not attempt to calclulate that. */ public const int ETA_MODE_EXTERNAL = 1; /** * Glympse API will attempt to calclulate ETA in this mode. */ public const int ETA_MODE_INTERNAL = 2; /** * @name Invite Decoding Modes * * Various flags that can be applied when decoding invites. * * @see IGlympse#decodeInvite */ /** * Default mode for invites decoding. * * Platform starts viewing ticket invites automatically in this mode * (without any confirmations). * * Request invite will still result in GE::PLATFORM_INVITE_REQUEST being spread. * Platform prevents automatic replying to ticket requests because of security * considerations. */ public const int INVITE_MODE_DEFAULT = 0x00000000; /** * Enables viewing confirmation for ticket invites. GE::PLATFORM_INVITE_TICKET is spread * to all subscribers of IGlympse event sink. Explicit action is required to start * viewing ticket invite (see IGlympse::viewTicket()), if this mode is specified. */ public const int INVITE_MODE_PROMPT_BEFORE_VIEWING = 0x00000001; /** * Newly added standalone user will automatically be activated, * if this mode is specified. This mode only makes sense in conjunction with * INVITE_MODE_DEFAULT, where users are added automatically. */ public const int INVITE_MODE_ACTIVATE_USER = 0x00000002; /** * @name User Tracking Modes * * User tracking mode defines the way platform deals with multiple concurrent incoming * tickets received from a user. * * @see IUserManager#setUserTrackingMode */ /** * When running in this mode, platform tracks and provides host application with updates * regarding the only ticket for a given user (the most recently received one). This ticket object is * accessible through IUser#getActiveStandalone method. All other tickets received from * the user remain on the list, but are never updated. The order of tickets changes only when * new ticket is received from the user or currently active ticket expires. * * User trail information is always available under track object belonging to active ticket. * When active ticket changes, its track is merged with to newly activated ticket. * * Platform automatically unsubscribes listeners from events spread by active ticket * when it changes. */ public const int USER_TRACKING_MODE_ACTIVE = 0x00000001; /** * Platform pulls updates for all active tickets received from a given user, when running in * this mode. * * User trail is still available through active standalone ticket. Major difference * is that properties of all other tickets received from this user are also updated up until * expiration. * * In this mode platform never unsubscribes listeners of user's tickets. */ public const int USER_TRACKING_MODE_ALL = 0x00000002; /** * @name Ticket States * * Supported ticket states. */ public const int TICKET_STATE_NONE = 0x00000001; public const int TICKET_STATE_ADDING = 0x00000002; public const int TICKET_STATE_INVALID = 0x00000004; public const int TICKET_STATE_ACTIVE = 0x00000010; public const int TICKET_STATE_EXPIRING = 0x00000020; public const int TICKET_STATE_EXPIRED = 0x00000040; public const int TICKET_STATE_DELETING = 0x00000080; public const int TICKET_STATE_DELETED = 0x00000100; public const int TICKET_STATE_FAILED_TO_CREATE = 0x00000200; public const int TICKET_STATE_CANCELLED = 0x00000400; public const int TICKET_STATE_DECODING = TICKET_STATE_ADDING | TICKET_STATE_ACTIVE; public const int TICKET_STATE_ACTIVATING = TICKET_STATE_ADDING | TICKET_STATE_ACTIVE; /** * @name Invite Aspects * * Glympse invite code (6 or 8 character string separated by a dash) * always points to an object in Glympse universe (e.g. ticket or request to share location). * Invite aspect identifies type of that object. */ /** * Invite of unknown aspect. The value usually indicates that invite aspect * cannot be determined locally. See IGlympse#decodeInvite() for more details. */ public const int INVITE_ASPECT_UNKNOWN = 0; /** * Identifies invite pointing to ticket object. */ public const int INVITE_ASPECT_TICKET = 1; /** * Invite of this type represents a request to share location. */ public const int INVITE_ASPECT_REQUEST = 2; /** * Invite of this type represents an invite to join a card. */ public const int INVITE_ASPECT_CARD = 3; /** * @name Invite Types * * Supported invite delivery mechanisms. */ public const int INVITE_TYPE_UNKNOWN = 0; public const int INVITE_TYPE_ACCOUNT = 1; public const int INVITE_TYPE_EMAIL = 2; public const int INVITE_TYPE_SMS = 3; public const int INVITE_TYPE_TWITTER = 4; public const int INVITE_TYPE_FACEBOOK = 5; public const int INVITE_TYPE_LINK = 6; public const int INVITE_TYPE_GROUP = 7; public const int INVITE_TYPE_SHARE = 8; public const int INVITE_TYPE_CLIPBOARD = 9; public const int INVITE_TYPE_EVERNOTE = 10; public const int INVITE_TYPE_APP = 11; /** * @name Invite States * * Supported invite states. */ public const int INVITE_STATE_NONE = 0; public const int INVITE_STATE_SERVERSENDING = 1; public const int INVITE_STATE_CLIENTSENDING = 2; public const int INVITE_STATE_NEEDTOSEND = 3; public const int INVITE_STATE_SUCCEEDED = 4; public const int INVITE_STATE_DELETING = 5; public const int INVITE_STATE_DELETED = 6; public const int INVITE_STATE_FAILED_TO_CREATE = 7; public const int INVITE_STATE_FAILED_TO_SEND = 8; public const int INVITE_STATE_FAILED_TO_DELETE = 9; /** * @name Image States * * Supported image states. */ public const int IMAGE_STATE_NONE = 0; public const int IMAGE_STATE_LOADING = 1; public const int IMAGE_STATE_LOADED = 2; public const int IMAGE_STATE_FAILED = 3; /** * @name Group States * * Supported group states. */ public const int GROUP_STATE_NONE = 0; public const int GROUP_STATE_INVALID = 1; public const int GROUP_STATE_ADDING = 2; /** * Intermediate group state, in which group finds itself once being decoded * but not yet accepted by the user. */ public const int GROUP_STATE_PENDING = 3; public const int GROUP_STATE_ACTIVE = 4; public const int GROUP_STATE_LEAVING = 5; public const int GROUP_STATE_LEFT = 6; public const int GROUP_STATE_FAILED_TO_CREATE = 7; public const int GROUP_STATE_FAILED_TO_JOIN = 8; public const int GROUP_STATE_FAILED_TO_LEAVE = 9; /** * @name XoA (Expire on Arrival) Modes * * Supported XoA modes. */ /** * Automatic expiration logic is totally turned off in this mode. */ public const int EXPIRE_ON_ARRIVAL_NONE = 0; /** * Ticket subscribers are notified with GE::TICKET_ARRIVED event upon arrival * to the destination. */ public const int EXPIRE_ON_ARRIVAL_NOTIFY = 1; /** * Ticket is automatically expired upon arrival. GE::TICKET_EXPIRED is spread to * ticket subscribers. */ public const int EXPIRE_ON_ARRIVAL_AUTO = 2; /** * @name Delete after Complete modes */ /** * No ticket deletion will automatically occur after ticket completion (default) */ public const int DELETE_AFTER_COMPLETE_OFF = 0; /** * Tickets will be deleted automatically after they complete */ public const int DELETE_AFTER_COMPLETE_IMMEDIATE = 1; /** * Tickets will be deleted after a scheduled period of time following complete */ public const int DELETE_AFTER_COMPLETE_SCHEDULED = 2; /** * @name Group Name Verification Options * * Values returned by IGroupManager#validateGroupName(). */ /** * Specified group name conforms to group name requirements. */ public const int GROUP_NAME_CORRECT = 0; /** * Specified group name is too short. */ public const int GROUP_NAME_TOO_SHORT = 1; /** * Specified group name contains invalid character. */ public const int GROUP_NAME_INVALID_CHARACTER = 2; /** * Group name cannot consist of just numbers. */ public const int GROUP_NAME_JUST_DIGITS = 3; /** * @name Miscellaneous Defaults * * Default and no change constants. */ /** * This constant can be used with the ITicket::modify method to specify that the duration * should not be changed when modifying a ticket. */ public const int DURATION_NO_CHANGE = -1; /** * The value indicates that client platform falls back to default lookback interval specified on server side. * It can be passed to IGlympse#setHistoryLookback() and returned by IGlympse#getHistoryLookback(). */ public const long HISTORY_LOOKBACK_DEFAULT = -1; /** * @name Context Constants * * Constants defining the range of supported context keys. */ /** * Minimum value of context key. */ public const long CONTEXT_KEY_MIN = 0x0L; /** * Maximum value of specific key. */ public const long CONTEXT_KEY_MAX = 0xffffffffffffL; /** * @name Ticket Fields * * The list of fields generally available under ticket object. */ /** * Refers to the list of invites. */ public const int TICKET_FIELD_INVITES = 0x00000001; /** * Refers to ticket duration. */ public const int TICKET_FIELD_DURATION = 0x00000002; /** * Refers to ticket message. */ public const int TICKET_FIELD_MESSAGE = 0x00000004; /** * Refers to ticket destination. */ public const int TICKET_FIELD_DESTINATION = 0x00000008; /** * @name External Handoff Actions * * Actions commonly supported by handoff providers. */ /** * Initiates sending a Glympse from a browser. */ public const int HANDOFF_ACTION_SEND = 0x00000001; /** * @name Travel Modes * * Supported travel modes. */ /** * Default travel mode. */ public const int TRAVEL_MODE_DEFAULT = 0; /** * Driving mode. */ public const int TRAVEL_MODE_DRIVE = 1; /** * Cycling mode. */ public const int TRAVEL_MODE_CYCLE = 2; /** * Walking mode. */ public const int TRAVEL_MODE_WALK = 3; /** * Flying mode. */ public const int TRAVEL_MODE_AIRLINE = 4; /** * Transit mode. */ public const int TRAVEL_MODE_TRANSIT = 5; /** * @name Eta/Route Query Modes * * Supported modes for querying eta and route. */ /** * Always query eta/route (when enabled). */ public const int ETA_QUERY_MODE_ALWAYS = 0; /** * Only query eta/route when watched by someone, including self (i.e. when platform is active). */ public const int ETA_QUERY_MODE_WATCHED = 1; /** * @name Ticket visibility */ /** * TICKET_VISIBILITY_KEY_LOCATION() value indicating visible location. */ public static String TICKET_VISIBILITY_LOCATION_VISIBLE() { return CoreFactory.createString("visible"); } /** * TICKET_VISIBILITY_KEY_LOCATION() value indicating cloaked location. */ public static String TICKET_VISIBILITY_LOCATION_CLOAKED() { return CoreFactory.createString("cloaked"); } /** * TICKET_VISIBILITY_KEY_LOCATION() value indicating hidden location. */ public static String TICKET_VISIBILITY_LOCATION_HIDDEN() { return CoreFactory.createString("hidden"); } /** * Key to retrieve the location visibility from ITicket::getVisibility. */ public static String TICKET_VISIBILITY_KEY_LOCATION() { return CoreFactory.createString("location"); } /** * Key to retrieve the visibility context from ITicket::getVisibility. */ public static String TICKET_VISIBILITY_KEY_CONTEXT() { return CoreFactory.createString("context"); } /** * @name Linked Accounts */ /** * Facebook. */ public static String LINKED_ACCOUNT_TYPE_FACEBOOK() { return CoreFactory.createString("facebook"); } /** * Twitter. */ public static String LINKED_ACCOUNT_TYPE_TWITTER() { return CoreFactory.createString("twitter"); } /** * Evernote. */ public static String LINKED_ACCOUNT_TYPE_EVERNOTE() { return CoreFactory.createString("evernote"); } /** * Google+. */ public static String LINKED_ACCOUNT_TYPE_GOOGLE() { return CoreFactory.createString("google_plus"); } /** * Pairing Code. */ public static String LINKED_ACCOUNT_TYPE_PAIRING() { return CoreFactory.createString("pairing"); } /** * Phone Number. */ public static String LINKED_ACCOUNT_TYPE_PHONE() { return CoreFactory.createString("phone"); } /** * Email Address. */ public static String LINKED_ACCOUNT_TYPE_EMAIL() { return CoreFactory.createString("email"); } /** * @name Linked Account Properties */ /** * This property controls whether invites of the associated linked account type * are sent by the sever, or whether the host application perfers to send them * itself. By default, this property is false for all linked account types, so * invites will be sent by the server. */ public static String LINKED_ACCOUNT_PROPERTY_INVITE_CLIENT_SEND() { return CoreFactory.createString("invite_client_send"); } /** * @name Linked Account States * * All possible states for linked account objects. */ /** * Unknown. */ public const int LINKED_ACCOUNT_STATE_NONE = 0; /** * Linking in progress. */ public const int LINKED_ACCOUNT_STATE_LINKING = 1; /** * Linked. */ public const int LINKED_ACCOUNT_STATE_LINKED = 2; /** * Failed to link. */ public const int LINKED_ACCOUNT_STATE_FAILED_TO_LINK = 3; /** * Unlinking in progress. */ public const int LINKED_ACCOUNT_STATE_UNLINKING = 4; /** * Unlinked. */ public const int LINKED_ACCOUNT_STATE_UNLINKED = 5; /** * Failed to unlink. */ public const int LINKED_ACCOUNT_STATE_FAILED_TO_UNLINK = 6; /** * Refreshing in progress. */ public const int LINKED_ACCOUNT_STATE_REFRESHING = 7; /** * @name Linked Account Status * * All possible status codes for linked account objects. */ /** * Unknown. */ public const int LINKED_ACCOUNT_STATUS_NONE = 0; /** * Account status is good. */ public const int LINKED_ACCOUNT_STATUS_OK = 1; /** * Account metadata needs to be refreshed. */ public const int LINKED_ACCOUNT_STATUS_REFRESH_NEEDED = 2; /** * @name Linked Account Login Authorization * * All possible states for linked account federated login permission. */ /** * Unknown. */ public const int LINKED_ACCOUNT_LOGIN_NONE = 0; /** * Login enabled. */ public const int LINKED_ACCOUNT_LOGIN_ENABLED = 1; /** * Login disabled. */ public const int LINKED_ACCOUNT_LOGIN_DISABLED = 2; /** * @name Server error types. * * Classes of errors that may be reported by the server. */ /** * Generic or unknown error. */ public const int SERVER_ERROR_UNKNOWN = 1; /** * The format of the request is invalid. */ public const int SERVER_ERROR_FORMAT = 2; /** * The request was denied due to access rights. */ public const int SERVER_ERROR_ACCESS_DENIED = 3; /** * The request failed because third-party account validation failed. */ public const int SERVER_ERROR_LINK_FAILED = 4; /** * The request failed because the third-party account specified is not the one linked to the user account. */ public const int SERVER_ERROR_LINK_MISMATCH = 5; /** * The request failed because the third-party account is already linked with a different user account. */ public const int SERVER_ERROR_EXISTING_LINK = 6; /** * The request failed because no third-party account of the specified type is linked. */ public const int SERVER_ERROR_NOT_LINKED = 7; /** * The request failed because a required token is invalid or expired. */ public const int SERVER_ERROR_INVALID_TOKEN = 8; /** * The request failed because server disabled current platform installation. * Upon receiving this error platform will stop talking to Glympse server * until it sees a change in application version. */ public const int SERVER_ERROR_DISABLED = 9; /** * @name Expiration Mode * * Ticket expiration mode defines platform behavior with regards to ticket expiration. * Depending on currently applied mode the platform requires server confirmation in order to * alter local state (switch to 'not sharing' state from 'sharing') or is capable of performing * the switch on its own. * * @see IHistoryManager#setExpirationMode */ /** * All properties taken into account has to be synchronized with server, when running in this mode. */ public const int EXPIRATION_MODE_SYNCHRONIZED = 0; /** * Platform relies on local ticket state as well in order to make some decisions. */ public const int EXPIRATION_MODE_DETACHED = 1; /** * @name Track Sources * * Track source specifies where track information is coming from. */ /** * The origin on track data is unknown. */ public const int TRACK_SOURCE_UNKNOWN = 0; /** * Track data is provided by Google Directions API. */ public const int TRACK_SOURCE_GOOGLE_DIRECTIONS = 1; /** * Track information is retrieved from a flight tracking service. */ public const int TRACK_SOURCE_INFLIGHT = 2; /** * Track data is provided by HERE Directions API. */ public const int TRACK_SOURCE_HERE_DIRECTIONS = 3; /** * Track data is provided by Glympse Directions API. */ public const int TRACK_SOURCE_GLYMPSE_DIRECTIONS = 4; /** * @name Directions state. * * State of Directions object. */ /** * The directions state is unknown. Normally prior to a directions request. */ public const int DIRECTIONS_STATE_UNKNOWN = 0; /** * The directions state is fetching. Directions request has been sent to the server. */ public const int DIRECTIONS_STATE_FETCHING = 1; /** * The directions state is succeeded. Directions were successfully retrieved. */ public const int DIRECTIONS_STATE_SUCCESS = 2; /** * The directions state is failed. Directions were not successfully retrieved. */ public const int DIRECTIONS_STATE_FAILED = 3; /** * @name Trigger Types * * Trigger types based on criteria used to fire associated action. */ /** * Trigger that is fired when user leaves specified geofence. */ public const int TRIGGER_TYPE_GEO = 1; /** * Trigger that is fired at a specific time. */ public const int TRIGGER_TYPE_CHRONO = 2; /** * Trigger that is fired based on a give ticket's ETA. */ public const int TRIGGER_TYPE_ETA = 3; /** * Trigger that is fired when the configured provider detects arrival. */ public const int TRIGGER_TYPE_ARRIVAL = 4; /** * Trigger that is fired when the configured provider detects that the user has departed a given location. */ public const int TRIGGER_TYPE_DEPARTURE = 5; /** * Remote trigger that is fired when a user enters a circular geofence */ public const int TRIGGER_TYPE_REMOTE_GEO_CIRCLE = 6; /** * Remote trigger that is fired when an ETA threshold is crossed. */ public const int TRIGGER_TYPE_REMOTE_ETA = 7; /** * @name Remote trigger type strings */ public static String TRIGGER_REMOTE_GEO_CIRCLE_KEY() { return CoreFactory.createString("geo_circle"); } public static String TRIGGER_REMOTE_ETA_KEY() { return CoreFactory.createString("eta"); } /** * @name Network Response * * Success criteria constants for netwrok response. */ public const int NETWORK_RESPONSE_CODE_ANY = 0x00000000; public const int NETWORK_RESPONSE_CODE_ANY_VALID = 0x00000001; public const int NETWORK_RESPONSE_CODE_2XX = 0x00000002; public const int NETWORK_RESPONSE_BODY_ANY = 0x00000000; public const int NETWORK_RESPONSE_BODY_NOT_EMPTY = 0x00000010; public const int NETWORK_RESPONSE_BODY_VALID_JSON = 0x00000030; /** * @name CardTicket Replies * * Supported card ticket replies. */ public const int CARD_TICKET_REPLY_INACTIVE = 0x00000001; public const int CARD_TICKET_REPLY_NONE = 0x00000002; public const int CARD_TICKET_REPLY_ACCEPT = 0x00000004; public const int CARD_TICKET_REPLY_DECLINE = 0x00000008; public const int CARD_TICKET_REPLY_ANY = CARD_TICKET_REPLY_ACCEPT | CARD_TICKET_REPLY_DECLINE; /** * @name Card Object types * * Constants defining what type of object a card object is. */ public static String CARD_OBJECT_TYPE_POI() { return CoreFactory.createString("poi"); } public static String CARD_OBJECT_TYPE_INVITE() { return CoreFactory.createString("invite"); } public static String CARD_OBJECT_TYPE_UNKNOWN() { return CoreFactory.createString("unknown"); } /** * @name Card States * * Supported card states. */ /** * Initial state of card object. Card exists in none state until it is registered on the manager. */ public const int CARD_STATE_NONE = 0x00000001; /** * Card is in process of being created. */ public const int CARD_STATE_CREATING = 0x00000002; /** * State representing the card decoded from invite. */ public const int CARD_STATE_PREVIEW = 0x00000004; /** * The start card is turned into while client is waiting for acceptance from server. */ public const int CARD_STATE_JOINING = 0x00000008; /** * Indicates completely initialized card maintained by card manager. */ public const int CARD_STATE_ACTIVE = 0x00000010; /** * User is in process of leaving the card. */ public const int CARD_STATE_LEAVING = 0x00000020; /** * Fatal state indicating failure to create a card. * Card with this state should not be registered on card manager's list. */ public const int CARD_STATE_FAILED_TO_CREATE = 0x00000040; /** * Fatal state indicating failure to join a card. * Card with this state should not be registered on card manager's list. */ public const int CARD_STATE_FAILED_TO_JOIN = 0x00000080; /** * @name Card IDs * * Supported card ids, to be used when creating a card with GlympseFactory::createCard(...) */ /** * Private group card ID */ public static String CARD_ID_PRIVATE_GROUP() { return CoreFactory.createString("559364b74d76b03a2f46096e"); } /** * @name Consent types * * Consent type indicates whether user consent is from a parent/guardian or the subject */ /** * Indicates the user is agreeing for themself */ public static String CONSENT_TYPE_SUBJECT() { return CoreFactory.createString("subject"); } /** * Indicates the user is providing consent for a minor */ public static String CONSENT_TYPE_GUARDIAN() { return CoreFactory.createString("guardian"); } /** * @name Consent states * * Consent state is used to indicate whether the user has granted/denied/never been shown the consent dialog */ /** * Consent has never been acted on (default state). Choice should * be displayed to the user as soon as possible. The user will not be able * to create new data while in this state. */ public static String USER_CONSENT_NONE() { return CoreFactory.createString("none"); } /** * Consent has been denied. The user will not be able to create new * data through the platform while in this state. */ public static String USER_CONSENT_NO() { return CoreFactory.createString("no"); } /** * Consent has been granted. The user will have normal ability to interact * with the platform without restrictions while in this state. */ public static String USER_CONSENT_YES() { return CoreFactory.createString("yes"); } public static String USER_CONSENT_EXEMPT() { return CoreFactory.createString("exempt"); } /** * @name Glympse Privacy URLs */ /** * URL for Glympse's Privacy Policy */ public static String PRIVACY_POLICY_URL() { return CoreFactory.createString("https://glympse.com/privacy/"); } /** * URL for Glympse's Terms & Conditions */ public static String TERMS_AND_CONDITIONS_URL() { return CoreFactory.createString("https://glympse.com/terms/"); } /** * Customer Pickup phases */ public static String CUSTOMER_PICKUP_PHASE_NEW() { return CoreFactory.createString("new"); } public static String CUSTOMER_PICKUP_PHASE_READY() { return CoreFactory.createString("ready"); } public static String CUSTOMER_PICKUP_PHASE_LIVE() { return CoreFactory.createString("live"); } public static String CUSTOMER_PICKUP_PHASE_ARRIVED() { return CoreFactory.createString("arrived"); } public static String CUSTOMER_PICKUP_PHASE_COMPLETED() { return CoreFactory.createString("completed"); } public static String CUSTOMER_PICKUP_PHASE_HOLD() { return CoreFactory.createString("not_completed"); } public static String CUSTOMER_PICKUP_PHASE_CANCELLED() { return CoreFactory.createString("cancelled"); } }; }
/* 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; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Providers; namespace Orleans.Storage { /// <summary> /// This is a simple in-memory grain implementation of a storage provider. /// </summary> /// <remarks> /// This storage provider is ONLY intended for simple in-memory Development / Unit Test scenarios. /// This class should NOT be used in Production environment, /// because [by-design] it does not provide any resilience /// or long-term persistence capabilities. /// </remarks> /// <example> /// Example configuration for this storage provider in OrleansConfiguration.xml file: /// <code> /// &lt;OrleansConfiguration xmlns="urn:orleans"> /// &lt;Globals> /// &lt;StorageProviders> /// &lt;Provider Type="Orleans.Storage.MemoryStorage" Name="MemoryStore" /> /// &lt;/StorageProviders> /// </code> /// </example> [DebuggerDisplay("MemoryStore:{Name}")] public class MemoryStorage : IStorageProvider { private const int DEFAULT_NUM_STORAGE_GRAINS = 10; private const string NUM_STORAGE_GRAINS = "NumStorageGrains"; private int numStorageGrains; private static int counter; private readonly int id; private const string STATE_STORE_NAME = "MemoryStorage"; private string etag; private Lazy<IMemoryStorageGrain>[] storageGrains; /// <summary> Name of this storage provider instance. </summary> /// <see cref="IProvider#Name"/> public string Name { get; private set; } /// <summary> Logger used by this storage provider instance. </summary> /// <see cref="IStorageProvider#Log"/> public Logger Log { get; private set; } public MemoryStorage() : this(DEFAULT_NUM_STORAGE_GRAINS) { } protected MemoryStorage(int numStoreGrains) { id = Interlocked.Increment(ref counter); numStorageGrains = numStoreGrains; } protected virtual string GetLoggerName() { return string.Format("Storage.{0}.{1}", GetType().Name, id); } #region IStorageProvider methods /// <summary> Initialization function for this storage provider. </summary> /// <see cref="IProvider#Init"/> public virtual Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config) { Name = name; Log = providerRuntime.GetLogger(GetLoggerName()); string numStorageGrainsStr; if (config.Properties.TryGetValue(NUM_STORAGE_GRAINS, out numStorageGrainsStr)) numStorageGrains = Int32.Parse(numStorageGrainsStr); Log.Info("Init: Name={0} NumStorageGrains={1}", Name, numStorageGrains); storageGrains = new Lazy<IMemoryStorageGrain>[numStorageGrains]; for (int i = 0; i < numStorageGrains; i++) { int idx = i; // Capture variable to avoid modified closure error storageGrains[idx] = new Lazy<IMemoryStorageGrain>(() => providerRuntime.GrainFactory.GetGrain<IMemoryStorageGrain>(idx)); } return TaskDone.Done; } /// <summary> Shutdown function for this storage provider. </summary> /// <see cref="IStorageProvider#Close"/> public virtual Task Close() { for (int i = 0; i < numStorageGrains; i++) storageGrains[i] = null; return TaskDone.Done; } /// <summary> Read state data function for this storage provider. </summary> /// <see cref="IStorageProvider#ReadStateAsync"/> public virtual async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { var keys = MakeKeys(grainType, grainReference); if (Log.IsVerbose2) Log.Verbose2("Read Keys={0}", StorageProviderUtils.PrintKeys(keys)); string id = HierarchicalKeyStore.MakeStoreKey(keys); IMemoryStorageGrain storageGrain = GetStorageGrain(id); IDictionary<string, object> state = await storageGrain.ReadStateAsync(STATE_STORE_NAME, id); if (state != null) { grainState.SetAll(state); } } /// <summary> Write state data function for this storage provider. </summary> /// <see cref="IStorageProvider#WriteStateAsync"/> public virtual async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { var keys = MakeKeys(grainType, grainReference); var data = grainState.AsDictionary(); string receivedEtag = grainState.Etag; if (Log.IsVerbose2) Log.Verbose2("Write {0} ", StorageProviderUtils.PrintOneWrite(keys, data, receivedEtag)); if (receivedEtag != null && receivedEtag != etag) throw new InconsistentStateException(string.Format("Etag mismatch durign Write: Expected = {0} Received = {1}", etag, receivedEtag)); string key = HierarchicalKeyStore.MakeStoreKey(keys); IMemoryStorageGrain storageGrain = GetStorageGrain(key); await storageGrain.WriteStateAsync(STATE_STORE_NAME, key, data); etag = NewEtag(); } /// <summary> Delete / Clear state data function for this storage provider. </summary> /// <see cref="IStorageProvider#ClearStateAsync"/> public virtual async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { var keys = MakeKeys(grainType, grainReference); string eTag = grainState.Etag; // TOD: Should this be 'null' for always Delete? if (Log.IsVerbose2) Log.Verbose2("Delete Keys={0} Etag={1}", StorageProviderUtils.PrintKeys(keys), eTag); if (eTag != null && eTag != etag) throw new InconsistentStateException(string.Format("Etag mismatch durign Delete: Expected = {0} Received = {1}", this.etag, eTag)); string key = HierarchicalKeyStore.MakeStoreKey(keys); IMemoryStorageGrain storageGrain = GetStorageGrain(key); await storageGrain.DeleteStateAsync(STATE_STORE_NAME, key); etag = NewEtag(); } #endregion private static IEnumerable<Tuple<string, string>> MakeKeys(string grainType, GrainReference grain) { return new[] { Tuple.Create("GrainType", grainType), Tuple.Create("GrainId", grain.ToKeyString()) }; } private IMemoryStorageGrain GetStorageGrain(string id) { int idx = StorageProviderUtils.PositiveHash(id.GetHashCode(), numStorageGrains); IMemoryStorageGrain storageGrain = storageGrains[idx].Value; return storageGrain; } internal static Func<IDictionary<string, object>, bool> GetComparer<T>(string rangeParamName, T fromValue, T toValue) where T : IComparable { Comparer comparer = Comparer.DefaultInvariant; bool sameRange = comparer.Compare(fromValue, toValue) == 0; // FromValue == ToValue bool insideRange = comparer.Compare(fromValue, toValue) < 0; // FromValue < ToValue Func<IDictionary<string, object>, bool> compareClause; if (sameRange) { compareClause = data => { if (data == null || data.Count <= 0) return false; if (!data.ContainsKey(rangeParamName)) { var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}", rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data)); throw new KeyNotFoundException(error); } T obj = (T) data[rangeParamName]; return comparer.Compare(obj, fromValue) == 0; }; } else if (insideRange) { compareClause = data => { if (data == null || data.Count <= 0) return false; if (!data.ContainsKey(rangeParamName)) { var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}", rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data)); throw new KeyNotFoundException(error); } T obj = (T) data[rangeParamName]; return comparer.Compare(obj, fromValue) >= 0 && comparer.Compare(obj, toValue) <= 0; }; } else { compareClause = data => { if (data == null || data.Count <= 0) return false; if (!data.ContainsKey(rangeParamName)) { var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}", rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data)); throw new KeyNotFoundException(error); } T obj = (T) data[rangeParamName]; return comparer.Compare(obj, fromValue) >= 0 || comparer.Compare(obj, toValue) <= 0; }; } return compareClause; } private static string NewEtag() { return DateTime.UtcNow.ToString(CultureInfo.InvariantCulture); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using Lucene.Net.Search; using NumericTokenStream = Lucene.Net.Analysis.NumericTokenStream; using TokenStream = Lucene.Net.Analysis.TokenStream; using NumericUtils = Lucene.Net.Util.NumericUtils; using FieldCache = Lucene.Net.Search.FieldCache; using SortField = Lucene.Net.Search.SortField; namespace Lucene.Net.Documents { // javadocs /// <summary> <p/>This class provides a <see cref="Field" /> that enables indexing /// of numeric values for efficient range filtering and /// sorting. Here's an example usage, adding an int value: /// <code> /// document.add(new NumericField(name).setIntValue(value)); /// </code> /// /// For optimal performance, re-use the /// <c>NumericField</c> and <see cref="Document" /> instance for more than /// one document: /// /// <code> /// NumericField field = new NumericField(name); /// Document document = new Document(); /// document.add(field); /// /// for(all documents) { /// ... /// field.setIntValue(value) /// writer.addDocument(document); /// ... /// } /// </code> /// /// <p/>The .Net native types <c>int</c>, <c>long</c>, /// <c>float</c> and <c>double</c> are /// directly supported. However, any value that can be /// converted into these native types can also be indexed. /// For example, date/time values represented by a /// <see cref="System.DateTime" /> can be translated into a long /// value using the <c>java.util.Date.getTime</c> method. If you /// don't need millisecond precision, you can quantize the /// value, either by dividing the result of /// <c>java.util.Date.getTime</c> or using the separate getters /// (for year, month, etc.) to construct an <c>int</c> or /// <c>long</c> value.<p/> /// /// <p/>To perform range querying or filtering against a /// <c>NumericField</c>, use <see cref="NumericRangeQuery{T}" /> or <see cref="NumericRangeFilter{T}" /> ///. To sort according to a /// <c>NumericField</c>, use the normal numeric sort types, eg /// <see cref="SortField.INT" /> <c>NumericField</c> values /// can also be loaded directly from <see cref="FieldCache" />.<p/> /// /// <p/>By default, a <c>NumericField</c>'s value is not stored but /// is indexed for range filtering and sorting. You can use /// the <see cref="NumericField(String,Field.Store,bool)" /> /// constructor if you need to change these defaults.<p/> /// /// <p/>You may add the same field name as a <c>NumericField</c> to /// the same document more than once. Range querying and /// filtering will be the logical OR of all values; so a range query /// will hit all documents that have at least one value in /// the range. However sort behavior is not defined. If you need to sort, /// you should separately index a single-valued <c>NumericField</c>.<p/> /// /// <p/>A <c>NumericField</c> will consume somewhat more disk space /// in the index than an ordinary single-valued field. /// However, for a typical index that includes substantial /// textual content per document, this increase will likely /// be in the noise. <p/> /// /// <p/>Within Lucene, each numeric value is indexed as a /// <em>trie</em> structure, where each term is logically /// assigned to larger and larger pre-defined brackets (which /// are simply lower-precision representations of the value). /// The step size between each successive bracket is called the /// <c>precisionStep</c>, measured in bits. Smaller /// <c>precisionStep</c> values result in larger number /// of brackets, which consumes more disk space in the index /// but may result in faster range search performance. The /// default value, 4, was selected for a reasonable tradeoff /// of disk space consumption versus performance. You can /// use the expert constructor <see cref="NumericField(String,int,Field.Store,bool)" /> /// if you'd /// like to change the value. Note that you must also /// specify a congruent value when creating <see cref="NumericRangeQuery{T}" /> /// or <see cref="NumericRangeFilter{T}" />. /// For low cardinality fields larger precision steps are good. /// If the cardinality is &lt; 100, it is fair /// to use <see cref="int.MaxValue" />, which produces one /// term per value. /// /// <p/>For more information on the internals of numeric trie /// indexing, including the <a /// href="../search/NumericRangeQuery.html#precisionStepDesc"><c>precisionStep</c></a> /// configuration, see <see cref="NumericRangeQuery{T}" />. The format of /// indexed values is described in <see cref="NumericUtils" />. /// /// <p/>If you only need to sort by numeric value, and never /// run range querying/filtering, you can index using a /// <c>precisionStep</c> of <see cref="int.MaxValue" />. /// This will minimize disk space consumed. <p/> /// /// <p/>More advanced users can instead use <see cref="NumericTokenStream" /> /// directly, when indexing numbers. This /// class is a wrapper around this token stream type for /// easier, more intuitive usage.<p/> /// /// <p/><b>NOTE:</b> This class is only used during /// indexing. When retrieving the stored field value from a /// <see cref="Document" /> instance after search, you will get a /// conventional <see cref="IFieldable" /> instance where the numeric /// values are returned as <see cref="String" />s (according to /// <c>toString(value)</c> of the used data type). /// /// <p/><font color="red"><b>NOTE:</b> This API is /// experimental and might change in incompatible ways in the /// next release.</font> /// /// </summary> /// <since> 2.9 /// </since> //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 public sealed class NumericField:AbstractField { new private readonly NumericTokenStream tokenStream; /// <summary> Creates a field for numeric values using the default <c>precisionStep</c> /// <see cref="NumericUtils.PRECISION_STEP_DEFAULT" /> (4). The instance is not yet initialized with /// a numeric value, before indexing a document containing this field, /// set a value using the various set<em>???</em>Value() methods. /// This constructor creates an indexed, but not stored field. /// </summary> /// <param name="name">the field name /// </param> public NumericField(System.String name):this(name, NumericUtils.PRECISION_STEP_DEFAULT, Field.Store.NO, true) { } /// <summary> Creates a field for numeric values using the default <c>precisionStep</c> /// <see cref="NumericUtils.PRECISION_STEP_DEFAULT" /> (4). The instance is not yet initialized with /// a numeric value, before indexing a document containing this field, /// set a value using the various set<em>???</em>Value() methods. /// </summary> /// <param name="name">the field name /// </param> /// <param name="store">if the field should be stored in plain text form /// (according to <c>toString(value)</c> of the used data type) /// </param> /// <param name="index">if the field should be indexed using <see cref="NumericTokenStream" /> /// </param> public NumericField(System.String name, Field.Store store, bool index):this(name, NumericUtils.PRECISION_STEP_DEFAULT, store, index) { } /// <summary> Creates a field for numeric values with the specified /// <c>precisionStep</c>. The instance is not yet initialized with /// a numeric value, before indexing a document containing this field, /// set a value using the various set<em>???</em>Value() methods. /// This constructor creates an indexed, but not stored field. /// </summary> /// <param name="name">the field name /// </param> /// <param name="precisionStep">the used <a href="../search/NumericRangeQuery.html#precisionStepDesc">precision step</a> /// </param> public NumericField(System.String name, int precisionStep):this(name, precisionStep, Field.Store.NO, true) { } /// <summary> Creates a field for numeric values with the specified /// <c>precisionStep</c>. The instance is not yet initialized with /// a numeric value, before indexing a document containing this field, /// set a value using the various set<em>???</em>Value() methods. /// </summary> /// <param name="name">the field name /// </param> /// <param name="precisionStep">the used <a href="../search/NumericRangeQuery.html#precisionStepDesc">precision step</a> /// </param> /// <param name="store">if the field should be stored in plain text form /// (according to <c>toString(value)</c> of the used data type) /// </param> /// <param name="index">if the field should be indexed using <see cref="NumericTokenStream" /> /// </param> public NumericField(System.String name, int precisionStep, Field.Store store, bool index):base(name, store, index?Field.Index.ANALYZED_NO_NORMS:Field.Index.NO, Field.TermVector.NO) { OmitTermFreqAndPositions = true; tokenStream = new NumericTokenStream(precisionStep); } /// <summary>Returns a <see cref="NumericTokenStream" /> for indexing the numeric value. </summary> public override TokenStream TokenStreamValue { get { return IsIndexed ? tokenStream : null; } } /// <summary>Returns always <c>null</c> for numeric fields </summary> public override byte[] GetBinaryValue(byte[] result) { return null; } /// <summary>Returns always <c>null</c> for numeric fields </summary> public override TextReader ReaderValue { get { return null; } } /// <summary>Returns the numeric value as a string (how it is stored, when <see cref="Field.Store.YES" /> is chosen). </summary> public override string StringValue { get { return (fieldsData == null) ? null : fieldsData.ToString(); } } /// <summary>Returns the current numeric value as a subclass of <see cref="Number" />, <c>null</c> if not yet initialized. </summary> public ValueType NumericValue { get { return (System.ValueType) fieldsData; } } /// <summary> Initializes the field with the supplied <c>long</c> value.</summary> /// <param name="value_Renamed">the numeric value /// </param> /// <returns> this instance, because of this you can use it the following way: /// <c>document.add(new NumericField(name, precisionStep).SetLongValue(value))</c> /// </returns> public NumericField SetLongValue(long value_Renamed) { tokenStream.SetLongValue(value_Renamed); fieldsData = value_Renamed; return this; } /// <summary> Initializes the field with the supplied <c>int</c> value.</summary> /// <param name="value_Renamed">the numeric value /// </param> /// <returns> this instance, because of this you can use it the following way: /// <c>document.add(new NumericField(name, precisionStep).setIntValue(value))</c> /// </returns> public NumericField SetIntValue(int value_Renamed) { tokenStream.SetIntValue(value_Renamed); fieldsData = value_Renamed; return this; } /// <summary> Initializes the field with the supplied <c>double</c> value.</summary> /// <param name="value_Renamed">the numeric value /// </param> /// <returns> this instance, because of this you can use it the following way: /// <c>document.add(new NumericField(name, precisionStep).setDoubleValue(value))</c> /// </returns> public NumericField SetDoubleValue(double value_Renamed) { tokenStream.SetDoubleValue(value_Renamed); fieldsData = value_Renamed; return this; } /// <summary> Initializes the field with the supplied <c>float</c> value.</summary> /// <param name="value_Renamed">the numeric value /// </param> /// <returns> this instance, because of this you can use it the following way: /// <c>document.add(new NumericField(name, precisionStep).setFloatValue(value))</c> /// </returns> public NumericField SetFloatValue(float value_Renamed) { tokenStream.SetFloatValue(value_Renamed); fieldsData = value_Renamed; return this; } } }
// DirectXTK MakeSpriteFont tool // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkId=248929 using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace MakeSpriteFont { // Assorted helpers for doing useful things with bitmaps. public static class BitmapUtils { // Copies a rectangular area from one bitmap to another. public static void CopyRect(Bitmap source, Rectangle sourceRegion, Bitmap output, Rectangle outputRegion) { if (sourceRegion.Width != outputRegion.Width || sourceRegion.Height != outputRegion.Height) { throw new ArgumentException(); } using (var sourceData = new PixelAccessor(source, ImageLockMode.ReadOnly, sourceRegion)) using (var outputData = new PixelAccessor(output, ImageLockMode.WriteOnly, outputRegion)) { for (int y = 0; y < sourceRegion.Height; y++) { for (int x = 0; x < sourceRegion.Width; x++) { outputData[x, y] = sourceData[x, y]; } } } } // Checks whether an area of a bitmap contains entirely the specified alpha value. public static bool IsAlphaEntirely(byte expectedAlpha, Bitmap bitmap, Rectangle? region = null) { using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadOnly, region)) { for (int y = 0; y < bitmapData.Region.Height; y++) { for (int x = 0; x < bitmapData.Region.Width; x++) { byte alpha = bitmapData[x, y].A; if (alpha != expectedAlpha) return false; } } } return true; } // Checks whether a bitmap contains entirely the specified RGB value. public static bool IsRgbEntirely(Color expectedRgb, Bitmap bitmap) { using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadOnly)) { for (int y = 0; y < bitmap.Height; y++) { for (int x = 0; x < bitmap.Width; x++) { Color color = bitmapData[x, y]; if (color.A == 0) continue; if ((color.R != expectedRgb.R) || (color.G != expectedRgb.G) || (color.B != expectedRgb.B)) { return false; } } } } return true; } // Converts greyscale luminosity to alpha data. public static void ConvertGreyToAlpha(Bitmap bitmap) { using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadWrite)) { for (int y = 0; y < bitmap.Height; y++) { for (int x = 0; x < bitmap.Width; x++) { Color color = bitmapData[x, y]; // Average the red, green and blue values to compute brightness. int alpha = (color.R + color.G + color.B) / 3; bitmapData[x, y] = Color.FromArgb(alpha, 255, 255, 255); } } } } // Converts a bitmap to premultiplied alpha format. public static void PremultiplyAlpha(Bitmap bitmap) { using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadWrite)) { for (int y = 0; y < bitmap.Height; y++) { for (int x = 0; x < bitmap.Width; x++) { Color color = bitmapData[x, y]; int a = color.A; int r = color.R * a / 255; int g = color.G * a / 255; int b = color.B * a / 255; bitmapData[x, y] = Color.FromArgb(a, r, g, b); } } } } // To avoid filtering artifacts when scaling or rotating fonts that do not use premultiplied alpha, // make sure the one pixel border around each glyph contains the same RGB values as the edge of the // glyph itself, but with zero alpha. This processing is an elaborate no-op when using premultiplied // alpha, because the premultiply conversion will change the RGB of all such zero alpha pixels to black. public static void PadBorderPixels(Bitmap bitmap, Rectangle region) { using (var bitmapData = new PixelAccessor(bitmap, ImageLockMode.ReadWrite)) { // Pad the top and bottom. for (int x = region.Left; x < region.Right; x++) { CopyBorderPixel(bitmapData, x, region.Top, x, region.Top - 1); CopyBorderPixel(bitmapData, x, region.Bottom - 1, x, region.Bottom); } // Pad the left and right. for (int y = region.Top; y < region.Bottom; y++) { CopyBorderPixel(bitmapData, region.Left, y, region.Left - 1, y); CopyBorderPixel(bitmapData, region.Right - 1, y, region.Right, y); } // Pad the four corners. CopyBorderPixel(bitmapData, region.Left, region.Top, region.Left - 1, region.Top - 1); CopyBorderPixel(bitmapData, region.Right - 1, region.Top, region.Right, region.Top - 1); CopyBorderPixel(bitmapData, region.Left, region.Bottom - 1, region.Left - 1, region.Bottom); CopyBorderPixel(bitmapData, region.Right - 1, region.Bottom - 1, region.Right, region.Bottom); } } // Copies a single pixel within a bitmap, preserving RGB but forcing alpha to zero. static void CopyBorderPixel(PixelAccessor bitmapData, int sourceX, int sourceY, int destX, int destY) { Color color = bitmapData[sourceX, sourceY]; bitmapData[destX, destY] = Color.FromArgb(0, color); } // Converts a bitmap to the specified pixel format. public static Bitmap ChangePixelFormat(Bitmap bitmap, PixelFormat format) { Rectangle bounds = new Rectangle(0, 0, bitmap.Width, bitmap.Height); return bitmap.Clone(bounds, format); } // Helper for locking a bitmap and efficiently reading or writing its pixels. public sealed class PixelAccessor : IDisposable { // Constructor locks the bitmap. public PixelAccessor(Bitmap bitmap, ImageLockMode mode, Rectangle? region = null) { this.bitmap = bitmap; this.Region = region.GetValueOrDefault(new Rectangle(0, 0, bitmap.Width, bitmap.Height)); this.data = bitmap.LockBits(Region, mode, PixelFormat.Format32bppArgb); } // Dispose unlocks the bitmap. public void Dispose() { if (data != null) { bitmap.UnlockBits(data); data = null; } } // Query what part of the bitmap is locked. public Rectangle Region { get; private set; } // Get or set a pixel value. public Color this[int x, int y] { get { return Color.FromArgb(Marshal.ReadInt32(PixelAddress(x, y))); } set { Marshal.WriteInt32(PixelAddress(x, y), value.ToArgb()); } } // Helper computes the address of the specified pixel. IntPtr PixelAddress(int x, int y) { return data.Scan0 + (y * data.Stride) + (x * sizeof(int)); } // Fields. Bitmap bitmap; BitmapData data; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Feedback.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Packaging; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using NuGet.VisualStudio; using Roslyn.Utilities; using Roslyn.VisualStudio.ProjectSystem; using VSLangProj; using VSLangProj140; using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// The Workspace for running inside Visual Studio. /// </summary> internal abstract class VisualStudioWorkspaceImpl : VisualStudioWorkspace { private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1); private const string AppCodeFolderName = "App_Code"; protected readonly IServiceProvider ServiceProvider; private readonly IVsUIShellOpenDocument _shellOpenDocument; private readonly IVsTextManager _textManager; // Not readonly because it needs to be set in the derived class' constructor. private VisualStudioProjectTracker _projectTracker; // document worker coordinator private ISolutionCrawlerRegistrationService _registrationService; private readonly ForegroundThreadAffinitizedObject _foregroundObject = new ForegroundThreadAffinitizedObject(); public VisualStudioWorkspaceImpl( SVsServiceProvider serviceProvider, WorkspaceBackgroundWork backgroundWork) : base( CreateHostServices(serviceProvider), backgroundWork) { this.ServiceProvider = serviceProvider; _textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager; _shellOpenDocument = serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); var session = serviceProvider.GetService(typeof(SVsLog)) as IVsSqmMulti; var profileService = serviceProvider.GetService(typeof(SVsFeedbackProfile)) as IVsFeedbackProfile; // We have Watson hits where this came back null, so guard against it if (profileService != null) { Sqm.LogSession(session, profileService.IsMicrosoftInternal); } } internal static HostServices CreateHostServices(SVsServiceProvider serviceProvider) { var composition = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); return MefV1HostServices.Create(composition.DefaultExportProvider); } protected void InitializeStandardVisualStudioWorkspace(SVsServiceProvider serviceProvider, SaveEventsService saveEventsService) { var projectTracker = new VisualStudioProjectTracker(serviceProvider); // Ensure the document tracking service is initialized on the UI thread var documentTrackingService = this.Services.GetService<IDocumentTrackingService>(); var documentProvider = new RoslynDocumentProvider(projectTracker, serviceProvider, documentTrackingService); projectTracker.DocumentProvider = documentProvider; projectTracker.MetadataReferenceProvider = this.Services.GetService<VisualStudioMetadataReferenceManager>(); projectTracker.RuleSetFileProvider = this.Services.GetService<VisualStudioRuleSetManager>(); this.SetProjectTracker(projectTracker); var workspaceHost = new VisualStudioWorkspaceHost(this); projectTracker.RegisterWorkspaceHost(workspaceHost); projectTracker.StartSendingEventsToWorkspaceHost(workspaceHost); saveEventsService.StartSendingSaveEvents(); // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); } /// <summary>NOTE: Call only from derived class constructor</summary> protected void SetProjectTracker(VisualStudioProjectTracker projectTracker) { _projectTracker = projectTracker; } internal VisualStudioProjectTracker ProjectTracker { get { return _projectTracker; } } internal void ClearReferenceCache() { _projectTracker.MetadataReferenceProvider.ClearCache(); } internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId) { var project = GetHostProject(documentId.ProjectId); if (project != null) { return project.GetDocumentOrAdditionalDocument(documentId); } return null; } internal IVisualStudioHostProject GetHostProject(ProjectId projectId) { return this.ProjectTracker.GetProject(projectId); } private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project) { project = GetHostProject(projectId); return project != null; } internal override bool TryApplyChanges( Microsoft.CodeAnalysis.Solution newSolution, IProgressTracker progressTracker) { // first make sure we can edit the document we will be updating (check them out from source control, etc) var changedDocs = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().SelectMany(pd => pd.GetChangedDocuments()).ToList(); if (changedDocs.Count > 0) { this.EnsureEditableDocuments(changedDocs); } return base.TryApplyChanges(newSolution, progressTracker); } public override bool CanOpenDocuments { get { return true; } } internal override bool CanChangeActiveContextDocument { get { return true; } } public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: case ApplyChangesKind.AddAdditionalDocument: case ApplyChangesKind.RemoveAdditionalDocument: case ApplyChangesKind.ChangeAdditionalDocument: return true; default: return false; } } private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { hierarchy = null; project = null; return this.TryGetHostProject(projectId, out hostProject) && this.TryGetHierarchy(projectId, out hierarchy) && hierarchy.TryGetProject(out project); } internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project)) { throw new ArgumentException(string.Format(ServicesVSResources.CouldNotFindProject, projectId)); } } internal EnvDTE.Project TryGetDTEProject(ProjectId projectId) { IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; return TryGetProjectData(projectId, out hostProject, out hierarchy, out project) ? project : null; } internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName) { IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; try { GetProjectData(projectId, out hostProject, out hierarchy, out project); } catch (ArgumentException) { return false; } var vsProject = (VSProject)project.Object; try { vsProject.References.Add(assemblyName); } catch (Exception) { return false; } return true; } private string GetAnalyzerPath(AnalyzerReference analyzerReference) { return analyzerReference.FullPath; } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Add(filePath); } } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Remove(filePath); } } private string GetMetadataPath(MetadataReference metadataReference) { var fileMetadata = metadataReference as PortableExecutableReference; if (fileMetadata != null) { return fileMetadata.FilePath; } return null; } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSProject vsProject = (VSProject)project.Object; vsProject.References.Add(filePath); } } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; VSLangProj.Reference reference = vsProject.References.Find(filePath); if (reference != null) { reference.Remove(); } } } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; vsProject.References.AddProject(refProject); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; foreach (VSLangProj.Reference reference in vsProject.References) { if (reference.SourceProject == refProject) { reference.Remove(); } } } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: false); } protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: true); } private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(info.Id.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. var folders = info.Folders.AsEnumerable(); if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } folders = FilterFolderForProjectType(project, folders); if (IsWebsite(project)) { AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else if (folders.Any()) { AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else { AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } } private bool IsWebsite(EnvDTE.Project project) { return project.Kind == VsWebSite.PrjKind.prjKindVenusProject; } private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders) { foreach (var folder in folders) { var items = GetAllItems(project.ProjectItems); var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0); if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile) { yield return folder; } } } private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems) { if (projectItems == null) { return SpecializedCollections.EmptyEnumerable<ProjectItem>(); } var items = projectItems.OfType<ProjectItem>(); return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems))); } #if false protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } var name = Path.GetFileName(filePath); if (folders.Any()) { AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } else { AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } } #endif private ProjectItem AddDocumentToProject( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { string folderPath; if (!project.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToFolder( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, IEnumerable<string> folders, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { var folder = project.FindOrCreateFolder(folders); string folderPath; if (!folder.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToProjectItems( IVisualStudioHostProject hostProject, ProjectItems projectItems, DocumentId documentId, string folderPath, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText, string filePath, bool isAdditionalDocument) { if (filePath == null) { var baseName = Path.GetFileNameWithoutExtension(documentName); var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind); var uniqueName = projectItems.GetUniqueName(baseName, extension); filePath = Path.Combine(folderPath, uniqueName); } if (initialText != null) { using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8)) { initialText.Write(writer); } } using (var documentIdHint = _projectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId)) { return projectItems.AddFromFile(filePath); } } protected void RemoveDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var document = this.GetHostDocument(documentId); if (document != null) { var project = document.Project.Hierarchy as IVsProject3; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // it is no longer part of the solution return; } int result; project.RemoveItem(0, itemId, out result); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } public override void OpenDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void CloseDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public override void CloseAdditionalDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public bool TryGetInfoBarData(out IVsWindowFrame frame, out IVsInfoBarUIFactory factory) { frame = null; factory = null; var monitorSelectionService = ServiceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; object value = null; // We want to get whichever window is currently in focus (including toolbars) as we could have had an exception thrown from the error list or interactive window if (monitorSelectionService != null && ErrorHandler.Succeeded(monitorSelectionService.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_WindowFrame, out value))) { frame = value as IVsWindowFrame; } else { return false; } factory = ServiceProvider.GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory; return frame != null && factory != null; } public void OpenDocumentCore(DocumentId documentId, bool activate = true) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (!_foregroundObject.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.ThisWorkspaceOnlySupportsOpeningDocumentsOnTheUIThread); } var document = this.GetHostDocument(documentId); if (document != null && document.Project != null) { IVsWindowFrame frame; if (TryGetFrame(document, out frame)) { if (activate) { frame.Show(); } else { frame.ShowNoActivate(); } } } } private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame) { frame = null; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // If the ItemId is Nil, then IVsProject would not be able to open the // document using its ItemId. Thus, we must use OpenDocumentViaProject, which only // depends on the file path. uint itemid; IVsUIHierarchy uiHierarchy; OLEServiceProvider oleServiceProvider; return ErrorHandler.Succeeded(_shellOpenDocument.OpenDocumentViaProject( document.FilePath, VSConstants.LOGVIEWID.TextView_guid, out oleServiceProvider, out uiHierarchy, out itemid, out frame)); } else { // If the ItemId is not Nil, then we should not call IVsUIShellDocument // .OpenDocumentViaProject here because that simply takes a file path and opens the // file within the context of the first project it finds. That would cause problems // if the document we're trying to open is actually a linked file in another // project. So, we get the project's hierarchy and open the document using its item // ID. // It's conceivable that IVsHierarchy might not implement IVsProject. However, // OpenDocumentViaProject itself relies upon this QI working, so it should be OK to // use here. var vsProject = document.Project.Hierarchy as IVsProject; return vsProject != null && ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame)); } } public void CloseDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (this.IsDocumentOpen(documentId)) { var document = this.GetHostDocument(documentId); if (document != null) { IVsUIHierarchy uiHierarchy; IVsWindowFrame frame; int isOpen; if (ErrorHandler.Succeeded(_shellOpenDocument.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out uiHierarchy, null, out frame, out isOpen))) { // TODO: do we need save argument for CloseDocument? frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } } } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind) { // No extension was provided. Pick a good one based on the type of host project. switch (hostProject.Language) { case LanguageNames.CSharp: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx"; return ".cs"; case LanguageNames.VisualBasic: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx"; return ".vb"; default: throw new InvalidOperationException(); } } public override IVsHierarchy GetHierarchy(ProjectId projectId) { var project = this.GetHostProject(projectId); if (project == null) { return null; } return project.Hierarchy; } internal override void SetDocumentContext(DocumentId documentId) { var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var hierarchy = hostDocument.Project.Hierarchy; var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { if (sharedHierarchy.SetProperty( (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK) { // The ASP.NET 5 intellisense project is now updated. return; } else { // Universal Project shared files // Change the SharedItemContextHierarchy of the project's parent hierarchy, then // hierarchy events will trigger the workspace to update. var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy); } } else { // Regular linked files // Transfer the item (open buffer) to the new hierarchy, and then hierarchy events // will trigger the workspace to update. var vsproj = hierarchy as IVsProject3; var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null); } } internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId) { // TODO: This is a very roundabout way to update the context // The sharedHierarchy passed in has a new context, but we don't know what it is. // The documentId passed in is associated with this sharedHierarchy, and this method // will be called once for each such documentId. During this process, one of these // documentIds will actually belong to the new SharedItemContextHierarchy. Once we // find that one, we can map back to the open buffer and set its active context to // the appropriate project. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); if (hostProject.Hierarchy == sharedHierarchy) { // How? return; } if (hostProject.Id != documentId.ProjectId) { // While this documentId is associated with one of the head projects for this // sharedHierarchy, it is not associated with the new context hierarchy. Another // documentId will be passed to this method and update the context. return; } // This documentId belongs to the new SharedItemContextHierarchy. Update the associated // buffer. OnDocumentContextUpdated(documentId); } /// <summary> /// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that /// is in the current context. For regular files (non-shared and non-linked) and closed /// linked files, this is always the provided <see cref="DocumentId"/>. For open linked /// files and open shared files, the active context is already tracked by the /// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the /// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/> /// is preferred. /// </summary> internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId) { // If the document is open, then the Workspace knows the current context for both // linked and shared files if (IsDocumentOpen(documentId)) { return base.GetDocumentIdInCurrentContext(documentId); } var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // An itemid is required to determine whether the file belongs to a Shared Project return base.GetDocumentIdInCurrentContext(documentId); } // If this is a regular document or a closed linked (non-shared) document, then use the // default logic for determining current context. var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy == null) { return base.GetDocumentIdInCurrentContext(documentId); } // This is a closed shared document, so we must determine the correct context. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); var matchingProject = CurrentSolution.GetProject(hostProject.Id); if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy) { return base.GetDocumentIdInCurrentContext(documentId); } if (matchingProject.ContainsDocument(documentId)) { // The provided documentId is in the current context project return documentId; } // The current context document is from another project. var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds(); var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id); return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId); } internal bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy) { hierarchy = this.GetHierarchy(projectId); return hierarchy != null; } public override string GetFilePath(DocumentId documentId) { var document = this.GetHostDocument(documentId); if (document == null) { return null; } else { return document.FilePath; } } internal void StartSolutionCrawler() { if (_registrationService == null) { lock (this) { if (_registrationService == null) { _registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>(); _registrationService.Register(this); } } } } internal void StopSolutionCrawler() { if (_registrationService != null) { lock (this) { if (_registrationService != null) { _registrationService.Unregister(this, blockingShutdown: true); _registrationService = null; } } } } protected override void Dispose(bool finalize) { // workspace is going away. unregister this workspace from work coordinator StopSolutionCrawler(); base.Dispose(finalize); } public void EnsureEditableDocuments(IEnumerable<DocumentId> documents) { var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GetService(typeof(SVsQueryEditQuerySave)); var fileNames = documents.Select(GetFilePath).ToArray(); uint editVerdict; uint editResultFlags; // TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn int result = queryEdit.QueryEditFiles( rgfQueryEdit: 0, cFiles: fileNames.Length, rgpszMkDocuments: fileNames, rgrgf: new uint[fileNames.Length], rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length], pfEditVerdict: out editVerdict, prgfMoreInfo: out editResultFlags); if (ErrorHandler.Failed(result) || editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { throw new Exception("Unable to check out the files from source control."); } if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0) { throw new Exception("A file was reloaded during the source control checkout."); } } public void EnsureEditableDocuments(params DocumentId[] documents) { this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents); } internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader); } internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader); } public TInterface GetVsService<TService, TInterface>() where TService : class where TInterface : class { return this.ServiceProvider.GetService(typeof(TService)) as TInterface; } internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject) { _foregroundObject.AssertIsForeground(); IVsHierarchy referencingHierarchy; IVsHierarchy referencedHierarchy; if (!TryGetHierarchy(referencingProject, out referencingHierarchy) || !TryGetHierarchy(referencedProject, out referencedHierarchy)) { // Couldn't even get a hierarchy for this project. So we have to assume // that adding a reference is disallowed. return false; } // First we have to see if either project disallows the reference being added. const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference; uint canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; uint canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; var referencingProjectFlavor3 = referencingHierarchy as IVsProjectFlavorReferences3; if (referencingProjectFlavor3 != null) { string unused; if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } var referencedProjectFlavor3 = referencedHierarchy as IVsProjectFlavorReferences3; if (referencedProjectFlavor3 != null) { string unused; if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } // Neither project denied the reference being added. At this point, if either project // allows the reference to be added, and the other doesn't block it, then we can add // the reference. if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW || canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW) { return true; } // In both directions things are still unknown. Fallback to the reference manager // to make the determination here. var referenceManager = GetVsService<SVsReferenceManager, IVsReferenceManager>(); if (referenceManager == null) { // Couldn't get the reference manager. Have to assume it's not allowed. return false; } // As long as the reference manager does not deny things, then we allow the // reference to be added. var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy); return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY; } /// <summary> /// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just /// forwards the calls down to the underlying Workspace. /// </summary> protected sealed class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkspaceHost2, IVisualStudioWorkingFolder { private readonly VisualStudioWorkspaceImpl _workspace; private Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>(); public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace) { _workspace = workspace; } void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions) { _workspace.OnCompilationOptionsChanged(projectId, compilationOptions); _workspace.OnParseOptionsChanged(projectId, parseOptions); } void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo) { _workspace.OnDocumentAdded(documentInfo); } void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext) { // TODO: Move this out to DocumentProvider. As is, this depends on being able to // access the host document which will already be deleted in some cases, causing // a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a // Mercury shared document is closed. // UnsubscribeFromSharedHierarchyEvents(documentId); using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed")) { _workspace.OnDocumentClosed(documentId, loader, updateActiveContext); } } void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext) { SubscribeToSharedHierarchyEvents(documentId); _workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext); } private void SubscribeToSharedHierarchyEvents(DocumentId documentId) { // Todo: maybe avoid double alerts. var hostDocument = _workspace.GetHostDocument(documentId); if (hostDocument == null) { return; } var hierarchy = hostDocument.Project.Hierarchy; var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId); var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out cookie); if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId)) { _documentIdToHierarchyEventsCookieMap.Add(documentId, cookie); } } } private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId) { var hostDocument = _workspace.GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out cookie)) { var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie); _documentIdToHierarchyEventsCookieMap.Remove(documentId); } } } private void RegisterPrimarySolutionForPersistentStorage(SolutionId solutionId) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.RegisterPrimarySolution(solutionId); } private void UnregisterPrimarySolutionForPersistentStorage(SolutionId solutionId, bool synchronousShutdown) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.UnregisterPrimarySolution(solutionId, synchronousShutdown); } void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId) { _workspace.OnDocumentRemoved(documentId); } void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceAdded(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceRemoved(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project")) { _workspace.OnProjectAdded(projectInfo); } } void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceAdded(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceRemoved(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project")) { _workspace.OnProjectRemoved(projectId); } } void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo) { RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id); _workspace.OnSolutionAdded(solutionInfo); } void IVisualStudioWorkspaceHost.OnSolutionRemoved() { var solutionId = _workspace.CurrentSolution.Id; _workspace.OnSolutionRemoved(); _workspace.ClearReferenceCache(); UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false); } void IVisualStudioWorkspaceHost.ClearSolution() { _workspace.ClearSolution(); _workspace.ClearReferenceCache(); } void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName) { _workspace.OnAssemblyNameChanged(id, assemblyName); } void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath) { _workspace.OnOutputFilePathChanged(id, outputFilePath); } void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath) { _workspace.OnProjectNameChanged(projectId, name, filePath); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo additionalDocumentInfo) { _workspace.OnAdditionalDocumentAdded(additionalDocumentInfo); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId additionalDocumentId) { _workspace.OnAdditionalDocumentRemoved(additionalDocumentId); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext) { _workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader) { _workspace.OnAdditionalDocumentClosed(documentId, loader); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnAdditionalDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost2.OnHasAllInformation(ProjectId projectId, bool hasAllInformation) { _workspace.OnHasAllInformationChanged(projectId, hasAllInformation); } void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange() { UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true); } void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange() { var solutionId = _workspace.CurrentSolution.Id; _workspace.ProjectTracker.UpdateSolutionProperties(solutionId); RegisterPrimarySolutionForPersistentStorage(solutionId); } } } }
//-- // Windows Forms Aero Controls // http://www.CodePlex.com/VistaControls // // Copyright (c) 2008 Jachym Kouba // Licensed under Microsoft Reciprocal License (Ms-RL) //-- using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; namespace WindowsFormsAero { public class TabStripAeroRenderer : TabStripRenderer { private const float TabBackgroundRatio = 0.25f; private const float TabStripBackgroundRatio = 0.4f; private const int BusyTimerInterval = 100; private const int BusyImagePadding = 12; private static readonly Color TabBorderColor = Color.FromArgb(145, 150, 162); private static readonly Color[] SelectedColors = new Color[] { Color.FromArgb(252, 253, 253), Color.FromArgb(198, 221, 247), Color.FromArgb(153, 198, 238), Color.FromArgb(224, 236, 251), }; private static readonly Color[] CheckedColors = new Color[] { Color.FromArgb(252, 253, 253), Color.FromArgb(231, 245, 251), Color.FromArgb(207, 231, 250), Color.FromArgb(185, 209, 250), }; private static readonly Color[] NormalColors = new Color[] { Color.White, Color.FromArgb(227, 232, 244), Color.FromArgb(207, 215, 235), Color.FromArgb(233, 236, 250), }; private Int32 _currentTickCount; private Image _currentBusyImage; public TabStripAeroRenderer() : base(new ToolStripAeroRenderer()) { BusyTabRefreshInterval = TimeSpan.FromMilliseconds(BusyTimerInterval); RenderUsingVisualStyles = true; RenderBackground = true; } public bool RenderBackground { get; set; } public bool RenderUsingVisualStyles { get; set; } public override Color SelectedTabBottomColor { get { return CheckedColors[3]; } } public override Size GetBusyImageSize(ToolStripItem item) { return BusyImageSize; } public override Size GetCloseButtonSize(ToolStripItem item) { return new Size(17, 16); } protected override void OnRenderToolStripBackground(ToolStripRenderEventArgs e) { if (e.ToolStrip is TabStrip) { if (VisualStylesAvailable && RenderBackground) { FillGradient(e.Graphics, GetTabStripUpperBorderPath(e), NormalColors, TabStripBackgroundRatio); } else if (VisualStylesAvailable) { e.Graphics.Clear(Color.FromArgb(0, Color.White)); } else { e.Graphics.Clear(SystemColors.Control); } } else { base.OnRenderToolStripBackground(e); } } protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) { var tabStrip = e.ToolStrip as TabStrip; if (tabStrip != null) { if (VisualStylesAvailable) { RenderToolStripBorderUsingVisualStyles(e, tabStrip); } } else { base.OnRenderToolStripBorder(e); } } protected override void OnRenderTabInsertionMark(TabStripInsertionMarkRenderEventArgs e) { var padding = e.TabStrip.Padding; var height = e.TabStrip.Height; var boundsDown = new Rectangle(e.Location - 3, padding.Top + 1, 7, 4); var boundsUp = new Rectangle(e.Location - 4, height - padding.Bottom - 5, 8, 5); using (var path = GetTriangleDownPath(boundsDown)) { e.Graphics.FillPath(Brushes.Black, path); } using (var path = GetTriangleUpPath(boundsUp)) { e.Graphics.FillPath(Brushes.Black, path); } } protected override void OnRenderTabItemBackground(TabStripItemRenderEventArgs e) { var isChecked = false; var button = e.Item as ToolStripButton; if (button != null && button.Checked) { isChecked = true; } if (VisualStylesAvailable) { RenderTabItemBackgroundUsingVisualStyles(e, isChecked); } else { var rect = new Rectangle(0, 0, e.Item.Width - 1, e.Item.Height - 1); if (isChecked) { using (var brush = new LinearGradientBrush(rect, SystemColors.ControlLightLight, SystemColors.Control, LinearGradientMode.Vertical)) { e.Graphics.FillRectangle(brush, rect); } } ControlPaint.DrawBorder3D(e.Graphics, rect, Border3DStyle.Raised, Border3DSide.Left | Border3DSide.Top | Border3DSide.Right); if (!e.CloseButtonRectangle.IsEmpty) { var closeRect = e.CloseButtonRectangle; if (e.CloseButtonState != TabStripCloseButtonState.Pressed) { closeRect.Offset(-2, -2); } using (var marlett = new Font("Marlett", 8)) { TextRenderer.DrawText(e.Graphics, "r", marlett, closeRect, SystemColors.ControlText); } } } } protected override void OnRenderTabItemBusyImage(TabStripItemBusyImageRenderEventArgs e) { UpdateBusyImage(e.TickCount); e.Graphics.DrawImageUnscaled(_currentBusyImage, e.ImageRectangle); } protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) { if (e.ImageRectangle.Width > 0 && e.ImageRectangle.Height > 0) { if (e.Item.Enabled) { e.Graphics.DrawImage(e.Image, e.ImageRectangle); } else { base.OnRenderItemImage(e); } } } #if TABSTRIP_AERORENDERER_GDIPLUS protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) { if (e.Item is TabStripButtonBase) { var sf = new StringFormat(StringFormatFlags.NoWrap) { LineAlignment = StringAlignment.Center, Trimming = StringTrimming.EllipsisCharacter }; if ((e.ToolStrip != null) && (e.ToolStrip.RightToLeft == RightToLeft.Yes)) { sf.FormatFlags |= StringFormatFlags.DirectionRightToLeft; } using (var brush = new SolidBrush(e.TextColor)) { // use GDI+ instead of TextRenderer to be compatible // with the glass effect e.Graphics.DrawString(e.Text, e.TextFont, brush, e.TextRectangle, sf); } } else { base.OnRenderItemText(e); } } #endif protected override void OnRenderTabScrollChevron(TabStripScrollButtonRenderEventArgs e) { const int ChevronWidth = 8; const int ChevronHeight = 5; Pen pen = Pens.Black; try { int x = e.ChevronRectangle.Left + ((e.ChevronRectangle.Width - ChevronWidth) / 2); int y = e.ChevronRectangle.Top + ((e.ChevronRectangle.Height - ChevronHeight) / 2); bool left = (e.ScrollDirection == TabStripScrollDirection.Left) && (e.ToolStrip.RightToLeft == RightToLeft.No); if (e.ToolStrip.RightToLeft == RightToLeft.Yes) { left = (e.ScrollDirection == TabStripScrollDirection.Right); } if (left) { x += 2; } if (!e.Item.Enabled) { pen = new Pen(Color.FromArgb(178, 178, 178), 1); } for (int i = 0; i < ChevronHeight; i++, y++) { e.Graphics.DrawLine(pen, x, y, x + 1, y); e.Graphics.DrawLine(pen, x + 4, y, x + 4 + 1, y); if (i < (ChevronHeight / 2)) { x += (left) ? -1 : +1; } else { x += (left) ? +1 : -1; } } } finally { if (!e.Item.Enabled) { pen.Dispose(); } } } private void UpdateBusyImage(int tickCount) { var frameSize = BusyImageSize; if (_currentBusyImage == null) { _currentBusyImage = CreateDesktopCompatibleBitmap(frameSize); } else if (_currentTickCount == tickCount) { return; } _currentTickCount = tickCount; int frame = tickCount % (BusyImage.Width / frameSize.Width); int srcX = (frame * BusyImage.Height); var destRect = new Rectangle(Point.Empty, frameSize); var srcRect = new Rectangle(new Point(srcX, 0), frameSize); using (Graphics graphics = Graphics.FromImage(_currentBusyImage)) { graphics.Clear(Color.Transparent); graphics.DrawImage(BusyImage, destRect, srcRect, GraphicsUnit.Pixel); } } private Boolean VisualStylesAvailable { get { return VisualStyleRenderer.IsSupported && RenderUsingVisualStyles; } } private static void RenderToolStripBorderUsingVisualStyles(ToolStripRenderEventArgs e, TabStrip tabStrip) { var left = e.AffectedBounds.Left; var right = e.AffectedBounds.Right - 1; var y = e.AffectedBounds.Bottom - tabStrip.Padding.Bottom; var selectedTab = tabStrip.SelectedTab; using (var paddingPen = new Pen(CheckedColors[3], 1)) { using (var borderPen = new Pen(TabBorderColor)) { if (selectedTab != null) { e.Graphics.DrawLine(borderPen, left, y, selectedTab.Bounds.Left, y); e.Graphics.DrawLine(Pens.White, left, y + 1, selectedTab.Bounds.Left, y + 1); e.Graphics.DrawLine(paddingPen, selectedTab.Bounds.Left, y, selectedTab.Bounds.Right, y); e.Graphics.DrawLine(paddingPen, selectedTab.Bounds.Left, y + 1, selectedTab.Bounds.Right, y + 1); e.Graphics.DrawLine(borderPen, selectedTab.Bounds.Right, y, right, y); e.Graphics.DrawLine(Pens.White, selectedTab.Bounds.Right, y + 1, right, y + 1); } else { e.Graphics.DrawLine(borderPen, left, y, right, y); e.Graphics.DrawLine(Pens.White, left, y, right, y); } } using (var paddingBrush = new SolidBrush(paddingPen.Color)) { var paddingRect = Rectangle.FromLTRB( e.AffectedBounds.Left, y + 2, e.AffectedBounds.Right, e.AffectedBounds.Bottom); e.Graphics.FillRectangle(paddingBrush, paddingRect); } } } private static void RenderTabItemBackgroundUsingVisualStyles(TabStripItemRenderEventArgs e, bool isChecked) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; using (GraphicsPath outer = GetTabBorderPath(e.Item.Width, e.Item.Height, isChecked, false)) { var colors = NormalColors; if (e.Item.Enabled && isChecked) { colors = CheckedColors; } else if (e.Item.Selected) { colors = SelectedColors; } FillGradient(e.Graphics, outer, colors, TabBackgroundRatio); using (Pen pen = new Pen(TabBorderColor, 1)) { e.Graphics.DrawPath(Pens.Gray, outer); } using (GraphicsPath inner = GetTabBorderPath(e.Item.Width, e.Item.Height, isChecked, true)) { e.Graphics.DrawPath(Pens.White, inner); } } if (!e.CloseButtonRectangle.IsEmpty) { var element = VisualStyleElement.ToolTip.Close.Normal; if (e.CloseButtonState == TabStripCloseButtonState.Selected) { element = VisualStyleElement.ToolTip.Close.Hot; } if (e.CloseButtonState == TabStripCloseButtonState.Pressed) { element = VisualStyleElement.ToolTip.Close.Pressed; } VisualStyleRenderer renderer = new VisualStyleRenderer(element); renderer.DrawBackground(e.Graphics, e.CloseButtonRectangle); } } private static GraphicsPath GetTabBorderPath(int w, int h, bool isChecked, bool inner) { int top = isChecked ? 2 : 4; int delta = inner ? 1 : 0; return new GraphicsPath( new Point[] { new Point(delta, h), new Point(delta, top + delta + 2), new Point(delta + 2, top + delta), new Point(w - delta - 3, top + delta), new Point(w - delta - 1, top + delta + 2), new Point(w - delta - 1, h), }, new byte[] { (byte)(PathPointType.Start), (byte)(PathPointType.Line), (byte)(PathPointType.Line), (byte)(PathPointType.Line), (byte)(PathPointType.Line), (byte)(PathPointType.Line), }); } private static GraphicsPath GetTabStripUpperBorderPath(ToolStripRenderEventArgs e) { var bounds = e.AffectedBounds; return new GraphicsPath(new Point[] { new Point(bounds.Left, bounds.Bottom), new Point(bounds.Left, bounds.Top + 1), new Point(bounds.Left + 1, bounds.Top), new Point(bounds.Right - 2, bounds.Top), new Point(bounds.Right - 1, bounds.Top + 1), new Point(bounds.Right - 1, bounds.Bottom) }, new byte[] { (byte)(PathPointType.Start), (byte)(PathPointType.Line), (byte)(PathPointType.Line), (byte)(PathPointType.Line), (byte)(PathPointType.Line), (byte)(PathPointType.Line), }); } private static Brush GetUpperBackgroundBrush(ref RectangleF rect, Color[] colors, float ratio) { rect.Height = 1 + (float)Math.Ceiling(rect.Height * ratio); return new LinearGradientBrush( rect, colors[0], colors[1], LinearGradientMode.Vertical); } private static Brush GetLowerBackgroundBrush(ref RectangleF rect, Color[] colors, float ratio) { rect.Y += (float)Math.Floor(rect.Height * ratio); rect.Height = (float)Math.Ceiling(rect.Height * (1.0f - ratio)); return new LinearGradientBrush( rect, colors[2], colors[3], LinearGradientMode.Vertical); } private static void FillGradient(Graphics graphics, GraphicsPath path, Color[] colors, float ratio) { using (var clipRegion = new Region(path)) { var bounds = clipRegion.GetBounds(graphics); var upperRect = bounds; var lowerRect = bounds; using (var oldClip = GraphicsExtensions.SwitchClip(graphics, clipRegion)) { using (var brush = GetUpperBackgroundBrush(ref upperRect, colors, ratio)) { graphics.FillRectangle(brush, upperRect); } using (var brush = GetLowerBackgroundBrush(ref lowerRect, colors, ratio)) { graphics.FillRectangle(brush, lowerRect); } } } } private static GraphicsPath GetTriangleDownPath(Rectangle bounds) { return new GraphicsPath ( new Point[] { new Point(bounds.Left, bounds.Top), new Point(bounds.Left + bounds.Width / 2, bounds.Bottom), new Point(bounds.Right, bounds.Top), }, new Byte[] { (Byte)PathPointType.Start, (Byte)PathPointType.Line, (Byte)PathPointType.Line, } ); } private static GraphicsPath GetTriangleUpPath(Rectangle bounds) { return new GraphicsPath ( new Point[] { new Point(bounds.Left, bounds.Bottom), new Point(bounds.Left + bounds.Width / 2, bounds.Top), new Point(bounds.Right, bounds.Bottom), }, new Byte[] { (Byte)PathPointType.Start, (Byte)PathPointType.Line, (Byte)PathPointType.Line, } ); } private static Bitmap CreateDesktopCompatibleBitmap(Size size) { using (Graphics desktop = Graphics.FromHwnd(IntPtr.Zero)) { return new Bitmap(size.Width, size.Height, desktop); } } private static Image BusyImage { get { return Resources.Images.TabBusy; } } private static Size BusyImageSize { get { return new Size(BusyImage.Height, BusyImage.Height); } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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 DiscUtils { using System; using System.Collections.Generic; using System.IO; /// <summary> /// Provides a thread-safe wrapping around a sparse stream. /// </summary> /// <remarks> /// <para>Streams are inherently not thread-safe (because read/write is not atomic w.r.t. Position). /// This method enables multiple 'views' of a stream to be created (each with their own Position), and ensures /// only a single operation is executing on the wrapped stream at any time.</para> /// <para>This example shows the pattern of use:</para> /// <example> /// <code> /// SparseStream baseStream = ...; /// ThreadSafeStream tss = new ThreadSafeStream(baseStream); /// for(int i = 0; i &lt; 10; ++i) /// { /// SparseStream streamForThread = tss.OpenView(); /// } /// </code> /// </example> /// <para>This results in 11 streams that can be used in different streams - <c>tss</c> and ten 'views' created from <c>tss</c>.</para> /// <para>Note, the stream length cannot be changed.</para> /// </remarks> public class ThreadSafeStream : SparseStream { private CommonState _common; private bool _ownsCommon; private long _position; /// <summary> /// Initializes a new instance of the ThreadSafeStream class. /// </summary> /// <param name="toWrap">The stream to wrap</param> /// <remarks>Do not directly modify <c>toWrap</c> after wrapping it, unless the thread-safe views /// will no longer be used.</remarks> public ThreadSafeStream(SparseStream toWrap) : this(toWrap, Ownership.None) { } /// <summary> /// Initializes a new instance of the ThreadSafeStream class. /// </summary> /// <param name="toWrap">The stream to wrap</param> /// <param name="ownership">Whether to transfer ownership of <c>toWrap</c> to the new instance</param> /// <remarks>Do not directly modify <c>toWrap</c> after wrapping it, unless the thread-safe views /// will no longer be used.</remarks> public ThreadSafeStream(SparseStream toWrap, Ownership ownership) { if (!toWrap.CanSeek) { throw new ArgumentException("Wrapped stream must support seeking", "toWrap"); } _common = new CommonState { WrappedStream = toWrap, WrappedStreamOwnership = ownership }; _ownsCommon = true; } private ThreadSafeStream(ThreadSafeStream toClone) { _common = toClone._common; if (_common == null) { throw new ObjectDisposedException("toClone"); } } /// <summary> /// Gets the parts of the stream that are stored. /// </summary> /// <remarks>This may be an empty enumeration if all bytes are zero.</remarks> public override IEnumerable<StreamExtent> Extents { get { lock (_common) { return Wrapped.Extents; } } } /// <summary> /// Gets a value indicating if this stream supports reads. /// </summary> public override bool CanRead { get { lock (_common) { return Wrapped.CanRead; } } } /// <summary> /// Gets a value indicating if this stream supports seeking (always true). /// </summary> public override bool CanSeek { get { return true; } } /// <summary> /// Gets a value indicating if this stream supports writes (currently, always false). /// </summary> public override bool CanWrite { get { lock (_common) { return Wrapped.CanWrite; } } } /// <summary> /// Gets the length of the stream. /// </summary> public override long Length { get { lock (_common) { return Wrapped.Length; } } } /// <summary> /// Gets the current stream position - each 'view' has it's own Position. /// </summary> public override long Position { get { return _position; } set { _position = value; } } private SparseStream Wrapped { get { SparseStream wrapped = _common.WrappedStream; if (wrapped == null) { throw new ObjectDisposedException("ThreadSafeStream"); } return wrapped; } } /// <summary> /// Opens a new thread-safe view on the stream. /// </summary> /// <returns>The new view</returns> public SparseStream OpenView() { return new ThreadSafeStream(this); } /// <summary> /// Gets the parts of a stream that are stored, within a specified range. /// </summary> /// <param name="start">The offset of the first byte of interest</param> /// <param name="count">The number of bytes of interest</param> /// <returns>An enumeration of stream extents, indicating stored bytes</returns> public override IEnumerable<StreamExtent> GetExtentsInRange(long start, long count) { lock (_common) { return Wrapped.GetExtentsInRange(start, count); } } /// <summary> /// Causes the stream to flush all changes. /// </summary> public override void Flush() { lock (_common) { Wrapped.Flush(); } } /// <summary> /// Reads data from the stream. /// </summary> /// <param name="buffer">The buffer to fill</param> /// <param name="offset">The first byte in buffer to fill</param> /// <param name="count">The requested number of bytes to read</param> /// <returns>The actual number of bytes read</returns> public override int Read(byte[] buffer, int offset, int count) { lock (_common) { SparseStream wrapped = Wrapped; wrapped.Position = _position; int numRead = wrapped.Read(buffer, offset, count); _position += numRead; return numRead; } } /// <summary> /// Changes the current stream position (each view has it's own Position). /// </summary> /// <param name="offset">The relative location to move to</param> /// <param name="origin">The origin of the location</param> /// <returns>The new location as an absolute position</returns> public override long Seek(long offset, SeekOrigin origin) { long effectiveOffset = offset; if (origin == SeekOrigin.Current) { effectiveOffset += _position; } else if (origin == SeekOrigin.End) { effectiveOffset += Length; } if (effectiveOffset < 0) { throw new IOException("Attempt to move before beginning of disk"); } else { _position = effectiveOffset; return _position; } } /// <summary> /// Sets the length of the stream (not supported). /// </summary> /// <param name="value">The new length</param> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Writes data to the stream (not currently supported). /// </summary> /// <param name="buffer">The data to write</param> /// <param name="offset">The first byte to write</param> /// <param name="count">The number of bytes to write</param> public override void Write(byte[] buffer, int offset, int count) { lock (_common) { SparseStream wrapped = Wrapped; if (_position + count > wrapped.Length) { throw new IOException("Attempt to extend stream"); } wrapped.Position = _position; wrapped.Write(buffer, offset, count); _position += count; } } /// <summary> /// Disposes of this instance, invalidating any remaining views. /// </summary> /// <param name="disposing"><c>true</c> if disposing, lese <c>false</c></param> protected override void Dispose(bool disposing) { if (disposing) { if (_ownsCommon && _common != null) { lock (_common) { if (_common.WrappedStreamOwnership == Ownership.Dispose) { _common.WrappedStream.Dispose(); } _common.Dispose(); } } } _common = null; } private sealed class CommonState : IDisposable { public SparseStream WrappedStream; public Ownership WrappedStreamOwnership; #region IDisposable Members public void Dispose() { WrappedStream = null; } #endregion } } }
// This file contains general utilities to aid in development. // Classes here generally shouldn't be exposed publicly since // they're not particular to any library functionality. // Because the classes here are internal, it's likely this file // might be included in multiple assemblies. namespace Standard { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; internal enum SafeCopyFileOptions { PreserveOriginal, Overwrite, FindBetterName, } internal static partial class Utility { private static readonly Random _randomNumberGenerator = new Random(); [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static bool _MemCmp(IntPtr left, IntPtr right, long cb) { int offset = 0; for (; offset < (cb - sizeof(Int64)); offset += sizeof(Int64)) { Int64 left64 = Marshal.ReadInt64(left, offset); Int64 right64 = Marshal.ReadInt64(right, offset); if (left64 != right64) { return false; } } for (; offset < cb; offset += sizeof(byte)) { byte left8 = Marshal.ReadByte(left, offset); byte right8 = Marshal.ReadByte(right, offset); if (left8 != right8) { return false; } } return true; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static Exception FailableFunction<T>(Func<T> function, out T result) { return FailableFunction(5, function, out result); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static T FailableFunction<T>(Func<T> function) { T result; Exception e = FailableFunction(function, out result); if (e != null) { throw e; } return result; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static T FailableFunction<T>(int maxRetries, Func<T> function) { T result; Exception e = FailableFunction(maxRetries, function, out result); if (e != null) { throw e; } return result; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static Exception FailableFunction<T>(int maxRetries, Func<T> function, out T result) { Assert.IsNotNull(function); Assert.BoundedInteger(1, maxRetries, 100); int i = 0; while (true) { try { result = function(); return null; } catch (Exception e) { if (i == maxRetries) { result = default(T); return e; } } ++i; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static string GetHashString(string value) { using (MD5 md5 = MD5.Create()) { byte[] signatureHash = md5.ComputeHash(Encoding.UTF8.GetBytes(value)); string signature = signatureHash.Aggregate( new StringBuilder(), (sb, b) => sb.Append(b.ToString("x2", CultureInfo.InvariantCulture))).ToString(); return signature; } } // See: http://stackoverflow.com/questions/7913325/win-api-in-c-get-hi-and-low-word-from-intptr/7913393#7913393 [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static System.Windows.Point GetPoint(IntPtr ptr) { var xy = unchecked(Environment.Is64BitProcess ? (uint)ptr.ToInt64() : (uint)ptr.ToInt32()); var x = unchecked((short)xy); var y = unchecked((short)(xy >> 16)); return new System.Windows.Point(x, y); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static int GET_X_LPARAM(IntPtr lParam) { return LOWORD(lParam.ToInt32()); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static int GET_Y_LPARAM(IntPtr lParam) { return HIWORD(lParam.ToInt32()); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static int HIWORD(int i) { return (short)(i >> 16); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static int LOWORD(int i) { return (short)(i & 0xFFFF); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] public static bool AreStreamsEqual(Stream left, Stream right) { if (null == left) { return right == null; } if (null == right) { return false; } if (!left.CanRead || !right.CanRead) { throw new NotSupportedException("The streams can't be read for comparison"); } if (left.Length != right.Length) { return false; } var length = (int)left.Length; // seek to beginning left.Position = 0; right.Position = 0; // total bytes read int totalReadLeft = 0; int totalReadRight = 0; // bytes read on this iteration int cbReadLeft = 0; int cbReadRight = 0; // where to store the read data var leftBuffer = new byte[512]; var rightBuffer = new byte[512]; // pin the left buffer GCHandle handleLeft = GCHandle.Alloc(leftBuffer, GCHandleType.Pinned); IntPtr ptrLeft = handleLeft.AddrOfPinnedObject(); // pin the right buffer GCHandle handleRight = GCHandle.Alloc(rightBuffer, GCHandleType.Pinned); IntPtr ptrRight = handleRight.AddrOfPinnedObject(); try { while (totalReadLeft < length) { Assert.AreEqual(totalReadLeft, totalReadRight); cbReadLeft = left.Read(leftBuffer, 0, leftBuffer.Length); cbReadRight = right.Read(rightBuffer, 0, rightBuffer.Length); // verify the contents are an exact match if (cbReadLeft != cbReadRight) { return false; } if (!_MemCmp(ptrLeft, ptrRight, cbReadLeft)) { return false; } totalReadLeft += cbReadLeft; totalReadRight += cbReadRight; } Assert.AreEqual(cbReadLeft, cbReadRight); Assert.AreEqual(totalReadLeft, totalReadRight); Assert.AreEqual(length, totalReadLeft); return true; } finally { handleLeft.Free(); handleRight.Free(); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool GuidTryParse(string guidString, out Guid guid) { Verify.IsNeitherNullNorEmpty(guidString, "guidString"); try { guid = new Guid(guidString); return true; } catch (FormatException) { } catch (OverflowException) { } // Doesn't seem to be a valid guid. guid = default(Guid); return false; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsFlagSet(int value, int mask) { return 0 != (value & mask); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsFlagSet(uint value, uint mask) { return 0 != (value & mask); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsFlagSet(long value, long mask) { return 0 != (value & mask); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsFlagSet(ulong value, ulong mask) { return 0 != (value & mask); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool IsInterfaceImplemented(Type objectType, Type interfaceType) { Assert.IsNotNull(objectType); Assert.IsNotNull(interfaceType); Assert.IsTrue(interfaceType.IsInterface); return objectType.GetInterfaces().Any(type => type == interfaceType); } /// <summary> /// Wrapper around File.Copy to provide feedback as to whether the file wasn't copied because it didn't exist. /// </summary> /// <returns></returns> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static string SafeCopyFile(string sourceFileName, string destFileName, SafeCopyFileOptions options) { switch (options) { case SafeCopyFileOptions.PreserveOriginal: if (!File.Exists(destFileName)) { File.Copy(sourceFileName, destFileName); return destFileName; } return null; case SafeCopyFileOptions.Overwrite: File.Copy(sourceFileName, destFileName, true); return destFileName; case SafeCopyFileOptions.FindBetterName: string directoryPart = Path.GetDirectoryName(destFileName); string fileNamePart = Path.GetFileNameWithoutExtension(destFileName); string extensionPart = Path.GetExtension(destFileName); foreach (string path in GenerateFileNames(directoryPart, fileNamePart, extensionPart)) { if (!File.Exists(path)) { File.Copy(sourceFileName, path); return path; } } return null; } throw new ArgumentException("Invalid enumeration value", "options"); } /// <summary> /// Simple guard against the exceptions that File.Delete throws on null and empty strings. /// </summary> /// <param name="path">The path to delete. Unlike File.Delete, this can be null or empty.</param> /// <remarks> /// Note that File.Delete, and by extension SafeDeleteFile, does not throw an exception /// if the file does not exist. /// </remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void SafeDeleteFile(string path) { if (!string.IsNullOrEmpty(path)) { File.Delete(path); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void SafeDispose<T>(ref T disposable) where T : IDisposable { // Dispose can safely be called on an object multiple times. IDisposable t = disposable; disposable = default(T); if (null != t) { t.Dispose(); } } /// <summary> /// Utility to help classes catenate their properties for implementing ToString(). /// </summary> /// <param name="source">The StringBuilder to catenate the results into.</param> /// <param name="propertyName">The name of the property to be catenated.</param> /// <param name="value">The value of the property to be catenated.</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void GeneratePropertyString(StringBuilder source, string propertyName, string value) { Assert.IsNotNull(source); Assert.IsFalse(string.IsNullOrEmpty(propertyName)); if (0 != source.Length) { source.Append(' '); } source.Append(propertyName); source.Append(": "); if (string.IsNullOrEmpty(value)) { source.Append("<null>"); } else { source.Append('\"'); source.Append(value); source.Append('\"'); } } /// <summary> /// Generates ToString functionality for a struct. This is an expensive way to do it, /// it exists for the sake of debugging while classes are in flux. /// Eventually this should just be removed and the classes should /// do this without reflection. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="object"></param> /// <returns></returns> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [Obsolete] public static string GenerateToString<T>(T @object) where T : struct { var sbRet = new StringBuilder(); foreach (PropertyInfo property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (0 != sbRet.Length) { sbRet.Append(", "); } Assert.AreEqual(0, property.GetIndexParameters().Length); object value = property.GetValue(@object, null); string format = null == value ? "{0}: <null>" : "{0}: \"{1}\""; sbRet.AppendFormat(format, property.Name, value); } return sbRet.ToString(); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void CopyStream(Stream destination, Stream source) { Assert.IsNotNull(source); Assert.IsNotNull(destination); destination.Position = 0; // If we're copying from, say, a web stream, don't fail because of this. if (source.CanSeek) { source.Position = 0; // Consider that this could throw because // the source stream doesn't know it's size... destination.SetLength(source.Length); } var buffer = new byte[4096]; int cbRead; do { cbRead = source.Read(buffer, 0, buffer.Length); if (0 != cbRead) { destination.Write(buffer, 0, cbRead); } } while (buffer.Length == cbRead); // Reset the Seek pointer before returning. destination.Position = 0; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static string HashStreamMD5(Stream stm) { stm.Position = 0; var hashBuilder = new StringBuilder(); using (MD5 md5 = MD5.Create()) { foreach (byte b in md5.ComputeHash(stm)) { hashBuilder.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } } return hashBuilder.ToString(); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static void EnsureDirectory(string path) { if (!path.EndsWith(@"\", StringComparison.Ordinal)) { path += @"\"; } path = Path.GetDirectoryName(path); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool MemCmp(byte[] left, byte[] right, int cb) { Assert.IsNotNull(left); Assert.IsNotNull(right); Assert.IsTrue(cb <= Math.Min(left.Length, right.Length)); // pin this buffer GCHandle handleLeft = GCHandle.Alloc(left, GCHandleType.Pinned); IntPtr ptrLeft = handleLeft.AddrOfPinnedObject(); // pin the other buffer GCHandle handleRight = GCHandle.Alloc(right, GCHandleType.Pinned); IntPtr ptrRight = handleRight.AddrOfPinnedObject(); bool fRet = _MemCmp(ptrLeft, ptrRight, cb); handleLeft.Free(); handleRight.Free(); return fRet; } private class _UrlDecoder { private readonly Encoding _encoding; private readonly char[] _charBuffer; private readonly byte[] _byteBuffer; private int _byteCount; private int _charCount; [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public _UrlDecoder(int size, Encoding encoding) { _encoding = encoding; _charBuffer = new char[size]; _byteBuffer = new byte[size]; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void AddByte(byte b) { _byteBuffer[_byteCount++] = b; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void AddChar(char ch) { _FlushBytes(); _charBuffer[_charCount++] = ch; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void _FlushBytes() { if (_byteCount > 0) { _charCount += _encoding.GetChars(_byteBuffer, 0, _byteCount, _charBuffer, _charCount); _byteCount = 0; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string GetString() { _FlushBytes(); if (_charCount > 0) { return new string(_charBuffer, 0, _charCount); } return ""; } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static string UrlDecode(string url) { if (url == null) { return null; } var decoder = new _UrlDecoder(url.Length, Encoding.UTF8); int length = url.Length; for (int i = 0; i < length; ++i) { char ch = url[i]; if (ch == '+') { decoder.AddByte((byte)' '); continue; } if (ch == '%' && i < length - 2) { // decode %uXXXX into a Unicode character. if (url[i + 1] == 'u' && i < length - 5) { int a = _HexToInt(url[i + 2]); int b = _HexToInt(url[i + 3]); int c = _HexToInt(url[i + 4]); int d = _HexToInt(url[i + 5]); if (a >= 0 && b >= 0 && c >= 0 && d >= 0) { decoder.AddChar((char)((a << 12) | (b << 8) | (c << 4) | d)); i += 5; continue; } } else { // decode %XX into a Unicode character. int a = _HexToInt(url[i + 1]); int b = _HexToInt(url[i + 2]); if (a >= 0 && b >= 0) { decoder.AddByte((byte)((a << 4) | b)); i += 2; continue; } } } // Add any 7bit character as a byte. if ((ch & 0xFF80) == 0) { decoder.AddByte((byte)ch); } else { decoder.AddChar(ch); } } return decoder.GetString(); } /// <summary> /// Encodes a URL string. Duplicated functionality from System.Web.HttpUtility.UrlEncode. /// </summary> /// <param name="url"></param> /// <returns></returns> /// <remarks> /// Duplicated from System.Web.HttpUtility because System.Web isn't part of the client profile. /// URL Encoding replaces ' ' with '+' and unsafe ASCII characters with '%XX'. /// Safe characters are defined in RFC2396 (http://www.ietf.org/rfc/rfc2396.txt). /// They are the 7-bit ASCII alphanumerics and the mark characters "-_.!~*'()". /// This implementation does not treat '~' as a safe character to be consistent with the System.Web version. /// </remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static string UrlEncode(string url) { if (url == null) { return null; } byte[] bytes = Encoding.UTF8.GetBytes(url); bool needsEncoding = false; int unsafeCharCount = 0; foreach (byte b in bytes) { if (b == ' ') { needsEncoding = true; } else if (!_UrlEncodeIsSafe(b)) { ++unsafeCharCount; needsEncoding = true; } } if (needsEncoding) { var buffer = new byte[bytes.Length + (unsafeCharCount * 2)]; int writeIndex = 0; foreach (byte b in bytes) { if (_UrlEncodeIsSafe(b)) { buffer[writeIndex++] = b; } else if (b == ' ') { buffer[writeIndex++] = (byte)'+'; } else { buffer[writeIndex++] = (byte)'%'; buffer[writeIndex++] = _IntToHex((b >> 4) & 0xF); buffer[writeIndex++] = _IntToHex(b & 0xF); } } bytes = buffer; Assert.AreEqual(buffer.Length, writeIndex); } return Encoding.ASCII.GetString(bytes); } // HttpUtility's UrlEncode is slightly different from the RFC. // RFC2396 describes unreserved characters as alphanumeric or // the list "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" // The System.Web version unnecessarily escapes '~', which should be okay... // Keeping that same pattern here just to be consistent. [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static bool _UrlEncodeIsSafe(byte b) { if (_IsAsciiAlphaNumeric(b)) { return true; } switch ((char)b) { case '-': case '_': case '.': case '!': //case '~': case '*': case '\'': case '(': case ')': return true; } return false; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static bool _IsAsciiAlphaNumeric(byte b) { return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9'); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static byte _IntToHex(int n) { Assert.BoundedInteger(0, n, 16); if (n <= 9) { return (byte)(n + '0'); } return (byte)(n - 10 + 'A'); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static int _HexToInt(char h) { if (h >= '0' && h <= '9') { return h - '0'; } if (h >= 'a' && h <= 'f') { return h - 'a' + 10; } if (h >= 'A' && h <= 'F') { return h - 'A' + 10; } Assert.Fail("Invalid hex character " + h); return -1; } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static string MakeValidFileName(string invalidPath) { return invalidPath .Replace('\\', '_') .Replace('/', '_') .Replace(':', '_') .Replace('*', '_') .Replace('?', '_') .Replace('\"', '_') .Replace('<', '_') .Replace('>', '_') .Replace('|', '_'); } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static IEnumerable<string> GenerateFileNames(string directory, string primaryFileName, string extension) { Verify.IsNeitherNullNorEmpty(directory, "directory"); Verify.IsNeitherNullNorEmpty(primaryFileName, "primaryFileName"); primaryFileName = MakeValidFileName(primaryFileName); for (int i = 0; i <= 50; ++i) { if (0 == i) { yield return Path.Combine(directory, primaryFileName) + extension; } else if (40 >= i) { yield return Path.Combine(directory, primaryFileName) + " (" + i.ToString((IFormatProvider)null) + ")" + extension; } else { // At this point we're hitting pathological cases. This should stir things up enough that it works. // If this fails because of naming conflicts after an extra 10 tries, then I don't care. yield return Path.Combine(directory, primaryFileName) + " (" + _randomNumberGenerator.Next(41, 9999) + ")" + extension; } } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static bool TryFileMove(string sourceFileName, string destFileName) { if (!File.Exists(destFileName)) { try { File.Move(sourceFileName, destFileName); } catch (IOException) { return false; } return true; } return false; } } }
using System; using Mint.Reflection.Parameters.Attributes; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Mint.MethodBinding; using Mint.Reflection; namespace Mint { /* ::methods: [] try_convert #methods: initialize bsearch dig hash permutation rotate sum initialize_copy bsearch_index drop include? pop rotate! take & clear drop_while index product sample take_while * collect each insert push select to_a + collect! each_index inspect rassoc select! to_ary - combination empty? join reject shift to_h << compact eql? keep_if reject! shuffle to_s <=> compact! fetch last repeated_combination shuffle! transpose == concat fill length repeated_permutation size uniq [] count find_index map replace slice uniq! []= cycle first map! reverse slice! unshift any? delete flatten max reverse! sort values_at assoc delete_at flatten! min reverse_each sort! zip at delete_if frozen? pack rindex sort_by! | */ [RubyClass] public class Array : BaseObject, IEnumerable<iObject> { private static readonly Comparer COMPARER = new Comparer(); [ThreadStatic] private static ISet<Tuple<Array, Array>> equalsRecursionSet; private readonly List<iObject> list; public Array(IEnumerable<iObject> objs) : base(Class.ARRAY) { list = objs == null ? new List<iObject>() : new List<iObject>(objs); } public Array() : this((IEnumerable<iObject>) null) { } public Array(params iObject[] objs) : this((IEnumerable<iObject>) objs) { } public Array(int count, iObject obj) : this(Enumerable.Repeat(obj, count)) { } public Array(int count) : this(count, new NilClass()) { } [RubyMethod("count")] [RubyMethod("length")] [RubyMethod("size")] public int Count => list.Count; [RubyMethod("[]")] public iObject this[int index] { get { if(index < 0) { index += list.Count; } return 0 <= index && index < list.Count ? list[index] : new NilClass(); } set { if(index < -list.Count) { throw new IndexError($"index {index} too small for array; minimum: -{list.Count}"); } if(index < 0) { index += list.Count; } if(index >= list.Count) { list.AddRange(Enumerable.Repeat<iObject>(new NilClass(), index - list.Count + 1)); } list[index] = value; } } public iObject Push(params iObject[] elements) { list.AddRange(elements); return this; } [RubyMethod("<<")] public Array Add(iObject element) { list.Add(element); return this; } public IEnumerator<iObject> GetEnumerator() => list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => list.GetEnumerator(); [RubyMethod("to_s")] public override string ToString() => $"[{string.Join(", ", list.Select(_ => _.Inspect()))}]"; [RubyMethod("&")] public Array AndAlso(Array other) { var result = new Array(list); result.list.RemoveAll(item => !other.list.Contains(item)); result.UniqSelf(); return result; } [RubyMethod("first")] public iObject First => this[0]; [RubyMethod("last")] public iObject Last => this[-1]; [RubyMethod("clear")] public Array Clear() { list.Clear(); return this; } [RubyMethod("compact!")] public Array CompactSelf() { list.RemoveAll(NilClass.IsNil); return this; } [RubyMethod("compact")] public Array Compact() => new Array(list).CompactSelf(); [RubyMethod("join")] public String Join([Optional] String str = null) { if(str == null) { str = new String(""); } return new String(string.Join(str.ToString(), list)); } [RubyMethod("replace")] public Array Replace(Array other) { if(other == null) { throw new TypeError("no implicit conversion of nil into Array"); } list.Clear(); list.AddRange(other.list); return this; } [RubyMethod("reverse!")] public Array ReverseSelf() { list.Reverse(); return this; } [RubyMethod("reverse")] public Array Reverse() => new Array(list).ReverseSelf(); [RubyMethod("uniq!")] public Array UniqSelf() { var buffer = list.Distinct().ToList(); list.Clear(); list.AddRange(buffer); return this; } [RubyMethod("uniq")] public Array Uniq() => new Array(list).UniqSelf(); [RubyMethod("==")] public override bool Equals(object other) => other is iObject && Equals((iObject) other); [RubyMethod("==")] public bool Equals(iObject other) { return other is Array ary ? Equals(ary) : Object.RespondTo(other, Symbol.TO_ARY) && Object.ToBool(Class.EqOp.Call(other, this)); } [RubyMethod("==")] public bool Equals(Array other) { if(ReferenceEquals(this, other)) { return true; } if(other == null || Count != other.Count) { return false; } var topLevel = equalsRecursionSet == null; if(topLevel) { equalsRecursionSet = new HashSet<Tuple<Array, Array>>(COMPARER); } try { var pair = new Tuple<Array, Array>(this, other); if(equalsRecursionSet.Contains(pair)) { return true; } equalsRecursionSet.Add(pair); var elements = list.Zip(other.list, (l, r) => Class.EqOp.Call(l, r)); return elements.Select(Object.ToBool).All(eq => eq); } finally { if(topLevel) { equalsRecursionSet = null; } } } [RubyMethod("+")] public static Array operator +(Array left, Array right) { if(left == null || right == null) { throw new TypeError("no implicit conversion of nil into Array"); } var result = new Array(left.list); result.list.AddRange(right); return result; } [RubyMethod("*")] public static Array operator *(Array left, Fixnum right) { if(left == null) { throw new TypeError("undefined method `*' for nil:NilClass"); } var result = new Array(); for(var i = 0; i < right.Value; i++) { result.list.AddRange(left); } return result; } [RubyMethod("*")] public static String operator *(Array left, String right) => left.Join(right); [RubyMethod("-")] public static Array operator -(Array left, Array right) { if (left == null || right == null) { throw new TypeError("no implicit conversion of nil into Array"); } var result = new Array(left.list); result.list.RemoveAll(right.Contains); return result; } public static explicit operator Array(iObject[] objects) => new Array(objects); [RubyMethod("initialize", Visibility = Visibility.Private)] [RubyMethod("initialize_copy", Visibility = Visibility.Private)] [RubyMethod("<=>")] [RubyMethod("any?")] [RubyMethod("assoc")] [RubyMethod("at")] [RubyMethod("bsearch")] [RubyMethod("bsearch_index")] [RubyMethod("collect")] [RubyMethod("collect!")] [RubyMethod("combination")] [RubyMethod("concat")] [RubyMethod("cycle")] [RubyMethod("delete")] [RubyMethod("delete_at")] [RubyMethod("delete_if")] [RubyMethod("dig")] [RubyMethod("drop")] [RubyMethod("drop_while")] [RubyMethod("each")] [RubyMethod("each_index")] [RubyMethod("empty?")] [RubyMethod("eql?")] [RubyMethod("fetch")] [RubyMethod("fill")] [RubyMethod("find_index")] [RubyMethod("flatten")] [RubyMethod("flatten!")] [RubyMethod("frozen?")] [RubyMethod("hash")] [RubyMethod("include?")] [RubyMethod("index")] [RubyMethod("insert")] [RubyMethod("inspect")] [RubyMethod("keep_if")] [RubyMethod("map")] [RubyMethod("map!")] [RubyMethod("max")] [RubyMethod("min")] [RubyMethod("pack")] [RubyMethod("permutation")] [RubyMethod("pop")] [RubyMethod("product")] [RubyMethod("push")] [RubyMethod("rassoc")] [RubyMethod("reject")] [RubyMethod("reject!")] [RubyMethod("repeated_combination")] [RubyMethod("repeated_permutation")] [RubyMethod("reverse_each")] [RubyMethod("rindex")] [RubyMethod("rotate")] [RubyMethod("rotate!")] [RubyMethod("sample")] [RubyMethod("select")] [RubyMethod("select!")] [RubyMethod("shift")] [RubyMethod("shuffle")] [RubyMethod("shuffle!")] [RubyMethod("slice")] [RubyMethod("slice!")] [RubyMethod("sort")] [RubyMethod("sort!")] [RubyMethod("sort_by!")] [RubyMethod("sum")] [RubyMethod("take")] [RubyMethod("take_while")] [RubyMethod("to_a")] [RubyMethod("to_ary")] [RubyMethod("to_h")] [RubyMethod("transpose")] [RubyMethod("unshift")] [RubyMethod("values_at")] [RubyMethod("zip")] [RubyMethod("|")] public void NotImplemented([Rest] Array args, [Block] object block) => throw new NotImplementedException( $"{nameof(Array)}#{CallFrame.Current.CallSite.MethodName.Name}" ); internal static ModuleBuilder<Array> Build() => ModuleBuilder<Array>.DescribeClass() .GenerateAllocator() .AutoDefineMethods() ; private class Comparer : IEqualityComparer<Tuple<Array, Array>> { public bool Equals(Tuple<Array, Array> x, Tuple<Array, Array> y) => ReferenceEquals(x, y) || (ReferenceEquals(x.Item1, y.Item1) && ReferenceEquals(x.Item2, y.Item2)) || (ReferenceEquals(x.Item1, y.Item2) && ReferenceEquals(x.Item2, y.Item1)); public int GetHashCode(Tuple<Array, Array> obj) => obj.Item1.GetHashCode() ^ obj.Item2.GetHashCode(); } public static class Reflection { public static readonly ConstructorInfo CtorDefault = Reflector.Ctor<Array>(); public static readonly ConstructorInfo Ctor = Reflector<Array>.Ctor<IEnumerable<iObject>>(); } public static class Expressions { public static NewExpression New(Expression values) => Expression.New(Reflection.Ctor, values); public static NewExpression New() => Expression.New(Reflection.CtorDefault); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.EventHub { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// NamespacesOperations operations. /// </summary> public partial interface INamespacesOperations { /// <summary> /// Check the give Namespace name availability. /// </summary> /// <param name='parameters'> /// Parameters to check availability of the given Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckNameAvailabilityResult>> CheckNameAvailabilityWithHttpMessagesAsync(CheckNameAvailabilityParameter parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the available Namespaces within a subscription, /// irrespective of the resource groups. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<EHNamespace>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available Namespaces within a resource group. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<EHNamespace>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for creating a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EHNamespace>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, EHNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the description of the specified namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EHNamespace>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for updating a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EHNamespace>> UpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, EHNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of authorization rules for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<AuthorizationRule>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an AuthorizationRule for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// The shared access AuthorizationRule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AuthorizationRule>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, AuthorizationRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an AuthorizationRule for a Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets an AuthorizationRule for a Namespace by rule name. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AuthorizationRule>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the primary and secondary connection strings for the /// Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AccessKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the primary or secondary connection strings for the /// specified Namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorization rule name. /// </param> /// <param name='parameters'> /// Parameters required to regenerate the connection string. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<AccessKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateAccessKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='parameters'> /// Parameters for creating a namespace resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<EHNamespace>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, EHNamespace parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group within the azure subscription. /// </param> /// <param name='namespaceName'> /// The Namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the available Namespaces within a subscription, /// irrespective of the resource groups. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<EHNamespace>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available Namespaces within a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<EHNamespace>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a list of authorization rules for a Namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<AuthorizationRule>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.AspNetCore.Razor.Language; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation { public class CompilerFailedExceptionFactoryTest { [Fact] public void GetCompilationFailedResult_ReadsRazorErrorsFromPage() { // Arrange var viewPath = "/Views/Home/Index.cshtml"; var fileSystem = new VirtualRazorProjectFileSystem(); var projectItem = new TestRazorProjectItem(viewPath, "<span name=\"@(User.Id\">"); var razorEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem).Engine; var codeDocument = GetCodeDocument(projectItem); // Act razorEngine.Process(codeDocument); var csharpDocument = codeDocument.GetCSharpDocument(); var compilationResult = CompilationFailedExceptionFactory.Create(codeDocument, csharpDocument.Diagnostics); // Assert var failure = Assert.Single(compilationResult.CompilationFailures); Assert.Equal(viewPath, failure.SourceFilePath); var orderedMessages = failure.Messages.OrderByDescending(messages => messages.Message); Assert.Collection(orderedMessages, message => Assert.StartsWith( @"Unterminated string literal.", message.Message), message => Assert.StartsWith( @"The explicit expression block is missing a closing "")"" character.", message.Message)); } [Fact] public void GetCompilationFailedResult_WithMissingReferences() { // Arrange var expected = "One or more compilation references may be missing. If you're seeing this in a published application, set 'CopyRefAssembliesToPublishDirectory' to true in your project file to ensure files in the refs directory are published."; var compilation = CSharpCompilation.Create("Test", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var syntaxTree = CSharpSyntaxTree.ParseText("@class Test { public string Test { get; set; } }"); compilation = compilation.AddSyntaxTrees(syntaxTree); var emitResult = compilation.Emit(new MemoryStream()); // Act var exception = CompilationFailedExceptionFactory.Create( RazorCodeDocument.Create(RazorSourceDocument.Create("Test", "Index.cshtml"), Enumerable.Empty<RazorSourceDocument>()), syntaxTree.ToString(), "Test", emitResult.Diagnostics); // Assert Assert.Collection( exception.CompilationFailures, failure => Assert.Equal(expected, failure.FailureSummary)); } [Fact] public void GetCompilationFailedResult_UsesPhysicalPath() { // Arrange var viewPath = "/Views/Home/Index.cshtml"; var physicalPath = @"x:\myapp\views\home\index.cshtml"; var projectItem = new TestRazorProjectItem(viewPath, "<span name=\"@(User.Id\">", physicalPath: physicalPath); var codeDocument = GetCodeDocument(projectItem); var csharpDocument = codeDocument.GetCSharpDocument(); // Act var compilationResult = CompilationFailedExceptionFactory.Create(codeDocument, csharpDocument.Diagnostics); // Assert var failure = Assert.Single(compilationResult.CompilationFailures); Assert.Equal(physicalPath, failure.SourceFilePath); } [Fact] public void GetCompilationFailedResult_ReadsContentFromSourceDocuments() { // Arrange var viewPath = "/Views/Home/Index.cshtml"; var fileContent = @" @if (User.IsAdmin) { <span> } </span>"; var projectItem = new TestRazorProjectItem(viewPath, fileContent); var codeDocument = GetCodeDocument(projectItem); var csharpDocument = codeDocument.GetCSharpDocument(); // Act var compilationResult = CompilationFailedExceptionFactory.Create(codeDocument, csharpDocument.Diagnostics); // Assert var failure = Assert.Single(compilationResult.CompilationFailures); Assert.Equal(fileContent, failure.SourceFileContent); } [Fact] public void GetCompilationFailedResult_ReadsContentFromImports() { // Arrange var viewPath = "/Views/Home/Index.cshtml"; var importsPath = "/Views/_MyImports.cshtml"; var fileContent = "@ "; var importsContent = "@(abc"; var projectItem = new TestRazorProjectItem(viewPath, fileContent); var importsItem = new TestRazorProjectItem(importsPath, importsContent); var codeDocument = GetCodeDocument(projectItem, importsItem); var csharpDocument = codeDocument.GetCSharpDocument(); // Act var compilationResult = CompilationFailedExceptionFactory.Create(codeDocument, csharpDocument.Diagnostics); // Assert Assert.Collection( compilationResult.CompilationFailures, failure => { Assert.Equal(viewPath, failure.SourceFilePath); Assert.Collection(failure.Messages, message => { Assert.Equal(@"A space or line break was encountered after the ""@"" character. Only valid identifiers, keywords, comments, ""("" and ""{"" are valid at the start of a code block and they must occur immediately following ""@"" with no space in between.", message.Message); }); }, failure => { Assert.Equal(importsPath, failure.SourceFilePath); Assert.Collection(failure.Messages, message => { Assert.Equal(@"The explicit expression block is missing a closing "")"" character. Make sure you have a matching "")"" character for all the ""("" characters within this block, and that none of the "")"" characters are being interpreted as markup.", message.Message); }); }); } [Fact] public void GetCompilationFailedResult_GroupsMessages() { // Arrange var viewPath = "views/index.razor"; var viewImportsPath = "views/global.import.cshtml"; var codeDocument = RazorCodeDocument.Create( Create(viewPath, "View Content"), new[] { Create(viewImportsPath, "Global Import Content") }); var diagnostics = new[] { GetRazorDiagnostic("message-1", new SourceLocation(1, 2, 17), length: 1), GetRazorDiagnostic("message-2", new SourceLocation(viewPath, 1, 4, 6), length: 7), GetRazorDiagnostic("message-3", SourceLocation.Undefined, length: -1), GetRazorDiagnostic("message-4", new SourceLocation(viewImportsPath, 1, 3, 8), length: 4), }; // Act var result = CompilationFailedExceptionFactory.Create(codeDocument, diagnostics); // Assert Assert.Collection(result.CompilationFailures, failure => { Assert.Equal(viewPath, failure.SourceFilePath); Assert.Equal("View Content", failure.SourceFileContent); Assert.Collection(failure.Messages, message => { Assert.Equal(diagnostics[0].GetMessage(CultureInfo.CurrentCulture), message.Message); Assert.Equal(viewPath, message.SourceFilePath); Assert.Equal(3, message.StartLine); Assert.Equal(17, message.StartColumn); Assert.Equal(3, message.EndLine); Assert.Equal(18, message.EndColumn); }, message => { Assert.Equal(diagnostics[1].GetMessage(CultureInfo.CurrentCulture), message.Message); Assert.Equal(viewPath, message.SourceFilePath); Assert.Equal(5, message.StartLine); Assert.Equal(6, message.StartColumn); Assert.Equal(5, message.EndLine); Assert.Equal(13, message.EndColumn); }, message => { Assert.Equal(diagnostics[2].GetMessage(CultureInfo.CurrentCulture), message.Message); Assert.Equal(viewPath, message.SourceFilePath); Assert.Equal(0, message.StartLine); Assert.Equal(-1, message.StartColumn); Assert.Equal(0, message.EndLine); Assert.Equal(-2, message.EndColumn); }); }, failure => { Assert.Equal(viewImportsPath, failure.SourceFilePath); Assert.Equal("Global Import Content", failure.SourceFileContent); Assert.Collection(failure.Messages, message => { Assert.Equal(diagnostics[3].GetMessage(CultureInfo.CurrentCulture), message.Message); Assert.Equal(viewImportsPath, message.SourceFilePath); Assert.Equal(4, message.StartLine); Assert.Equal(8, message.StartColumn); Assert.Equal(4, message.EndLine); Assert.Equal(12, message.EndColumn); }); }); } [Fact] public void GetCompilationFailedResult_ReturnsCompilationResult_WithGroupedMessages() { // Arrange var viewPath = "Views/Home/Index"; var generatedCodeFileName = "Generated Code"; var codeDocument = RazorCodeDocument.Create(RazorSourceDocument.Create("view-content", viewPath)); var assemblyName = "random-assembly-name"; var diagnostics = new[] { Diagnostic.Create( GetRoslynDiagnostic("message-1"), Location.Create( viewPath, new TextSpan(10, 5), new LinePositionSpan(new LinePosition(10, 1), new LinePosition(10, 2)))), Diagnostic.Create( GetRoslynDiagnostic("message-2"), Location.Create( assemblyName, new TextSpan(1, 6), new LinePositionSpan(new LinePosition(1, 2), new LinePosition(3, 4)))), Diagnostic.Create( GetRoslynDiagnostic("message-3"), Location.Create( viewPath, new TextSpan(40, 50), new LinePositionSpan(new LinePosition(30, 5), new LinePosition(40, 12)))), }; // Act var compilationResult = CompilationFailedExceptionFactory.Create( codeDocument, "compilation-content", assemblyName, diagnostics); // Assert Assert.Collection(compilationResult.CompilationFailures, failure => { Assert.Equal(viewPath, failure.SourceFilePath); Assert.Equal("view-content", failure.SourceFileContent); Assert.Collection(failure.Messages, message => { Assert.Equal("message-1", message.Message); Assert.Equal(viewPath, message.SourceFilePath); Assert.Equal(11, message.StartLine); Assert.Equal(2, message.StartColumn); Assert.Equal(11, message.EndLine); Assert.Equal(3, message.EndColumn); }, message => { Assert.Equal("message-3", message.Message); Assert.Equal(viewPath, message.SourceFilePath); Assert.Equal(31, message.StartLine); Assert.Equal(6, message.StartColumn); Assert.Equal(41, message.EndLine); Assert.Equal(13, message.EndColumn); }); }, failure => { Assert.Equal(generatedCodeFileName, failure.SourceFilePath); Assert.Equal("compilation-content", failure.SourceFileContent); Assert.Collection(failure.Messages, message => { Assert.Equal("message-2", message.Message); Assert.Equal(assemblyName, message.SourceFilePath); Assert.Equal(2, message.StartLine); Assert.Equal(3, message.StartColumn); Assert.Equal(4, message.EndLine); Assert.Equal(5, message.EndColumn); }); }); } private static RazorSourceDocument Create(string path, string template) { var stream = new MemoryStream(Encoding.UTF8.GetBytes(template)); return RazorSourceDocument.ReadFrom(stream, path); } private static RazorDiagnostic GetRazorDiagnostic(string message, SourceLocation sourceLocation, int length) { var diagnosticDescriptor = new RazorDiagnosticDescriptor("test-id", () => message, RazorDiagnosticSeverity.Error); var sourceSpan = new SourceSpan(sourceLocation, length); return RazorDiagnostic.Create(diagnosticDescriptor, sourceSpan); } private static DiagnosticDescriptor GetRoslynDiagnostic(string messageFormat) { return new DiagnosticDescriptor( id: "someid", title: "sometitle", messageFormat: messageFormat, category: "some-category", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); } private static RazorCodeDocument GetCodeDocument(TestRazorProjectItem projectItem, TestRazorProjectItem imports = null) { var sourceDocument = RazorSourceDocument.ReadFrom(projectItem); var fileSystem = new VirtualRazorProjectFileSystem(); fileSystem.Add(projectItem); var codeDocument = RazorCodeDocument.Create(sourceDocument); if (imports != null) { fileSystem.Add(imports); codeDocument = RazorCodeDocument.Create(sourceDocument, new[] { RazorSourceDocument.ReadFrom(imports) }); } var razorEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem).Engine; razorEngine.Process(codeDocument); return codeDocument; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using NuGet.Common; using NuGet.Frameworks; namespace NupkgWrench { /// <summary> /// Add, Modify, Remove dependencies /// </summary> public static class DependenciesUtil { public static void Process(XDocument nuspecXml, EditType verb, HashSet<NuGetFramework> frameworks, string id, string version, string exclude, string include, bool clearExclude, bool clearInclude, ILogger log) { var metadata = Util.GetMetadataElement(nuspecXml); var nameNamespaceName = metadata.Name.NamespaceName; var dependenciesXName = XName.Get("dependencies", nameNamespaceName); var groupXName = XName.Get("group", nameNamespaceName); var dependencyXName = XName.Get("dependency", nameNamespaceName); var dependenciesNode = metadata.Element(dependenciesXName); // Create the dependencies node if it does not exist if (dependenciesNode == null && verb == EditType.Add) { dependenciesNode = new XElement(dependenciesXName); metadata.Add(dependenciesNode); } var groups = dependenciesNode?.Elements(groupXName).ToList() ?? new List<XElement>(); if (verb == EditType.Add) { var rootDependencies = dependenciesNode?.Elements(dependencyXName).ToList() ?? new List<XElement>(); // Migrate from root level dependencies to groups if needed if (groups.Count < 1 && rootDependencies.Count > 0) { var group = new XElement(groupXName); dependenciesNode.Add(group); groups.Add(group); rootDependencies.ForEach(e => { e.Remove(); group.Add(e); }); } // Create a default group if adding and no frameworks exist if (frameworks.Count < 1 && groups.Count < 1) { frameworks.Add(NuGetFramework.AnyFramework); } } // Filter groups if (frameworks.Count > 0) { groups.RemoveAll(e => !frameworks.Contains(e.GetFramework())); if (verb == EditType.Add) { foreach (var framework in frameworks) { if (!groups.Any(e => framework.Equals(e.GetFramework()))) { var group = CreateGroupNode(nameNamespaceName, framework); dependenciesNode.Add(group); groups.Add(group); } } } } else { // if no framework and dependency node exists, working on dependencies node if (groups.Count == 0 && dependenciesNode != null) { groups.Add(dependenciesNode); } } groups.ForEach(e => ProcessDependency(e, verb, id, version, exclude, include, clearExclude, clearInclude)); } public static void ProcessDependency(XElement dependencies, EditType type, string id, string version, string exclude, string include, bool clearExclude, bool clearInclude) { var metadata = Util.GetMetadataElement(dependencies.Document); var nameNamespaceName = metadata.Name.NamespaceName; var idXName = XName.Get("id"); var versionXName = XName.Get("version"); var excludeXName = XName.Get("exclude"); var includeXName = XName.Get("include"); if (dependencies == null && type == EditType.Add) { throw new ArgumentNullException(nameof(dependencies)); } var toUpdate = new List<XElement>(); if (string.IsNullOrEmpty(id) && type == EditType.Modify) { // Modify can run on all dependencies if no id was used toUpdate.AddRange(dependencies.Elements()); } else { var existing = dependencies?.Elements(XName.Get("dependency", nameNamespaceName)) .FirstOrDefault(e => string.Equals(e.Attribute(idXName)?.Value, id, StringComparison.OrdinalIgnoreCase)); // This is expected to add null if it does not exist toUpdate.Add(existing); } foreach (var currentNode in toUpdate) { var dependency = currentNode; if (type == EditType.Clear) { // Clear everything dependencies.Elements().ToList().ForEach(e => e.Remove()); dependency = null; } if (dependency != null && (type == EditType.Add || type == EditType.Remove)) { // Remove the dependency dependency.Remove(); dependency = null; } if (type == EditType.Add) { // Add node dependency = new XElement(XName.Get("dependency", nameNamespaceName)); dependency.SetAttributeValue(idXName, id); dependency.SetAttributeValue(versionXName, version); if (exclude != null) { dependency.SetAttributeValue(excludeXName, exclude); } if (include != null) { dependency.SetAttributeValue(includeXName, include); } dependencies.Add(dependency); } if (dependency != null && type == EditType.Modify) { // Modify existing if (version != null) { dependency.SetAttributeValue(versionXName, version); } if (exclude != null) { dependency.SetAttributeValue(excludeXName, exclude); } else if (clearExclude) { dependency.Attribute(excludeXName) ?.Remove(); } if (include != null) { dependency.SetAttributeValue(includeXName, include); } else if (clearInclude) { dependency.Attribute(includeXName) ?.Remove(); } } } } public static XElement CreateGroupNode(string ns, NuGetFramework fw) { var groupNode = new XElement(XName.Get("group", ns)); if (!fw.IsAny) { var version = fw.Version.ToString(); if (version.EndsWith(".0.0")) { version = version.Substring(0, version.Length - 4); } if (version.EndsWith(".0") && version.IndexOf('.') != version.LastIndexOf('.')) { version = version.Substring(0, version.Length - 2); } groupNode.Add(new XAttribute(XName.Get("targetFramework"), $"{fw.Framework}{version}")); } return groupNode; } private static NuGetFramework GetFramework(this XElement node) { var targetFramework = node.Attribute(XName.Get("targetFramework"))?.Value; if (string.IsNullOrEmpty(targetFramework)) { return NuGetFramework.AnyFramework; } return NuGetFramework.Parse(targetFramework); } public enum EditType { Add, Modify, Remove, Clear } } }
#region Using declarations using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Xml.Serialization; using NinjaTrader.Cbi; using NinjaTrader.Gui; using NinjaTrader.Gui.Chart; using NinjaTrader.Gui.SuperDom; using NinjaTrader.Gui.Tools; using NinjaTrader.Data; using NinjaTrader.NinjaScript; using NinjaTrader.Core.FloatingPoint; using NinjaTrader.NinjaScript.DrawingTools; using System.Web.Script.Serialization; using System.Net; #endregion //This namespace holds Indicators in this folder and is required. Do not change it. namespace NinjaTrader.NinjaScript.Indicators { public class SignificantMove3 : Indicator { private const string frogboxUrl = "http://127.0.0.1:8888/query?ticker={0}&date={1}"; private const string smUrl = "http://127.0.0.1:8889/query?ticker={0}"; private const int BARS_IGNORE = 45; private LinReg RL30; private int lastSignal = 0, lastNotSignal = 0; private int todayStartBar = 0; private double sm_multiplier = double.MinValue; private bool isIgnore = false; private FrogModel fm; protected override void OnStateChange() { if (State == State.SetDefaults) { Description = @""; Name = "SignificantMove3"; Calculate = Calculate.OnBarClose; IsOverlay = false; DisplayInDataBox = true; DrawOnPricePanel = true; DrawHorizontalGridLines = true; DrawVerticalGridLines = true; PaintPriceMarkers = true; ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right; //Disable this property if your indicator requires custom values that cumulate with each new market data event. //See Help Guide for additional information. IsSuspendedWhileInactive = true; Period = 30; SignalAreaColor = Brushes.Orange; SignalAreaOpacity = 30; AddPlot(Brushes.Transparent, "MarketAnalyzerPlot"); } else if (State == State.Configure) { RL30 = LinReg(30); } } protected override void OnBarUpdate() { if (sm_multiplier < 0) { initSMMultiplier(); } if (CurrentBar <= Period) { return; } if (Time[0].Date != Time[1].Date) { fm = getFrogModel(); todayStartBar = CurrentBar; updateIgnoreFlag(); } if (!ignoreSignal() && isMovingSameDirection()) { MarketAnalyzerPlot[0] = 1; if (lastSignal > lastNotSignal) // indicates the previous bar is a signal bar too { RemoveDrawObject(getTagString(CurrentBar)); } else { lastSignal = CurrentBar; } Draw.Rectangle(this, getTagString(lastSignal), true, CurrentBar - lastSignal, Close[lastSignal], -1, Close[0], Brushes.Transparent, SignalAreaColor, SignalAreaOpacity); } else { MarketAnalyzerPlot[0] = 0; lastNotSignal = CurrentBar; } } private void initSMMultiplier() { using (var client = new WebClient()) { var val = client.DownloadString(smUrl); sm_multiplier = double.Parse(val); } } private FrogModel getFrogModel() { string url = String.Format(frogboxUrl, base.Instrument.FullName, Time[0].Date.ToString("yyyy-MM-dd")); using (var client = new WebClient()) { var json = client.DownloadString(url); var serializer = new JavaScriptSerializer(); var model = serializer.Deserialize<FrogModel>(json); model.range = model.rangestat; return model; } } public class FrogModel { public double rangestat {get;set;} public double fb {get;set;} public double hfb {get;set;} public double range {get;set;} } private void updateIgnoreFlag() { isIgnore = Math.Abs(Open[0] - Close[1]) > fm.fb * sm_multiplier; } private string getTagString(int bar) { return "SignificantMove3" + bar; } private bool ignoreSignal() { return isIgnore && (CurrentBar - todayStartBar <= BARS_IGNORE); } private bool isMovingSameDirection() { bool flag = RL30[0] > RL30[1]; for (int i = 1; i < Period; i++) { if (RL30[i] > RL30[i + 1] != flag) { return false; } } return true; } #region Properties [NinjaScriptProperty] [Range(1, int.MaxValue)] [Display(Name="Period", Order=1, GroupName="Parameters")] public int Period { get; set; } [NinjaScriptProperty] [XmlIgnore] [Display(Name="SignalAreaColor", Order=2, GroupName="Parameters")] public Brush SignalAreaColor { get; set; } [Browsable(false)] public string SignalAreaColorSerializable { get { return Serialize.BrushToString(SignalAreaColor); } set { SignalAreaColor = Serialize.StringToBrush(value); } } [NinjaScriptProperty] [Range(1, int.MaxValue)] [Display(Name="SignalAreaOpacity", Order=3, GroupName="Parameters")] public int SignalAreaOpacity { get; set; } [Browsable(false)] [XmlIgnore] public Series<double> MarketAnalyzerPlot { get { return Values[0]; } } #endregion } } #region NinjaScript generated code. Neither change nor remove. namespace NinjaTrader.NinjaScript.Indicators { public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase { private SignificantMove3[] cacheSignificantMove3; public SignificantMove3 SignificantMove3(int period, Brush signalAreaColor, int signalAreaOpacity) { return SignificantMove3(Input, period, signalAreaColor, signalAreaOpacity); } public SignificantMove3 SignificantMove3(ISeries<double> input, int period, Brush signalAreaColor, int signalAreaOpacity) { if (cacheSignificantMove3 != null) for (int idx = 0; idx < cacheSignificantMove3.Length; idx++) if (cacheSignificantMove3[idx] != null && cacheSignificantMove3[idx].Period == period && cacheSignificantMove3[idx].SignalAreaColor == signalAreaColor && cacheSignificantMove3[idx].SignalAreaOpacity == signalAreaOpacity && cacheSignificantMove3[idx].EqualsInput(input)) return cacheSignificantMove3[idx]; return CacheIndicator<SignificantMove3>(new SignificantMove3(){ Period = period, SignalAreaColor = signalAreaColor, SignalAreaOpacity = signalAreaOpacity }, input, ref cacheSignificantMove3); } } } namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns { public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase { public Indicators.SignificantMove3 SignificantMove3(int period, Brush signalAreaColor, int signalAreaOpacity) { return indicator.SignificantMove3(Input, period, signalAreaColor, signalAreaOpacity); } public Indicators.SignificantMove3 SignificantMove3(ISeries<double> input , int period, Brush signalAreaColor, int signalAreaOpacity) { return indicator.SignificantMove3(input, period, signalAreaColor, signalAreaOpacity); } } } namespace NinjaTrader.NinjaScript.Strategies { public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase { public Indicators.SignificantMove3 SignificantMove3(int period, Brush signalAreaColor, int signalAreaOpacity) { return indicator.SignificantMove3(Input, period, signalAreaColor, signalAreaOpacity); } public Indicators.SignificantMove3 SignificantMove3(ISeries<double> input , int period, Brush signalAreaColor, int signalAreaOpacity) { return indicator.SignificantMove3(input, period, signalAreaColor, signalAreaOpacity); } } } #endregion
using System; using System.Drawing; using System.Diagnostics.CodeAnalysis; namespace xDockPanel { public sealed class DockPanelExtender { public interface IDockPaneFactory { DockPane CreateDockPane(IDockContent content, DockState visibleState, bool show); DockPane CreateDockPane(IDockContent content, FloatWindow floatWindow, bool show); DockPane CreateDockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, double proportion, bool show); DockPane CreateDockPane(IDockContent content, Rectangle floatWindowBounds, bool show); } public interface IFloatWindowFactory { FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane); FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds); } public interface IDockPaneCaptionFactory { DockPaneCaptionBase CreateDockPaneCaption(DockPane pane); } public interface IDockPaneStripFactory { DockPaneStripBase CreateDockPaneStrip(DockPane pane); } public interface IAutoHideStripFactory { AutoHideStripBase CreateAutoHideStrip(DockPanel panel); } #region DefaultDockPaneFactory private class DefaultDockPaneFactory : IDockPaneFactory { public DockPane CreateDockPane(IDockContent content, DockState visibleState, bool show) { return new DockPane(content, visibleState, show); } public DockPane CreateDockPane(IDockContent content, FloatWindow floatWindow, bool show) { return new DockPane(content, floatWindow, show); } public DockPane CreateDockPane(IDockContent content, DockPane prevPane, DockAlignment alignment, double proportion, bool show) { return new DockPane(content, prevPane, alignment, proportion, show); } public DockPane CreateDockPane(IDockContent content, Rectangle floatWindowBounds, bool show) { return new DockPane(content, floatWindowBounds, show); } } #endregion #region DefaultFloatWindowFactory private class DefaultFloatWindowFactory : IFloatWindowFactory { public FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane) { return new FloatWindow(dockPanel, pane); } public FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds) { return new FloatWindow(dockPanel, pane, bounds); } } #endregion #region DefaultDockPaneCaptionFactory private class DefaultDockPaneCaptionFactory : IDockPaneCaptionFactory { public DockPaneCaptionBase CreateDockPaneCaption(DockPane pane) { return new VS2005DockPaneCaption(pane); } } #endregion #region DefaultDockPaneTabStripFactory private class DefaultDockPaneStripFactory : IDockPaneStripFactory { public DockPaneStripBase CreateDockPaneStrip(DockPane pane) { return new VS2005DockPaneStrip(pane); } } #endregion #region DefaultAutoHideStripFactory private class DefaultAutoHideStripFactory : IAutoHideStripFactory { public AutoHideStripBase CreateAutoHideStrip(DockPanel panel) { return new VS2005AutoHideStrip(panel); } } #endregion internal DockPanelExtender(DockPanel dockPanel) { m_dockPanel = dockPanel; } private DockPanel m_dockPanel; private DockPanel DockPanel { get { return m_dockPanel; } } private IDockPaneFactory m_dockPaneFactory = null; public IDockPaneFactory DockPaneFactory { get { if (m_dockPaneFactory == null) m_dockPaneFactory = new DefaultDockPaneFactory(); return m_dockPaneFactory; } set { if (DockPanel.Panes.Count > 0) throw new InvalidOperationException(); m_dockPaneFactory = value; } } private IFloatWindowFactory m_floatWindowFactory = null; public IFloatWindowFactory FloatWindowFactory { get { if (m_floatWindowFactory == null) m_floatWindowFactory = new DefaultFloatWindowFactory(); return m_floatWindowFactory; } set { if (DockPanel.FloatWindows.Count > 0) throw new InvalidOperationException(); m_floatWindowFactory = value; } } private IDockPaneCaptionFactory m_dockPaneCaptionFactory = null; public IDockPaneCaptionFactory DockPaneCaptionFactory { get { if (m_dockPaneCaptionFactory == null) m_dockPaneCaptionFactory = new DefaultDockPaneCaptionFactory(); return m_dockPaneCaptionFactory; } set { if (DockPanel.Panes.Count > 0) throw new InvalidOperationException(); m_dockPaneCaptionFactory = value; } } private IDockPaneStripFactory m_dockPaneStripFactory = null; public IDockPaneStripFactory DockPaneStripFactory { get { if (m_dockPaneStripFactory == null) m_dockPaneStripFactory = new DefaultDockPaneStripFactory(); return m_dockPaneStripFactory; } set { if (DockPanel.Contents.Count > 0) throw new InvalidOperationException(); m_dockPaneStripFactory = value; } } private IAutoHideStripFactory m_autoHideStripFactory = null; public IAutoHideStripFactory AutoHideStripFactory { get { if (m_autoHideStripFactory == null) m_autoHideStripFactory = new DefaultAutoHideStripFactory(); return m_autoHideStripFactory; } set { if (DockPanel.Contents.Count > 0) throw new InvalidOperationException(); if (m_autoHideStripFactory == value) return; m_autoHideStripFactory = value; DockPanel.ResetAutoHideStripControl(); } } } }
namespace Microsoft.Protocols.TestSuites.MS_COPYS { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// The TestSuite base class of MS-COPYS. /// </summary> [TestClass] public class TestSuiteBase : TestClassBase { #region variables /// <summary> /// Gets or sets an instance of IMS_COPYSAdapter /// </summary> protected static IMS_COPYSAdapter MSCopysAdapter { get; set; } /// <summary> /// Gets or sets an instance of IMS_COPYSSutControlAdapter /// </summary> protected static IMS_COPYSSUTControlAdapter MSCOPYSSutControlAdapter { get; set; } /// <summary> /// Gets or sets an uint indicate the file name number value on current test case. /// </summary> protected static uint FileNameCounterOfPerTestCases { get; set; } /// <summary> /// Gets or sets an base64 string indicates the file contents of source file. /// </summary> protected static string SourceFileContentBase64Value { get; set; } /// <summary> /// Gets or sets a list type instance used to record all URLs of files added by TestSuiteHelper /// </summary> private static List<string> FilesUrlRecordOfDestination { get; set; } #endregion variables #region Test Suite Initialization /// <summary> /// Initialize the variable for the test suite. /// </summary> /// <param name="testContext">The context of the test suite.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { // A method is used to initialize the variables. TestClassBase.Initialize(testContext); if (null == MSCopysAdapter) { MSCopysAdapter = BaseTestSite.GetAdapter<IMS_COPYSAdapter>(); } if (null == MSCOPYSSutControlAdapter) { MSCOPYSSutControlAdapter = BaseTestSite.GetAdapter<IMS_COPYSSUTControlAdapter>(); } if (null == FilesUrlRecordOfDestination) { FilesUrlRecordOfDestination = new List<string>(); } if (string.IsNullOrEmpty(SourceFileContentBase64Value)) { string sourceFileContent = Common.GetConfigurationPropertyValue("SourceFileContents", BaseTestSite); byte[] souceFileContentBinaries = Encoding.UTF8.GetBytes(sourceFileContent); SourceFileContentBase64Value = Convert.ToBase64String(souceFileContentBinaries); } } /// <summary> /// A method is used to clean up the test suite. /// </summary> [ClassCleanup] public static void ClassCleanup() { if (null != FilesUrlRecordOfDestination && 0 != FilesUrlRecordOfDestination.Count) { StringBuilder strBuilder = new StringBuilder(); foreach (string fileUrlItem in FilesUrlRecordOfDestination) { strBuilder.Append(fileUrlItem + @";"); } string fileUrlValues = strBuilder.ToString(); bool isDeleteAllFilesSuccessful; isDeleteAllFilesSuccessful = MSCOPYSSutControlAdapter.DeleteFiles(fileUrlValues); if (!isDeleteAllFilesSuccessful) { throw new InvalidOperationException("Not all the files are deleted clearly."); } } TestClassBase.Cleanup(); } /// <summary> /// This method will run before test case executes /// </summary> [TestInitialize] public void TestCaseInitialize() { Common.CheckCommonProperties(this.Site, true); // Reset to the default user. MSCopysAdapter.SwitchUser(TestSuiteManageHelper.DefaultUser, TestSuiteManageHelper.PasswordOfDefaultUser, TestSuiteManageHelper.DomainOfDefaultUser); // Initialize the unique resource counter FileNameCounterOfPerTestCases = 0; } #endregion Test Suite Initialization #region protected methods /// <summary> /// A method is used to generate the destination URL. The file name in the URL is unique. /// </summary> /// <param name="destinationType">A parameter represents the destination URL type.</param> /// <returns>A return value represents the destination URL.</returns> protected string GetDestinationFileUrl(DestinationFileUrlType destinationType) { string urlPatternValueOfDestinationFile = string.Empty; string expectedPropertyName = string.Empty; switch (destinationType) { case DestinationFileUrlType.NormalDesLibraryOnDesSUT: { expectedPropertyName = "UrlPatternOfDesFileOnDestinationSUT"; break; } case DestinationFileUrlType.MWSLibraryOnDestinationSUT: { expectedPropertyName = "UrlPatternOfDesFileForMWSOnDestinationSUT"; break; } default: { throw new InvalidOperationException("The test suite only supports two destination type: [NormalDesLibraryOnDesSUT] and [MWSLibraryOnDestinationSUT]."); } } // Get match URL pattern. urlPatternValueOfDestinationFile = Common.GetConfigurationPropertyValue(expectedPropertyName, this.Site); if (urlPatternValueOfDestinationFile.IndexOf("{FileName}", StringComparison.OrdinalIgnoreCase) <= 0) { throw new InvalidOperationException(string.Format(@"The [{0}] property should contain the ""{fileName}"" placeholder.", expectedPropertyName)); } string fileNameValue = this.GetUniqueFileName(); string actualDestinationFileUrl = urlPatternValueOfDestinationFile.ToLower().Replace("{filename}", fileNameValue); // Verify the URL whether point to a file. FileUrlHelper.ValidateFileUrl(actualDestinationFileUrl); return actualDestinationFileUrl; } /// <summary> /// A method used to get source file URL. The URL's file name is unique. /// </summary> /// <param name="sourceFileType">A parameter represents the source URL type.</param> /// <returns>A return value represents the destination URL.</returns> protected string GetSourceFileUrl(SourceFileUrlType sourceFileType) { string expectedPropertyName; switch (sourceFileType) { case SourceFileUrlType.SourceFileOnDesSUT: { expectedPropertyName = "SourceFileUrlOnDesSUT"; break; } case SourceFileUrlType.SourceFileOnSourceSUT: { expectedPropertyName = "SourceFileUrlOnSourceSUT"; break; } default: { throw new InvalidOperationException("The test suite only support two source URL type: [SourceFileUrlOnDesSUT] and [SourceFileUrlOnSourceSUT]."); } } string expectedSourceFileUrl = Common.GetConfigurationPropertyValue(expectedPropertyName, this.Site); // Verify the URL whether point to a file. FileUrlHelper.ValidateFileUrl(expectedSourceFileUrl); return expectedSourceFileUrl; } /// <summary> /// A method is used to get a unique name of file which is used to upload into document library list. /// </summary> /// <returns>A return value represents the unique name that is combined with the file Object name and time stamp</returns> protected string GetUniqueFileName() { FileNameCounterOfPerTestCases += 1; // Sleep 1 seconds in order to ensure "Common.GenerateResourceName" method will not generate same file names for invoke it twice. Thread.Sleep(1000); string fileName = Common.GenerateResourceName(this.Site, "file", FileNameCounterOfPerTestCases); return string.Format("{0}.txt", fileName); } /// <summary> /// A method used to select a field by specified field attribute value. The "DisplayName" is not a unique identifier for a field, so the method return the first match item when using "DisplayName" attribute value. If there are no any fields are found, this method will raise an InvalidOperationException. /// </summary> /// <param name="fields">A parameter represents the fields array.</param> /// <param name="expectedAttributeValue">A parameter represents the expected attribute value which is used to match field item.</param> /// <param name="usedAttribute">A parameter represents the attribute type which is used to compare with the expected attribute value.</param> /// <returns>A return value represents the selected field.</returns> protected FieldInformation SelectFieldBySpecifiedAtrribute(FieldInformation[] fields, string expectedAttributeValue, FieldAttributeType usedAttribute) { FieldInformation selectedField = this.FindOutTheField(fields, expectedAttributeValue, usedAttribute); if (null == selectedField) { string errorMsg = string.Format( "Could not find the expected field by specified value:[{0}] of [{1}] attribute.", expectedAttributeValue, usedAttribute); throw new InvalidOperationException(errorMsg); } return selectedField; } /// <summary> /// A method used to verify whether all copy results are successful. If there is any non-success copy result, it raise an exception. /// </summary> /// <param name="copyResults">A parameter represents the copy results collection.</param> /// <param name="raiseAssertEx">A parameter indicates the method whether raise an assert exception, if not all the copy result are successful. The 'true' means raise an exception.</param> /// <returns>Return 'true' indicating all copy results are success, otherwise return 'false'. If the "raiseAssertEx" is set to true, the method will raise a exception instead of returning 'false'.</returns> protected bool VerifyAllCopyResultsSuccess(CopyResult[] copyResults, bool raiseAssertEx = true) { if (null == copyResults) { throw new ArgumentNullException("copyResults"); } if (0 == copyResults.Length) { throw new ArgumentException("The copy results collection should contain at least one item", "copyResults"); } var notSuccessResultItem = from resultItem in copyResults where CopyErrorCode.Success != resultItem.ErrorCode select resultItem; bool verifyResult = false; if (notSuccessResultItem.Count() > 0) { StringBuilder strBuilderOfErrorResult = new StringBuilder(); foreach (CopyResult resultItem in notSuccessResultItem) { string errorMsgItem = string.Format( "ErrorCode:[{0}]\r\nErrorMessage:[{1}]\r\nDestinationUrl:[{2}]", resultItem.ErrorCode, string.IsNullOrEmpty(resultItem.ErrorMessage) ? "None" : resultItem.ErrorMessage, resultItem.DestinationUrl); strBuilderOfErrorResult.AppendLine(errorMsgItem); strBuilderOfErrorResult.AppendLine("==========="); } this.Site.Log.Add( LogEntryKind.Debug, "Total non-successful copy results:[{0}]\r\n{1}", notSuccessResultItem.Count(), strBuilderOfErrorResult.ToString()); if (raiseAssertEx) { this.Site.Assert.Fail("Not all copy result are successful."); } } else { verifyResult = true; } return verifyResult; } /// <summary> /// A method used to generate invalid file URL by confusing the folder path. The method will confuse the path part which is nearest to the file name part. /// </summary> /// <param name="originalFilePath">A parameter represents the original file path.</param> /// <returns>A return value represents a file URL with an invalid folder path.</returns> protected string GenerateInvalidFolderPathForFileUrl(string originalFilePath) { string fileName = FileUrlHelper.ValidateFileUrl(originalFilePath); string directoryName = Path.GetDirectoryName(originalFilePath); // Append a guid value to ensure the folder name is not a valid folder. string invalidDirectoryName = directoryName + Guid.NewGuid().ToString("N"); string invalidFileUrl = Path.Combine(invalidDirectoryName, fileName); // Work around for local path format mapping to URL path format. invalidFileUrl = invalidFileUrl.Replace(@"\", @"/"); invalidFileUrl = invalidFileUrl.Replace(@":/", @"://"); return invalidFileUrl; } /// <summary> /// A method used to generate invalid file URL by construct a not-existing file name. /// </summary> /// <param name="originalFilePath">A parameter represents the original file path, it must be a valid URL.</param> /// <returns>A return value represents a file URL with a not-existing file name.</returns> protected string GenerateInvalidFileUrl(string originalFilePath) { FileUrlHelper.ValidateFileUrl(originalFilePath); string directoryName = Path.GetDirectoryName(originalFilePath); // Append an invalid URL char to file name is not. string invalidFileName = string.Format(@"Invalid{0}File{1}Name.txt", @"%", @"&"); string invalidFileUrl = Path.Combine(directoryName, invalidFileName); // Work around for local path format mapping to URL path format. invalidFileUrl = invalidFileUrl.Replace(@"\", @"/"); invalidFileUrl = invalidFileUrl.Replace(@":/", @"://"); return invalidFileUrl; } /// <summary> /// A method used to collect a file by specified file URL. The test suite will try to delete all collect files. /// </summary> /// <param name="fileUrl">A parameter represents the URL of a file which will be collected to delete. The file must be stored in the destination SUT which is indicated by "SutComputerName" property in "SharePointCommonConfiguration.deployment.ptfconfig" file.</param> protected void CollectFileByUrl(string fileUrl) { FileUrlHelper.ValidateFileUrl(fileUrl); this.CollectFileToRecorder(fileUrl); } /// <summary> /// A method used to collect files from specified file URLs. The test suite will try to delete all collect files. /// </summary> /// <param name="fileUrls">A parameter represents the arrays of file URLs of files which will be collected to delete. All the files must be stored in the destination SUT which is indicated by "SutComputerName" property in "SharePointCommonConfiguration.deployment.ptfconfig" file.</param> protected void CollectFileByUrl(string[] fileUrls) { if (null == fileUrls || 0 == fileUrls.Length) { throw new ArgumentNullException("fileUrls"); } foreach (string fileUrlItem in fileUrls) { this.CollectFileByUrl(fileUrlItem); } } /// <summary> /// A method used to upload a txt file to the destination SUT. /// </summary> /// <param name="fileUrl">A parameter represents the expected URL of a file which will be uploaded into the destination SUT. The file URL must point to the destination SUT which is indicated by "SutComputerName" property in "SharePointCommonConfiguration.deployment.ptfconfig" file.</param> protected void UploadTxtFileByFileUrl(string fileUrl) { if (null == MSCOPYSSutControlAdapter) { throw new InvalidOperationException("The SUT control adapter is not initialized."); } FileUrlHelper.ValidateFileUrl(fileUrl); bool isFileUploadSuccessful = MSCOPYSSutControlAdapter.UploadTextFile(fileUrl); if (!isFileUploadSuccessful) { this.Site.Assert.Fail("Could not upload a txt file to the destination SUT. Expected file URL:[{0}]", fileUrl); } this.CollectFileToRecorder(fileUrl); } #endregion protected methods #region private methods /// <summary> /// A method used to collect a file by specified file URL. /// </summary> /// <param name="fileUrl">A parameter represents the URL of a file which will be collected to delete.</param> private void CollectFileToRecorder(string fileUrl) { if (null == FilesUrlRecordOfDestination) { FilesUrlRecordOfDestination = new List<string>(); } FilesUrlRecordOfDestination.Add(fileUrl); } /// <summary> /// A method used to find out a field by specified field attribute value. The "DisplayName" is not a unique identifier for a field, so the method return the first match item when using "DisplayName" attribute value. /// </summary> /// <param name="fields">A parameter represents the fields array.</param> /// <param name="expectedAttributeValue">A parameter represents the expected attribute value which is used to match field item.</param> /// <param name="usedAttribute">A parameter represents the attribute type which is used to compare with the expected attribute value.</param> /// <returns>A return value represents the selected field.</returns> private FieldInformation FindOutTheField(FieldInformation[] fields, string expectedAttributeValue, FieldAttributeType usedAttribute) { #region validate parameters if (null == fields) { throw new ArgumentNullException("fields"); } if (string.IsNullOrEmpty(expectedAttributeValue)) { throw new ArgumentNullException("attributeValue"); } if (0 == fields.Length) { throw new ArgumentException("The fields' array should contain at least one item."); } #endregion validate parameters FieldInformation selectedField = null; #region select the field by specified attribute value switch (usedAttribute) { case FieldAttributeType.InternalName: { var selectResult = from fieldItem in fields where expectedAttributeValue.Equals(fieldItem.InternalName, StringComparison.OrdinalIgnoreCase) select fieldItem; selectedField = 1 == selectResult.Count() ? selectResult.ElementAt<FieldInformation>(0) : null; break; } case FieldAttributeType.Id: { Guid expectedGuidValue; if (!Guid.TryParse(expectedAttributeValue, out expectedGuidValue)) { throw new InvalidOperationException( string.Format( @"The attributeValue parameter value should be a valid GUID value when select field by using [Id] attribute. Current attributeValue parameter:[{0}].", expectedAttributeValue)); } var selectResult = from fieldItem in fields where expectedGuidValue.Equals(fieldItem.Id) select fieldItem; selectedField = 1 == selectResult.Count() ? selectResult.ElementAt<FieldInformation>(0) : null; break; } case FieldAttributeType.DisplayName: { var selectResult = from fieldItem in fields where expectedAttributeValue.Equals(fieldItem.InternalName, StringComparison.OrdinalIgnoreCase) select fieldItem; // The DisplayName attribute is not unique. selectedField = selectResult.Count() > 0 ? selectResult.ElementAt<FieldInformation>(0) : null; break; } } #endregion select the field by specified attribute value if (null == selectedField) { string errorMsg = string.Format( "Could not find the expected field by specified vale:[{0}] of [{1}] attribute.", expectedAttributeValue, usedAttribute); #region log the fields information StringBuilder logBuilder = new StringBuilder(); logBuilder.AppendLine(errorMsg); logBuilder.AppendLine("Fields in current field collection:"); foreach (FieldInformation fieldItem in fields) { string fieldInformation = string.Format( @"FieldName:[{0}] InternalName:[{1}] Type:[{2}] Value:[{3}]", fieldItem.DisplayName, string.IsNullOrEmpty(fieldItem.InternalName) ? "Null/Empty" : fieldItem.InternalName, fieldItem.Type, string.IsNullOrEmpty(fieldItem.Value) ? "Null/Empty" : fieldItem.Value); logBuilder.AppendLine(fieldInformation); } logBuilder.AppendLine("=================="); logBuilder.AppendLine(string.Format("Total fields:[{0}]", fields.Length)); this.Site.Log.Add(LogEntryKind.Debug, logBuilder.ToString()); #endregion log the fields information } return selectedField; } #endregion private methods } }
using System; using System.Collections.Generic; using SilentOrbit.Code; namespace SilentOrbit.ProtocolBuffers { static class FieldSerializer { #region Reader /// <summary> /// Return true for normal code and false if generated thrown exception. /// In the latter case a break is not needed to be generated afterwards. /// </summary> public static bool FieldReader(Field f, CodeWriter cw, Options options) { if (f.Rule == FieldRule.Repeated) { //Make sure we are not reading a list of interfaces if (f.ProtoType.OptionType == "interface") { cw.WriteLine("throw new NotSupportedException(\"Can't deserialize a list of interfaces\");"); return false; } if (f.OptionPacked == true) { cw.Comment("repeated packed"); cw.WriteLine("long end" + f.ID + " = global::SilentOrbit.ProtocolBuffers.ProtocolParser.ReadUInt32(stream);"); cw.WriteLine("end" + f.ID + " += stream.Position;"); cw.WhileBracket("stream.Position < end" + f.ID); cw.WriteLine("instance." + f.CsName + ".Add(" + FieldReaderType(f, "stream", "br", null) + ");"); cw.EndBracket(); cw.WriteLine("if (stream.Position != end" + f.ID + ")"); cw.WriteIndent("throw new global::SilentOrbit.ProtocolBuffers.ProtocolBufferException(\"Read too many bytes in packed data\");"); } else { cw.Comment("repeated"); cw.WriteLine("instance." + f.CsName + ".Add(" + FieldReaderType(f, "stream", "br", null) + ");"); } } else { if (f.OptionReadOnly) { //The only "readonly" fields we can modify //We could possibly support bytes primitive too but it would require the incoming length to match the wire length if (f.ProtoType is ProtoMessage) { cw.WriteLine(FieldReaderType(f, "stream", "br", "instance." + f.CsName) + ";"); return true; } cw.WriteLine("throw new InvalidOperationException(\"Can't deserialize into a readonly primitive field\");"); return false; } if (f.ProtoType is ProtoMessage) { if (f.ProtoType.OptionType == "struct") { if (options.Nullable) cw.WriteLine("instance." + f.CsName + " = " + FieldReaderType(f, "stream", "br", null) + ";"); else cw.WriteLine(FieldReaderType(f, "stream", "br", "ref instance." + f.CsName) + ";"); return true; } cw.WriteLine("if (instance." + f.CsName + " == null)"); if (f.ProtoType.OptionType == "interface") cw.WriteIndent("throw new InvalidOperationException(\"Can't deserialize into a interfaces null pointer\");"); else cw.WriteIndent("instance." + f.CsName + " = " + FieldReaderType(f, "stream", "br", null) + ";"); cw.WriteLine("else"); cw.WriteIndent(FieldReaderType(f, "stream", "br", "instance." + f.CsName) + ";"); return true; } cw.WriteLine("instance." + f.CsName + " = " + FieldReaderType(f, "stream", "br", "instance." + f.CsName) + ";"); } return true; } /// <summary> /// Read a primitive from the stream /// </summary> static string FieldReaderType(Field f, string stream, string binaryReader, string instance) { if (f.OptionCodeType != null) { switch (f.OptionCodeType) { case "DateTime": switch (f.ProtoType.ProtoName) { case ProtoBuiltin.UInt64: case ProtoBuiltin.Int64: case ProtoBuiltin.Fixed64: case ProtoBuiltin.SFixed64: return "new DateTime((long)" + FieldReaderPrimitive(f, stream, binaryReader, instance) + ")"; } throw new ProtoFormatException("Local feature, DateTime, must be stored in a 64 bit field", f.Source); case "TimeSpan": switch (f.ProtoType.ProtoName) { case ProtoBuiltin.UInt64: case ProtoBuiltin.Int64: case ProtoBuiltin.Fixed64: case ProtoBuiltin.SFixed64: return "new TimeSpan((long)" + FieldReaderPrimitive(f, stream, binaryReader, instance) + ")"; } throw new ProtoFormatException("Local feature, TimeSpan, must be stored in a 64 bit field", f.Source); default: //Assume enum return "(" + f.OptionCodeType + ")" + FieldReaderPrimitive(f, stream, binaryReader, instance); } } return FieldReaderPrimitive(f, stream, binaryReader, instance); } static string FieldReaderPrimitive(Field f, string stream, string binaryReader, string instance) { if (f.ProtoType is ProtoMessage) { var m = f.ProtoType as ProtoMessage; if (f.Rule == FieldRule.Repeated || instance == null) return m.FullSerializerType + ".DeserializeLengthDelimited(" + stream + ")"; else return m.FullSerializerType + ".DeserializeLengthDelimited(" + stream + ", " + instance + ")"; } if (f.ProtoType is ProtoEnum) return "(" + f.ProtoType.FullCsType + ")global::SilentOrbit.ProtocolBuffers.ProtocolParser.ReadUInt64(" + stream + ")"; if (f.ProtoType is ProtoBuiltin) { switch (f.ProtoType.ProtoName) { case ProtoBuiltin.Double: return binaryReader + ".ReadDouble()"; case ProtoBuiltin.Float: return binaryReader + ".ReadSingle()"; case ProtoBuiltin.Int32: //Wire format is 64 bit varint return "(int)global::SilentOrbit.ProtocolBuffers.ProtocolParser.ReadUInt64(" + stream + ")"; case ProtoBuiltin.Int64: return "(long)global::SilentOrbit.ProtocolBuffers.ProtocolParser.ReadUInt64(" + stream + ")"; case ProtoBuiltin.UInt32: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.ReadUInt32(" + stream + ")"; case ProtoBuiltin.UInt64: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.ReadUInt64(" + stream + ")"; case ProtoBuiltin.SInt32: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.ReadZInt32(" + stream + ")"; case ProtoBuiltin.SInt64: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.ReadZInt64(" + stream + ")"; case ProtoBuiltin.Fixed32: return binaryReader + ".ReadUInt32()"; case ProtoBuiltin.Fixed64: return binaryReader + ".ReadUInt64()"; case ProtoBuiltin.SFixed32: return binaryReader + ".ReadInt32()"; case ProtoBuiltin.SFixed64: return binaryReader + ".ReadInt64()"; case ProtoBuiltin.Bool: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.ReadBool(" + stream + ")"; case ProtoBuiltin.String: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.ReadString(" + stream + ")"; case ProtoBuiltin.Bytes: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.ReadBytes(" + stream + ")"; default: throw new ProtoFormatException("unknown build in: " + f.ProtoType.ProtoName, f.Source); } } throw new NotImplementedException(); } #endregion #region Writer static void KeyWriter(string stream, int id, Wire wire, CodeWriter cw) { uint n = ((uint)id << 3) | ((uint)wire); cw.Comment("Key for field: " + id + ", " + wire); //cw.WriteLine("ProtocolParser.WriteUInt32(" + stream + ", " + n + ");"); VarintWriter(stream, n, cw); } /// <summary> /// Generates writer for a varint value known at compile time /// </summary> static void VarintWriter(string stream, uint value, CodeWriter cw) { while (true) { byte b = (byte)(value & 0x7F); value = value >> 7; if (value == 0) { cw.WriteLine(stream + ".WriteByte(" + b + ");"); break; } //Write part of value b |= 0x80; cw.WriteLine(stream + ".WriteByte(" + b + ");"); } } /// <summary> /// Generates inline writer of a length delimited byte array /// </summary> static void BytesWriter(Field f, string stream, CodeWriter cw) { cw.Comment("Length delimited byte array"); //Original //cw.WriteLine("ProtocolParser.WriteBytes(" + stream + ", " + memoryStream + ".ToArray());"); //Much slower than original /* cw.WriteLine("ProtocolParser.WriteUInt32(" + stream + ", (uint)" + memoryStream + ".Length);"); cw.WriteLine(memoryStream + ".Seek(0, System.IO.SeekOrigin.Begin);"); cw.WriteLine(memoryStream + ".CopyTo(" + stream + ");"); */ //Same speed as original /* cw.WriteLine("ProtocolParser.WriteUInt32(" + stream + ", (uint)" + memoryStream + ".Length);"); cw.WriteLine(stream + ".Write(" + memoryStream + ".ToArray(), 0, (int)" + memoryStream + ".Length);"); */ //10% faster than original using GetBuffer rather than ToArray cw.WriteLine("uint length" + f.ID + " = (uint)msField.Length;"); cw.WriteLine("global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(" + stream + ", length" + f.ID + ");"); cw.WriteLine(stream + ".Write(msField.GetBuffer(), 0, (int)length" + f.ID + ");"); } /// <summary> /// Generates code for writing one field /// </summary> public static void FieldWriter(ProtoMessage m, Field f, CodeWriter cw, Options options) { if (f.Rule == FieldRule.Repeated) { if (f.OptionPacked == true) { //Repeated packed cw.IfBracket("instance." + f.CsName + " != null"); KeyWriter("stream", f.ID, Wire.LengthDelimited, cw); if (f.ProtoType.WireSize < 0) { //Un-optimized, unknown size cw.WriteLine("msField.SetLength(0);"); if (f.IsUsingBinaryWriter) cw.WriteLine("BinaryWriter bw" + f.ID + " = new BinaryWriter(ms" + f.ID + ");"); cw.ForeachBracket("var i" + f.ID + " in instance." + f.CsName); cw.WriteLine(FieldWriterType(f, "msField", "bw" + f.ID, "i" + f.ID)); cw.EndBracket(); BytesWriter(f, "stream", cw); } else { //Optimized with known size //No memorystream buffering, write size first at once //For constant size messages we can skip serializing to the MemoryStream cw.WriteLine("global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, " + f.ProtoType.WireSize + "u * (uint)instance." + f.CsName + ".Count);"); cw.ForeachBracket("var i" + f.ID + " in instance." + f.CsName); cw.WriteLine(FieldWriterType(f, "stream", "bw", "i" + f.ID)); cw.EndBracket(); } cw.EndBracket(); } else { //Repeated not packet cw.IfBracket("instance." + f.CsName + " != null"); cw.ForeachBracket("var i" + f.ID + " in instance." + f.CsName); KeyWriter("stream", f.ID, f.ProtoType.WireType, cw); cw.WriteLine(FieldWriterType(f, "stream", "bw", "i" + f.ID)); cw.EndBracket(); cw.EndBracket(); } return; } else if (f.Rule == FieldRule.Optional) { if (options.Nullable || f.ProtoType is ProtoMessage || f.ProtoType.ProtoName == ProtoBuiltin.String || f.ProtoType.ProtoName == ProtoBuiltin.Bytes) { if (f.ProtoType.Nullable || options.Nullable) //Struct always exist, not optional cw.IfBracket("instance." + f.CsName + " != null"); KeyWriter("stream", f.ID, f.ProtoType.WireType, cw); var needValue = !f.ProtoType.Nullable && options.Nullable; cw.WriteLine(FieldWriterType(f, "stream", "bw", "instance." + f.CsName + (needValue ? ".Value" : ""))); if (f.ProtoType.Nullable || options.Nullable) //Struct always exist, not optional cw.EndBracket(); return; } if (f.ProtoType is ProtoEnum) { if (f.OptionDefault != null) cw.IfBracket("instance." + f.CsName + " != " + f.ProtoType.CsType + "." + f.OptionDefault); KeyWriter("stream", f.ID, f.ProtoType.WireType, cw); cw.WriteLine(FieldWriterType(f, "stream", "bw", "instance." + f.CsName)); if (f.OptionDefault != null) cw.EndBracket(); return; } KeyWriter("stream", f.ID, f.ProtoType.WireType, cw); cw.WriteLine(FieldWriterType(f, "stream", "bw", "instance." + f.CsName)); return; } else if (f.Rule == FieldRule.Required) { if (f.ProtoType is ProtoMessage && f.ProtoType.OptionType != "struct" || f.ProtoType.ProtoName == ProtoBuiltin.String || f.ProtoType.ProtoName == ProtoBuiltin.Bytes) { cw.WriteLine("if (instance." + f.CsName + " == null)"); cw.WriteIndent("throw new ArgumentNullException(\"" + f.CsName + "\", \"Required by proto specification.\");"); } KeyWriter("stream", f.ID, f.ProtoType.WireType, cw); cw.WriteLine(FieldWriterType(f, "stream", "bw", "instance." + f.CsName)); return; } throw new NotImplementedException("Unknown rule: " + f.Rule); } static string FieldWriterType(Field f, string stream, string binaryWriter, string instance) { if (f.OptionCodeType != null) { switch (f.OptionCodeType) { case "DateTime": case "TimeSpan": return FieldWriterPrimitive(f, stream, binaryWriter, instance + ".Ticks"); default: //enum break; } } return FieldWriterPrimitive(f, stream, binaryWriter, instance); } static string FieldWriterPrimitive(Field f, string stream, string binaryWriter, string instance) { if (f.ProtoType is ProtoEnum) return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(" + stream + ",(ulong)" + instance + ");"; if (f.ProtoType is ProtoMessage) { ProtoMessage pm = f.ProtoType as ProtoMessage; CodeWriter cw = new CodeWriter(); cw.WriteLine("msField.SetLength(0);"); cw.WriteLine(pm.FullSerializerType + ".Serialize(msField, " + instance + ");"); BytesWriter(f, stream, cw); return cw.Code; } switch (f.ProtoType.ProtoName) { case ProtoBuiltin.Double: case ProtoBuiltin.Float: case ProtoBuiltin.Fixed32: case ProtoBuiltin.Fixed64: case ProtoBuiltin.SFixed32: case ProtoBuiltin.SFixed64: return binaryWriter + ".Write(" + instance + ");"; case ProtoBuiltin.Int32: //Serialized as 64 bit varint return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(" + stream + ",(ulong)" + instance + ");"; case ProtoBuiltin.Int64: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(" + stream + ",(ulong)" + instance + ");"; case ProtoBuiltin.UInt32: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(" + stream + ", " + instance + ");"; case ProtoBuiltin.UInt64: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(" + stream + ", " + instance + ");"; case ProtoBuiltin.SInt32: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteZInt32(" + stream + ", " + instance + ");"; case ProtoBuiltin.SInt64: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteZInt64(" + stream + ", " + instance + ");"; case ProtoBuiltin.Bool: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBool(" + stream + ", " + instance + ");"; case ProtoBuiltin.String: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(" + stream + ", Encoding.UTF8.GetBytes(" + instance + "));"; case ProtoBuiltin.Bytes: return "global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(" + stream + ", " + instance + ");"; } throw new NotImplementedException(); } #endregion } }
// // DiscUtils Copyright (c) 2008-2011, Kenneth Bell // // Original NativeFileSystem contributed by bsobel: // http://discutils.codeplex.com/workitem/5190 // // 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 DiscUtils { using System; using System.IO; /// <summary> /// Provides an implementation for OS-mounted file systems. /// </summary> public class NativeFileSystem : DiscFileSystem { private string _basePath; private bool _readOnly; /// <summary> /// Initializes a new instance of the NativeFileSystem class. /// </summary> /// <param name="basePath">The 'root' directory of the new instance.</param> /// <param name="readOnly">Only permit 'read' activities.</param> public NativeFileSystem(string basePath, bool readOnly) : base() { _basePath = basePath; if (!_basePath.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { _basePath += @"\"; } _readOnly = readOnly; } /// <summary> /// Gets the base path used to create the file system. /// </summary> public string BasePath { get { return _basePath; } } /// <summary> /// Provides a friendly description of the file system type. /// </summary> public override string FriendlyName { get { return "Native"; } } /// <summary> /// Indicates whether the file system is read-only or read-write. /// </summary> /// <returns>true if the file system is read-write.</returns> public override bool CanWrite { get { return !_readOnly; } } /// <summary> /// Gets the root directory of the file system. /// </summary> public override DiscDirectoryInfo Root { get { return new DiscDirectoryInfo(this, string.Empty); } } /// <summary> /// Gets the volume label. /// </summary> public override string VolumeLabel { get { return string.Empty; } } /// <summary> /// Gets a value indicating whether the file system is thread-safe. /// </summary> /// <remarks>The Native File System is thread safe.</remarks> public override bool IsThreadSafe { get { return true; } } /// <summary> /// Copies an existing file to a new file. /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="destinationFile">The destination file.</param> public override void CopyFile(string sourceFile, string destinationFile) { CopyFile(sourceFile, destinationFile, true); } /// <summary> /// Copies an existing file to a new file, allowing overwriting of an existing file. /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="destinationFile">The destination file.</param> /// <param name="overwrite">Whether to permit over-writing of an existing file.</param> public override void CopyFile(string sourceFile, string destinationFile, bool overwrite) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (sourceFile.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { sourceFile = sourceFile.Substring(1); } if (destinationFile.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { destinationFile = destinationFile.Substring(1); } File.Copy(Path.Combine(_basePath, sourceFile), Path.Combine(_basePath, destinationFile), true); } /// <summary> /// Creates a directory. /// </summary> /// <param name="path">The path of the new directory.</param> public override void CreateDirectory(string path) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } Directory.CreateDirectory(Path.Combine(_basePath, path)); } /// <summary> /// Deletes a directory. /// </summary> /// <param name="path">The path of the directory to delete.</param> public override void DeleteDirectory(string path) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } Directory.Delete(Path.Combine(_basePath, path)); } /// <summary> /// Deletes a directory, optionally with all descendants. /// </summary> /// <param name="path">The path of the directory to delete.</param> /// <param name="recursive">Determines if the all descendants should be deleted.</param> public override void DeleteDirectory(string path, bool recursive) { if (recursive) { foreach (string dir in GetDirectories(path)) { DeleteDirectory(dir, true); } foreach (string file in GetFiles(path)) { DeleteFile(file); } } DeleteDirectory(path); } /// <summary> /// Deletes a file. /// </summary> /// <param name="path">The path of the file to delete.</param> public override void DeleteFile(string path) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } File.Delete(Path.Combine(_basePath, path)); } /// <summary> /// Indicates if a directory exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the directory exists.</returns> public override bool DirectoryExists(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return Directory.Exists(Path.Combine(_basePath, path)); } /// <summary> /// Indicates if a file exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the file exists.</returns> public override bool FileExists(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return File.Exists(Path.Combine(_basePath, path)); } /// <summary> /// Indicates if a file or directory exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the file or directory exists.</returns> public override bool Exists(string path) { return FileExists(path) || DirectoryExists(path); } /// <summary> /// Gets the names of subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of directories.</returns> public override string[] GetDirectories(string path) { return GetDirectories(path, "*.*", SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of directories matching the search pattern.</returns> public override string[] GetDirectories(string path, string searchPattern) { return GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of directories matching the search pattern.</returns> public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } try { return CleanItems(Directory.GetDirectories(Path.Combine(_basePath, path), searchPattern, searchOption)); } catch (System.IO.IOException) { return new string[0]; } catch (System.UnauthorizedAccessException) { return new string[0]; } } /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files.</returns> public override string[] GetFiles(string path) { return GetFiles(path, "*.*", SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files matching the search pattern.</returns> public override string[] GetFiles(string path, string searchPattern) { return GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of files in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of files matching the search pattern.</returns> public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } try { return CleanItems(Directory.GetFiles(Path.Combine(_basePath, path), searchPattern, searchOption)); } catch (System.IO.IOException) { return new string[0]; } catch (System.UnauthorizedAccessException) { return new string[0]; } } /// <summary> /// Gets the names of all files and subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public override string[] GetFileSystemEntries(string path) { return GetFileSystemEntries(path, "*.*"); } /// <summary> /// Gets the names of files and subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public override string[] GetFileSystemEntries(string path, string searchPattern) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } try { return CleanItems(Directory.GetFileSystemEntries(Path.Combine(_basePath, path), searchPattern)); } catch (System.IO.IOException) { return new string[0]; } catch (System.UnauthorizedAccessException) { return new string[0]; } } /// <summary> /// Moves a directory. /// </summary> /// <param name="sourceDirectoryName">The directory to move.</param> /// <param name="destinationDirectoryName">The target directory name.</param> public override void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (sourceDirectoryName.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { sourceDirectoryName = sourceDirectoryName.Substring(1); } if (destinationDirectoryName.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { destinationDirectoryName = destinationDirectoryName.Substring(1); } Directory.Move(Path.Combine(_basePath, sourceDirectoryName), Path.Combine(_basePath, destinationDirectoryName)); } /// <summary> /// Moves a file. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> public override void MoveFile(string sourceName, string destinationName) { MoveFile(sourceName, destinationName, false); } /// <summary> /// Moves a file, allowing an existing file to be overwritten. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> /// <param name="overwrite">Whether to permit a destination file to be overwritten.</param> public override void MoveFile(string sourceName, string destinationName, bool overwrite) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (destinationName.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { destinationName = destinationName.Substring(1); } if (FileExists(Path.Combine(_basePath, destinationName))) { if (overwrite) { DeleteFile(Path.Combine(_basePath, destinationName)); } else { throw new IOException("File already exists"); } } if (sourceName.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { sourceName = sourceName.Substring(1); } File.Move(Path.Combine(_basePath, sourceName), Path.Combine(_basePath, destinationName)); } /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <returns>The new stream.</returns> public override SparseStream OpenFile(string path, FileMode mode) { return OpenFile(path, mode, FileAccess.ReadWrite); } /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <param name="access">The access permissions for the created stream.</param> /// <returns>The new stream.</returns> public override SparseStream OpenFile(string path, FileMode mode, FileAccess access) { if (_readOnly && access != FileAccess.Read) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } FileShare fileShare = FileShare.None; if (access == FileAccess.Read) { fileShare = FileShare.Read; } return SparseStream.FromStream(File.Open(Path.Combine(_basePath, path), mode, access, fileShare), Ownership.Dispose); } /// <summary> /// Gets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to inspect.</param> /// <returns>The attributes of the file or directory.</returns> public override FileAttributes GetAttributes(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return File.GetAttributes(Path.Combine(_basePath, path)); } /// <summary> /// Sets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to change.</param> /// <param name="newValue">The new attributes of the file or directory.</param> public override void SetAttributes(string path, FileAttributes newValue) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } File.SetAttributes(Path.Combine(_basePath, path), newValue); } /// <summary> /// Gets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> public override DateTime GetCreationTime(string path) { return GetCreationTimeUtc(path).ToLocalTime(); } /// <summary> /// Sets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetCreationTime(string path, DateTime newTime) { SetCreationTimeUtc(path, newTime.ToUniversalTime()); } /// <summary> /// Gets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> public override DateTime GetCreationTimeUtc(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return File.GetCreationTimeUtc(Path.Combine(_basePath, path)); } /// <summary> /// Sets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetCreationTimeUtc(string path, DateTime newTime) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } File.SetCreationTimeUtc(Path.Combine(_basePath, path), newTime); } /// <summary> /// Gets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last access time.</returns> public override DateTime GetLastAccessTime(string path) { return GetLastAccessTimeUtc(path).ToLocalTime(); } /// <summary> /// Sets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastAccessTime(string path, DateTime newTime) { SetLastAccessTimeUtc(path, newTime.ToUniversalTime()); } /// <summary> /// Gets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last access time.</returns> public override DateTime GetLastAccessTimeUtc(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return File.GetLastAccessTimeUtc(Path.Combine(_basePath, path)); } /// <summary> /// Sets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastAccessTimeUtc(string path, DateTime newTime) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } File.SetLastAccessTimeUtc(Path.Combine(_basePath, path), newTime); } /// <summary> /// Gets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last write time.</returns> public override DateTime GetLastWriteTime(string path) { return GetLastWriteTimeUtc(path).ToLocalTime(); } /// <summary> /// Sets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastWriteTime(string path, DateTime newTime) { SetLastWriteTimeUtc(path, newTime.ToUniversalTime()); } /// <summary> /// Gets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last write time.</returns> public override DateTime GetLastWriteTimeUtc(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return File.GetLastWriteTimeUtc(Path.Combine(_basePath, path)); } /// <summary> /// Sets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastWriteTimeUtc(string path, DateTime newTime) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } File.SetLastWriteTimeUtc(Path.Combine(_basePath, path), newTime); } /// <summary> /// Gets the length of a file. /// </summary> /// <param name="path">The path to the file.</param> /// <returns>The length in bytes.</returns> public override long GetFileLength(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return new FileInfo(Path.Combine(_basePath, path)).Length; } /// <summary> /// Gets an object representing a possible file. /// </summary> /// <param name="path">The file path.</param> /// <returns>The representing object.</returns> /// <remarks>The file does not need to exist.</remarks> public override DiscFileInfo GetFileInfo(string path) { return new DiscFileInfo(this, path); } /// <summary> /// Gets an object representing a possible directory. /// </summary> /// <param name="path">The directory path.</param> /// <returns>The representing object.</returns> /// <remarks>The directory does not need to exist.</remarks> public override DiscDirectoryInfo GetDirectoryInfo(string path) { return new DiscDirectoryInfo(this, path); } /// <summary> /// Gets an object representing a possible file system object (file or directory). /// </summary> /// <param name="path">The file system path.</param> /// <returns>The representing object.</returns> /// <remarks>The file system object does not need to exist.</remarks> public override DiscFileSystemInfo GetFileSystemInfo(string path) { return new DiscFileSystemInfo(this, path); } private string[] CleanItems(string[] dirtyItems) { string[] cleanList = new string[dirtyItems.Length]; for (int x = 0; x < dirtyItems.Length; x++) { cleanList[x] = dirtyItems[x].Substring(_basePath.Length - 1); } return cleanList; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Diagnostics; using System.Security.Cryptography; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Authentication { /// <summary> /// An opinionated abstraction for an <see cref="AuthenticationHandler{TOptions}"/> that performs authentication using a separately hosted /// provider. /// </summary> /// <typeparam name="TOptions">The type for the options used to configure the authentication handler.</typeparam> public abstract class RemoteAuthenticationHandler<TOptions> : AuthenticationHandler<TOptions>, IAuthenticationRequestHandler where TOptions : RemoteAuthenticationOptions, new() { private const string CorrelationProperty = ".xsrf"; private const string CorrelationMarker = "N"; private const string AuthSchemeKey = ".AuthScheme"; /// <summary> /// The authentication scheme used by default for signin. /// </summary> protected string? SignInScheme => Options.SignInScheme; /// <summary> /// The handler calls methods on the events which give the application control at certain points where processing is occurring. /// If it is not provided a default instance is supplied which does nothing when the methods are called. /// </summary> protected new RemoteAuthenticationEvents Events { get { return (RemoteAuthenticationEvents)base.Events!; } set { base.Events = value; } } /// <summary> /// Initializes a new instance of <see cref="RemoteAuthenticationHandler{TOptions}" />. /// </summary> /// <param name="options">The monitor for the options instance.</param> /// <param name="logger">The <see cref="ILoggerFactory"/>.</param> /// <param name="encoder">The <see cref="UrlEncoder"/>.</param> /// <param name="clock">The <see cref="ISystemClock"/>.</param> protected RemoteAuthenticationHandler(IOptionsMonitor<TOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) { } /// <inheritdoc /> protected override Task<object> CreateEventsAsync() => Task.FromResult<object>(new RemoteAuthenticationEvents()); /// <summary> /// Gets a value that determines if the current authentication request should be handled by <see cref="HandleRequestAsync" />. /// </summary> /// <returns><see langword="true"/> to handle the operation, otherwise <see langword="false"/>.</returns> public virtual Task<bool> ShouldHandleRequestAsync() => Task.FromResult(Options.CallbackPath == Request.Path); /// <summary> /// Handles the current authentication request. /// </summary> /// <returns><see langword="true"/> if authentication was handled, otherwise <see langword="false"/>.</returns> public virtual async Task<bool> HandleRequestAsync() { if (!await ShouldHandleRequestAsync()) { return false; } AuthenticationTicket? ticket = null; Exception? exception = null; AuthenticationProperties? properties = null; try { var authResult = await HandleRemoteAuthenticateAsync(); if (authResult == null) { exception = new InvalidOperationException("Invalid return state, unable to redirect."); } else if (authResult.Handled) { return true; } else if (authResult.Skipped || authResult.None) { return false; } else if (!authResult.Succeeded) { exception = authResult.Failure ?? new InvalidOperationException("Invalid return state, unable to redirect."); properties = authResult.Properties; } ticket = authResult?.Ticket; } catch (Exception ex) { exception = ex; } if (exception != null) { Logger.RemoteAuthenticationError(exception.Message); var errorContext = new RemoteFailureContext(Context, Scheme, Options, exception) { Properties = properties }; await Events.RemoteFailure(errorContext); if (errorContext.Result != null) { if (errorContext.Result.Handled) { return true; } else if (errorContext.Result.Skipped) { return false; } else if (errorContext.Result.Failure != null) { throw new Exception("An error was returned from the RemoteFailure event.", errorContext.Result.Failure); } } if (errorContext.Failure != null) { throw new Exception("An error was encountered while handling the remote login.", errorContext.Failure); } } // We have a ticket if we get here Debug.Assert(ticket != null); var ticketContext = new TicketReceivedContext(Context, Scheme, Options, ticket) { ReturnUri = ticket.Properties.RedirectUri }; ticket.Properties.RedirectUri = null; // Mark which provider produced this identity so we can cross-check later in HandleAuthenticateAsync ticketContext.Properties!.Items[AuthSchemeKey] = Scheme.Name; await Events.TicketReceived(ticketContext); if (ticketContext.Result != null) { if (ticketContext.Result.Handled) { Logger.SignInHandled(); return true; } else if (ticketContext.Result.Skipped) { Logger.SignInSkipped(); return false; } } await Context.SignInAsync(SignInScheme, ticketContext.Principal!, ticketContext.Properties); // Default redirect path is the base path if (string.IsNullOrEmpty(ticketContext.ReturnUri)) { ticketContext.ReturnUri = "/"; } Response.Redirect(ticketContext.ReturnUri); return true; } /// <summary> /// Authenticate the user identity with the identity provider. /// /// The method process the request on the endpoint defined by CallbackPath. /// </summary> protected abstract Task<HandleRequestResult> HandleRemoteAuthenticateAsync(); /// <inheritdoc /> protected override async Task<AuthenticateResult> HandleAuthenticateAsync() { var result = await Context.AuthenticateAsync(SignInScheme); if (result != null) { if (result.Failure != null) { return result; } // The SignInScheme may be shared with multiple providers, make sure this provider issued the identity. var ticket = result.Ticket; if (ticket != null && ticket.Principal != null && ticket.Properties != null && ticket.Properties.Items.TryGetValue(AuthSchemeKey, out var authenticatedScheme) && string.Equals(Scheme.Name, authenticatedScheme, StringComparison.Ordinal)) { return AuthenticateResult.Success(new AuthenticationTicket(ticket.Principal, ticket.Properties, Scheme.Name)); } return AuthenticateResult.Fail("Not authenticated"); } return AuthenticateResult.Fail("Remote authentication does not directly support AuthenticateAsync"); } /// <inheritdoc /> protected override Task HandleForbiddenAsync(AuthenticationProperties properties) => Context.ForbidAsync(SignInScheme); /// <summary> /// Produces a cookie containing a nonce used to correlate the current remote authentication request. /// </summary> /// <param name="properties"></param> protected virtual void GenerateCorrelationId(AuthenticationProperties properties) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } var bytes = new byte[32]; RandomNumberGenerator.Fill(bytes); var correlationId = Base64UrlTextEncoder.Encode(bytes); var cookieOptions = Options.CorrelationCookie.Build(Context, Clock.UtcNow); properties.Items[CorrelationProperty] = correlationId; var cookieName = Options.CorrelationCookie.Name + correlationId; Response.Cookies.Append(cookieName, CorrelationMarker, cookieOptions); } /// <summary> /// Validates that the current request correlates with the current remote authentication request. /// </summary> /// <param name="properties"></param> /// <returns></returns> protected virtual bool ValidateCorrelationId(AuthenticationProperties properties) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } if (!properties.Items.TryGetValue(CorrelationProperty, out var correlationId)) { Logger.CorrelationPropertyNotFound(Options.CorrelationCookie.Name!); return false; } properties.Items.Remove(CorrelationProperty); var cookieName = Options.CorrelationCookie.Name + correlationId; var correlationCookie = Request.Cookies[cookieName]; if (string.IsNullOrEmpty(correlationCookie)) { Logger.CorrelationCookieNotFound(cookieName); return false; } var cookieOptions = Options.CorrelationCookie.Build(Context, Clock.UtcNow); Response.Cookies.Delete(cookieName, cookieOptions); if (!string.Equals(correlationCookie, CorrelationMarker, StringComparison.Ordinal)) { Logger.UnexpectedCorrelationCookieValue(cookieName, correlationCookie); return false; } return true; } /// <summary> /// Derived types may override this method to handle access denied errors. /// </summary> /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param> /// <returns>The <see cref="HandleRequestResult"/>.</returns> protected virtual async Task<HandleRequestResult> HandleAccessDeniedErrorAsync(AuthenticationProperties properties) { Logger.AccessDeniedError(); var context = new AccessDeniedContext(Context, Scheme, Options) { AccessDeniedPath = Options.AccessDeniedPath, Properties = properties, ReturnUrl = properties?.RedirectUri, ReturnUrlParameter = Options.ReturnUrlParameter }; await Events.AccessDenied(context); if (context.Result != null) { if (context.Result.Handled) { Logger.AccessDeniedContextHandled(); } else if (context.Result.Skipped) { Logger.AccessDeniedContextSkipped(); } return context.Result; } // If an access denied endpoint was specified, redirect the user agent. // Otherwise, invoke the RemoteFailure event for further processing. if (context.AccessDeniedPath.HasValue) { string uri = context.AccessDeniedPath; if (!string.IsNullOrEmpty(context.ReturnUrlParameter) && !string.IsNullOrEmpty(context.ReturnUrl)) { uri = QueryHelpers.AddQueryString(uri, context.ReturnUrlParameter, context.ReturnUrl); } Response.Redirect(BuildRedirectUri(uri)); return HandleRequestResult.Handle(); } return HandleRequestResult.NoResult(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; using GenStrings; namespace System.Collections.Specialized.Tests { public class AddStrStrTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { IntlStrings intl; NameValueCollection nvc; // simple string values string[] values = { "", " ", "a", "aA", "text", " SPaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "oNe", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; // Count // initialize IntStrings intl = new IntlStrings(); // [] NameValueCollection is constructed as expected //----------------------------------------------------------------- nvc = new NameValueCollection(); // [] add simple strings // for (int i = 0; i < values.Length; i++) { cnt = nvc.Count; nvc.Add(keys[i], values[i]); if (nvc.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1)); } // verify that collection contains newly added item // if (Array.IndexOf(nvc.AllKeys, keys[i]) < 0) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // access the item // if (String.Compare(nvc[keys[i]], values[i]) != 0) { Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[keys[i]], values[i])); } } // // Intl strings // [] add Intl strings // int len = values.Length; string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant()) caseInsensitive = true; } // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = nvc.Count; nvc.Add(intlValues[i + len], intlValues[i]); if (nvc.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1)); } // verify that collection contains newly added item // if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // access the item // if (String.Compare(nvc[intlValues[i + len]], intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i])); } } // // [] Case sensitivity // Casing doesn't change ( keya are not converted to lower!) // string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpperInvariant(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLowerInvariant(); } nvc.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = nvc.Count; nvc.Add(intlValues[i + len], intlValues[i]); if (nvc.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1)); } // verify that collection contains newly added uppercase item // if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // access the item // if (String.Compare(nvc[intlValues[i + len]], intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i])); } // verify that collection doesn't contains lowercase item // if (!caseInsensitive && String.Compare(nvc[intlValuesLower[i + len]], intlValuesLower[i]) == 0) { Assert.False(true, string.Format("Error, returned item \"{1}\" is lowercase after adding uppercase", i, nvc[intlValuesLower[i + len]])); } // key is not converted to lower if (!caseInsensitive && Array.IndexOf(nvc.AllKeys, intlValuesLower[i + len]) >= 0) { Assert.False(true, string.Format("Error, key was converted to lower", i)); } // but search among keys is case-insensitive if (String.Compare(nvc[intlValuesLower[i + len]], intlValues[i]) != 0) { Assert.False(true, string.Format("Error, could not find item using differently cased key", i)); } } // // [] Add multiple values with the same key // nvc.Clear(); len = values.Length; string k = "keykey"; for (int i = 0; i < len; i++) { nvc.Add(k, "Value" + i); } if (nvc.Count != 1) { Assert.False(true, string.Format("Error, count is {0} instead of 1}", nvc.Count)); } if (nvc.AllKeys.Length != 1) { Assert.False(true, "Error, should contain only 1 key"); } // verify that collection contains newly added item // if (Array.IndexOf(nvc.AllKeys, k) < 0) { Assert.False(true, "Error, collection doesn't contain key of new item"); } // access the item // string[] vals = nvc.GetValues(k); if (vals.Length != len) { Assert.False(true, string.Format("Error, number of values at given key is {0} instead of {1}", vals.Length, len)); } for (int i = 0; i < len; i++) { if (Array.IndexOf(vals, "Value" + i) < 0) { Assert.False(true, string.Format("Error, doesn't contain {1}", i, "Value" + i)); } } // // [] Add null value // cnt = nvc.Count; k = "kk"; nvc.Add(k, null); if (nvc.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1)); } if (Array.IndexOf(nvc.AllKeys, k) < 0) { Assert.False(true, "Error, collection doesn't contain key of new item"); } // verify that collection contains null // if (nvc[k] != null) { Assert.False(true, "Error, returned non-null on place of null"); } // // [] Add item with null key // Add item with null key - NullReferenceException expected // cnt = nvc.Count; nvc.Add(null, "item"); if (nvc.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1)); } if (Array.IndexOf(nvc.AllKeys, null) < 0) { Assert.False(true, "Error, collection doesn't contain null key "); } // verify that collection contains null // if (nvc[null] != "item") { Assert.False(true, "Error, returned wrong value at null key"); } } } }
//#define GSOLVER_LOG #define DO_PREPROPAGATION using System; using AutoDiff; using AD=AutoDiff; using System.IO; using System.Text; using Castor; using System.Collections.Generic; using Alica.Reasoner.IntervalPropagation; namespace Alica.Reasoner { public class CNSMTGSolver { protected class RpropResult : IComparable<RpropResult> { public double[] initialValue; public double[] finalValue; public double initialUtil; public double finalUtil; public bool aborted; public int CompareTo (RpropResult other) { return (this.finalUtil > other.finalUtil)?-1:1; } } public int Runs {get { return this.runCount;}} public int FEvals {get {return this.fevalsCount;}} double initialStepSize = 0.005; double utilitySignificanceThreshold = 1E-22; Random rand; int dim; double[,] limits; double[] ranges; double[] rpropStepWidth; double[] rpropStepConvergenceThreshold; public double RPropConvergenceStepSize {get; private set;} //AD.ICompiledTerm term; AD.Variable[] currentArgs; //Dictionary<int,AD.Term> currentAtoms; StreamWriter sw; static CNSMTGSolver instance=null; List<RpropResult> rResults; protected static int fcounter =0; //Configuration: protected bool seedWithUtilOptimum; protected CNSAT.CNSat ss; protected CNSAT.FormulaTransform ft; protected IntervalPropagator ip; protected double[] lastSeed; protected RpropResult r1=null; protected int probeCount = 0; protected int successProbeCount =0; protected int intervalCount = 0; protected int successIntervalCount =0; protected int fevalsCount = 0; protected int runCount = 0; public ulong maxSolveTime; public ulong begin; public long MaxFEvals {get; set;} public bool UseIntervalProp{get; set;} public bool Optimize{get;set;} public CNSMTGSolver () { AD.Term.SetAnd(AD.Term.AndType.and); AD.Term.SetOr(AD.Term.OrType.max); this.rand = new Random(); this.rResults = new List<RpropResult>(); //this.seedWithUtilOptimum = true; this.ft = new CNSAT.FormulaTransform(); this.ip = new IntervalPropagator(); instance = this; this.MaxFEvals = SystemConfig.LocalInstance["Alica"].GetInt("Alica","CSPSolving","MaxFunctionEvaluations"); this.maxSolveTime = ((ulong)SystemConfig.LocalInstance["Alica"].GetInt("Alica","CSPSolving","MaxSolveTime"))*1000000; //RPropConvergenceStepSize = 1E-2; RPropConvergenceStepSize = 0; UseIntervalProp = true; Optimize = false; } protected void InitLog() { string logFile = "/tmp/test"+(fcounter++)+".dbg"; FileStream file = new FileStream(logFile, FileMode.Create); this.sw = new StreamWriter(file); sw.AutoFlush = true; } protected void Log(double util, double[] val) { sw.Write(util); sw.Write("\t"); for(int i=0; i <dim; i++) { sw.Write(val[i]); sw.Write("\t"); } sw.WriteLine(); } protected void LogStep() { sw.WriteLine(); sw.WriteLine(); } protected void CloseLog() { if (sw != null) { sw.Close(); sw=null; } } public double[] Solve(AD.Term equation, AD.Variable[] args, double[,] limits, out double util) { return Solve(equation, args, limits, null, out util); } public double[] Solve(AD.Term equation, AD.Variable[] args, double[,] limits, double[][] seeds, out double util) { lastSeed=null; probeCount = 0; successProbeCount = 0; intervalCount = 0; successIntervalCount = 0; fevalsCount = 0; runCount = 0; this.begin = RosCS.RosSharp.Now(); //this.FEvals = 0; util = 0; #if (GSOLVER_LOG) InitLog(); #endif //ft.Reset(); rResults.Clear(); currentArgs = args; this.dim = args.Length; this.limits = limits; this.ranges = new double[dim]; this.rpropStepWidth = new double[dim]; this.rpropStepConvergenceThreshold = new double[dim]; equation = equation.AggregateConstants(); AD.ConstraintUtility cu = (AD.ConstraintUtility) equation; bool utilIsConstant =(cu.Utility is AD.Constant); bool constraintIsConstant = (cu.Constraint is AD.Constant); if (constraintIsConstant) { if(((AD.Constant)cu.Constraint).Value < 0.25) { util = ((AD.Constant)cu.Constraint).Value; double[] ret = new double[dim]; for(int i=0; i<dim; i++) { ret[i] = (this.limits[i,1]+this.limits[i,0])/2.0; //this.ranges[i]/2.0+this.limits[i,0]; } return ret; } } ss = new CNSAT.CNSat(); ss.UseIntervalProp = this.UseIntervalProp; //Console.WriteLine(cu.Constraint); LinkedList<CNSAT.Clause> cnf = ft.TransformToCNF(cu.Constraint,ss); /*Console.WriteLine("Atoms: {0}, Occurrence: {1}",ft.Atoms.Count,ft.AtomOccurrence); Console.WriteLine("Clauses: {0}",cnf.Count); foreach(AD.Term atom in ft.Atoms.Keys) { Console.WriteLine("-------"); Console.WriteLine(atom); Console.WriteLine("-------"); }*/ /* int litc=1; List<AD.Term> terms = new List<AD.Term>(ft.Atoms); currentAtoms = new Dictionary<int, Term>(); foreach(AD.Term t in terms) { foreach(Literal l in ft.References[t]) { l.Id = litc; } currentAtoms.Add(litc,t); litc++; }*/ if(UseIntervalProp) { ip.SetGlobalRanges(args, limits,ss); } foreach(CNSAT.Clause c in cnf) { if(!c.IsTautologic) { if (c.Literals.Count == 0) { util = Double.MinValue; double[] ret = new double[dim]; for(int i=0; i<dim; i++) { ret[i] = (this.limits[i,1]+this.limits[i,0])/2.0; } return ret; } //Post Clause Here //Console.Write("\nAdding Clause with "+c.Literals.Count+" Literals\n"); //c.Print(); ss.addBasicClause(c); } } ss.CNSMTGSolver = this; ss.Init(); //PRE-Propagation: if(UseIntervalProp) { #if DO_PREPROPAGATION if(!ip.PrePropagate(ss.Variables)) { Console.WriteLine("Unsatisfiable (unit propagation)"); return null; } #endif } //END-PrePropagation //Console.WriteLine("Variable Count: " + ss.Variables.Count); bool solutionFound = false; ss.UnitDecissions = ss.Decisions.Count; do { if(!solutionFound) { ss.EmptySATClause(); ss.EmptyTClause(); ss.backTrack(ss.UnitDecissions); } solutionFound = ss.solve(); if(Optimize) r1 = RPropOptimizeFeasible(ss.Decisions, ((AD.ConstraintUtility)equation).Utility, args, r1.finalValue, false); if(!solutionFound && r1.finalUtil > 0) r1.finalUtil=-1; util = r1.finalUtil; if(!Optimize && solutionFound) return r1.finalValue; else if(Optimize) { //optimization case rResults.Add(r1); CNSAT.Clause c = new Alica.Reasoner.CNSAT.Clause(); foreach(CNSAT.Var v in ss.Decisions) { c.Add(new CNSAT.Lit(v, v.Assignment==CNSAT.Assignment.True ? CNSAT.Assignment.False : CNSAT.Assignment.True)); } //ss.addBasicClause(c); ss.addIClause(c); ss.backTrack(ss.Decisions[ss.Decisions.Count-1].DecisionLevel); solutionFound = false; } } while (!solutionFound && this.begin + this.maxSolveTime > RosCS.RosSharp.Now() /*&& this.runCount < this.MaxFEvals*/); //Console.WriteLine("Probes: {0}/{1}\tIntervals: {2}/{3}",successProbeCount,probeCount,successIntervalCount,intervalCount); //ip.PrintStats(); //Console.WriteLine("Rprop Runs: {0}\t FEvals {1}\t Solutions Found: {2}",this.runCount,this.fevalsCount, rResults.Count); //return best result if(rResults.Count>0) { foreach(RpropResult rp in rResults) { if(rp.finalUtil>util) { util = rp.finalUtil; r1 = rp; } } return r1.finalValue; } Console.WriteLine("Unsatisfiable"); return null; } //Stripped down method for simpler testing public double[] SolveTest(AD.Term equation, AD.Variable[] args, double[,] limits) { lastSeed = null; probeCount = 0; successProbeCount = 0; intervalCount = 0; successIntervalCount = 0; fevalsCount = 0; runCount = 0; //this.FEvals = 0; double util = 0; this.begin = RosCS.RosSharp.Now(); #if (GSOLVER_LOG) InitLog(); #endif //ft.Reset(); rResults.Clear(); currentArgs = args; this.dim = args.Length; this.limits = limits; this.ranges = new double[dim]; this.rpropStepWidth = new double[dim]; this.rpropStepConvergenceThreshold = new double[dim]; equation = equation.AggregateConstants(); ss = new CNSAT.CNSat(); ss.UseIntervalProp = this.UseIntervalProp; //Console.WriteLine(cu.Constraint); LinkedList<CNSAT.Clause> cnf = ft.TransformToCNF(equation,ss); /*Console.WriteLine("Atoms: {0}, Occurrence: {1}",ft.Atoms.Count,ft.AtomOccurrence); Console.WriteLine("Clauses: {0}",cnf.Count); foreach(AD.Term atom in ft.Atoms.Keys) { Console.WriteLine("-------"); Console.WriteLine(atom); Console.WriteLine("-------"); }*/ /* int litc=1; List<AD.Term> terms = new List<AD.Term>(ft.Atoms); currentAtoms = new Dictionary<int, Term>(); foreach(AD.Term t in terms) { foreach(Literal l in ft.References[t]) { l.Id = litc; } currentAtoms.Add(litc,t); litc++; }*/ ip.SetGlobalRanges(args, limits,ss); foreach(CNSAT.Clause c in cnf) { if(!c.IsTautologic) { if (c.Literals.Count == 0) { util = Double.MinValue; double[] ret = new double[dim]; for(int i=0; i<dim; i++) { ret[i] = (this.limits[i,1]+this.limits[i,0])/2.0; } return ret; } //Post Clause Here //Console.Write("\nAdding Clause with "+c.Literals.Count+" Literals\n"); //c.Print(); ss.addBasicClause(c); } } ss.CNSMTGSolver = this; ss.Init(); //PRE-Propagation: #if DO_PREPROPAGATION if(!ip.PrePropagate(ss.Variables)) { Console.WriteLine("Unsatisfiable (unit propagation)"); //return null; } #endif //END-PrePropagation //Console.WriteLine("Variable Count: " + ss.Variables.Count); bool solutionFound = false; solutionFound = ss.solve(); //Console.WriteLine("Solution Found!!!!!"); if(!solutionFound && r1.finalUtil > 0) r1.finalUtil=-1; util = r1.finalUtil; //if(util>this.utilitySignificanceThreshold) return r1.finalValue; return r1.finalValue; } public bool IntervalPropagate(List<CNSAT.Var> decisions, out double[,] curRanges) { intervalCount++; /*Console.Write("SAT proposed({0}): ", decisions.Count); foreach(CNSAT.Var v in decisions) { v.Print(); Console.Write(" "); } Console.WriteLine(); */ //double[,] curRanges=null; List<CNSAT.Var> offending=null; if(!ip.Propagate(decisions,out curRanges,out offending)) { /*Console.WriteLine("Propagation FAILED offenders are:"); foreach(CNSAT.Var v in offending) { //Console.WriteLine(v + "\t"+(v.Assignment==CNSAT.Assignment.True?v.Term:v.Term.Negate())); Console.Write(v + " "); } Console.WriteLine();*/ if(offending!=null) { CNSAT.Clause learnt = new CNSAT.Clause(); foreach(CNSAT.Var v in offending) { learnt.Add(new CNSAT.Lit(v, v.Assignment==CNSAT.Assignment.True ? CNSAT.Assignment.False : CNSAT.Assignment.True)); } //if(learnt.Literals.Count>0) { ss.addIClause(learnt); //} } return false; } //Console.WriteLine("Propagation succeeded"); this.limits = curRanges; successIntervalCount++; return true; } public bool ProbeForSolution(List<CNSAT.Var> decisions, out double[] solution) { probeCount++; /*Console.Write("SAT proposed({0}): ", decisions.Count); foreach(CNSAT.Var v in decisions) { v.Print(); Console.Write(" "); } Console.WriteLine();*/ solution=null; for(int i=0; i<dim; i++) { // Console.WriteLine("[{0}..{1}]",this.limits[i,0],this.limits[i,1]); this.ranges[i] = (this.limits[i,1]-this.limits[i,0]); } for(int i=0; i<decisions.Count; i++) { decisions[i].CurTerm = (decisions[i].Assignment==CNSAT.Assignment.True?decisions[i].PositiveTerm:decisions[i].NegativeTerm); } //int idx = Math.Max(0,ss.DecisionLevel.Count-1); //r1 = RPropFindFeasible(decisions, ss.DecisionLevel[idx].Seed); r1 = RPropFindFeasible(decisions, lastSeed); if (r1.finalUtil < 0.5) r1 = RPropFindFeasible(decisions, null); if(r1.finalUtil < 0.5) { //Probe was not successfull -> assignment not valid //Console.Write("."); //Console.WriteLine("Could not find point for {0}",constraint); CNSAT.Clause learnt = new CNSAT.Clause(); foreach(CNSAT.Var v in decisions) { learnt.Add(new CNSAT.Lit(v,v.Assignment==CNSAT.Assignment.True ? CNSAT.Assignment.False : CNSAT.Assignment.True)); } ss.addTClause(learnt); return false; } //ss.DecisionLevel[ss.DecisionLevel.Count-1].Seed = r1.finalValue; lastSeed = r1.finalValue; solution = r1.finalValue; successProbeCount++; return true; } protected RpropResult RPropFindFeasible(List<CNSAT.Var> constraints, double[] seed) { runCount++; InitialStepSize(); double[] curGradient; RpropResult ret = new RpropResult(); // curGradient = InitialPoint(constraints, ret); if(seed != null) { curGradient = InitialPointFromSeed(constraints, ret, seed); } else { curGradient = InitialPoint(constraints, ret); } double curUtil = ret.initialUtil; if (curUtil > 0.5) { return ret; } double[] formerGradient = new double[dim]; double[] curValue = new double[dim]; //Tuple<double[],double> tup; Buffer.BlockCopy(ret.initialValue,0,curValue,0,sizeof(double)*dim); formerGradient = curGradient; int itcounter = 0; int badcounter = 0; #if (GSOLVER_LOG) Log(curUtil,curValue); #endif int maxIter = 60; int maxBad = 30; double minStep = 1E-11; while(itcounter++ < maxIter && badcounter < maxBad) { for(int i=0; i<dim; i++) { if (curGradient[i] * formerGradient[i] > 0) rpropStepWidth[i] *= 1.3; else if (curGradient[i] * formerGradient[i] < 0) rpropStepWidth[i] *= 0.5; rpropStepWidth[i] = Math.Max(minStep,rpropStepWidth[i]); if (curGradient[i] > 0) curValue[i] += rpropStepWidth[i]; else if (curGradient[i] < 0) curValue[i] -= rpropStepWidth[i]; if (curValue[i] > limits[i,1]) curValue[i] = limits[i,1]; else if (curValue[i] < limits[i,0]) curValue[i] = limits[i,0]; } this.fevalsCount++; formerGradient = curGradient; Differentiate(constraints,curValue,out curGradient,out curUtil); bool allZero = true; for(int i=0; i < dim; i++) { if (Double.IsNaN(curGradient[i])) { //Console.Error.WriteLine("NaN in gradient, aborting!"); ret.aborted=true; #if (GSOLVER_LOG) LogStep(); #endif return ret; } allZero &= (curGradient[i]==0); } #if (GSOLVER_LOG) Log(curUtil,curValue); #endif //Console.WriteLine("CurUtil: {0} Final {1}",curUtil,ret.finalUtil); if (curUtil > ret.finalUtil) { badcounter = 0;//Math.Max(0,badcounter-1); ret.finalUtil = curUtil; Buffer.BlockCopy(curValue,0,ret.finalValue,0,sizeof(double)*dim); //ret.finalValue = curValue; if (curUtil > 0.75) return ret; } else { badcounter++; } if (allZero) { ret.aborted = false; #if (GSOLVER_LOG) LogStep(); #endif return ret; } } #if (GSOLVER_LOG) LogStep(); #endif ret.aborted = false; return ret; } protected RpropResult RPropOptimizeFeasible(List<CNSAT.Var> constraints, AD.Term ut, AD.Variable[] args, double[] seed, bool precise) { //Compiled Term zusammenbauen AD.Term constr = AD.Term.True; foreach(CNSAT.Var v in constraints) { if(v.Assignment == Alica.Reasoner.CNSAT.Assignment.True) constr &= v.Term; else constr &= ConstraintBuilder.Not(v.Term); } AD.ConstraintUtility cu = new AD.ConstraintUtility(constr, ut); AD.ICompiledTerm term = AD.TermUtils.Compile(cu, args); Tuple<double[],double> tup; //fertig zusammengebaut runCount++; InitialStepSize(); double[] curGradient; RpropResult ret = new RpropResult(); // curGradient = InitialPoint(constraints, ret); if(seed != null) { curGradient = InitialPointFromSeed(constraints, ret, seed); } else { curGradient = InitialPoint(constraints, ret); } double curUtil = ret.initialUtil; double[] formerGradient = new double[dim]; double[] curValue = new double[dim]; //Tuple<double[],double> tup; Buffer.BlockCopy(ret.initialValue,0,curValue,0,sizeof(double)*dim); formerGradient = curGradient; int itcounter = 0; int badcounter = 0; #if (GSOLVER_LOG) Log(curUtil,curValue); #endif int maxIter = 60; int maxBad = 30; double minStep = 1E-11; if(precise) { maxIter = 120; //110 maxBad = 60; //60 minStep = 1E-15;//15 } int convergendDims = 0; while(itcounter++ < maxIter && badcounter < maxBad) { convergendDims = 0; for(int i=0; i<dim; i++) { if (curGradient[i] * formerGradient[i] > 0) rpropStepWidth[i] *= 1.3; else if (curGradient[i] * formerGradient[i] < 0) rpropStepWidth[i] *= 0.5; rpropStepWidth[i] = Math.Max(minStep,rpropStepWidth[i]); //rpropStepWidth[i] = Math.Max(0.000001,rpropStepWidth[i]); if (curGradient[i] > 0) curValue[i] += rpropStepWidth[i]; else if (curGradient[i] < 0) curValue[i] -= rpropStepWidth[i]; if (curValue[i] > limits[i,1]) curValue[i] = limits[i,1]; else if (curValue[i] < limits[i,0]) curValue[i] = limits[i,0]; //Console.Write("{0}\t",curValue[i]); if(rpropStepWidth[i] < rpropStepConvergenceThreshold[i]) { ++convergendDims; } } //Abort if all dimensions are converged if(!precise && convergendDims>=dim) { return ret; } this.fevalsCount++; formerGradient = curGradient; tup = term.Differentiate(curValue); bool allZero = true; for(int i=0; i < dim; i++) { if (Double.IsNaN(tup.Item1[i])) { ret.aborted=false;//true; //HACK! #if (GSOLVER_LOG) LogStep(); #endif return ret; } allZero &= (tup.Item1[i]==0); } curUtil = tup.Item2; formerGradient = curGradient; curGradient = tup.Item1; #if (GSOLVER_LOG) Log(curUtil,curValue); #endif //Console.WriteLine("CurUtil: {0} Final {1}",curUtil,ret.finalUtil); if (curUtil > ret.finalUtil) { badcounter = 0;//Math.Max(0,badcounter-1); ret.finalUtil = curUtil; Buffer.BlockCopy(curValue,0,ret.finalValue,0,sizeof(double)*dim); //ret.finalValue = curValue; if (curUtil > 0.75) return ret; } else { badcounter++; } if (allZero) { ret.aborted = false; #if (GSOLVER_LOG) LogStep(); #endif return ret; } } #if (GSOLVER_LOG) LogStep(); #endif ret.aborted = false; return ret; } protected void Differentiate(List<CNSAT.Var> constraints,double[] val,out double[] gradient, out double util) { Tuple<double[],double> t1 = constraints[0].CurTerm.Differentiate(val); gradient = t1.Item1; util = t1.Item2; for(int i=1; i<constraints.Count; i++) { Tuple<double[],double> tup = constraints[i].CurTerm.Differentiate(val); if(tup.Item2 <=0) { if(util > 0) util=tup.Item2; else util += tup.Item2; for(int j=0; j<dim; j++) { gradient[j] += tup.Item1[j]; } } } //return new Tuple<double[], double>(gradient,util); } protected double[] InitialPointFromSeed(List<CNSAT.Var> constraints, RpropResult res, double[] seed) { Tuple<double[],double> tup; bool found = true; res.initialValue = new double[dim]; res.finalValue = new double[dim]; double[] gradient; do { gradient = new double[dim]; found = true; res.initialUtil = 1; for(int i=0; i<dim; i++) { if (Double.IsNaN(seed[i])) { res.initialValue[i] = rand.NextDouble()*ranges[i]+limits[i,0]; } else { res.initialValue[i] = Math.Min(Math.Max(seed[i],limits[i,0]),limits[i,1]); } } //why this? this.fevalsCount++; for(int i=0; i<constraints.Count; i++) { if(constraints[i].Assignment == CNSAT.Assignment.True) { if (constraints[i].PositiveTerm == null) constraints[i].PositiveTerm = TermUtils.Compile(constraints[i].Term,this.currentArgs); constraints[i].CurTerm = constraints[i].PositiveTerm; } else { if(constraints[i].NegativeTerm == null) constraints[i].NegativeTerm = TermUtils.Compile(constraints[i].Term.Negate(),this.currentArgs); constraints[i].CurTerm = constraints[i].NegativeTerm; } tup = constraints[i].CurTerm.Differentiate(res.initialValue); for(int j=0; j<dim; j++) { if (Double.IsNaN(tup.Item1[j])) { found = false; break; } gradient[j] += tup.Item1[j]; } if(!found) break; if(tup.Item2 <= 0.0) { if (res.initialUtil > 0.0) res.initialUtil = tup.Item2; else res.initialUtil += tup.Item2; } } //tup = term.Differentiate(res.initialValue); } while(!found); res.finalUtil = res.initialUtil; Buffer.BlockCopy(res.initialValue,0,res.finalValue,0,sizeof(double)*dim); return gradient; } protected double[] InitialPoint(List<CNSAT.Var> constraints,RpropResult res) { Tuple<double[],double> tup; bool found = true; res.initialValue = new double[dim]; res.finalValue = new double[dim]; double[] gradient; do { gradient = new double[dim]; found = true; res.initialUtil = 1; for(int i=0; i<dim; i++) { res.initialValue[i] = rand.NextDouble()*ranges[i]+limits[i,0]; } this.fevalsCount++; for(int i=0; i<constraints.Count; i++) { if(constraints[i].Assignment == CNSAT.Assignment.True) { if (constraints[i].PositiveTerm == null) constraints[i].PositiveTerm = TermUtils.Compile(constraints[i].Term,this.currentArgs); constraints[i].CurTerm = constraints[i].PositiveTerm; } else { if(constraints[i].NegativeTerm == null) constraints[i].NegativeTerm = TermUtils.Compile(constraints[i].Term.Negate(),this.currentArgs); constraints[i].CurTerm = constraints[i].NegativeTerm; } tup = constraints[i].CurTerm.Differentiate(res.initialValue); for(int j=0; j<dim; j++) { if (Double.IsNaN(tup.Item1[j])) { found = false; break; } gradient[j] += tup.Item1[j]; } if(!found) break; if(tup.Item2 <= 0.0) { if (res.initialUtil > 0.0) res.initialUtil = tup.Item2; else res.initialUtil += tup.Item2; } } //tup = term.Differentiate(res.initialValue); } while(!found); res.finalUtil = res.initialUtil; Buffer.BlockCopy(res.initialValue,0,res.finalValue,0,sizeof(double)*dim); return gradient; } protected void InitialStepSize() { for(int i=0; i<this.dim; i++) { this.rpropStepWidth[i] = initialStepSize*ranges[i]; this.rpropStepConvergenceThreshold[i] = rpropStepWidth[i]*this.RPropConvergenceStepSize; } } public bool CurrentCacheConsistent() { if (this.lastSeed == null) return false; for(int i = dim-1; i>=0; --i) { if(this.lastSeed[i] < this.limits[i,0]) return false; if(this.lastSeed[i] > this.limits[i,1]) return false; } return true; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Group Membership Eligibility Criteria Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SGSGDataSet : EduHubDataSet<SGSG> { /// <inheritdoc /> public override string Name { get { return "SGSG"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SGSGDataSet(EduHubContext Context) : base(Context) { Index_SGLINK = new Lazy<NullDictionary<string, IReadOnlyList<SGSG>>>(() => this.ToGroupedNullDictionary(i => i.SGLINK)); Index_SGSGKEY = new Lazy<Dictionary<string, IReadOnlyList<SGSG>>>(() => this.ToGroupedDictionary(i => i.SGSGKEY)); Index_TID = new Lazy<Dictionary<int, SGSG>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SGSG" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SGSG" /> fields for each CSV column header</returns> internal override Action<SGSG, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SGSG, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "SGSGKEY": mapper[i] = (e, v) => e.SGSGKEY = v; break; case "SGLINK": mapper[i] = (e, v) => e.SGLINK = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SGSG" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SGSG" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SGSG" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SGSG}"/> of entities</returns> internal override IEnumerable<SGSG> ApplyDeltaEntities(IEnumerable<SGSG> Entities, List<SGSG> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.SGSGKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.SGSGKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<SGSG>>> Index_SGLINK; private Lazy<Dictionary<string, IReadOnlyList<SGSG>>> Index_SGSGKEY; private Lazy<Dictionary<int, SGSG>> Index_TID; #endregion #region Index Methods /// <summary> /// Find SGSG by SGLINK field /// </summary> /// <param name="SGLINK">SGLINK value used to find SGSG</param> /// <returns>List of related SGSG entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SGSG> FindBySGLINK(string SGLINK) { return Index_SGLINK.Value[SGLINK]; } /// <summary> /// Attempt to find SGSG by SGLINK field /// </summary> /// <param name="SGLINK">SGLINK value used to find SGSG</param> /// <param name="Value">List of related SGSG entities</param> /// <returns>True if the list of related SGSG entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySGLINK(string SGLINK, out IReadOnlyList<SGSG> Value) { return Index_SGLINK.Value.TryGetValue(SGLINK, out Value); } /// <summary> /// Attempt to find SGSG by SGLINK field /// </summary> /// <param name="SGLINK">SGLINK value used to find SGSG</param> /// <returns>List of related SGSG entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SGSG> TryFindBySGLINK(string SGLINK) { IReadOnlyList<SGSG> value; if (Index_SGLINK.Value.TryGetValue(SGLINK, out value)) { return value; } else { return null; } } /// <summary> /// Find SGSG by SGSGKEY field /// </summary> /// <param name="SGSGKEY">SGSGKEY value used to find SGSG</param> /// <returns>List of related SGSG entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SGSG> FindBySGSGKEY(string SGSGKEY) { return Index_SGSGKEY.Value[SGSGKEY]; } /// <summary> /// Attempt to find SGSG by SGSGKEY field /// </summary> /// <param name="SGSGKEY">SGSGKEY value used to find SGSG</param> /// <param name="Value">List of related SGSG entities</param> /// <returns>True if the list of related SGSG entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySGSGKEY(string SGSGKEY, out IReadOnlyList<SGSG> Value) { return Index_SGSGKEY.Value.TryGetValue(SGSGKEY, out Value); } /// <summary> /// Attempt to find SGSG by SGSGKEY field /// </summary> /// <param name="SGSGKEY">SGSGKEY value used to find SGSG</param> /// <returns>List of related SGSG entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SGSG> TryFindBySGSGKEY(string SGSGKEY) { IReadOnlyList<SGSG> value; if (Index_SGSGKEY.Value.TryGetValue(SGSGKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find SGSG by TID field /// </summary> /// <param name="TID">TID value used to find SGSG</param> /// <returns>Related SGSG entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SGSG FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find SGSG by TID field /// </summary> /// <param name="TID">TID value used to find SGSG</param> /// <param name="Value">Related SGSG entity</param> /// <returns>True if the related SGSG entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out SGSG Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find SGSG by TID field /// </summary> /// <param name="TID">TID value used to find SGSG</param> /// <returns>Related SGSG entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SGSG TryFindByTID(int TID) { SGSG value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SGSG table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SGSG]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SGSG]( [TID] int IDENTITY NOT NULL, [SGSGKEY] varchar(12) NOT NULL, [SGLINK] varchar(12) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SGSG_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE NONCLUSTERED INDEX [SGSG_Index_SGLINK] ON [dbo].[SGSG] ( [SGLINK] ASC ); CREATE CLUSTERED INDEX [SGSG_Index_SGSGKEY] ON [dbo].[SGSG] ( [SGSGKEY] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGSG]') AND name = N'SGSG_Index_SGLINK') ALTER INDEX [SGSG_Index_SGLINK] ON [dbo].[SGSG] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGSG]') AND name = N'SGSG_Index_TID') ALTER INDEX [SGSG_Index_TID] ON [dbo].[SGSG] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGSG]') AND name = N'SGSG_Index_SGLINK') ALTER INDEX [SGSG_Index_SGLINK] ON [dbo].[SGSG] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SGSG]') AND name = N'SGSG_Index_TID') ALTER INDEX [SGSG_Index_TID] ON [dbo].[SGSG] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SGSG"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SGSG"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SGSG> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[SGSG] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SGSG data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SGSG data set</returns> public override EduHubDataSetDataReader<SGSG> GetDataSetDataReader() { return new SGSGDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SGSG data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SGSG data set</returns> public override EduHubDataSetDataReader<SGSG> GetDataSetDataReader(List<SGSG> Entities) { return new SGSGDataReader(new EduHubDataSetLoadedReader<SGSG>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SGSGDataReader : EduHubDataSetDataReader<SGSG> { public SGSGDataReader(IEduHubDataSetReader<SGSG> Reader) : base (Reader) { } public override int FieldCount { get { return 6; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // SGSGKEY return Current.SGSGKEY; case 2: // SGLINK return Current.SGLINK; case 3: // LW_DATE return Current.LW_DATE; case 4: // LW_TIME return Current.LW_TIME; case 5: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // SGLINK return Current.SGLINK == null; case 3: // LW_DATE return Current.LW_DATE == null; case 4: // LW_TIME return Current.LW_TIME == null; case 5: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // SGSGKEY return "SGSGKEY"; case 2: // SGLINK return "SGLINK"; case 3: // LW_DATE return "LW_DATE"; case 4: // LW_TIME return "LW_TIME"; case 5: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "SGSGKEY": return 1; case "SGLINK": return 2; case "LW_DATE": return 3; case "LW_TIME": return 4; case "LW_USER": return 5; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
// // 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 Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateVirtualMachineScaleSetReimageDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceIds = new RuntimeDefinedParameter(); pInstanceIds.Name = "InstanceId"; pInstanceIds.ParameterType = typeof(string[]); pInstanceIds.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = false }); pInstanceIds.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceIds); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 4, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteVirtualMachineScaleSetReimageMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string vmScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]); System.Collections.Generic.IList<string> instanceIds = null; if (invokeMethodInputParameters[2] != null) { var inputArray2 = Array.ConvertAll((object[]) ParseParameter(invokeMethodInputParameters[2]), e => e.ToString()); instanceIds = inputArray2.ToList(); } var result = VirtualMachineScaleSetsClient.Reimage(resourceGroupName, vmScaleSetName, instanceIds); WriteObject(result); } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateVirtualMachineScaleSetReimageParameters() { string resourceGroupName = string.Empty; string vmScaleSetName = string.Empty; var instanceIds = new string[0]; return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "VMScaleSetName", "InstanceIds" }, new object[] { resourceGroupName, vmScaleSetName, instanceIds }); } } [Cmdlet(VerbsCommon.Set, "AzureRmVmss", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)] [OutputType(typeof(PSOperationStatusResponse))] public partial class SetAzureRmVmss : ComputeAutomationBaseCmdlet { public override void ExecuteCmdlet() { ExecuteClientAction(() => { if (ShouldProcess(this.VMScaleSetName, VerbsCommon.Set)) { string resourceGroupName = this.ResourceGroupName; string vmScaleSetName = this.VMScaleSetName; System.Collections.Generic.IList<string> instanceIds = this.InstanceId; if (this.ParameterSetName.Equals("FriendMethod")) { var result = VirtualMachineScaleSetsClient.ReimageAll(resourceGroupName, vmScaleSetName, instanceIds); var psObject = new PSOperationStatusResponse(); ComputeAutomationAutoMapperProfile.Mapper.Map<Azure.Management.Compute.Models.OperationStatusResponse, PSOperationStatusResponse>(result, psObject); WriteObject(psObject); } else { var result = VirtualMachineScaleSetsClient.Reimage(resourceGroupName, vmScaleSetName, instanceIds); var psObject = new PSOperationStatusResponse(); ComputeAutomationAutoMapperProfile.Mapper.Map<Azure.Management.Compute.Models.OperationStatusResponse, PSOperationStatusResponse>(result, psObject); WriteObject(psObject); } } }); } [Parameter( ParameterSetName = "DefaultParameter", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Parameter( ParameterSetName = "FriendMethod", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [AllowNull] [ResourceManager.Common.ArgumentCompleters.ResourceGroupCompleter()] public string ResourceGroupName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Parameter( ParameterSetName = "FriendMethod", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Alias("Name")] [AllowNull] public string VMScaleSetName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 3, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Parameter( ParameterSetName = "FriendMethod", Position = 3, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [AllowNull] public string [] InstanceId { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = true)] [AllowNull] public SwitchParameter Reimage { get; set; } [Parameter( ParameterSetName = "FriendMethod", Mandatory = true)] [AllowNull] public SwitchParameter ReimageAll { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { 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> /// WaitingsStatistic /// </summary> [DataContract] public partial class WaitingsStatistic : IEquatable<WaitingsStatistic>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="WaitingsStatistic" /> class. /// </summary> /// <param name="InList">InList.</param> /// <param name="Called">Called.</param> /// <param name="TablesAvailable">TablesAvailable.</param> /// <param name="TotalCovers">TotalCovers.</param> /// <param name="CoversAvailable">CoversAvailable.</param> /// <param name="OneTwoGroup">OneTwoGroup.</param> /// <param name="ThreeFourGroup">ThreeFourGroup.</param> /// <param name="FiveSixGroup">FiveSixGroup.</param> /// <param name="WaitByGroup">WaitByGroup.</param> public WaitingsStatistic(int? InList = null, int? Called = null, int? TablesAvailable = null, int? TotalCovers = null, int? CoversAvailable = null, AverageWaitingTime OneTwoGroup = null, AverageWaitingTime ThreeFourGroup = null, AverageWaitingTime FiveSixGroup = null, List<WaitingStatLine> WaitByGroup = null) { this.InList = InList; this.Called = Called; this.TablesAvailable = TablesAvailable; this.TotalCovers = TotalCovers; this.CoversAvailable = CoversAvailable; this.OneTwoGroup = OneTwoGroup; this.ThreeFourGroup = ThreeFourGroup; this.FiveSixGroup = FiveSixGroup; this.WaitByGroup = WaitByGroup; } /// <summary> /// Gets or Sets InList /// </summary> [DataMember(Name="inList", EmitDefaultValue=true)] public int? InList { get; set; } /// <summary> /// Gets or Sets Called /// </summary> [DataMember(Name="called", EmitDefaultValue=true)] public int? Called { get; set; } /// <summary> /// Gets or Sets TablesAvailable /// </summary> [DataMember(Name="tablesAvailable", EmitDefaultValue=true)] public int? TablesAvailable { get; set; } /// <summary> /// Gets or Sets TotalCovers /// </summary> [DataMember(Name="totalCovers", EmitDefaultValue=true)] public int? TotalCovers { get; set; } /// <summary> /// Gets or Sets CoversAvailable /// </summary> [DataMember(Name="coversAvailable", EmitDefaultValue=true)] public int? CoversAvailable { get; set; } /// <summary> /// Gets or Sets OneTwoGroup /// </summary> [DataMember(Name="oneTwoGroup", EmitDefaultValue=true)] public AverageWaitingTime OneTwoGroup { get; set; } /// <summary> /// Gets or Sets ThreeFourGroup /// </summary> [DataMember(Name="threeFourGroup", EmitDefaultValue=true)] public AverageWaitingTime ThreeFourGroup { get; set; } /// <summary> /// Gets or Sets FiveSixGroup /// </summary> [DataMember(Name="fiveSixGroup", EmitDefaultValue=true)] public AverageWaitingTime FiveSixGroup { get; set; } /// <summary> /// Gets or Sets WaitByGroup /// </summary> [DataMember(Name="waitByGroup", EmitDefaultValue=true)] public List<WaitingStatLine> WaitByGroup { 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 WaitingsStatistic {\n"); sb.Append(" InList: ").Append(InList).Append("\n"); sb.Append(" Called: ").Append(Called).Append("\n"); sb.Append(" TablesAvailable: ").Append(TablesAvailable).Append("\n"); sb.Append(" TotalCovers: ").Append(TotalCovers).Append("\n"); sb.Append(" CoversAvailable: ").Append(CoversAvailable).Append("\n"); sb.Append(" OneTwoGroup: ").Append(OneTwoGroup).Append("\n"); sb.Append(" ThreeFourGroup: ").Append(ThreeFourGroup).Append("\n"); sb.Append(" FiveSixGroup: ").Append(FiveSixGroup).Append("\n"); sb.Append(" WaitByGroup: ").Append(WaitByGroup).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 WaitingsStatistic); } /// <summary> /// Returns true if WaitingsStatistic instances are equal /// </summary> /// <param name="other">Instance of WaitingsStatistic to be compared</param> /// <returns>Boolean</returns> public bool Equals(WaitingsStatistic other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.InList == other.InList || this.InList != null && this.InList.Equals(other.InList) ) && ( this.Called == other.Called || this.Called != null && this.Called.Equals(other.Called) ) && ( this.TablesAvailable == other.TablesAvailable || this.TablesAvailable != null && this.TablesAvailable.Equals(other.TablesAvailable) ) && ( this.TotalCovers == other.TotalCovers || this.TotalCovers != null && this.TotalCovers.Equals(other.TotalCovers) ) && ( this.CoversAvailable == other.CoversAvailable || this.CoversAvailable != null && this.CoversAvailable.Equals(other.CoversAvailable) ) && ( this.OneTwoGroup == other.OneTwoGroup || this.OneTwoGroup != null && this.OneTwoGroup.Equals(other.OneTwoGroup) ) && ( this.ThreeFourGroup == other.ThreeFourGroup || this.ThreeFourGroup != null && this.ThreeFourGroup.Equals(other.ThreeFourGroup) ) && ( this.FiveSixGroup == other.FiveSixGroup || this.FiveSixGroup != null && this.FiveSixGroup.Equals(other.FiveSixGroup) ) && ( this.WaitByGroup == other.WaitByGroup || this.WaitByGroup != null && this.WaitByGroup.SequenceEqual(other.WaitByGroup) ); } /// <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.InList != null) hash = hash * 59 + this.InList.GetHashCode(); if (this.Called != null) hash = hash * 59 + this.Called.GetHashCode(); if (this.TablesAvailable != null) hash = hash * 59 + this.TablesAvailable.GetHashCode(); if (this.TotalCovers != null) hash = hash * 59 + this.TotalCovers.GetHashCode(); if (this.CoversAvailable != null) hash = hash * 59 + this.CoversAvailable.GetHashCode(); if (this.OneTwoGroup != null) hash = hash * 59 + this.OneTwoGroup.GetHashCode(); if (this.ThreeFourGroup != null) hash = hash * 59 + this.ThreeFourGroup.GetHashCode(); if (this.FiveSixGroup != null) hash = hash * 59 + this.FiveSixGroup.GetHashCode(); if (this.WaitByGroup != null) hash = hash * 59 + this.WaitByGroup.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2010 Stephen M. McKamey 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 License using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using JsonFx.IO; using JsonFx.Model; using JsonFx.Serialization; using JsonFx.Utils; namespace JsonFx.Json { public partial class JsonReader { /// <summary> /// Generates a sequence of tokens from JSON text /// </summary> public class JsonTokenizer : ITextTokenizer<ModelTokenType> { #region NeedsValueDelim private enum NeedsValueDelim { /// <summary> /// It is an error for the next token to be a value delim /// </summary> Forbidden, /// <summary> /// Forbidden but differentiates between empty array/object and just written /// </summary> CurrentIsDelim, /// <summary> /// It is an error for the next token to NOT be a value delim /// </summary> Required, } #endregion NeedsValueDelim #region Constants // tokenizing errors private const string ErrorUnrecognizedToken = "Illegal JSON sequence"; private const string ErrorUnterminatedComment = "Unterminated comment block"; private const string ErrorUnterminatedString = "Unterminated JSON string"; private const string ErrorIllegalNumber = "Illegal JSON number"; private const string ErrorMissingValueDelim = "Missing value delimiter"; private const string ErrorExtraValueDelim = "Extraneous value delimiter"; private const int DefaultBufferSize = 0x20; #endregion Constants #region Fields private ITextStream Scanner = TextReaderStream.Null; #endregion Fields #region Properties /// <summary> /// Gets the total number of characters read from the input /// </summary> public int Column { get { return this.Scanner.Column; } } /// <summary> /// Gets the total number of lines read from the input /// </summary> public int Line { get { return this.Scanner.Line; } } /// <summary> /// Gets the current position within the input /// </summary> public long Index { get { return this.Scanner.Index; } } #endregion Properties #region Scanning Methods /// <summary> /// Gets a token sequence from the scanner stream /// </summary> /// <param name="scanner"></param> /// <returns></returns> protected IEnumerable<Token<ModelTokenType>> GetTokens(ITextStream scanner) { if (scanner == null) { throw new ArgumentNullException("scanner"); } // store for external access to Index/Line/Column this.Scanner = scanner; int depth = 0; NeedsValueDelim needsValueDelim = NeedsValueDelim.Forbidden; while (true) { // skip comments and whitespace between tokens JsonTokenizer.SkipCommentsAndWhitespace(scanner); if (scanner.IsCompleted) { this.Scanner = StringStream.Null; scanner.Dispose(); yield break; } bool hasUnaryOp = false; char ch = scanner.Peek(); switch (ch) { case JsonGrammar.OperatorArrayBegin: { scanner.Pop(); if (needsValueDelim == NeedsValueDelim.Required) { throw new DeserializationException(JsonTokenizer.ErrorMissingValueDelim, scanner.Index, scanner.Line, scanner.Column); } yield return ModelGrammar.TokenArrayBeginUnnamed; depth++; needsValueDelim = NeedsValueDelim.Forbidden; continue; } case JsonGrammar.OperatorArrayEnd: { scanner.Pop(); if (needsValueDelim == NeedsValueDelim.CurrentIsDelim) { throw new DeserializationException(JsonTokenizer.ErrorExtraValueDelim, scanner.Index, scanner.Line, scanner.Column); } yield return ModelGrammar.TokenArrayEnd; // resetting at zero allows streaming mode depth--; needsValueDelim = (depth > 0) ? NeedsValueDelim.Required : NeedsValueDelim.Forbidden; continue; } case JsonGrammar.OperatorObjectBegin: { scanner.Pop(); if (needsValueDelim == NeedsValueDelim.Required) { throw new DeserializationException(JsonTokenizer.ErrorMissingValueDelim, scanner.Index, scanner.Line, scanner.Column); } yield return ModelGrammar.TokenObjectBeginUnnamed; depth++; needsValueDelim = NeedsValueDelim.Forbidden; continue; } case JsonGrammar.OperatorObjectEnd: { scanner.Pop(); if (needsValueDelim == NeedsValueDelim.CurrentIsDelim) { throw new DeserializationException(JsonTokenizer.ErrorExtraValueDelim, scanner.Index, scanner.Line, scanner.Column); } yield return ModelGrammar.TokenObjectEnd; // resetting at zero allows streaming mode depth--; needsValueDelim = (depth > 0) ? NeedsValueDelim.Required : NeedsValueDelim.Forbidden; continue; } case JsonGrammar.OperatorStringDelim: case JsonGrammar.OperatorStringDelimAlt: { if (needsValueDelim == NeedsValueDelim.Required) { throw new DeserializationException(JsonTokenizer.ErrorMissingValueDelim, scanner.Index, scanner.Line, scanner.Column); } string value = JsonTokenizer.ScanString(scanner); JsonTokenizer.SkipCommentsAndWhitespace(scanner); if (scanner.Peek() == JsonGrammar.OperatorPairDelim) { scanner.Pop(); yield return ModelGrammar.TokenProperty(new DataName(value)); needsValueDelim = NeedsValueDelim.Forbidden; continue; } yield return ModelGrammar.TokenPrimitive(value); needsValueDelim = NeedsValueDelim.Required; continue; } case JsonGrammar.OperatorUnaryMinus: case JsonGrammar.OperatorUnaryPlus: { hasUnaryOp = true; break; } case JsonGrammar.OperatorValueDelim: { scanner.Pop(); if (needsValueDelim != NeedsValueDelim.Required) { throw new DeserializationException(JsonTokenizer.ErrorExtraValueDelim, scanner.Index, scanner.Line, scanner.Column); } needsValueDelim = NeedsValueDelim.CurrentIsDelim; continue; } case JsonGrammar.OperatorPairDelim: { throw new DeserializationException(JsonTokenizer.ErrorUnrecognizedToken, scanner.Index+1, scanner.Line, scanner.Column); } } if (needsValueDelim == NeedsValueDelim.Required) { throw new DeserializationException(JsonTokenizer.ErrorMissingValueDelim, scanner.Index, scanner.Line, scanner.Column); } // scan for numbers Token<ModelTokenType> token = JsonTokenizer.ScanNumber(scanner); if (token != null) { yield return token; needsValueDelim = NeedsValueDelim.Required; continue; } // hold for Infinity, clear for others if (!hasUnaryOp) { ch = default(char); } // store for unterminated cases long strPos = scanner.Index+1; int strLine = scanner.Line; int strCol = scanner.Column; // scan for identifiers, then check if they are keywords string ident = JsonTokenizer.ScanIdentifier(scanner); if (!String.IsNullOrEmpty(ident)) { token = JsonTokenizer.ScanKeywords(scanner, ident, ch, out needsValueDelim); if (token != null) { yield return token; continue; } } throw new DeserializationException(JsonTokenizer.ErrorUnrecognizedToken, strPos, strLine, strCol); } } private static void SkipCommentsAndWhitespace(ITextStream scanner) { while (true) { // skip leading and trailing whitespace JsonTokenizer.SkipWhitespace(scanner); // check for block and line comments if (scanner.IsCompleted || scanner.Peek() != JsonGrammar.OperatorCommentBegin[0]) { return; } // read first char of comment start scanner.Pop(); // store for unterminated case long commentStart = scanner.Index; int commentCol = scanner.Column; int commentLine = scanner.Line; if (scanner.IsCompleted) { throw new DeserializationException(JsonTokenizer.ErrorUnterminatedComment, commentStart, commentLine, commentCol); } // peek second char of comment start char ch = scanner.Peek(); bool isBlockComment; if (ch == JsonGrammar.OperatorCommentBegin[1]) { isBlockComment = true; } else if (ch == JsonGrammar.OperatorCommentLine[1]) { isBlockComment = false; } else { throw new DeserializationException(JsonTokenizer.ErrorUnterminatedComment, commentStart, commentLine, commentCol); } // start reading comment content if (isBlockComment) { // skip over everything until reach block comment ending while (true) { do { scanner.Pop(); if (scanner.IsCompleted) { throw new DeserializationException(JsonTokenizer.ErrorUnterminatedComment, commentStart, commentLine, commentCol); } } while (scanner.Peek() != JsonGrammar.OperatorCommentEnd[0]); scanner.Pop(); if (scanner.IsCompleted) { throw new DeserializationException(JsonTokenizer.ErrorUnterminatedComment, commentStart, commentLine, commentCol); } if (scanner.Peek() == JsonGrammar.OperatorCommentEnd[1]) { // move past block comment end token scanner.Pop(); break; } } } else { // skip over everything until reach line ending or end of input do { scanner.Pop(); ch = scanner.Peek(); } while (!scanner.IsCompleted && ('\r' != ch) && ('\n' != ch)); } } } private static void SkipWhitespace(ITextStream scanner) { while (!scanner.IsCompleted && CharUtility.IsWhiteSpace(scanner.Peek())) { scanner.Pop(); } } private static Token<ModelTokenType> ScanNumber(ITextStream scanner) { // store for error cases long numPos = scanner.Index+1; int numLine = scanner.Line; int numCol = scanner.Column; scanner.BeginChunk(); char ch = scanner.Peek(); bool isNeg = false; if (ch == JsonGrammar.OperatorUnaryPlus) { // consume positive signing (as is extraneous) scanner.Pop(); ch = scanner.Peek(); // reset buffering scanner.BeginChunk(); } else if (ch == JsonGrammar.OperatorUnaryMinus) { // optional minus part scanner.Pop(); ch = scanner.Peek(); isNeg = true; } if (!CharUtility.IsDigit(ch) && ch != JsonGrammar.OperatorDecimalPoint) { // possibly "-Infinity" scanner.EndChunk(); return null; } // integer part while (!scanner.IsCompleted && CharUtility.IsDigit(ch)) { // consume digit scanner.Pop(); ch = scanner.Peek(); } bool hasDecimal = false; if (!scanner.IsCompleted && (ch == JsonGrammar.OperatorDecimalPoint)) { // consume decimal scanner.Pop(); ch = scanner.Peek(); // fraction part while (!scanner.IsCompleted && CharUtility.IsDigit(ch)) { // consume digit scanner.Pop(); ch = scanner.Peek(); hasDecimal = true; } if (!hasDecimal) { // fractional digits required when '.' present throw new DeserializationException(JsonTokenizer.ErrorIllegalNumber, numPos, numLine, numCol); } } // note the number of significant digits int precision = scanner.ChunkSize; if (hasDecimal) { precision--; } if (isNeg) { precision--; } if (precision < 1) { // missing digits all together throw new DeserializationException(JsonTokenizer.ErrorIllegalNumber, numPos, numLine, numCol); } bool hasExponent = false; // optional exponent part if (!scanner.IsCompleted && (ch == 'e' || ch == 'E')) { // consume 'e' scanner.Pop(); ch = scanner.Peek(); // optional minus/plus part if (!scanner.IsCompleted && ch == JsonGrammar.OperatorUnaryMinus || ch == JsonGrammar.OperatorUnaryPlus) { // consume sign scanner.Pop(); ch = scanner.Peek(); } // exp part while (!scanner.IsCompleted && CharUtility.IsDigit(ch)) { // consume digit scanner.Pop(); ch = scanner.Peek(); hasExponent = true; } if (!hasExponent) { // exponent digits required when 'e' present throw new DeserializationException(JsonTokenizer.ErrorIllegalNumber, numPos, numLine, numCol); } } // specifically check for 0x-style hex numbers if (!scanner.IsCompleted && CharUtility.IsLetter(ch)) { throw new DeserializationException(JsonTokenizer.ErrorIllegalNumber, numPos, numLine, numCol); } // by this point, we have the full number string and know its characteristics string buffer = scanner.EndChunk(); if (!hasDecimal && !hasExponent && precision < 19) { // Integer value decimal number = 0; try{ number = Decimal.Parse( buffer, NumberStyles.Integer, NumberFormatInfo.InvariantInfo); }catch(Exception){ throw new DeserializationException(JsonTokenizer.ErrorIllegalNumber, numPos, numLine, numCol); } if (number >= Int32.MinValue && number <= Int32.MaxValue) { // int most common return ModelGrammar.TokenPrimitive((int)number); } if (number >= Int64.MinValue && number <= Int64.MaxValue) { // long more flexible return ModelGrammar.TokenPrimitive((long)number); } // decimal most flexible return ModelGrammar.TokenPrimitive(number); } else { // Floating Point value double number; try{ number = Double.Parse( buffer, NumberStyles.Float, NumberFormatInfo.InvariantInfo); }catch(Exception){ throw new DeserializationException(JsonTokenizer.ErrorIllegalNumber, numPos, numLine, numCol); } // native EcmaScript number (IEEE-754) return ModelGrammar.TokenPrimitive(number); } } private static string ScanString(ITextStream scanner) { // store for unterminated cases long strPos = scanner.Index+1; int strLine = scanner.Line; int strCol = scanner.Column; char stringDelim = scanner.Peek(); scanner.Pop(); char ch = scanner.Peek(); // start chunking scanner.BeginChunk(); StringBuilder buffer = new StringBuilder(JsonTokenizer.DefaultBufferSize); while (true) { // look ahead if (scanner.IsCompleted || CharUtility.IsControl(ch) && ch != '\t') { // reached end or line break before string delim throw new DeserializationException(JsonTokenizer.ErrorUnterminatedString, strPos, strLine, strCol); } // check each character for ending delim if (ch == stringDelim) { // end chunking scanner.EndChunk(buffer); // flush closing delim scanner.Pop(); // output string return buffer.ToString(); } if (ch != JsonGrammar.OperatorCharEscape) { // accumulate scanner.Pop(); ch = scanner.Peek(); continue; } // pause chunking to replace escape char scanner.EndChunk(buffer); // flush escape char scanner.Pop(); ch = scanner.Peek(); if (scanner.IsCompleted || CharUtility.IsControl(ch) && ch != '\t') { // reached end or line break before string delim throw new DeserializationException(JsonTokenizer.ErrorUnterminatedString, strPos, strLine, strCol); } // begin decode switch (ch) { case '0': { // consume and do not allow NULL char '\0' // causes CStrings to terminate scanner.Pop(); ch = scanner.Peek(); break; } case 'b': { // backspace buffer.Append('\b'); scanner.Pop(); ch = scanner.Peek(); break; } case 'f': { // formfeed buffer.Append('\f'); scanner.Pop(); ch = scanner.Peek(); break; } case 'n': { // newline buffer.Append('\n'); scanner.Pop(); ch = scanner.Peek(); break; } case 'r': { // carriage return buffer.Append('\r'); scanner.Pop(); ch = scanner.Peek(); break; } case 't': { // tab buffer.Append('\t'); scanner.Pop(); ch = scanner.Peek(); break; } case 'u': { // Unicode escape sequence // e.g. (c) => "\u00A9" const int UnicodeEscapeLength = 4; scanner.Pop(); ch = scanner.Peek(); string escapeSeq = String.Empty; for (int i=UnicodeEscapeLength; !scanner.IsCompleted && CharUtility.IsHexDigit(ch) && (i > 0); i--) { escapeSeq += ch; scanner.Pop(); ch = scanner.Peek(); } // unicode ordinal int utf16 = 0; bool parsed = true; try{ utf16 = Int32.Parse( escapeSeq, NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo); }catch(Exception){ parsed = false; }; if (escapeSeq.Length == UnicodeEscapeLength && parsed) { buffer.Append(CharUtility.ConvertFromUtf32(utf16)); } else { // using FireFox-style recovery, if not a valid hex // escape sequence then treat as single escaped 'u' // followed by rest of string buffer.Append('u'); buffer.Append(escapeSeq); } break; } default: { // all unrecognized sequences are interpreted as plain chars buffer.Append(ch); scanner.Pop(); ch = scanner.Peek(); break; } } // resume chunking scanner.BeginChunk(); } } private static Token<ModelTokenType> ScanKeywords(ITextStream scanner, string ident, char unary, out NeedsValueDelim needsValueDelim) { needsValueDelim = NeedsValueDelim.Required; switch (ident) { case JsonGrammar.KeywordFalse: { if (unary != default(char)) { return null; } return ModelGrammar.TokenFalse; } case JsonGrammar.KeywordTrue: { if (unary != default(char)) { return null; } return ModelGrammar.TokenTrue; } case JsonGrammar.KeywordNull: { if (unary != default(char)) { return null; } return ModelGrammar.TokenNull; } case JsonGrammar.KeywordNaN: { if (unary != default(char)) { return null; } return ModelGrammar.TokenNaN; } case JsonGrammar.KeywordInfinity: { if (unary == default(char) || unary == JsonGrammar.OperatorUnaryPlus) { return ModelGrammar.TokenPositiveInfinity; } if (unary == JsonGrammar.OperatorUnaryMinus) { return ModelGrammar.TokenNegativeInfinity; } return null; } case JsonGrammar.KeywordUndefined: { if (unary != default(char)) { return null; } return ModelGrammar.TokenNull; } } if (unary != default(char)) { ident = Char.ToString(unary)+ident; } JsonTokenizer.SkipCommentsAndWhitespace(scanner); if (scanner.Peek() == JsonGrammar.OperatorPairDelim) { scanner.Pop(); needsValueDelim = NeedsValueDelim.Forbidden; return ModelGrammar.TokenProperty(new DataName(ident)); } return null; } /// <summary> /// Scans for the longest valid EcmaScript identifier /// </summary> /// <returns>identifier</returns> /// <remarks> /// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf /// /// IdentifierName = /// IdentifierStart | IdentifierName IdentifierPart /// IdentifierStart = /// Letter | '$' | '_' /// IdentifierPart = /// IdentifierStart | Digit /// </remarks> private static string ScanIdentifier(ITextStream scanner) { bool identPart = false; scanner.BeginChunk(); while (true) { char ch = scanner.Peek(); // digits are only allowed after first char // rest can be in head or tail if ((identPart && CharUtility.IsDigit(ch)) || CharUtility.IsLetter(ch) || (ch == '_') || (ch == '$')) { identPart = true; scanner.Pop(); ch = scanner.Peek(); continue; } // get ident string return scanner.EndChunk(); } } #endregion Scanning Methods #region ITextTokenizer<DataTokenType> Members /// <summary> /// Gets a token sequence from the TextReader /// </summary> /// <param name="reader"></param> /// <returns></returns> public IEnumerable<Token<ModelTokenType>> GetTokens(TextReader reader) { // buffer the output so multiple passes over the results can access it // otherwise second pass would result in empty list since stream is used up return new SequenceBuffer<Token<ModelTokenType>>(this.GetTokens(new TextReaderStream(reader))); } /// <summary> /// Gets a token sequence from the string /// </summary> /// <param name="text"></param> /// <returns></returns> public IEnumerable<Token<ModelTokenType>> GetTokens(string text) { // buffer the output so multiple passes over the results can access it // otherwise second pass would result in empty list since stream is used up return new SequenceBuffer<Token<ModelTokenType>>(this.GetTokens(new StringStream(text))); } #endregion ITextTokenizer<DataTokenType> Members #region IDisposable Members public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.Scanner.Dispose(); } } #endregion IDisposable Members } } }
// 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.Reflection; using Xunit; namespace System.Tests { public static class ActivatorTests { [Fact] public static void CreateInstance() { // Passing null args is equivalent to an empty array of args. Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), null)); Assert.Equal(1, c.I); c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { })); Assert.Equal(1, c.I); c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { 42 })); Assert.Equal(2, c.I); c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { "Hello" })); Assert.Equal(3, c.I); c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { 5.1, "Hello" })); Assert.Equal(4, c.I); Activator.CreateInstance(typeof(StructTypeWithoutReflectionMetadata)); } [Fact] public static void CreateInstance_ConstructorWithPrimitive_PerformsPrimitiveWidening() { // Primitive widening is allowed by the binder, but not by Dynamic.DelegateInvoke(). Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { (short)-2 })); Assert.Equal(2, c.I); } [Fact] public static void CreateInstance_ConstructorWithParamsParameter() { // C# params arguments are honored by Activator.CreateInstance() Choice1 c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs() })); Assert.Equal(5, c.I); c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs(), "P1" })); Assert.Equal(5, c.I); c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarArgs(), "P1", "P2" })); Assert.Equal(5, c.I); c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs() })); Assert.Equal(6, c.I); c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), "P1" })); Assert.Equal(6, c.I); c = (Choice1)(Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), "P1", "P2" })); Assert.Equal(6, c.I); } [Fact] public static void CreateInstance_Invalid() { Assert.Throws<ArgumentNullException>("type", () => Activator.CreateInstance(null)); // Type is null Assert.Throws<ArgumentNullException>("type", () => Activator.CreateInstance(null, new object[0])); // Type is null Assert.Throws<AmbiguousMatchException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { null })); // C# designated optional parameters are not optional as far as Activator.CreateInstance() is concerned. Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { 5.1 })); Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { 5.1, Type.Missing })); // Invalid params args Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { new VarStringArgs(), 5, 6 })); // Primitive widening not supported for "params" arguments. // // (This is probably an accidental behavior on the desktop as the default binder specifically checks to see if the params arguments are widenable to the // params array element type and gives it the go-ahead if it is. Unfortunately, the binder then bollixes itself by using Array.Copy() to copy // the params arguments. Since Array.Copy() doesn't tolerate this sort of type mismatch, it throws an InvalidCastException which bubbles out // out of Activator.CreateInstance. Accidental or not, we'll inherit that behavior on .NET Native.) Assert.Throws<InvalidCastException>(() => Activator.CreateInstance(typeof(Choice1), new object[] { new VarIntArgs(), 1, (short)2 })); Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<TypeWithoutDefaultCtor>()); // Type has no default constructor Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance<TypeWithDefaultCtorThatThrows>()); // Type has a default constructor throws an exception } [Fact] public static void CreateInstance_Generic() { Choice1 c = Activator.CreateInstance<Choice1>(); Assert.Equal(1, c.I); Activator.CreateInstance<DateTime>(); Activator.CreateInstance<StructTypeWithoutReflectionMetadata>(); } [Fact] public static void CreateInstance_Generic_Invalid() { Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<int[]>()); // Cannot create array type Assert.ThrowsAny<MissingMemberException>(() => Activator.CreateInstance<TypeWithoutDefaultCtor>()); // Type has no default constructor Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance<TypeWithDefaultCtorThatThrows>()); // Type has a default constructor that throws } class PrivateType { public PrivateType() { } } class PrivateTypeWithDefaultCtor { private PrivateTypeWithDefaultCtor() { } } class PrivateTypeWithoutDefaultCtor { private PrivateTypeWithoutDefaultCtor(int x) { } } class PrivateTypeWithDefaultCtorThatThrows { public PrivateTypeWithDefaultCtorThatThrows() { throw new Exception(); } } [Fact] public static void CreateInstance_Type_Bool() { Assert.Equal(typeof(PrivateType), Activator.CreateInstance(typeof(PrivateType), true).GetType()); Assert.Equal(typeof(PrivateType), Activator.CreateInstance(typeof(PrivateType), false).GetType()); Assert.Equal(typeof(PrivateTypeWithDefaultCtor), Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtor), true).GetType()); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtor), false).GetType()); Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtorThatThrows), true).GetType()); Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(typeof(PrivateTypeWithDefaultCtorThatThrows), false).GetType()); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithoutDefaultCtor), true).GetType()); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(typeof(PrivateTypeWithoutDefaultCtor), false).GetType()); } public class Choice1 : Attribute { public Choice1() { I = 1; } public Choice1(int i) { I = 2; } public Choice1(string s) { I = 3; } public Choice1(double d, string optionalS = "Hey") { I = 4; } public Choice1(VarArgs varArgs, params object[] parameters) { I = 5; } public Choice1(VarStringArgs varArgs, params string[] parameters) { I = 6; } public Choice1(VarIntArgs varArgs, params int[] parameters) { I = 7; } public int I; } public class VarArgs { } public class VarStringArgs { } public class VarIntArgs { } public struct StructTypeWithoutReflectionMetadata { } public class TypeWithoutDefaultCtor { private TypeWithoutDefaultCtor(int x) { } } public class TypeWithDefaultCtorThatThrows { public TypeWithDefaultCtorThatThrows() { throw new Exception(); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcav = Google.Cloud.AIPlatform.V1; using sys = System; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Resource name for the <c>Model</c> resource.</summary> public sealed partial class ModelName : gax::IResourceName, sys::IEquatable<ModelName> { /// <summary>The possible contents of <see cref="ModelName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/models/{model}</c>. /// </summary> ProjectLocationModel = 1, } private static gax::PathTemplate s_projectLocationModel = new gax::PathTemplate("projects/{project}/locations/{location}/models/{model}"); /// <summary>Creates a <see cref="ModelName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ModelName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static ModelName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ModelName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ModelName"/> with the pattern <c>projects/{project}/locations/{location}/models/{model}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ModelName"/> constructed from the provided ids.</returns> public static ModelName FromProjectLocationModel(string projectId, string locationId, string modelId) => new ModelName(ResourceNameType.ProjectLocationModel, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), modelId: gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ModelName"/> with pattern /// <c>projects/{project}/locations/{location}/models/{model}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ModelName"/> with pattern /// <c>projects/{project}/locations/{location}/models/{model}</c>. /// </returns> public static string Format(string projectId, string locationId, string modelId) => FormatProjectLocationModel(projectId, locationId, modelId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ModelName"/> with pattern /// <c>projects/{project}/locations/{location}/models/{model}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ModelName"/> with pattern /// <c>projects/{project}/locations/{location}/models/{model}</c>. /// </returns> public static string FormatProjectLocationModel(string projectId, string locationId, string modelId) => s_projectLocationModel.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId))); /// <summary>Parses the given resource name string into a new <see cref="ModelName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/models/{model}</c></description></item> /// </list> /// </remarks> /// <param name="modelName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ModelName"/> if successful.</returns> public static ModelName Parse(string modelName) => Parse(modelName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ModelName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/models/{model}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="modelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ModelName"/> if successful.</returns> public static ModelName Parse(string modelName, bool allowUnparsed) => TryParse(modelName, allowUnparsed, out ModelName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ModelName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/models/{model}</c></description></item> /// </list> /// </remarks> /// <param name="modelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ModelName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string modelName, out ModelName result) => TryParse(modelName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ModelName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/models/{model}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="modelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ModelName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string modelName, bool allowUnparsed, out ModelName result) { gax::GaxPreconditions.CheckNotNull(modelName, nameof(modelName)); gax::TemplatedResourceName resourceName; if (s_projectLocationModel.TryParseName(modelName, out resourceName)) { result = FromProjectLocationModel(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(modelName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ModelName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string modelId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ModelId = modelId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ModelName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/models/{model}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param> public ModelName(string projectId, string locationId, string modelId) : this(ResourceNameType.ProjectLocationModel, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), modelId: gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Model</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ModelId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationModel: return s_projectLocationModel.Expand(ProjectId, LocationId, ModelId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ModelName); /// <inheritdoc/> public bool Equals(ModelName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ModelName a, ModelName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ModelName a, ModelName b) => !(a == b); } public partial class Model { /// <summary> /// <see cref="gcav::ModelName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::ModelName ModelName { get => string.IsNullOrEmpty(Name) ? null : gcav::ModelName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="TrainingPipelineName"/>-typed view over the <see cref="TrainingPipeline"/> resource name /// property. /// </summary> public TrainingPipelineName TrainingPipelineAsTrainingPipelineName { get => string.IsNullOrEmpty(TrainingPipeline) ? null : TrainingPipelineName.Parse(TrainingPipeline, allowUnparsed: true); set => TrainingPipeline = value?.ToString() ?? ""; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // 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.AzureStack.Management; using Microsoft.AzureStack.Management.Models; using Newtonsoft.Json.Linq; namespace Microsoft.AzureStack.Management { /// <summary> /// Public gallery items operations. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> internal partial class PublicGalleryItemOperations : IServiceOperations<AzureStackClient>, IPublicGalleryItemOperations { /// <summary> /// Initializes a new instance of the PublicGalleryItemOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PublicGalleryItemOperations(AzureStackClient client) { this._client = client; } private AzureStackClient _client; /// <summary> /// Gets a reference to the /// Microsoft.AzureStack.Management.AzureStackClient. /// </summary> public AzureStackClient Client { get { return this._client; } } /// <summary> /// Public gallery items list. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Public gallery items list result. /// </returns> public async Task<PublicGalleryItemListResult> ListAllAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAllAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/providers/Microsoft.Gallery/galleryitems"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); 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 PublicGalleryItemListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new PublicGalleryItemListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken galleryItemsArray = responseDoc; if (galleryItemsArray != null && galleryItemsArray.Type != JTokenType.Null) { foreach (JToken galleryItemsValue in ((JArray)galleryItemsArray)) { GalleryItem galleryItemInstance = new GalleryItem(); result.GalleryItems.Add(galleryItemInstance); JToken additionalPropertiesSequenceElement = ((JToken)galleryItemsValue["additionalProperties"]); if (additionalPropertiesSequenceElement != null && additionalPropertiesSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in additionalPropertiesSequenceElement) { string additionalPropertiesKey = ((string)property.Name); string additionalPropertiesValue = ((string)property.Value); galleryItemInstance.AdditionalProperties.Add(additionalPropertiesKey, additionalPropertiesValue); } } JToken categoryIdsArray = galleryItemsValue["categoryIds"]; if (categoryIdsArray != null && categoryIdsArray.Type != JTokenType.Null) { foreach (JToken categoryIdsValue in ((JArray)categoryIdsArray)) { galleryItemInstance.CategoryIds.Add(((string)categoryIdsValue)); } } JToken definitionTemplatesValue = galleryItemsValue["definitionTemplates"]; if (definitionTemplatesValue != null && definitionTemplatesValue.Type != JTokenType.Null) { DefinitionTemplates definitionTemplatesInstance = new DefinitionTemplates(); galleryItemInstance.DefinitionTemplates = definitionTemplatesInstance; JToken defaultDeploymentTemplateIdValue = definitionTemplatesValue["defaultDeploymentTemplateId"]; if (defaultDeploymentTemplateIdValue != null && defaultDeploymentTemplateIdValue.Type != JTokenType.Null) { string defaultDeploymentTemplateIdInstance = ((string)defaultDeploymentTemplateIdValue); definitionTemplatesInstance.DefaultDeploymentTemplateId = defaultDeploymentTemplateIdInstance; } JToken deploymentFragmentFileUrisSequenceElement = ((JToken)definitionTemplatesValue["deploymentFragmentFileUris"]); if (deploymentFragmentFileUrisSequenceElement != null && deploymentFragmentFileUrisSequenceElement.Type != JTokenType.Null) { foreach (JProperty property2 in deploymentFragmentFileUrisSequenceElement) { string deploymentFragmentFileUrisKey = ((string)property2.Name); string deploymentFragmentFileUrisValue = ((string)property2.Value); definitionTemplatesInstance.DeploymentFragmentFileUris.Add(deploymentFragmentFileUrisKey, deploymentFragmentFileUrisValue); } } JToken deploymentTemplateFileUrisSequenceElement = ((JToken)definitionTemplatesValue["deploymentTemplateFileUris"]); if (deploymentTemplateFileUrisSequenceElement != null && deploymentTemplateFileUrisSequenceElement.Type != JTokenType.Null) { foreach (JProperty property3 in deploymentTemplateFileUrisSequenceElement) { string deploymentTemplateFileUrisKey = ((string)property3.Name); string deploymentTemplateFileUrisValue = ((string)property3.Value); definitionTemplatesInstance.DeploymentTemplateFileUris.Add(deploymentTemplateFileUrisKey, deploymentTemplateFileUrisValue); } } JToken uiDefinitionFileUriValue = definitionTemplatesValue["uiDefinitionFileUri"]; if (uiDefinitionFileUriValue != null && uiDefinitionFileUriValue.Type != JTokenType.Null) { string uiDefinitionFileUriInstance = ((string)uiDefinitionFileUriValue); definitionTemplatesInstance.UiDefinitionFileUri = uiDefinitionFileUriInstance; } } JToken descriptionValue = galleryItemsValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); galleryItemInstance.Description = descriptionInstance; } JToken identityValue = galleryItemsValue["identity"]; if (identityValue != null && identityValue.Type != JTokenType.Null) { string identityInstance = ((string)identityValue); galleryItemInstance.Identity = identityInstance; } JToken itemDisplayNameValue = galleryItemsValue["itemDisplayName"]; if (itemDisplayNameValue != null && itemDisplayNameValue.Type != JTokenType.Null) { string itemDisplayNameInstance = ((string)itemDisplayNameValue); galleryItemInstance.ItemDisplayName = itemDisplayNameInstance; } JToken itemNameValue = galleryItemsValue["itemName"]; if (itemNameValue != null && itemNameValue.Type != JTokenType.Null) { string itemNameInstance = ((string)itemNameValue); galleryItemInstance.ItemName = itemNameInstance; } JToken linksArray = galleryItemsValue["links"]; if (linksArray != null && linksArray.Type != JTokenType.Null) { foreach (JToken linksValue in ((JArray)linksArray)) { LinkProperties linkPropertiesInstance = new LinkProperties(); galleryItemInstance.Links.Add(linkPropertiesInstance); JToken displayNameValue = linksValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); linkPropertiesInstance.DisplayName = displayNameInstance; } JToken idValue = linksValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); linkPropertiesInstance.Id = idInstance; } JToken uriValue = linksValue["uri"]; if (uriValue != null && uriValue.Type != JTokenType.Null) { string uriInstance = ((string)uriValue); linkPropertiesInstance.Uri = uriInstance; } } } JToken longSummaryValue = galleryItemsValue["longSummary"]; if (longSummaryValue != null && longSummaryValue.Type != JTokenType.Null) { string longSummaryInstance = ((string)longSummaryValue); galleryItemInstance.LongSummary = longSummaryInstance; } JToken publisherValue = galleryItemsValue["publisher"]; if (publisherValue != null && publisherValue.Type != JTokenType.Null) { string publisherInstance = ((string)publisherValue); galleryItemInstance.Publisher = publisherInstance; } JToken publisherDisplayNameValue = galleryItemsValue["publisherDisplayName"]; if (publisherDisplayNameValue != null && publisherDisplayNameValue.Type != JTokenType.Null) { string publisherDisplayNameInstance = ((string)publisherDisplayNameValue); galleryItemInstance.PublisherDisplayName = publisherDisplayNameInstance; } JToken resourceGroupNameValue = galleryItemsValue["resourceGroupName"]; if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null) { string resourceGroupNameInstance = ((string)resourceGroupNameValue); galleryItemInstance.ResourceGroupName = resourceGroupNameInstance; } JToken screenshotUrisArray = galleryItemsValue["screenshotUris"]; if (screenshotUrisArray != null && screenshotUrisArray.Type != JTokenType.Null) { foreach (JToken screenshotUrisValue in ((JArray)screenshotUrisArray)) { galleryItemInstance.ScreenshotUris.Add(((string)screenshotUrisValue)); } } JToken summaryValue = galleryItemsValue["summary"]; if (summaryValue != null && summaryValue.Type != JTokenType.Null) { string summaryInstance = ((string)summaryValue); galleryItemInstance.Summary = summaryInstance; } JToken versionValue = galleryItemsValue["version"]; if (versionValue != null && versionValue.Type != JTokenType.Null) { string versionInstance = ((string)versionValue); galleryItemInstance.Version = versionInstance; } } } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Numerics { /// <summary> /// Contains various methods useful for creating, manipulating, combining, and converting generic vectors with one another. /// </summary> public static class Vector { // JIT is not looking at the Vector class methods // all methods here should be inlined and they must be implemented in terms of Vector<T> intrinsics #region Select Methods /// <summary> /// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector. /// </summary> /// <param name="condition">The integral mask vector used to drive selection.</param> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The new vector with elements selected based on the mask.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<Single> ConditionalSelect(Vector<int> condition, Vector<Single> left, Vector<Single> right) { return (Vector<Single>)Vector<Single>.ConditionalSelect((Vector<Single>)condition, left, right); } /// <summary> /// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector. /// </summary> /// <param name="condition">The integral mask vector used to drive selection.</param> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The new vector with elements selected based on the mask.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<double> ConditionalSelect(Vector<long> condition, Vector<double> left, Vector<double> right) { return (Vector<double>)Vector<double>.ConditionalSelect((Vector<double>)condition, left, right); } /// <summary> /// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector. /// </summary> /// <param name="condition">The mask vector used to drive selection.</param> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The new vector with elements selected based on the mask.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> ConditionalSelect<T>(Vector<T> condition, Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.ConditionalSelect(condition, left, right); } #endregion Select Methods #region Comparison methods #region Equals methods /// <summary> /// Returns a new vector whose elements signal whether the elements in left and right were equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Equals<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.Equals(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether elements in the left and right floating point vectors were equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<int> Equals(Vector<Single> left, Vector<Single> right) { return (Vector<int>)Vector<Single>.Equals(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left and right were equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<int> Equals(Vector<int> left, Vector<int> right) { return Vector<int>.Equals(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether elements in the left and right floating point vectors were equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<long> Equals(Vector<double> left, Vector<double> right) { return (Vector<long>)Vector<double>.Equals(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left and right were equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<long> Equals(Vector<long> left, Vector<long> right) { return Vector<long>.Equals(left, right); } /// <summary> /// Returns a boolean indicating whether each pair of elements in the given vectors are equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The first vector to compare.</param> /// <returns>True if all elements are equal; False otherwise.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static bool EqualsAll<T>(Vector<T> left, Vector<T> right) where T : struct { return left == right; } /// <summary> /// Returns a boolean indicating whether any single pair of elements in the given vectors are equal. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if any element pairs are equal; False if no element pairs are equal.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static bool EqualsAny<T>(Vector<T> left, Vector<T> right) where T : struct { return !Vector<T>.Equals(left, right).Equals(Vector<T>.Zero); } #endregion Equals methods #region Lessthan Methods /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> LessThan<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.LessThan(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were less than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<int> LessThan(Vector<Single> left, Vector<Single> right) { return (Vector<int>)Vector<Single>.LessThan(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<int> LessThan(Vector<int> left, Vector<int> right) { return Vector<int>.LessThan(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were less than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<long> LessThan(Vector<double> left, Vector<double> right) { return (Vector<long>)Vector<double>.LessThan(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<long> LessThan(Vector<long> left, Vector<long> right) { return Vector<long>.LessThan(left, right); } /// <summary> /// Returns a boolean indicating whether all of the elements in left are less than their corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if all elements in left are less than their corresponding elements in right; False otherwise.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static bool LessThanAll<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.LessThan(left, right); return cond.Equals(Vector<int>.AllOnes); } /// <summary> /// Returns a boolean indicating whether any element in left is less than its corresponding element in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if any elements in left are less than their corresponding elements in right; False otherwise.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static bool LessThanAny<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.LessThan(left, right); return !cond.Equals(Vector<int>.Zero); } #endregion LessthanMethods #region Lessthanorequal methods /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> LessThanOrEqual<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.LessThanOrEqual(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were less than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<int> LessThanOrEqual(Vector<Single> left, Vector<Single> right) { return (Vector<int>)Vector<Single>.LessThanOrEqual(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<int> LessThanOrEqual(Vector<int> left, Vector<int> right) { return Vector<int>.LessThanOrEqual(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were less than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<long> LessThanOrEqual(Vector<long> left, Vector<long> right) { return Vector<long>.LessThanOrEqual(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were less than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<long> LessThanOrEqual(Vector<double> left, Vector<double> right) { return (Vector<long>)Vector<double>.LessThanOrEqual(left, right); } /// <summary> /// Returns a boolean indicating whether all elements in left are less than or equal to their corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if all elements in left are less than or equal to their corresponding elements in right; False otherwise.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static bool LessThanOrEqualAll<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.LessThanOrEqual(left, right); return cond.Equals(Vector<int>.AllOnes); } /// <summary> /// Returns a boolean indicating whether any element in left is less than or equal to its corresponding element in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if any elements in left are less than their corresponding elements in right; False otherwise.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static bool LessThanOrEqualAny<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.LessThanOrEqual(left, right); return !cond.Equals(Vector<int>.Zero); } #endregion Lessthanorequal methods #region Greaterthan methods /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> GreaterThan<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.GreaterThan(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were greater than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<int> GreaterThan(Vector<Single> left, Vector<Single> right) { return (Vector<int>)Vector<Single>.GreaterThan(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<int> GreaterThan(Vector<int> left, Vector<int> right) { return Vector<int>.GreaterThan(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were greater than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<long> GreaterThan(Vector<double> left, Vector<double> right) { return (Vector<long>)Vector<double>.GreaterThan(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<long> GreaterThan(Vector<long> left, Vector<long> right) { return Vector<long>.GreaterThan(left, right); } /// <summary> /// Returns a boolean indicating whether all elements in left are greater than the corresponding elements in right. /// elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if all elements in left are greater than their corresponding elements in right; False otherwise.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanAll<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.GreaterThan(left, right); return cond.Equals(Vector<int>.AllOnes); } /// <summary> /// Returns a boolean indicating whether any element in left is greater than its corresponding element in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if any elements in left are greater than their corresponding elements in right; False otherwise.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanAny<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.GreaterThan(left, right); return !cond.Equals(Vector<int>.Zero); } #endregion Greaterthan methods #region Greaterthanorequal methods /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> GreaterThanOrEqual<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.GreaterThanOrEqual(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were greater than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<int> GreaterThanOrEqual(Vector<Single> left, Vector<Single> right) { return (Vector<int>)Vector<Single>.GreaterThanOrEqual(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<int> GreaterThanOrEqual(Vector<int> left, Vector<int> right) { return Vector<int>.GreaterThanOrEqual(left, right); } /// <summary> /// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their /// corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<long> GreaterThanOrEqual(Vector<long> left, Vector<long> right) { return Vector<long>.GreaterThanOrEqual(left, right); } /// <summary> /// Returns an integral vector whose elements signal whether the elements in left were greater than or equal to /// their corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>The resultant integral vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<long> GreaterThanOrEqual(Vector<double> left, Vector<double> right) { return (Vector<long>)Vector<double>.GreaterThanOrEqual(left, right); } /// <summary> /// Returns a boolean indicating whether all of the elements in left are greater than or equal to /// their corresponding elements in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if all elements in left are greater than or equal to their corresponding elements in right; False otherwise.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanOrEqualAll<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.GreaterThanOrEqual(left, right); return cond.Equals(Vector<int>.AllOnes); } /// <summary> /// Returns a boolean indicating whether any element in left is greater than or equal to its corresponding element in right. /// </summary> /// <param name="left">The first vector to compare.</param> /// <param name="right">The second vector to compare.</param> /// <returns>True if any elements in left are greater than or equal to their corresponding elements in right; False otherwise.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanOrEqualAny<T>(Vector<T> left, Vector<T> right) where T : struct { Vector<int> cond = (Vector<int>)Vector<T>.GreaterThanOrEqual(left, right); return !cond.Equals(Vector<int>.Zero); } #endregion Greaterthanorequal methods #endregion Comparison methods #region Vector Math Methods // Every operation must either be a JIT intrinsic or implemented over a JIT intrinsic // as a thin wrapper // Operations implemented over a JIT intrinsic should be inlined // Methods that do not have a <T> type parameter are recognized as intrinsics /// <summary> /// Returns whether or not vector operations are subject to hardware acceleration through JIT intrinsic support. /// </summary> [JitIntrinsic] public static bool IsHardwareAccelerated { get { return false; } } // Vector<T> // Basic Math // All Math operations for Vector<T> are aggresively inlined here /// <summary> /// Returns a new vector whose elements are the absolute values of the given vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The absolute value vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Abs<T>(Vector<T> value) where T : struct { return Vector<T>.Abs(value); } /// <summary> /// Returns a new vector whose elements are the minimum of each pair of elements in the two given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The minimum vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Min<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.Min(left, right); } /// <summary> /// Returns a new vector whose elements are the maximum of each pair of elements in the two given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The maximum vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Max<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.Max(left, right); } // Specialized vector operations /// <summary> /// Returns the dot product of two vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The dot product.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static T Dot<T>(Vector<T> left, Vector<T> right) where T : struct { return Vector<T>.DotProduct(left, right); } /// <summary> /// Returns a new vector whose elements are the square roots of the given vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The square root vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> SquareRoot<T>(Vector<T> value) where T : struct { return Vector<T>.SquareRoot(value); } #endregion Vector Math Methods #region Named Arithmetic Operators /// <summary> /// Creates a new vector whose values are the sum of each pair of elements from the two given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The summed vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Add<T>(Vector<T> left, Vector<T> right) where T : struct { return left + right; } /// <summary> /// Creates a new vector whose values are the difference between each pairs of elements in the given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The difference vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Subtract<T>(Vector<T> left, Vector<T> right) where T : struct { return left - right; } /// <summary> /// Creates a new vector whose values are the product of each pair of elements from the two given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The summed vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Multiply<T>(Vector<T> left, Vector<T> right) where T : struct { return left * right; } /// <summary> /// Returns a new vector whose values are the values of the given vector each multiplied by a scalar value. /// </summary> /// <param name="left">The source vector.</param> /// <param name="right">The scalar factor.</param> /// <returns>The scaled vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Multiply<T>(Vector<T> left, T right) where T : struct { return left * right; } /// <summary> /// Returns a new vector whose values are the values of the given vector each multiplied by a scalar value. /// </summary> /// <param name="left">The scalar factor.</param> /// <param name="right">The source vector.</param> /// <returns>The scaled vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Multiply<T>(T left, Vector<T> right) where T : struct { return left * right; } /// <summary> /// Returns a new vector whose values are the result of dividing the first vector's elements /// by the corresponding elements in the second vector. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The divided vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Divide<T>(Vector<T> left, Vector<T> right) where T : struct { return left / right; } /// <summary> /// Returns a new vector whose elements are the given vector's elements negated. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The negated vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Negate<T>(Vector<T> value) where T : struct { return -value; } #endregion Named Arithmetic Operators #region Named Bitwise Operators /// <summary> /// Returns a new vector by performing a bitwise-and operation on each of the elements in the given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> BitwiseAnd<T>(Vector<T> left, Vector<T> right) where T : struct { return left & right; } /// <summary> /// Returns a new vector by performing a bitwise-or operation on each of the elements in the given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> BitwiseOr<T>(Vector<T> left, Vector<T> right) where T : struct { return left | right; } /// <summary> /// Returns a new vector whose elements are obtained by taking the one's complement of the given vector's elements. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The one's complement vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> OnesComplement<T>(Vector<T> value) where T : struct { return ~value; } /// <summary> /// Returns a new vector by performing a bitwise-exclusive-or operation on each of the elements in the given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> Xor<T>(Vector<T> left, Vector<T> right) where T : struct { return left ^ right; } /// <summary> /// Returns a new vector by performing a bitwise-and-not operation on each of the elements in the given vectors. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The resultant vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<T> AndNot<T>(Vector<T> left, Vector<T> right) where T : struct { return left & ~right; } #endregion Named Bitwise Operators #region Conversion Methods /// <summary> /// Reinterprets the bits of the given vector into those of a vector of unsigned bytes. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<Byte> AsVectorByte<T>(Vector<T> value) where T : struct { return (Vector<Byte>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of signed bytes. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<SByte> AsVectorSByte<T>(Vector<T> value) where T : struct { return (Vector<SByte>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of 16-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<UInt16> AsVectorUInt16<T>(Vector<T> value) where T : struct { return (Vector<UInt16>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of signed 16-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<Int16> AsVectorInt16<T>(Vector<T> value) where T : struct { return (Vector<Int16>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of unsigned 32-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<UInt32> AsVectorUInt32<T>(Vector<T> value) where T : struct { return (Vector<UInt32>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of signed 32-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<Int32> AsVectorInt32<T>(Vector<T> value) where T : struct { return (Vector<Int32>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of unsigned 64-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<UInt64> AsVectorUInt64<T>(Vector<T> value) where T : struct { return (Vector<UInt64>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of signed 64-bit integers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<Int64> AsVectorInt64<T>(Vector<T> value) where T : struct { return (Vector<Int64>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of 32-bit floating point numbers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<Single> AsVectorSingle<T>(Vector<T> value) where T : struct { return (Vector<Single>)value; } /// <summary> /// Reinterprets the bits of the given vector into those of a vector of 64-bit floating point numbers. /// </summary> /// <param name="value">The source vector</param> /// <returns>The reinterpreted vector.</returns> [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static Vector<Double> AsVectorDouble<T>(Vector<T> value) where T : struct { return (Vector<Double>)value; } #endregion Conversion Methods } }
//----------------------------------------------------------------------- // <copyright file="CslaModelBinder.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Model binder for use with CSLA .NET editable business objects.</summary> //----------------------------------------------------------------------- #if NETSTANDARD2_0 using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace Csla.Web.Mvc { /// <summary> /// Model binder for use with CSLA .NET editable business /// objects. /// </summary> public class CslaModelBinder : Csla.Server.ObjectFactory, IModelBinder { /// <summary> /// Creates a model binder wth an instance creator for root objects. /// </summary> /// <param name="instanceCreator">Instance creator for root objects.</param> public CslaModelBinder(Func<Type, Task<object>> instanceCreator) { _instanceCreator = instanceCreator; } /// <summary> /// Creates a model binder wth instance creators for root and child objects. /// </summary> /// <param name="instanceCreator">Instance creator for root objects.</param> /// <param name="childCreator">Instance creator for child objects.</param> public CslaModelBinder(Func<Type, Task<object>> instanceCreator, Func<IList, Type, Dictionary<string, string>, object> childCreator) { _instanceCreator = instanceCreator; _childCreator = childCreator; } private readonly Func<Type, Task<object>> _instanceCreator; private readonly Func<IList, Type, Dictionary<string, string>, object> _childCreator; /// <summary> /// Bind the form data to a new instance of an IBusinessBase object. /// </summary> /// <param name="bindingContext">Binding context</param> public async Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException(nameof(bindingContext)); } var result = await _instanceCreator(bindingContext.ModelType); if (result == null) return; if (typeof(Csla.Core.IEditableCollection).IsAssignableFrom(bindingContext.ModelType)) { BindBusinessListBase(bindingContext, result); } else if (typeof(Csla.Core.IEditableBusinessObject).IsAssignableFrom(bindingContext.ModelType)) { BindBusinessBase(bindingContext, result); } else { return; } bindingContext.Result = ModelBindingResult.Success(result); return; } private void BindBusinessBase(ModelBindingContext bindingContext, object result) { var properties = Csla.Core.FieldManager.PropertyInfoManager.GetRegisteredProperties(bindingContext.ModelType); foreach (var item in properties) { var index = $"{bindingContext.ModelName}.{item.Name}"; BindSingleProperty(bindingContext, result, item, index); } } private void BindBusinessListBase(ModelBindingContext bindingContext, object result) { var formKeys = bindingContext.ActionContext.HttpContext.Request.Form.Keys.Where(_ => _.StartsWith(bindingContext.ModelName)); var childType = Csla.Utilities.GetChildItemType(bindingContext.ModelType); var properties = Csla.Core.FieldManager.PropertyInfoManager.GetRegisteredProperties(childType); var list = (IList)result; var itemCount = formKeys.Count() / properties.Count(); for (int i = 0; i < itemCount; i++) { var child = _childCreator( list, childType, GetFormValuesForObject(bindingContext.ActionContext.HttpContext.Request.Form, bindingContext.ModelName, i, properties)); MarkAsChild(child); if (child == null) throw new InvalidOperationException($"Could not create instance of child type {childType}"); foreach (var item in properties) { var index = $"{bindingContext.ModelName}[{i}].{item.Name}"; BindSingleProperty(bindingContext, child, item, index); } if (!list.Contains(child)) list.Add(child); } } private Dictionary<string, string> GetFormValuesForObject( Microsoft.AspNetCore.Http.IFormCollection formData, string modelName, int index, Core.FieldManager.PropertyInfoList properties) { var result = new Dictionary<string, string>(); foreach (var item in properties) { var key = $"{modelName}[{index}].{item.Name}"; result.Add(item.Name, formData[key]); } return result; } private void BindSingleProperty(ModelBindingContext bindingContext, object result, Core.IPropertyInfo item, string index) { try { var value = bindingContext.ActionContext.HttpContext.Request.Form[index].FirstOrDefault(); if (!string.IsNullOrWhiteSpace(value)) { try { if (item.Type.Equals(typeof(string))) Csla.Reflection.MethodCaller.CallPropertySetter(result, item.Name, value); else Csla.Reflection.MethodCaller.CallPropertySetter(result, item.Name, Csla.Utilities.CoerceValue(item.Type, value.GetType(), null, value)); } catch { if (item.Type.Equals(typeof(string))) LoadProperty(result, item, value); else LoadProperty(result, item, Csla.Utilities.CoerceValue(item.Type, value.GetType(), null, value)); } } } catch (Exception ex) { throw new Exception($"Could not map {index} to model", ex); } } } /// <summary> /// Model binder provider that will use the CslaModelBinder for /// any type that implements the IBusinessBase interface. /// </summary> public class CslaModelBinderProvider : IModelBinderProvider { /// <summary> /// Creates a model binder provider that uses the default /// instance and child creators. /// </summary> public CslaModelBinderProvider() : this(CreateInstance, CreateChild) { } /// <summary> /// Creates a model binder provider that use custom /// instance and child creators. /// </summary> /// <param name="instanceCreator">Instance creator for root objects.</param> /// <param name="childCreator">Instance creator for child objects.</param> public CslaModelBinderProvider(Func<Type, Task<object>> instanceCreator, Func<IList, Type, Dictionary<string, string>, object> childCreator) { _instanceCreator = instanceCreator; _childCreator = childCreator; } internal static Task<object> CreateInstance(Type type) { var tcs = new TaskCompletionSource<object>(); tcs.SetResult(Csla.Reflection.MethodCaller.CreateInstance(type)); return tcs.Task; } internal static object CreateChild(IList parent, Type type, Dictionary<string, string> values) { return Csla.Reflection.MethodCaller.CreateInstance(type); } private readonly Func<Type, Task<object>> _instanceCreator; private readonly Func<IList, Type, Dictionary<string, string>, object> _childCreator; /// <summary> /// Gets the CslaModelBinder provider. /// </summary> /// <param name="context">Model binder provider context.</param> public IModelBinder GetBinder(ModelBinderProviderContext context) { if (typeof(Csla.Core.IEditableCollection).IsAssignableFrom(context.Metadata.ModelType)) return new CslaModelBinder(_instanceCreator, _childCreator); if (typeof(Csla.IBusinessBase).IsAssignableFrom(context.Metadata.ModelType)) return new CslaModelBinder(_instanceCreator); return null; } } } #elif !NETSTANDARD using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using System.ComponentModel; using System.Collections; namespace Csla.Web.Mvc { /// <summary> /// Model binder for use with CSLA .NET editable business /// objects. /// </summary> public class CslaModelBinder : DefaultModelBinder { private bool _checkRulesOnModelUpdated; /// <summary> /// Creates an instance of the model binder. /// </summary> /// <param name="CheckRulesOnModelUpdated">Value indicating if business rules will be checked after the model is updated.</param> public CslaModelBinder(bool CheckRulesOnModelUpdated = true) { _checkRulesOnModelUpdated = CheckRulesOnModelUpdated; } /// <summary> /// Binds the model by using the specified controller context and binding context. /// </summary> /// <param name="controllerContext">Controller Context</param> /// <param name="bindingContext">Binding Context</param> /// <returns>Bound object</returns> public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (typeof(Csla.Core.IEditableCollection).IsAssignableFrom((bindingContext.ModelType))) return BindCslaCollection(controllerContext, bindingContext); var suppress = bindingContext.Model as Csla.Core.ICheckRules; if (suppress != null) suppress.SuppressRuleChecking(); var result = base.BindModel(controllerContext, bindingContext); return result; } /// <summary> /// Bind CSLA Collection object using specified controller context and binding context /// </summary> /// <param name="controllerContext">Controller Context</param> /// <param name="bindingContext">Binding Context</param> /// <returns>Bound CSLA collection object</returns> private object BindCslaCollection(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext.Model == null) bindingContext.ModelMetadata.Model = CreateModel(controllerContext, bindingContext, bindingContext.ModelType); var collection = (IList)bindingContext.Model; for (int currIdx = 0; currIdx < collection.Count; currIdx++) { string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currIdx); if (!bindingContext.ValueProvider.ContainsPrefix(subIndexKey)) continue; //no value to update skip var elementModel = collection[currIdx]; var suppress = elementModel as Csla.Core.ICheckRules; if (suppress != null) suppress.SuppressRuleChecking(); var elementContext = new ModelBindingContext() { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => elementModel, elementModel.GetType()), ModelName = subIndexKey, ModelState = bindingContext.ModelState, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; if (OnModelUpdating(controllerContext, elementContext)) { //update element's properties foreach (PropertyDescriptor property in GetFilteredModelProperties(controllerContext, elementContext)) { BindProperty(controllerContext, elementContext, property); } OnModelUpdated(controllerContext, elementContext); } } return bindingContext.Model; } /// <summary> /// Creates an instance of the model if the controller implements /// IModelCreator. /// </summary> /// <param name="controllerContext">Controller context</param> /// <param name="bindingContext">Binding context</param> /// <param name="modelType">Type of model object</param> protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) { var controller = controllerContext.Controller as IModelCreator; if (controller != null) return controller.CreateModel(modelType); else return base.CreateModel(controllerContext, bindingContext, modelType); } /// <summary> /// Checks the validation rules for properties /// after the Model has been updated. /// </summary> /// <param name="controllerContext">Controller context</param> /// <param name="bindingContext">Binding context</param> protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) { var obj = bindingContext.Model as Csla.Core.BusinessBase; if (obj != null) { if (this._checkRulesOnModelUpdated) { var suppress = obj as Csla.Core.ICheckRules; if (suppress != null) { suppress.ResumeRuleChecking(); suppress.CheckRules(); } } var errors = from r in obj.BrokenRulesCollection where r.Severity == Csla.Rules.RuleSeverity.Error select r; foreach (var item in errors) { ModelState state; string mskey = CreateSubPropertyName(bindingContext.ModelName, item.Property ?? string.Empty); if (bindingContext.ModelState.TryGetValue(mskey, out state)) { if (state.Errors.Where(e => e.ErrorMessage == item.Description).Any()) continue; else bindingContext.ModelState.AddModelError(mskey, item.Description); } else if (mskey == string.Empty) bindingContext.ModelState.AddModelError(bindingContext.ModelName, item.Description); } } else if (!(bindingContext.Model is IViewModel)) base.OnModelUpdated(controllerContext, bindingContext); } /// <summary> /// Prevents IDataErrorInfo validation from /// operating against editable objects. /// </summary> /// <param name="controllerContext">Controller context</param> /// <param name="bindingContext">Binding context</param> /// <param name="propertyDescriptor">Property descriptor</param> /// <param name="value">Value</param> protected override void OnPropertyValidated(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value) { if (!(bindingContext.Model is Csla.Core.BusinessBase)) base.OnPropertyValidated(controllerContext, bindingContext, propertyDescriptor, value); } } } #endif
using System.Runtime.CompilerServices; namespace System { [Imported(ObeysTypeSystem = true)] [ScriptNamespace("ss")] public struct TimeSpan : IComparable<TimeSpan>, IEquatable<TimeSpan> { [InlineConstant] public const long TicksPerMillisecond = 10000L; [InlineConstant] public const long TicksPerSecond = 10000000L; [InlineConstant] public const long TicksPerMinute = 600000000L; [InlineConstant] public const long TicksPerHour = 36000000000L; [InlineConstant] public const long TicksPerDay = 864000000000L; public static readonly TimeSpan Zero = new TimeSpan(0); //TODO //public static readonly TimeSpan MinValue = new TimeSpan(long.MinValue); //public static readonly TimeSpan MaxValue = new TimeSpan(long.MaxValue); private TimeSpan(DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor _) { } public TimeSpan(long ticks) { } [InlineCode("new {$System.TimeSpan}(((({hours} * 60 + {minutes}) * 60) + {seconds}) * 10000000)")] public TimeSpan(int hours, int minutes, int seconds) { } [InlineCode("new {$System.TimeSpan}((((({days} * 24 + {hours}) * 60 + {minutes}) * 60) + {seconds}) * 10000000)")] public TimeSpan(int days, int hours, int minutes, int seconds) { } [InlineCode("new {$System.TimeSpan}(((((({days} * 24 + {hours}) * 60 + {minutes}) * 60) + {seconds}) * 1000 + {milliseconds}) * 10000)")] public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { } public int Days { [InlineCode("{this}.ticks / 864000000000 | 0")] get { return 0; } } public int Hours { [InlineCode("{this}.ticks / 36000000000 % 24 | 0")] get { return 0; } } public int Milliseconds { [InlineCode("{this}.ticks / 10000 % 1000 | 0")] get { return 0; } } public int Minutes { [InlineCode("{this}.ticks / 600000000 % 60 | 0")] get { return 0; } } public int Seconds { [InlineCode("{this}.ticks / 10000000 % 60 | 0")] get { return 0; } } [IntrinsicProperty] public long Ticks { get { return 0; } } public double TotalDays { [InlineCode("{this}.ticks / 864000000000")] get { return 0; } } public double TotalHours { [InlineCode("{this}.ticks / 36000000000")] get { return 0; } } public double TotalMilliseconds { [InlineCode("{this}.ticks / 10000")] get { return 0; } } public double TotalMinutes { [InlineCode("{this}.ticks / 600000000")] get { return 0; } } public double TotalSeconds { [InlineCode("{this}.ticks / 10000000")] get { return 0; } } [InlineCode("new {$System.TimeSpan}({this}.ticks + {ts}.ticks)")] public TimeSpan Add(TimeSpan ts) { return default(TimeSpan); } [InlineCode("new {$System.TimeSpan}({this}.ticks - {ts}.ticks)")] public TimeSpan Subtract(TimeSpan ts) { return default(TimeSpan); } [InlineCode("new {$System.TimeSpan}({$System.Math}.abs({this}.ticks))")] public TimeSpan Duration() { return default(TimeSpan); } [InlineCode("new {$System.TimeSpan}(-{this}.ticks)")] public TimeSpan Negate() { return default(TimeSpan); } [InlineCode("{t1}.compareTo({t2})")] public static int Compare(TimeSpan t1, TimeSpan t2) { return 0; } public int CompareTo(TimeSpan other) { return 0; } public bool Equals(TimeSpan other) { return false; } [InlineCode("{t1}.ticks === {t2}.ticks")] public static bool Equals(TimeSpan t1, TimeSpan t2) { return false; } [InlineCode("new {$System.TimeSpan}({value} * 864000000000)")] public static TimeSpan FromDays(double value) { return default(TimeSpan); } [InlineCode("new {$System.TimeSpan}({value} * 36000000000)")] public static TimeSpan FromHours(double value) { return default(TimeSpan); } [InlineCode("new {$System.TimeSpan}({value} * 10000)")] public static TimeSpan FromMilliseconds(double value) { return default(TimeSpan); } [InlineCode("new {$System.TimeSpan}({value} * 600000000)")] public static TimeSpan FromMinutes(double value) { return default(TimeSpan); } [InlineCode("new {$System.TimeSpan}({value} * 10000000)")] public static TimeSpan FromSeconds(double value) { return default(TimeSpan); } [InlineCode("new {$System.TimeSpan}({value})")] public static TimeSpan FromTicks(long value) { return default(TimeSpan); } [InlineCode("new {$System.TimeSpan}({t1}.ticks + {t2}.ticks)")] public static TimeSpan operator+(TimeSpan t1, TimeSpan t2) { return default(TimeSpan); } [InlineCode("new {$System.TimeSpan}({t1}.ticks - {t2}.ticks)")] public static TimeSpan operator-(TimeSpan t1, TimeSpan t2) { return default(TimeSpan); } [InlineCode("{t1}.ticks === {t2}.ticks")] public static bool operator==(TimeSpan t1, TimeSpan t2) { return false; } [InlineCode("{t1}.ticks !== {t2}.ticks")] public static bool operator!=(TimeSpan t1, TimeSpan t2) { return false; } [InlineCode("{t1}.ticks > {t2}.ticks")] public static bool operator>(TimeSpan t1, TimeSpan t2) { return false; } [InlineCode("{t1}.ticks >= {t2}.ticks")] public static bool operator>=(TimeSpan t1, TimeSpan t2) { return false; } [InlineCode("{t1}.ticks < {t2}.ticks")] public static bool operator<(TimeSpan t1, TimeSpan t2) { return false; } [InlineCode("{t1}.ticks <= {t2}.ticks")] public static bool operator<=(TimeSpan t1, TimeSpan t2) { return false; } [InlineCode("new {$System.TimeSpan}(-{ts}.ticks)")] public static TimeSpan operator-(TimeSpan ts) { return default(TimeSpan); } [InlineCode("new {$System.TimeSpan}({ts}.ticks)")] public static TimeSpan operator+(TimeSpan ts) { return default(TimeSpan); } } }