context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
namespace System.Abstract
{
/// <summary>
/// ServiceCacheRegistrar
/// </summary>
/// <remarks>
/// [Wrap]SC\\{Anchor.FullName}::{Registration.Name}[#]
/// ServiceCacheRegistrar._namePrefix - SC\\{Anchor.FullName}::
/// Registration.AbsoluteName = SC\\{Anchor.FullName}::{Registration.Name}
/// </remarks>
public class ServiceCacheRegistrar
{
private static ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
private static Dictionary<Type, ServiceCacheRegistrar> _items = new Dictionary<Type, ServiceCacheRegistrar>();
private ReaderWriterLockSlim _setRwLock = new ReaderWriterLockSlim();
private HashSet<IServiceCacheRegistration> _set = new HashSet<IServiceCacheRegistration>();
private Dictionary<string, IServiceCacheRegistration> _setAsName = new Dictionary<string, IServiceCacheRegistration>();
private string _namePrefix;
/// <summary>
/// IDispatch
/// </summary>
public interface IDispatch { }
internal ServiceCacheRegistrar(Type anchorType)
{
_namePrefix = "SC\\" + anchorType.FullName + "::";
AnchorType = anchorType;
}
/// <summary>
/// Gets this instance.
/// </summary>
/// <typeparam name="TAnchor">The type of the anchor.</typeparam>
/// <returns></returns>
public static ServiceCacheRegistrar Get<TAnchor>() { return Get(typeof(TAnchor)); }
/// <summary>
/// Gets the specified anchor type.
/// </summary>
/// <param name="anchorType">Type of the anchor.</param>
/// <returns></returns>
public static ServiceCacheRegistrar Get(Type anchorType)
{
ServiceCacheRegistrar registrar;
TryGet(anchorType, out registrar, true);
return registrar;
}
/// <summary>
/// Registers all below.
/// </summary>
/// <typeparam name="T"></typeparam>
public static void RegisterAllBelow<T>() { RegisterAllBelow(typeof(T)); }
/// <summary>
/// Registers all below.
/// </summary>
/// <param name="type">The type.</param>
public static void RegisterAllBelow(Type type)
{
var registrationType = typeof(IServiceCacheRegistration);
var registrar = Get(type);
var types = type.GetFields(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic)
.Where(f => registrationType.IsAssignableFrom(f.FieldType))
.Select(f => (ServiceCacheRegistration)f.GetValue(null));
foreach (var t in types)
registrar.Register(t);
// recurse down
foreach (var t in type.GetNestedTypes())
RegisterAllBelow(t);
}
/// <summary>
/// Gets or sets the type of the anchor.
/// </summary>
/// <value>
/// The type of the anchor.
/// </value>
public Type AnchorType { get; private set; }
/// <summary>
/// Registers the specified registration.
/// </summary>
/// <param name="name">The registration name.</param>
/// <param name="builder">The builder.</param>
/// <param name="cacheTags">The cache tags.</param>
public void Register(string name, CacheItemBuilder builder, params string[] cacheTags) { Register(new ServiceCacheRegistration(name, new CacheItemPolicy(60), builder, cacheTags)); }
/// <summary>
/// Registers the specified registration.
/// </summary>
/// <param name="name">The registration name.</param>
/// <param name="minuteTimeout">The minute timeout.</param>
/// <param name="builder">The builder.</param>
/// <param name="cacheTags">The cache tags.</param>
public void Register(string name, int minuteTimeout, CacheItemBuilder builder, params string[] cacheTags) { Register(new ServiceCacheRegistration(name, new CacheItemPolicy(minuteTimeout), builder, cacheTags)); }
/// <summary>
/// Registers the specified registration.
/// </summary>
/// <param name="name">The registration name.</param>
/// <param name="itemPolicy">The cache command.</param>
/// <param name="builder">The builder.</param>
/// <param name="cacheTags">The cache tags.</param>
public void Register(string name, CacheItemPolicy itemPolicy, CacheItemBuilder builder, params string[] cacheTags) { Register(new ServiceCacheRegistration(name, itemPolicy, builder, cacheTags)); }
/// <summary>
/// Registers the specified registration.
/// </summary>
/// <param name="registration">The registration.</param>
public void Register(IServiceCacheRegistration registration)
{
if (registration == null)
throw new ArgumentNullException("registration");
_setRwLock.EnterWriteLock();
try
{
if (_set.Contains(registration))
throw new InvalidOperationException(string.Format(Local.RedefineDataCacheAB, AnchorType.ToString(), registration.Name));
// add
var registrationName = registration.Name;
if (string.IsNullOrEmpty(registrationName))
throw new ArgumentNullException("registration.Name");
if (registrationName.IndexOf("::") > -1)
throw new ArgumentException(string.Format(Local.ScopeCharacterNotAllowedA, registrationName), "registration");
if (_setAsName.ContainsKey(registrationName))
throw new ArgumentException(string.Format(Local.RedefineNameA, registrationName), "registration");
_setAsName.Add(registrationName, registration);
_set.Add(registration);
// link-in
registration.AttachRegistrar(this, _namePrefix + registrationName);
}
finally { _setRwLock.ExitWriteLock(); }
}
/// <summary>
/// Clears this all registrations.
/// </summary>
public void Clear()
{
_setRwLock.EnterWriteLock();
try
{
_setAsName.Clear();
_set.Clear();
}
finally { _setRwLock.ExitWriteLock(); }
}
/// <summary>
/// Determines whether the specified key contains key.
/// </summary>
/// <param name="registration">The registration.</param>
/// <returns>
/// <c>true</c> if the specified key contains key; otherwise, <c>false</c>.
/// </returns>
public bool Contains(IServiceCacheRegistration registration)
{
_setRwLock.EnterReadLock();
try { return _set.Contains(registration); }
finally { _setRwLock.ExitReadLock(); }
}
/// <summary>
/// Determines whether the specified name has been registered.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>
/// <c>true</c> if the specified name has been registered; otherwise, <c>false</c>.
/// </returns>
public bool Contains(string name)
{
_setRwLock.EnterReadLock();
try { return _setAsName.ContainsKey(name); }
finally { _setRwLock.ExitReadLock(); }
}
/// <summary>
/// Removes the specified registration.
/// </summary>
/// <param name="registration">The registration.</param>
/// <returns></returns>
public bool Remove(IServiceCacheRegistration registration)
{
_setRwLock.EnterWriteLock();
try { _setAsName.Remove(registration.Name); return _set.Remove(registration); }
finally { _setRwLock.ExitWriteLock(); }
}
/// <summary>
/// Removes the specified registration.
/// </summary>
/// <param name="name">The registration name.</param>
/// <returns></returns>
public bool Remove(string name)
{
_setRwLock.EnterWriteLock();
try { var registration = _setAsName[name]; _setAsName.Remove(name); return _set.Remove(registration); }
finally { _setRwLock.ExitWriteLock(); }
}
internal IEnumerable<IServiceCacheRegistration> All
{
get { return _set; }
}
/// <summary>
/// Tries the get.
/// </summary>
/// <param name="anchorType">Type of the anchor.</param>
/// <param name="registrar">The registrar.</param>
/// <param name="createIfRequired">if set to <c>true</c> [create if required].</param>
/// <returns></returns>
public static bool TryGet(Type anchorType, out ServiceCacheRegistrar registrar, bool createIfRequired)
{
if (anchorType == null)
throw new ArgumentNullException("anchorType");
_rwLock.EnterUpgradeableReadLock();
try
{
var exists = _items.TryGetValue(anchorType, out registrar);
if (exists || !createIfRequired)
return exists;
_rwLock.EnterWriteLock();
try
{
if (!_items.TryGetValue(anchorType, out registrar))
{
// create
registrar = new ServiceCacheRegistrar(anchorType);
_items.Add(anchorType, registrar);
}
}
finally { _rwLock.ExitWriteLock(); }
return true;
}
finally { _rwLock.ExitUpgradeableReadLock(); }
}
/// <summary>
/// Tries the get value.
/// </summary>
/// <param name="registration">The registration.</param>
/// <param name="recurses">The recurses.</param>
/// <param name="foundRegistration">The found registration.</param>
/// <returns></returns>
public static bool TryGetValue(IServiceCacheRegistration registration, ref int recurses, out IServiceCacheRegistration foundRegistration)
{
_rwLock.EnterReadLock();
try
{
var registrar = registration.Registrar;
if (registrar != null)
{
// local check
var foreignRegistration = (registration as ServiceCacheForeignRegistration);
if (foreignRegistration == null)
{
foundRegistration = registration;
return true;
}
// foreign recurse
if (recurses++ > 4)
throw new InvalidOperationException(Local.ExceedRecurseCount);
// touch - starts foreign static constructor
var foreignType = foreignRegistration.ForeignType;
foreignType.InvokeMember("Touch", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static, null, null, null);
return TryGetValue(foreignType, foreignRegistration.ForeignName, ref recurses, out foundRegistration);
}
foundRegistration = null;
return false;
}
finally { _rwLock.ExitReadLock(); }
}
/// <summary>
/// Tries the get value.
/// </summary>
/// <param name="anchorType">Type of the anchor.</param>
/// <param name="registrationName">Name of the registration.</param>
/// <param name="recurses">The recurses.</param>
/// <param name="foundRegistration">The found registration.</param>
/// <returns></returns>
public static bool TryGetValue(Type anchorType, string registrationName, ref int recurses, out IServiceCacheRegistration foundRegistration)
{
_rwLock.EnterReadLock();
try
{
ServiceCacheRegistrar registrar;
if (_items.TryGetValue(anchorType, out registrar))
{
// registration locals
var setRwLock = registrar._setRwLock;
var setAsId = registrar._setAsName;
setRwLock.EnterReadLock();
try
{
IServiceCacheRegistration registration;
if (setAsId.TryGetValue(registrationName, out registration))
{
// local check
var foreignRegistration = (registration as ServiceCacheForeignRegistration);
if (foreignRegistration == null)
{
foundRegistration = registration;
return true;
}
// foreign recurse
if (recurses++ > 4)
throw new InvalidOperationException(Local.ExceedRecurseCount);
// touch - starts foreign static constructor
var foreignType = foreignRegistration.ForeignType;
foreignType.InvokeMember("Touch", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static, null, null, null);
return TryGetValue(foreignType, foreignRegistration.ForeignName, ref recurses, out foundRegistration);
}
}
finally { setRwLock.ExitReadLock(); }
}
foundRegistration = null;
return false;
}
finally { _rwLock.ExitReadLock(); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using log4net;
using Rhino.ServiceBus.DataStructures;
using Rhino.ServiceBus.Exceptions;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Internal;
using Rhino.ServiceBus.MessageModules;
using Rhino.ServiceBus.Messages;
namespace Rhino.ServiceBus.Msmq
{
public class MsmqSubscriptionStorage : ISubscriptionStorage, IMessageModule
{
private readonly Uri subscriptionQueue;
private readonly Hashtable<string, List<WeakReference>> localInstanceSubscriptions = new Hashtable<string, List<WeakReference>>();
private readonly MultiValueIndexHashtable<Guid, string, Uri, string> remoteInstanceSubscriptions = new MultiValueIndexHashtable<Guid, string, Uri, string>();
private readonly Hashtable<string, HashSet<Uri>> subscriptions = new Hashtable<string, HashSet<Uri>>();
private readonly Hashtable<TypeAndUriKey, IList<string>> subscriptionMessageIds = new Hashtable<TypeAndUriKey, IList<string>>();
private readonly IReflection reflection;
private readonly IMessageSerializer messageSerializer;
private readonly ILog logger = LogManager.GetLogger(typeof(MsmqSubscriptionStorage));
private readonly IQueueStrategy queueStrategy;
public MsmqSubscriptionStorage(
IReflection reflection,
IMessageSerializer messageSerializer,
Uri subscriptionQueue,
IQueueStrategy queueStrategy
)
{
this.reflection = reflection;
this.messageSerializer = messageSerializer;
this.queueStrategy = queueStrategy;
this.subscriptionQueue = this.queueStrategy.CreateSubscriptionQueueUri(subscriptionQueue);
}
public void Initialize()
{
logger.DebugFormat("Initializing msmq subscription storage on: {0}", subscriptionQueue);
using (var queue = CreateSubscriptionQueue(subscriptionQueue, QueueAccessMode.Receive))
using (var enumerator = queue.GetMessageEnumerator2())
{
while (enumerator.MoveNext(TimeSpan.FromMilliseconds(0)))
{
var current = enumerator.Current;
if (current == null)
continue;
object[] msgs;
try
{
msgs = messageSerializer.Deserialize(current.BodyStream);
}
catch (Exception e)
{
throw new SubscriptionException("Could not deserialize message from subscription queue", e);
}
try
{
foreach (var msg in msgs)
{
HandleAdministrativeMessage(new CurrentMessageInformation
{
AllMessages = msgs,
CorrelationId = CorrelationId.Empty,
Message = msg,
MessageId = CorrelationId.Parse(current.Id),
Source = subscriptionQueue,
});
}
}
catch (Exception e)
{
throw new SubscriptionException("Failed to process subscription records", e);
}
}
}
}
private void AddMessageIdentifierForTracking(string messageId, string messageType, Uri uri)
{
subscriptionMessageIds.Write(writer =>
{
var key = new TypeAndUriKey { TypeName = messageType, Uri = uri };
IList<string> value;
if (writer.TryGetValue(key, out value) == false)
{
value = new List<string>();
writer.Add(key, value);
}
value.Add(messageId);
});
}
private void RemoveSubscriptionMessageFromQueue(MessageQueue queue, string type, Uri uri)
{
subscriptionMessageIds.Write(writer =>
{
var key = new TypeAndUriKey
{
TypeName = type,
Uri = uri
};
IList<string> messageIds;
if (writer.TryGetValue(key, out messageIds) == false)
return;
foreach (var msgId in messageIds)
{
queue.ConsumeMessage(msgId);
}
writer.Remove(key);
});
}
private static MessageQueue CreateSubscriptionQueue(Uri subscriptionQueue, QueueAccessMode accessMode)
{
var description = MsmqUtil.GetQueuePath(subscriptionQueue);
MessageQueue queue;
try
{
queue = new MessageQueue(description, accessMode);
}
catch (Exception e)
{
throw new SubscriptionException("Could not open subscription queue (" + subscriptionQueue + ")", e);
}
queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
return queue;
}
public IEnumerable<Uri> GetSubscriptionsFor(Type type)
{
HashSet<Uri> subscriptionForType = null;
subscriptions.Read(reader => reader.TryGetValue(type.FullName, out subscriptionForType));
var subscriptionsFor = subscriptionForType ?? new HashSet<Uri>();
List<Uri> instanceSubscriptions;
remoteInstanceSubscriptions.TryGet(type.FullName, out instanceSubscriptions);
subscriptionsFor.UnionWith(instanceSubscriptions);
return subscriptionsFor;
}
public void RemoveLocalInstanceSubscription(IMessageConsumer consumer)
{
var messagesConsumes = reflection.GetMessagesConsumed(consumer);
bool changed = false;
var list = new List<WeakReference>();
localInstanceSubscriptions.Write(writer =>
{
foreach (var type in messagesConsumes)
{
List<WeakReference> value;
if (writer.TryGetValue(type.FullName, out value) == false)
continue;
writer.Remove(type.FullName);
list.AddRange(value);
}
});
foreach (WeakReference reference in list)
{
if (ReferenceEquals(reference.Target, consumer))
continue;
changed = true;
}
if (changed)
RaiseSubscriptionChanged();
}
public object[] GetInstanceSubscriptions(Type type)
{
List<WeakReference> value = null;
localInstanceSubscriptions.Read(reader => reader.TryGetValue(type.FullName, out value));
if (value == null)
return new object[0];
var liveInstances = value
.Select(x => x.Target)
.Where(x => x != null)
.ToArray();
if (liveInstances.Length != value.Count)//cleanup
{
localInstanceSubscriptions.Write(writer => value.RemoveAll(x => x.IsAlive == false));
}
return liveInstances;
}
public bool HandleAdministrativeMessage(CurrentMessageInformation msgInfo)
{
var addSubscription = msgInfo.Message as AddSubscription;
if (addSubscription != null)
{
return ConsumeAddSubscription(msgInfo, addSubscription);
}
var removeSubscription = msgInfo.Message as RemoveSubscription;
if (removeSubscription != null)
{
return ConsumeRemoveSubscription(removeSubscription);
}
var addInstanceSubscription = msgInfo.Message as AddInstanceSubscription;
if (addInstanceSubscription != null)
{
return ConsumeAddInstanceSubscription(msgInfo, addInstanceSubscription);
}
var removeInstanceSubscription = msgInfo.Message as RemoveInstanceSubscription;
if (removeInstanceSubscription != null)
{
return ConsumeRemoveInstanceSubscrion(removeInstanceSubscription);
}
return false;
}
private bool ConsumeRemoveInstanceSubscrion(RemoveInstanceSubscription subscription)
{
string msgId;
if(remoteInstanceSubscriptions.TryRemove(subscription.InstanceSubscriptionKey,out msgId))
{
using (var queue = CreateSubscriptionQueue(subscriptionQueue, QueueAccessMode.Receive))
{
queue.ConsumeMessage(msgId);
}
RaiseSubscriptionChanged();
}
return true;
}
private bool ConsumeAddInstanceSubscription(CurrentMessageInformation msgInfo, AddInstanceSubscription subscription)
{
remoteInstanceSubscriptions.Add(
subscription.InstanceSubscriptionKey,
subscription.Type,
new Uri(subscription.Endpoint),
msgInfo.MessageId);
var msmqMsgInfo = msgInfo as MsmqCurrentMessageInformation;
if (msmqMsgInfo != null)
queueStrategy.MoveToSubscriptionQueue(msmqMsgInfo.Queue, msmqMsgInfo.MsmqMessage);
RaiseSubscriptionChanged();
return true;
}
private bool ConsumeRemoveSubscription(RemoveSubscription removeSubscription)
{
RemoveSubscription(removeSubscription.Type, removeSubscription.Endpoint);
return true;
}
private bool ConsumeAddSubscription(CurrentMessageInformation msgInfo, AddSubscription addSubscription)
{
bool newSubscription = AddSubscription(addSubscription.Type, addSubscription.Endpoint);
AddMessageIdentifierForTracking(msgInfo.MessageId.ToString(), addSubscription.Type,
new Uri(addSubscription.Endpoint));
var msmqMsgInfo = msgInfo as MsmqCurrentMessageInformation;
if (msmqMsgInfo != null && newSubscription)
{
queueStrategy.MoveToSubscriptionQueue(msmqMsgInfo.Queue, msmqMsgInfo.MsmqMessage);
return true;
}
return false;
}
public event Action SubscriptionChanged;
public bool AddSubscription(string type, string endpoint)
{
bool added = false;
subscriptions.Write(writer =>
{
HashSet<Uri> subscriptionsForType;
if (writer.TryGetValue(type, out subscriptionsForType) == false)
{
subscriptionsForType = new HashSet<Uri>();
writer.Add(type, subscriptionsForType);
}
var uri = new Uri(endpoint);
added = subscriptionsForType.Add(uri);
logger.InfoFormat("Added subscription for {0} on {1}",
type, uri);
});
RaiseSubscriptionChanged();
return added;
}
private void RaiseSubscriptionChanged()
{
var copy = SubscriptionChanged;
if (copy != null)
copy();
}
public void RemoveSubscription(string type, string endpoint)
{
var uri = new Uri(endpoint);
using (var queue = CreateSubscriptionQueue(subscriptionQueue, QueueAccessMode.Receive))
{
RemoveSubscriptionMessageFromQueue(queue, type, uri);
}
subscriptions.Write(writer =>
{
HashSet<Uri> subscriptionsForType;
if (writer.TryGetValue(type, out subscriptionsForType) == false)
{
subscriptionsForType = new HashSet<Uri>();
writer.Add(type, subscriptionsForType);
}
subscriptionsForType.Remove(uri);
logger.InfoFormat("Removed subscription for {0} on {1}",
type, endpoint);
});
RaiseSubscriptionChanged();
}
public void AddLocalInstanceSubscription(IMessageConsumer consumer)
{
localInstanceSubscriptions.Write(writer =>
{
foreach (var type in reflection.GetMessagesConsumed(consumer))
{
List<WeakReference> value;
if (writer.TryGetValue(type.FullName, out value) == false)
{
value = new List<WeakReference>();
writer.Add(type.FullName, value);
}
value.Add(new WeakReference(consumer));
}
});
RaiseSubscriptionChanged();
}
void IMessageModule.Init(ITransport transport)
{
transport.AdministrativeMessageArrived += HandleAdministrativeMessage;
}
void IMessageModule.Stop(ITransport transport)
{
transport.AdministrativeMessageArrived -= HandleAdministrativeMessage;
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace CustomerManagerWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an add-in event
/// </summary>
/// <param name="properties">Properties of an add-in event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted add-in. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust add-in.
/// </summary>
/// <returns>True if this is a high trust add-in.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted add-in configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// Copyright (c) Rotorz Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Rotorz.Tile.Editor
{
/// <summary>
/// Base class for custom Unity editor windows.
/// </summary>
public abstract class RotorzWindow : EditorWindow, IRepaintableUI, IFocusableUI, ICloseableUI
{
/// <summary>
/// Indicates whether window should be centered when first shown.
/// </summary>
public enum CenterMode
{
/// <summary>
/// Do not automatically center window.
/// </summary>
No = 0,
/// <summary>
/// Automatically center window upon first being shown.
/// </summary>
Once,
/// <summary>
/// Always automatically center window upon being shown.
/// </summary>
Always,
}
/// <summary>
/// Provides efficient access to active window instances.
/// </summary>
private static Dictionary<Type, RotorzWindow> s_Instances = new Dictionary<Type, RotorzWindow>();
internal static T GetInstance<T>() where T : RotorzWindow
{
return s_Instances.ContainsKey(typeof(T))
? (T)s_Instances[typeof(T)]
: null;
}
private static bool s_ShouldAssignCenterOnEnable;
private static CenterMode s_AssignCenterOnEnable;
/// <summary>
/// Get utility window instance and create if not already shown.
/// </summary>
/// <typeparam name="T">Type of <see cref="RotorzWindow"/> to get.</typeparam>
/// <param name="title">Title text for window.</param>
/// <param name="focus">Indicates whether window should be focused.</param>
/// <returns>
/// The <see cref="RotorzWindow"/> instance.
/// </returns>
internal static T GetUtilityWindow<T>(string title, bool focus) where T : RotorzWindow
{
try {
s_ShouldAssignCenterOnEnable = true;
s_AssignCenterOnEnable = RtsPreferences.AlwaysCenterUtilityWindows
? CenterMode.Always
: CenterMode.Once;
return GetWindow<T>(true, title, focus);
}
finally {
s_ShouldAssignCenterOnEnable = false;
}
}
/// <inheritdoc cref="GetUtilityWindow{T}(string, bool)"/>
internal static T GetUtilityWindow<T>(string title) where T : RotorzWindow
{
return GetUtilityWindow<T>(title, true);
}
/// <inheritdoc cref="GetUtilityWindow{T}(string, bool)"/>
internal static T GetUtilityWindow<T>(bool focus) where T : RotorzWindow
{
return GetUtilityWindow<T>(null, focus);
}
/// <inheritdoc cref="GetUtilityWindow{T}(string, bool)"/>
internal static T GetUtilityWindow<T>() where T : RotorzWindow
{
return GetUtilityWindow<T>(null, true);
}
/// <summary>
/// Repaint window of specified type if window is shown.
/// </summary>
/// <typeparam name="T">Type of <see cref="RotorzWindow"/> to repaint.</typeparam>
internal static void RepaintIfShown<T>() where T : RotorzWindow
{
var window = GetInstance<T>();
if (window != null) {
window.Repaint();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="RotorzWindow"/> class.
/// </summary>
public RotorzWindow()
{
}
/// <summary>
/// Gets or sets whether window should be centered upon first being shown.
/// </summary>
public CenterMode CenterWhenFirstShown { get; set; }
/// <summary>
/// Gets or sets initial size of window.
/// </summary>
public Vector2 InitialSize { get; set; }
#region Messages and Events
private void OnEnable()
{
s_Instances[this.GetType()] = this;
if (s_ShouldAssignCenterOnEnable) {
s_ShouldAssignCenterOnEnable = false;
this.CenterWhenFirstShown = s_AssignCenterOnEnable;
}
this.DoEnable();
// Trigger repaint of window since existing windows no longer seem to get
// repainted after an assembly reload occurs in Unity 5.3.
this.Repaint();
}
private void OnDisable()
{
this.DoDisable();
}
private void OnDestroy()
{
s_Instances[this.GetType()] = null;
this.DoDestroy();
}
#endregion
[NonSerialized]
private bool hasInitializedPosition;
private void InitializePosition()
{
this.hasInitializedPosition = true;
string prefsKey = GetType().FullName + ".HasShownOnce";
if (this.CenterWhenFirstShown == CenterMode.Always || !EditorPrefs.GetBool(prefsKey)) {
EditorPrefs.SetBool(prefsKey, true);
Vector2 size = this.InitialSize;
if (size.x > 30 && size.y > 30) {
Rect newPosition = position;
if (this.CenterWhenFirstShown != CenterMode.No) {
newPosition.x = (Screen.currentResolution.width - size.x) / 2;
newPosition.y = (Screen.currentResolution.height - size.y) / 2;
}
newPosition.width = size.x;
newPosition.height = size.y;
this.position = newPosition;
}
}
}
private void OnGUI()
{
if (!this.hasInitializedPosition) {
this.InitializePosition();
}
this.titleContent.image = RotorzEditorStyles.Skin.DefaultWindowIcon;
this.DoGUI();
}
/// <summary>
/// Replacement for <c>OnEnable</c> which can be overridden as needed.
/// </summary>
protected virtual void DoEnable()
{
}
/// <summary>
/// Replacement for <c>OnDisable</c> which can be overridden as needed.
/// </summary>
protected virtual void DoDisable()
{
}
/// <summary>
/// Replacement for <c>OnDestroy</c> which can be overridden as needed.
/// </summary>
protected virtual void DoDestroy()
{
}
/// <summary>
/// Replacement for <c>OnGUI</c> which can be overridden as needed.
/// </summary>
protected virtual void DoGUI()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Localization;
using Nop.Core.Domain.Seo;
namespace Nop.Services.Seo
{
/// <summary>
/// Provides information about URL records
/// </summary>
public partial class UrlRecordService : IUrlRecordService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : entity ID
/// {1} : entity name
/// {2} : language ID
/// </remarks>
private const string URLRECORD_ACTIVE_BY_ID_NAME_LANGUAGE_KEY = "Nop.urlrecord.active.id-name-language-{0}-{1}-{2}";
/// <summary>
/// Key for caching
/// </summary>
private const string URLRECORD_ALL_KEY = "Nop.urlrecord.all";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : slug
/// </remarks>
private const string URLRECORD_BY_SLUG_KEY = "Nop.urlrecord.active.slug-{0}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string URLRECORD_PATTERN_KEY = "Nop.urlrecord.";
#endregion
#region Fields
private readonly IRepository<UrlRecord> _urlRecordRepository;
private readonly ICacheManager _cacheManager;
private readonly LocalizationSettings _localizationSettings;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="cacheManager">Cache manager</param>
/// <param name="urlRecordRepository">URL record repository</param>
/// <param name="localizationSettings">Localization settings</param>
public UrlRecordService(ICacheManager cacheManager,
IRepository<UrlRecord> urlRecordRepository,
LocalizationSettings localizationSettings)
{
this._cacheManager = cacheManager;
this._urlRecordRepository = urlRecordRepository;
this._localizationSettings = localizationSettings;
}
#endregion
#region Utilities
protected UrlRecordForCaching Map(UrlRecord record)
{
if (record == null)
throw new ArgumentNullException("record");
var urlRecordForCaching = new UrlRecordForCaching
{
Id = record.Id,
EntityId = record.EntityId,
EntityName = record.EntityName,
Slug = record.Slug,
IsActive = record.IsActive,
LanguageId = record.LanguageId
};
return urlRecordForCaching;
}
/// <summary>
/// Gets all cached URL records
/// </summary>
/// <returns>cached URL records</returns>
protected virtual IList<UrlRecordForCaching> GetAllUrlRecordsCached()
{
//cache
string key = string.Format(URLRECORD_ALL_KEY);
return _cacheManager.Get(key, () =>
{
//we use no tracking here for performance optimization
//anyway records are loaded only for read-only operations
var query = from ur in _urlRecordRepository.TableNoTracking
select ur;
var urlRecords = query.ToList();
var list = new List<UrlRecordForCaching>();
foreach (var ur in urlRecords)
{
var urlRecordForCaching = Map(ur);
list.Add(urlRecordForCaching);
}
return list;
});
}
#endregion
#region Nested classes
[Serializable]
public class UrlRecordForCaching
{
public int Id { get; set; }
public int EntityId { get; set; }
public string EntityName { get; set; }
public string Slug { get; set; }
public bool IsActive { get; set; }
public int LanguageId { get; set; }
}
#endregion
#region Methods
/// <summary>
/// Deletes an URL record
/// </summary>
/// <param name="urlRecord">URL record</param>
public virtual void DeleteUrlRecord(UrlRecord urlRecord)
{
if (urlRecord == null)
throw new ArgumentNullException("urlRecord");
_urlRecordRepository.Delete(urlRecord);
//cache
_cacheManager.RemoveByPattern(URLRECORD_PATTERN_KEY);
}
/// <summary>
/// Deletes an URL records
/// </summary>
/// <param name="urlRecords">URL records</param>
public virtual void DeleteUrlRecords(IList<UrlRecord> urlRecords)
{
if (urlRecords == null)
throw new ArgumentNullException("urlRecords");
_urlRecordRepository.Delete(urlRecords);
//cache
_cacheManager.RemoveByPattern(URLRECORD_PATTERN_KEY);
}
/// <summary>
/// Gets an URL records
/// </summary>
/// <param name="urlRecordIds">URL record identifiers</param>
/// <returns>URL record</returns>
public virtual IList<UrlRecord> GetUrlRecordsByIds(int[] urlRecordIds)
{
var query = _urlRecordRepository.Table;
return query.Where(p=>urlRecordIds.Contains(p.Id)).ToList();
}
/// <summary>
/// Gets an URL record
/// </summary>
/// <param name="urlRecordId">URL record identifier</param>
/// <returns>URL record</returns>
public virtual UrlRecord GetUrlRecordById(int urlRecordId)
{
if (urlRecordId == 0)
return null;
return _urlRecordRepository.GetById(urlRecordId);
}
/// <summary>
/// Inserts an URL record
/// </summary>
/// <param name="urlRecord">URL record</param>
public virtual void InsertUrlRecord(UrlRecord urlRecord)
{
if (urlRecord == null)
throw new ArgumentNullException("urlRecord");
_urlRecordRepository.Insert(urlRecord);
//cache
_cacheManager.RemoveByPattern(URLRECORD_PATTERN_KEY);
}
/// <summary>
/// Updates the URL record
/// </summary>
/// <param name="urlRecord">URL record</param>
public virtual void UpdateUrlRecord(UrlRecord urlRecord)
{
if (urlRecord == null)
throw new ArgumentNullException("urlRecord");
_urlRecordRepository.Update(urlRecord);
//cache
_cacheManager.RemoveByPattern(URLRECORD_PATTERN_KEY);
}
/// <summary>
/// Find URL record
/// </summary>
/// <param name="slug">Slug</param>
/// <returns>Found URL record</returns>
public virtual UrlRecord GetBySlug(string slug)
{
if (String.IsNullOrEmpty(slug))
return null;
var query = from ur in _urlRecordRepository.Table
where ur.Slug == slug
//first, try to find an active record
orderby ur.IsActive descending, ur.Id
select ur;
var urlRecord = query.FirstOrDefault();
return urlRecord;
}
/// <summary>
/// Find URL record (cached version).
/// This method works absolutely the same way as "GetBySlug" one but caches the results.
/// Hence, it's used only for performance optimization in public store
/// </summary>
/// <param name="slug">Slug</param>
/// <returns>Found URL record</returns>
public virtual UrlRecordForCaching GetBySlugCached(string slug)
{
if (String.IsNullOrEmpty(slug))
return null;
if (_localizationSettings.LoadAllUrlRecordsOnStartup)
{
//load all records (we know they are cached)
var source = GetAllUrlRecordsCached();
var query = from ur in source
where ur.Slug.Equals(slug, StringComparison.InvariantCultureIgnoreCase)
//first, try to find an active record
orderby ur.IsActive descending, ur.Id
select ur;
var urlRecordForCaching = query.FirstOrDefault();
return urlRecordForCaching;
}
//gradual loading
string key = string.Format(URLRECORD_BY_SLUG_KEY, slug);
return _cacheManager.Get(key, () =>
{
var urlRecord = GetBySlug(slug);
if (urlRecord == null)
return null;
var urlRecordForCaching = Map(urlRecord);
return urlRecordForCaching;
});
}
/// <summary>
/// Gets all URL records
/// </summary>
/// <param name="slug">Slug</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <returns>URL records</returns>
public virtual IPagedList<UrlRecord> GetAllUrlRecords(string slug = "", int pageIndex = 0, int pageSize = int.MaxValue)
{
var query = _urlRecordRepository.Table;
if (!String.IsNullOrWhiteSpace(slug))
query = query.Where(ur => ur.Slug.Contains(slug));
query = query.OrderBy(ur => ur.Slug);
var urlRecords = new PagedList<UrlRecord>(query, pageIndex, pageSize);
return urlRecords;
}
/// <summary>
/// Find slug
/// </summary>
/// <param name="entityId">Entity identifier</param>
/// <param name="entityName">Entity name</param>
/// <param name="languageId">Language identifier</param>
/// <returns>Found slug</returns>
public virtual string GetActiveSlug(int entityId, string entityName, int languageId)
{
if (_localizationSettings.LoadAllUrlRecordsOnStartup)
{
string key = string.Format(URLRECORD_ACTIVE_BY_ID_NAME_LANGUAGE_KEY, entityId, entityName, languageId);
return _cacheManager.Get(key, () =>
{
//load all records (we know they are cached)
var source = GetAllUrlRecordsCached();
var query = from ur in source
where ur.EntityId == entityId &&
ur.EntityName == entityName &&
ur.LanguageId == languageId &&
ur.IsActive
orderby ur.Id descending
select ur.Slug;
var slug = query.FirstOrDefault();
//little hack here. nulls aren't cacheable so set it to ""
if (slug == null)
slug = "";
return slug;
});
}
else
{
//gradual loading
string key = string.Format(URLRECORD_ACTIVE_BY_ID_NAME_LANGUAGE_KEY, entityId, entityName, languageId);
return _cacheManager.Get(key, () =>
{
var source = _urlRecordRepository.Table;
var query = from ur in source
where ur.EntityId == entityId &&
ur.EntityName == entityName &&
ur.LanguageId == languageId &&
ur.IsActive
orderby ur.Id descending
select ur.Slug;
var slug = query.FirstOrDefault();
//little hack here. nulls aren't cacheable so set it to ""
if (slug == null)
slug = "";
return slug;
});
}
}
/// <summary>
/// Save slug
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="entity">Entity</param>
/// <param name="slug">Slug</param>
/// <param name="languageId">Language ID</param>
public virtual void SaveSlug<T>(T entity, string slug, int languageId) where T : BaseEntity, ISlugSupported
{
if (entity == null)
throw new ArgumentNullException("entity");
int entityId = entity.Id;
string entityName = typeof(T).Name;
var query = from ur in _urlRecordRepository.Table
where ur.EntityId == entityId &&
ur.EntityName == entityName &&
ur.LanguageId == languageId
orderby ur.Id descending
select ur;
var allUrlRecords = query.ToList();
var activeUrlRecord = allUrlRecords.FirstOrDefault(x => x.IsActive);
if (activeUrlRecord == null && !string.IsNullOrWhiteSpace(slug))
{
//find in non-active records with the specified slug
var nonActiveRecordWithSpecifiedSlug = allUrlRecords
.FirstOrDefault(x => x.Slug.Equals(slug, StringComparison.InvariantCultureIgnoreCase) && !x.IsActive);
if (nonActiveRecordWithSpecifiedSlug != null)
{
//mark non-active record as active
nonActiveRecordWithSpecifiedSlug.IsActive = true;
UpdateUrlRecord(nonActiveRecordWithSpecifiedSlug);
}
else
{
//new record
var urlRecord = new UrlRecord
{
EntityId = entityId,
EntityName = entityName,
Slug = slug,
LanguageId = languageId,
IsActive = true,
};
InsertUrlRecord(urlRecord);
}
}
if (activeUrlRecord != null && string.IsNullOrWhiteSpace(slug))
{
//disable the previous active URL record
activeUrlRecord.IsActive = false;
UpdateUrlRecord(activeUrlRecord);
}
if (activeUrlRecord != null && !string.IsNullOrWhiteSpace(slug))
{
//it should not be the same slug as in active URL record
if (!activeUrlRecord.Slug.Equals(slug, StringComparison.InvariantCultureIgnoreCase))
{
//find in non-active records with the specified slug
var nonActiveRecordWithSpecifiedSlug = allUrlRecords
.FirstOrDefault(x => x.Slug.Equals(slug, StringComparison.InvariantCultureIgnoreCase) && !x.IsActive);
if (nonActiveRecordWithSpecifiedSlug != null)
{
//mark non-active record as active
nonActiveRecordWithSpecifiedSlug.IsActive = true;
UpdateUrlRecord(nonActiveRecordWithSpecifiedSlug);
//disable the previous active URL record
activeUrlRecord.IsActive = false;
UpdateUrlRecord(activeUrlRecord);
}
else
{
//insert new record
//we do not update the existing record because we should track all previously entered slugs
//to ensure that URLs will work fine
var urlRecord = new UrlRecord
{
EntityId = entityId,
EntityName = entityName,
Slug = slug,
LanguageId = languageId,
IsActive = true,
};
InsertUrlRecord(urlRecord);
//disable the previous active URL record
activeUrlRecord.IsActive = false;
UpdateUrlRecord(activeUrlRecord);
}
}
}
}
#endregion
}
}
| |
// Copyright (c) 2012 DotNetAnywhere
//
// 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.Runtime.CompilerServices;
#if LOCALTEST
namespace System_.Text {
#else
namespace System.Text {
#endif
public sealed class StringBuilder {
private const int defaultMaxCapacity = int.MaxValue;
private const int defaultInitialCapacity = 16;
private int length;
private int capacity;
private char[] data;
#region Constructors
public StringBuilder() : this(defaultInitialCapacity, defaultMaxCapacity) { }
public StringBuilder(int initialCapacity) : this(initialCapacity, defaultMaxCapacity) { }
public StringBuilder(int initialCapacity, int maxCapacity) {
this.capacity = Math.Max(initialCapacity, 2);
this.length = 0;
this.data = new char[this.capacity];
}
public StringBuilder(string value)
: this((value != null) ? value.Length : defaultInitialCapacity, defaultMaxCapacity) {
if (value != null) {
this.Append(value);
}
}
public StringBuilder(string value, int initialCapacity)
: this(initialCapacity, defaultMaxCapacity) {
if (value != null) {
this.Append(value);
}
}
public StringBuilder(string value, int startIndex, int length, int initialCapacity)
: this(initialCapacity, defaultMaxCapacity) {
if (value == null) {
value = string.Empty;
}
if (startIndex < 0 || length < 0 || startIndex + length > value.Length) {
throw new ArgumentOutOfRangeException();
}
this.Append(value, startIndex, length);
}
#endregion
public override string ToString() {
return new string(this.data, 0, this.length);
}
public string ToString(int startIndex, int length) {
if (startIndex < 0 || length < 0 || startIndex + length > this.length) {
throw new ArgumentOutOfRangeException();
}
return new string(this.data, startIndex, length);
}
private void EnsureSpace(int space) {
if (this.length + space > this.capacity) {
do {
this.capacity <<= 1;
} while (this.capacity < this.length + space);
char[] newData = new char[capacity];
Array.Copy(this.data, 0, newData, 0, this.length);
this.data = newData;
}
}
public int Length {
get {
return this.length;
}
set {
if (value < 0) {
throw new ArgumentOutOfRangeException();
}
if (value > this.length) {
this.EnsureSpace(this.length - value);
for (int i = this.length; i < value; i++) {
this.data[i] = '\x0000';
}
}
this.length = value;
}
}
public int Capacity {
get {
return this.capacity;
}
}
[IndexerName("Chars")]
public char this[int index] {
get {
if (index < 0 || index >= this.length) {
throw new IndexOutOfRangeException();
}
return this.data[index];
}
set {
if (index < 0 || index >= this.length) {
throw new IndexOutOfRangeException();
}
this.data[index] = value;
}
}
public void CopyTo(int srcIndex, char[] dst, int dstIndex, int count) {
if (dst == null) {
throw new ArgumentNullException("destination");
}
if (srcIndex < 0 || count < 0 || dstIndex < 0 ||
srcIndex + count > this.length || dstIndex + count > dst.Length) {
throw new ArgumentOutOfRangeException();
}
Array.Copy(this.data, srcIndex, dst, dstIndex, count);
}
public void EnsureCapacity(int capacity) {
if (this.capacity < capacity) {
// This is not quite right, as it will often over-allocate memory
this.EnsureSpace(capacity - this.capacity);
}
}
public StringBuilder Remove(int startIndex, int length) {
if (startIndex < 0 || length < 0 || startIndex + length > this.length) {
throw new ArgumentOutOfRangeException();
}
Array.Copy(this.data, startIndex + length, this.data, startIndex, this.length - length - startIndex);
this.length -= length;
return this;
}
#region Append Methods
public StringBuilder Append(string value) {
if (value == null) {
return this;
}
int len = value.Length;
this.EnsureSpace(len);
value.CopyTo(0, this.data, this.length, len);
this.length += len;
return this;
}
public StringBuilder Append(string value, int startIndex, int count) {
if (value == null) {
return this;
}
if (startIndex < 0 || count < 0 || startIndex + count > value.Length) {
throw new ArgumentOutOfRangeException();
}
this.EnsureSpace(count);
value.CopyTo(startIndex, this.data, this.length, count);
this.length += count;
return this;
}
public StringBuilder Append(char value) {
EnsureSpace(1);
data[length++] = value;
return this;
}
public StringBuilder Append(char value, int repeatCount) {
if (repeatCount < 0) {
throw new ArgumentOutOfRangeException();
}
EnsureSpace(repeatCount);
for (int i = 0; i < repeatCount; i++) {
this.data[this.length++] = value;
}
return this;
}
public StringBuilder Append(char[] value) {
if (value == null) {
return this;
}
int addLen = value.Length;
this.EnsureSpace(addLen);
Array.Copy(value, 0, this.data, this.length, addLen);
this.length += addLen;
return this;
}
public StringBuilder Append(char[] value, int startIndex, int charCount) {
if (value == null) {
return this;
}
if (charCount < 0 || startIndex < 0 || value.Length < (startIndex + charCount)) {
throw new ArgumentOutOfRangeException();
}
this.EnsureSpace(charCount);
Array.Copy(value, startIndex, this.data, this.length, charCount);
this.length += charCount;
return this;
}
public StringBuilder Append(object value) {
if (value == null) {
return this;
}
return Append(value.ToString());
}
public StringBuilder Append(bool value) {
return Append(value.ToString());
}
public StringBuilder Append(byte value) {
return Append(value.ToString());
}
public StringBuilder Append(decimal value) {
return Append(value.ToString());
}
public StringBuilder Append(double value) {
return Append(value.ToString());
}
public StringBuilder Append(short value) {
return Append(value.ToString());
}
public StringBuilder Append(int value) {
return Append(value.ToString());
}
public StringBuilder Append(long value) {
return Append(value.ToString());
}
public StringBuilder Append(sbyte value) {
return Append(value.ToString());
}
public StringBuilder Append(float value) {
return Append(value.ToString());
}
public StringBuilder Append(ushort value) {
return Append(value.ToString());
}
public StringBuilder Append(uint value) {
return Append(value.ToString());
}
public StringBuilder Append(ulong value) {
return Append(value.ToString());
}
#endregion
#region AppendFormat Methods
public StringBuilder AppendFormat(string format, object obj0) {
StringHelper.FormatHelper(this, null, format, obj0);
return this;
}
public StringBuilder AppendFormat(string format, object obj0, object obj1) {
StringHelper.FormatHelper(this, null, format, obj0, obj1);
return this;
}
public StringBuilder AppendFormat(string format, object obj0, object obj1, object obj2) {
StringHelper.FormatHelper(this, null, format, obj0, obj1, obj2);
return this;
}
public StringBuilder AppendFormat(string format, params object[] objs) {
StringHelper.FormatHelper(this, null, format, objs);
return this;
}
public StringBuilder AppendFormat(IFormatProvider provider, string format, params object[] objs) {
StringHelper.FormatHelper(this, provider, format, objs);
return this;
}
#endregion
#region AppendLine Methods
public StringBuilder AppendLine() {
return this.Append(Environment.NewLine);
}
public StringBuilder AppendLine(string value) {
return this.Append(value).Append(Environment.NewLine);
}
#endregion
#region Insert Methods
public StringBuilder Insert(int index, string value) {
if (index < 0 || index > this.length) {
throw new ArgumentOutOfRangeException("index");
}
if (string.IsNullOrEmpty(value)) {
return this;
}
int len = value.Length;
EnsureSpace(len);
Array.Copy(this.data, index, this.data, index + len, this.length - index);
value.CopyTo(0, this.data, index, len);
this.length += len;
return this;
}
public StringBuilder Insert(int index, bool value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, byte value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, char value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, char[] value) {
if (value == null) {
return this;
}
return this.Insert(index, new string(value));
}
public StringBuilder Insert(int index, decimal value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, double value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, short value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, int value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, long value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, object value) {
if (value == null) {
return this;
}
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, sbyte value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, float value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, ushort value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, uint value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, ulong value) {
return this.Insert(index, value.ToString());
}
public StringBuilder Insert(int index, string value, int count) {
if (count < 0) {
throw new ArgumentOutOfRangeException();
}
if (count == 0 || string.IsNullOrEmpty(value)) {
return this;
}
StringBuilder toInsert = new StringBuilder(value.Length * count);
for (; count > 0; count--) {
toInsert.Append(value);
}
return this.Insert(index, toInsert.ToString());
}
public StringBuilder Insert(int index, char[] value, int startIndex, int charCount) {
if (value == null && (startIndex != 0 || charCount != 0)) {
throw new ArgumentNullException("value");
}
if (startIndex < 0 || charCount < 0 || startIndex + charCount > value.Length) {
throw new ArgumentOutOfRangeException();
}
return this.Insert(index, new string(value, startIndex, charCount));
}
#endregion
#region Replace Methods
public StringBuilder Replace(char oldChar, char newChar) {
return this.Replace(oldChar, newChar, 0, this.length);
}
public StringBuilder Replace(string oldValue, string newValue) {
return this.Replace(oldValue, newValue, 0, this.length);
}
public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count) {
if (startIndex < 0 || count < 0 || startIndex + count > this.length) {
throw new ArgumentOutOfRangeException();
}
for (int i = 0; i < count; i++) {
if (this.data[startIndex + i] == oldChar) {
this.data[startIndex + i] = newChar;
}
}
return this;
}
public StringBuilder Replace(string oldValue, string newValue, int startIndex, int count) {
string subStr = this.ToString(startIndex, count);
subStr = subStr.Replace(oldValue, newValue);
this.Remove(startIndex, count);
this.Insert(startIndex, subStr);
return this;
}
#endregion
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Globalization;
using TheArtOfDev.HtmlRenderer.Adapters;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core.Dom;
using TheArtOfDev.HtmlRenderer.Core.Utils;
namespace TheArtOfDev.HtmlRenderer.Core.Parse
{
/// <summary>
/// Parse CSS properties values like numbers, Urls, etc.
/// </summary>
internal sealed class CssValueParser
{
#region Fields and Consts
/// <summary>
///
/// </summary>
private readonly RAdapter _adapter;
#endregion
/// <summary>
/// Init.
/// </summary>
public CssValueParser(RAdapter adapter)
{
ArgChecker.AssertArgNotNull(adapter, "global");
_adapter = adapter;
}
/// <summary>
/// Check if the given substring is a valid double number.
/// Assume given substring is not empty and all indexes are valid!<br/>
/// </summary>
/// <returns>true - valid double number, false - otherwise</returns>
public static bool IsFloat(string str, int idx, int length)
{
if (length < 1)
return false;
bool sawDot = false;
for (int i = 0; i < length; i++)
{
if (str[idx + i] == '.')
{
if (sawDot)
return false;
sawDot = true;
}
else if (!char.IsDigit(str[idx + i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Check if the given substring is a valid double number.
/// Assume given substring is not empty and all indexes are valid!<br/>
/// </summary>
/// <returns>true - valid int number, false - otherwise</returns>
public static bool IsInt(string str, int idx, int length)
{
if (length < 1)
return false;
for (int i = 0; i < length; i++)
{
if (!char.IsDigit(str[idx + i]))
return false;
}
return true;
}
/// <summary>
/// Check if the given string is a valid length value.
/// </summary>
/// <param name="value">the string value to check</param>
/// <returns>true - valid, false - invalid</returns>
public static bool IsValidLength(string value)
{
if (value.Length > 1)
{
string number = string.Empty;
if (value.EndsWith("%"))
{
number = value.Substring(0, value.Length - 1);
}
else if (value.Length > 2)
{
number = value.Substring(0, value.Length - 2);
}
double stub;
return double.TryParse(number, out stub);
}
return false;
}
/// <summary>
/// Evals a number and returns it. If number is a percentage, it will be multiplied by <see cref="hundredPercent"/>
/// </summary>
/// <param name="number">Number to be parsed</param>
/// <param name="hundredPercent">Number that represents the 100% if parsed number is a percentage</param>
/// <returns>Parsed number. Zero if error while parsing.</returns>
public static double ParseNumber(string number, double hundredPercent)
{
if (string.IsNullOrEmpty(number))
{
return 0f;
}
string toParse = number;
bool isPercent = number.EndsWith("%");
double result;
if (isPercent)
toParse = number.Substring(0, number.Length - 1);
if (!double.TryParse(toParse, NumberStyles.Number, NumberFormatInfo.InvariantInfo, out result))
{
return 0f;
}
if (isPercent)
{
result = (result / 100f) * hundredPercent;
}
return result;
}
/// <summary>
/// Parses a length. Lengths are followed by an unit identifier (e.g. 10px, 3.1em)
/// </summary>
/// <param name="length">Specified length</param>
/// <param name="hundredPercent">Equivalent to 100 percent when length is percentage</param>
/// <param name="fontAdjust">if the length is in pixels and the length is font related it needs to use 72/96 factor</param>
/// <param name="box"></param>
/// <returns>the parsed length value with adjustments</returns>
public static double ParseLength(string length, double hundredPercent, CssBoxProperties box, bool fontAdjust = false)
{
return ParseLength(length, hundredPercent, box.GetEmHeight(), null, fontAdjust, false);
}
/// <summary>
/// Parses a length. Lengths are followed by an unit identifier (e.g. 10px, 3.1em)
/// </summary>
/// <param name="length">Specified length</param>
/// <param name="hundredPercent">Equivalent to 100 percent when length is percentage</param>
/// <param name="box"></param>
/// <param name="defaultUnit"></param>
/// <returns>the parsed length value with adjustments</returns>
public static double ParseLength(string length, double hundredPercent, CssBoxProperties box, string defaultUnit)
{
return ParseLength(length, hundredPercent, box.GetEmHeight(), defaultUnit, false, false);
}
/// <summary>
/// Parses a length. Lengths are followed by an unit identifier (e.g. 10px, 3.1em)
/// </summary>
/// <param name="length">Specified length</param>
/// <param name="hundredPercent">Equivalent to 100 percent when length is percentage</param>
/// <param name="emFactor"></param>
/// <param name="defaultUnit"></param>
/// <param name="fontAdjust">if the length is in pixels and the length is font related it needs to use 72/96 factor</param>
/// <param name="returnPoints">Allows the return double to be in points. If false, result will be pixels</param>
/// <returns>the parsed length value with adjustments</returns>
public static double ParseLength(string length, double hundredPercent, double emFactor, string defaultUnit, bool fontAdjust, bool returnPoints)
{
//Return zero if no length specified, zero specified
if (string.IsNullOrEmpty(length) || length == "0")
return 0f;
//If percentage, use ParseNumber
if (length.EndsWith("%"))
return ParseNumber(length, hundredPercent);
//Get units of the length
bool hasUnit;
string unit = GetUnit(length, defaultUnit, out hasUnit);
//Factor will depend on the unit
double factor;
//Number of the length
string number = hasUnit ? length.Substring(0, length.Length - 2) : length;
//TODO: Units behave different in paper and in screen!
switch (unit)
{
case CssConstants.Em:
factor = emFactor;
break;
case CssConstants.Ex:
factor = emFactor / 2;
break;
case CssConstants.Px:
factor = fontAdjust ? 72f / 96f : 1f; //TODO:a check support for hi dpi
break;
case CssConstants.Mm:
factor = 3.779527559f; //3 pixels per millimeter
break;
case CssConstants.Cm:
factor = 37.795275591f; //37 pixels per centimeter
break;
case CssConstants.In:
factor = 96f; //96 pixels per inch
break;
case CssConstants.Pt:
factor = 96f / 72f; // 1 point = 1/72 of inch
if (returnPoints)
{
return ParseNumber(number, hundredPercent);
}
break;
case CssConstants.Pc:
factor = 16f; // 1 pica = 12 points
break;
default:
factor = 0f;
break;
}
return factor * ParseNumber(number, hundredPercent);
}
/// <summary>
/// Get the unit to use for the length, use default if no unit found in length string.
/// </summary>
private static string GetUnit(string length, string defaultUnit, out bool hasUnit)
{
var unit = length.Length >= 3 ? length.Substring(length.Length - 2, 2) : string.Empty;
switch (unit)
{
case CssConstants.Em:
case CssConstants.Ex:
case CssConstants.Px:
case CssConstants.Mm:
case CssConstants.Cm:
case CssConstants.In:
case CssConstants.Pt:
case CssConstants.Pc:
hasUnit = true;
break;
default:
hasUnit = false;
unit = defaultUnit ?? String.Empty;
break;
}
return unit;
}
/// <summary>
/// Check if the given color string value is valid.
/// </summary>
/// <param name="colorValue">color string value to parse</param>
/// <returns>true - valid, false - invalid</returns>
public bool IsColorValid(string colorValue)
{
RColor color;
return TryGetColor(colorValue, 0, colorValue.Length, out color);
}
/// <summary>
/// Parses a color value in CSS style; e.g. #ff0000, red, rgb(255,0,0), rgb(100%, 0, 0)
/// </summary>
/// <param name="colorValue">color string value to parse</param>
/// <returns>Color value</returns>
public RColor GetActualColor(string colorValue)
{
RColor color;
TryGetColor(colorValue, 0, colorValue.Length, out color);
return color;
}
/// <summary>
/// Parses a color value in CSS style; e.g. #ff0000, RED, RGB(255,0,0), RGB(100%, 0, 0)
/// </summary>
/// <param name="str">color substring value to parse</param>
/// <param name="idx">substring start idx </param>
/// <param name="length">substring length</param>
/// <param name="color">return the parsed color</param>
/// <returns>true - valid color, false - otherwise</returns>
public bool TryGetColor(string str, int idx, int length, out RColor color)
{
try
{
if (!string.IsNullOrEmpty(str))
{
if (length > 1 && str[idx] == '#')
{
return GetColorByHex(str, idx, length, out color);
}
else if (length > 10 && CommonUtils.SubStringEquals(str, idx, 4, "rgb(") && str[length - 1] == ')')
{
return GetColorByRgb(str, idx, length, out color);
}
else if (length > 13 && CommonUtils.SubStringEquals(str, idx, 5, "rgba(") && str[length - 1] == ')')
{
return GetColorByRgba(str, idx, length, out color);
}
else
{
return GetColorByName(str, idx, length, out color);
}
}
}
catch
{ }
color = RColor.Black;
return false;
}
/// <summary>
/// Parses a border value in CSS style; e.g. 1px, 1, thin, thick, medium
/// </summary>
/// <param name="borderValue"></param>
/// <param name="b"></param>
/// <returns></returns>
public static double GetActualBorderWidth(string borderValue, CssBoxProperties b)
{
if (string.IsNullOrEmpty(borderValue))
{
return GetActualBorderWidth(CssConstants.Medium, b);
}
switch (borderValue)
{
case CssConstants.Thin:
return 1f;
case CssConstants.Medium:
return 2f;
case CssConstants.Thick:
return 4f;
default:
return Math.Abs(ParseLength(borderValue, 1, b));
}
}
#region Private methods
/// <summary>
/// Get color by parsing given hex value color string (#A28B34).
/// </summary>
/// <returns>true - valid color, false - otherwise</returns>
private static bool GetColorByHex(string str, int idx, int length, out RColor color)
{
int r = -1;
int g = -1;
int b = -1;
if (length == 7)
{
r = ParseHexInt(str, idx + 1, 2);
g = ParseHexInt(str, idx + 3, 2);
b = ParseHexInt(str, idx + 5, 2);
}
else if (length == 4)
{
r = ParseHexInt(str, idx + 1, 1);
r = r * 16 + r;
g = ParseHexInt(str, idx + 2, 1);
g = g * 16 + g;
b = ParseHexInt(str, idx + 3, 1);
b = b * 16 + b;
}
if (r > -1 && g > -1 && b > -1)
{
color = RColor.FromArgb(r, g, b);
return true;
}
color = RColor.Empty;
return false;
}
/// <summary>
/// Get color by parsing given RGB value color string (RGB(255,180,90))
/// </summary>
/// <returns>true - valid color, false - otherwise</returns>
private static bool GetColorByRgb(string str, int idx, int length, out RColor color)
{
int r = -1;
int g = -1;
int b = -1;
if (length > 10)
{
int s = idx + 4;
r = ParseIntAtIndex(str, ref s);
if (s < idx + length)
{
g = ParseIntAtIndex(str, ref s);
}
if (s < idx + length)
{
b = ParseIntAtIndex(str, ref s);
}
}
if (r > -1 && g > -1 && b > -1)
{
color = RColor.FromArgb(r, g, b);
return true;
}
color = RColor.Empty;
return false;
}
/// <summary>
/// Get color by parsing given RGBA value color string (RGBA(255,180,90,180))
/// </summary>
/// <returns>true - valid color, false - otherwise</returns>
private static bool GetColorByRgba(string str, int idx, int length, out RColor color)
{
int r = -1;
int g = -1;
int b = -1;
int a = -1;
if (length > 13)
{
int s = idx + 5;
r = ParseIntAtIndex(str, ref s);
if (s < idx + length)
{
g = ParseIntAtIndex(str, ref s);
}
if (s < idx + length)
{
b = ParseIntAtIndex(str, ref s);
}
if (s < idx + length)
{
a = ParseIntAtIndex(str, ref s);
}
}
if (r > -1 && g > -1 && b > -1 && a > -1)
{
color = RColor.FromArgb(a, r, g, b);
return true;
}
color = RColor.Empty;
return false;
}
/// <summary>
/// Get color by given name, including .NET name.
/// </summary>
/// <returns>true - valid color, false - otherwise</returns>
private bool GetColorByName(string str, int idx, int length, out RColor color)
{
color = _adapter.GetColor(str.Substring(idx, length));
return color.A > 0;
}
/// <summary>
/// Parse the given decimal number string to positive int value.<br/>
/// Start at given <paramref name="startIdx"/>, ignore whitespaces and take
/// as many digits as possible to parse to int.
/// </summary>
/// <param name="str">the string to parse</param>
/// <param name="startIdx">the index to start parsing at</param>
/// <returns>parsed int or 0</returns>
private static int ParseIntAtIndex(string str, ref int startIdx)
{
int len = 0;
while (char.IsWhiteSpace(str, startIdx))
startIdx++;
while (char.IsDigit(str, startIdx + len))
len++;
var val = ParseInt(str, startIdx, len);
startIdx = startIdx + len + 1;
return val;
}
/// <summary>
/// Parse the given decimal number string to positive int value.
/// Assume given substring is not empty and all indexes are valid!<br/>
/// </summary>
/// <returns>int value, -1 if not valid</returns>
private static int ParseInt(string str, int idx, int length)
{
if (length < 1)
return -1;
int num = 0;
for (int i = 0; i < length; i++)
{
int c = str[idx + i];
if (!(c >= 48 && c <= 57))
return -1;
num = num * 10 + c - 48;
}
return num;
}
/// <summary>
/// Parse the given hex number string to positive int value.
/// Assume given substring is not empty and all indexes are valid!<br/>
/// </summary>
/// <returns>int value, -1 if not valid</returns>
private static int ParseHexInt(string str, int idx, int length)
{
if (length < 1)
return -1;
int num = 0;
for (int i = 0; i < length; i++)
{
int c = str[idx + i];
if (!(c >= 48 && c <= 57) && !(c >= 65 && c <= 70) && !(c >= 97 && c <= 102))
return -1;
num = num * 16 + (c <= 57 ? c - 48 : (10 + c - (c <= 70 ? 65 : 97)));
}
return num;
}
#endregion
}
}
| |
#pragma warning disable 1591
#pragma warning disable 0108
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Team Development for Sitecore.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Glass.Sitecore.Mapper.Configuration.Attributes;
using Glass.Sitecore.Mapper.Configuration;
using Glass.Sitecore.Mapper.FieldTypes;
using Sitecore.Globalization;
namespace SUGNL.TDS.Website
{
/// <summary>
/// IHomepage Interface
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/PageTemplates/Homepage</para>
/// <para>ID: 4eeeca4e-1b09-4047-abf4-78cbea602451</para>
/// </summary>
public interface IHomepage : IGlassBase , global::SUGNL.TDS.Website.IMetaBase, global::SUGNL.TDS.Website.IPageBase, global::SUGNL.TDS.Website.ITitleBase
{
}
/// <summary>
/// Homepage
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/PageTemplates/Homepage</para>
/// <para>ID: 4eeeca4e-1b09-4047-abf4-78cbea602451</para>
/// </summary>
[SitecoreClass(TemplateId="4eeeca4e-1b09-4047-abf4-78cbea602451")]
public partial class Homepage : GlassBase, IHomepage
{
/// <summary>
/// The MetaDescription field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 411f83b0-ffcf-4c64-bb8d-5c4b251493a3</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("MetaDescription")]
public virtual string MetaDescription {get; set;}
/// <summary>
/// The MetaKeywords field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: f29a2f77-3034-4307-84ba-0c48cdc8188d</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("MetaKeywords")]
public virtual string MetaKeywords {get; set;}
/// <summary>
/// The Title field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: fc20530b-c1f3-421c-b724-321a36152e91</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("Title")]
public virtual string Title {get; set;}
}
}
namespace SUGNL.TDS.Website
{
/// <summary>
/// ISnippet Interface
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/DataTemplates/Snippet</para>
/// <para>ID: 4f88101b-127b-4963-9964-ccf09a575ec3</para>
/// </summary>
public interface ISnippet : IGlassBase
{
}
/// <summary>
/// Snippet
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/DataTemplates/Snippet</para>
/// <para>ID: 4f88101b-127b-4963-9964-ccf09a575ec3</para>
/// </summary>
[SitecoreClass(TemplateId="4f88101b-127b-4963-9964-ccf09a575ec3")]
public partial class Snippet : GlassBase, ISnippet
{
}
}
namespace SUGNL.TDS.Website
{
/// <summary>
/// IBanner Interface
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/DataTemplates/Banner</para>
/// <para>ID: 853cc71a-df49-4253-8b20-c072bf40e236</para>
/// </summary>
public interface IBanner : IGlassBase
{
/// <summary>
/// The Image field.
/// <para></para>
/// <para>Field Type: Image</para>
/// <para>Field ID: 0e02d479-8216-4a17-8528-63b8d93fb545</para>
/// <para>Custom Data: </para>
/// </summary>
Image Image {get; set;}
/// <summary>
/// The Title field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 45e27472-168a-4bdc-95f4-cd64b0983674</para>
/// <para>Custom Data: </para>
/// </summary>
string Title {get; set;}
}
/// <summary>
/// Banner
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/DataTemplates/Banner</para>
/// <para>ID: 853cc71a-df49-4253-8b20-c072bf40e236</para>
/// </summary>
[SitecoreClass(TemplateId="853cc71a-df49-4253-8b20-c072bf40e236")]
public partial class Banner : GlassBase, IBanner
{
/// <summary>
/// The Image field.
/// <para></para>
/// <para>Field Type: Image</para>
/// <para>Field ID: 0e02d479-8216-4a17-8528-63b8d93fb545</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("Image")]
public virtual Image Image {get; set;}
/// <summary>
/// The Title field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 45e27472-168a-4bdc-95f4-cd64b0983674</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("Title")]
public virtual string Title {get; set;}
}
}
namespace SUGNL.TDS.Website
{
/// <summary>
/// INewsOverviewPage Interface
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/PageTemplates/NewsOverviewPage</para>
/// <para>ID: 893eeb21-51fa-47c9-b8a7-185ea0445322</para>
/// </summary>
public interface INewsOverviewPage : IGlassBase , global::SUGNL.TDS.Website.IPageBase, global::SUGNL.TDS.Website.IMetaBase, global::SUGNL.TDS.Website.ITitleBase
{
}
/// <summary>
/// NewsOverviewPage
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/PageTemplates/NewsOverviewPage</para>
/// <para>ID: 893eeb21-51fa-47c9-b8a7-185ea0445322</para>
/// </summary>
[SitecoreClass(TemplateId="893eeb21-51fa-47c9-b8a7-185ea0445322")]
public partial class NewsOverviewPage : GlassBase, INewsOverviewPage
{
/// <summary>
/// The MetaDescription field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 411f83b0-ffcf-4c64-bb8d-5c4b251493a3</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("MetaDescription")]
public virtual string MetaDescription {get; set;}
/// <summary>
/// The MetaKeywords field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: f29a2f77-3034-4307-84ba-0c48cdc8188d</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("MetaKeywords")]
public virtual string MetaKeywords {get; set;}
/// <summary>
/// The Title field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: fc20530b-c1f3-421c-b724-321a36152e91</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("Title")]
public virtual string Title {get; set;}
}
}
namespace SUGNL.TDS.Website
{
/// <summary>
/// IContentPage Interface
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/PageTemplates/ContentPage</para>
/// <para>ID: ba577308-fa5c-43ad-86d1-effbf5371d4f</para>
/// </summary>
public interface IContentPage : IGlassBase , global::SUGNL.TDS.Website.IMetaBase, global::SUGNL.TDS.Website.ITitleBase, global::SUGNL.TDS.Website.IIntroBase, global::SUGNL.TDS.Website.IPageBase, global::SUGNL.TDS.Website.IContentTextBase
{
}
/// <summary>
/// ContentPage
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/PageTemplates/ContentPage</para>
/// <para>ID: ba577308-fa5c-43ad-86d1-effbf5371d4f</para>
/// </summary>
[SitecoreClass(TemplateId="ba577308-fa5c-43ad-86d1-effbf5371d4f")]
public partial class ContentPage : GlassBase, IContentPage
{
/// <summary>
/// The MetaDescription field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 411f83b0-ffcf-4c64-bb8d-5c4b251493a3</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("MetaDescription")]
public virtual string MetaDescription {get; set;}
/// <summary>
/// The MetaKeywords field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: f29a2f77-3034-4307-84ba-0c48cdc8188d</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("MetaKeywords")]
public virtual string MetaKeywords {get; set;}
/// <summary>
/// The Title field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: fc20530b-c1f3-421c-b724-321a36152e91</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("Title")]
public virtual string Title {get; set;}
/// <summary>
/// The Intro field.
/// <para></para>
/// <para>Field Type: Multi-Line Text</para>
/// <para>Field ID: 5e82bcb3-e174-4f0d-9248-24be233a4635</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("Intro")]
public virtual string Intro {get; set;}
/// <summary>
/// The Content field.
/// <para></para>
/// <para>Field Type: Rich Text</para>
/// <para>Field ID: 3089399a-4f48-4bfe-b0b6-34f63c28797f</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("Content")]
public virtual string Content {get; set;}
}
}
namespace SUGNL.TDS.Website
{
/// <summary>
/// INewsDetailPage Interface
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/PageTemplates/NewsDetailPage</para>
/// <para>ID: d44bb872-ffd7-4caf-b2d8-e58f076641de</para>
/// </summary>
public interface INewsDetailPage : IGlassBase , global::SUGNL.TDS.Website.IMetaBase, global::SUGNL.TDS.Website.IPageBase, global::SUGNL.TDS.Website.IIntroBase, global::SUGNL.TDS.Website.IContentTextBase, global::SUGNL.TDS.Website.ITitleBase
{
/// <summary>
/// The Date field.
/// <para></para>
/// <para>Field Type: Date</para>
/// <para>Field ID: 0e36d427-8cc1-418b-b317-2d9f831325cc</para>
/// <para>Custom Data: </para>
/// </summary>
DateTime Date {get; set;}
}
/// <summary>
/// NewsDetailPage
/// <para></para>
/// <para>Path: /sitecore/templates/User Defined/SUGNL TDS V5 Demo/PageTemplates/NewsDetailPage</para>
/// <para>ID: d44bb872-ffd7-4caf-b2d8-e58f076641de</para>
/// </summary>
[SitecoreClass(TemplateId="d44bb872-ffd7-4caf-b2d8-e58f076641de")]
public partial class NewsDetailPage : GlassBase, INewsDetailPage
{
/// <summary>
/// The Date field.
/// <para></para>
/// <para>Field Type: Date</para>
/// <para>Field ID: 0e36d427-8cc1-418b-b317-2d9f831325cc</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("Date")]
public virtual DateTime Date {get; set;}
/// <summary>
/// The MetaDescription field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: 411f83b0-ffcf-4c64-bb8d-5c4b251493a3</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("MetaDescription")]
public virtual string MetaDescription {get; set;}
/// <summary>
/// The MetaKeywords field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: f29a2f77-3034-4307-84ba-0c48cdc8188d</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("MetaKeywords")]
public virtual string MetaKeywords {get; set;}
/// <summary>
/// The Intro field.
/// <para></para>
/// <para>Field Type: Multi-Line Text</para>
/// <para>Field ID: 5e82bcb3-e174-4f0d-9248-24be233a4635</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("Intro")]
public virtual string Intro {get; set;}
/// <summary>
/// The Content field.
/// <para></para>
/// <para>Field Type: Rich Text</para>
/// <para>Field ID: 3089399a-4f48-4bfe-b0b6-34f63c28797f</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("Content")]
public virtual string Content {get; set;}
/// <summary>
/// The Title field.
/// <para></para>
/// <para>Field Type: Single-Line Text</para>
/// <para>Field ID: fc20530b-c1f3-421c-b724-321a36152e91</para>
/// <para>Custom Data: </para>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Team Development for Sitecore - GlassItem.tt", "1.0")]
[SitecoreField("Title")]
public virtual string Title {get; set;}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERLevel;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G07_Country_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="G07_Country_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="G06_Country"/> collection.
/// </remarks>
[Serializable]
public partial class G07_Country_ReChild : BusinessBase<G07_Country_ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_Child_NameProperty = RegisterProperty<string>(p => p.Country_Child_Name, "Regions Child Name");
/// <summary>
/// Gets or sets the Regions Child Name.
/// </summary>
/// <value>The Regions Child Name.</value>
public string Country_Child_Name
{
get { return GetProperty(Country_Child_NameProperty); }
set { SetProperty(Country_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G07_Country_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G07_Country_ReChild"/> object.</returns>
internal static G07_Country_ReChild NewG07_Country_ReChild()
{
return DataPortal.CreateChild<G07_Country_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="G07_Country_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="country_ID2">The Country_ID2 parameter of the G07_Country_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="G07_Country_ReChild"/> object.</returns>
internal static G07_Country_ReChild GetG07_Country_ReChild(int country_ID2)
{
return DataPortal.FetchChild<G07_Country_ReChild>(country_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G07_Country_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G07_Country_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G07_Country_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G07_Country_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="country_ID2">The Country ID2.</param>
protected void Child_Fetch(int country_ID2)
{
var args = new DataPortalHookArgs(country_ID2);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IG07_Country_ReChildDal>();
var data = dal.Fetch(country_ID2);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="G07_Country_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Country_Child_NameProperty, dr.GetString("Country_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="G07_Country_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G06_Country parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IG07_Country_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Country_ID,
Country_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G07_Country_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(G06_Country parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IG07_Country_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Country_ID,
Country_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="G07_Country_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(G06_Country parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IG07_Country_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Country_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using Microsoft.SPOT;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Text;
using System.IO;
using Microsoft.SPOT.Net.NetworkInformation;
namespace HttpFileServer
{
public class FileServer : IDisposable
{
private const int Backlog = 1;
private Socket _socket = null;
private Thread _thread = null;
private string _location = null;
public FileServer(string location, int port = 80)
{
_location = location;
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(new IPEndPoint(IPAddress.Any, port));
_socket.Listen(Backlog);
NetworkInterface[] ips = NetworkInterface.GetAllNetworkInterfaces();
for (int i = 0; i < ips.Length; i++)
{
Debug.Print(ips[0].IPAddress.ToString() + ": " + port);
}
_thread = new Thread(new ThreadStart(ListenForClients));
_thread.Start();
}
// private const int BufferSize = 2048;
private const int BufferSize = 500;
private void ListenForClients()
{
while (true)
{
using (Socket client = _socket.Accept())
{
// Wait for data to become available
while (!client.Poll(10, SelectMode.SelectRead)) { }
if (client.Available > 0)
{
byte[] buffer = new byte[sizeof(int)];
client.Receive(buffer, sizeof(int), SocketFlags.None);
Operation op = (Operation)BitConverter.ToInt32(buffer, 0);
client.Receive(buffer, sizeof(int), SocketFlags.None);
int length = (int)BitConverter.ToInt32(buffer, 0);
if (length > BufferSize)
{
int received = 0;
while (received < length)
{
int xferSize = System.Math.Min(BufferSize, length - received);
buffer = new byte[xferSize];
client.Receive(buffer, 0, xferSize, SocketFlags.None);
received += xferSize;
}
SendFailure(client);
}
else if (length == 0)
{
Process(client, op, "");
}
else
{
buffer = new byte[length];
client.Receive(buffer, 0, length, SocketFlags.None);
string file = new string(Encoding.UTF8.GetChars(buffer));
Process(client, op, file);
}
}
}
}
}
private void SendFailure(Socket client)
{
byte[] retCode = BitConverter.GetBytes((int)ReturnCode.Failure);
client.Send(retCode, retCode.Length, SocketFlags.None);
// Workaround:
// http://forums.netduino.com/index.php?/topic/4555-socket-error-10055-wsaenobufs/
Thread.Sleep(100);
}
private void SendSuccess(Socket client)
{
byte[] retCode = BitConverter.GetBytes((int)ReturnCode.Success);
client.Send(retCode, retCode.Length, SocketFlags.None);
// Workaround:
// http://forums.netduino.com/index.php?/topic/4555-socket-error-10055-wsaenobufs/
Thread.Sleep(100);
}
private void Process(Socket client, Operation op, string file)
{
switch (op)
{
case Operation.List:
ListDirectory(client, file);
break;
case Operation.Get:
SendFile(client, file);
break;
case Operation.Put:
ReceiveFile(client, file);
break;
case Operation.Delete:
DeleteFile(client, file);
break;
default:
SendFailure(client);
break;
}
}
private void DeleteFile(Socket client, string file)
{
string fullPath = _location + @"\" + file;
if (File.Exists(fullPath))
{
File.Delete(fullPath);
SendSuccess(client);
}
else if (Directory.Exists(fullPath))
{
Directory.Delete(fullPath, true);
SendSuccess(client);
}
else
{
SendFailure(client);
}
}
private void ReceiveFile(Socket client, string file)
{
using (FileStream stream = File.Open(_location + @"\" + file, FileMode.Create))
{
SendSuccess(client);
byte[] buffer = new byte[sizeof(int)];
client.Receive(buffer, sizeof(int), SocketFlags.None);
int length = (int)BitConverter.ToInt32(buffer, 0);
int received = 0;
while (received < length)
{
int remSize = (int)(length - received);
int xferSize = System.Math.Min(remSize, BufferSize);
buffer = new byte[xferSize];
client.Receive(buffer, 0, xferSize, SocketFlags.None);
stream.Write(buffer, 0, xferSize);
received += xferSize;
// Workaround:
// http://forums.netduino.com/index.php?/topic/4555-socket-error-10055-wsaenobufs/
Thread.Sleep(100);
}
SendSuccess(client);
}
}
private void SendFile(Socket client, string file)
{
string filename = _location + @"\" + file;
if (File.Exists(filename))
{
SendSuccess(client);
using (FileStream stream = File.Open(filename, FileMode.Open))
{
int length = (int)stream.Length;
byte[] size = BitConverter.GetBytes(length);
client.Send(size, size.Length, SocketFlags.None);
// Workaround:
// http://forums.netduino.com/index.php?/topic/4555-socket-error-10055-wsaenobufs/
Thread.Sleep(100);
while (stream.Position < stream.Length)
{
int remSize = (int)(stream.Length - stream.Position);
int xferSize = System.Math.Min(remSize, BufferSize);
byte[] buffer = new byte[xferSize];
stream.Read(buffer, 0, xferSize);
client.Send(buffer, 0, xferSize, SocketFlags.None);
// Workaround:
// http://forums.netduino.com/index.php?/topic/4555-socket-error-10055-wsaenobufs/
Thread.Sleep(100);
}
SendSuccess(client);
}
}
else
{
SendFailure(client);
}
}
private void ListDirectory(Socket client, string dir)
{
string[] files = Directory.GetFiles(_location + @"\" + dir);
SendSuccess(client);
byte[] numFiles = BitConverter.GetBytes(files.Length);
client.Send(numFiles, numFiles.Length, SocketFlags.None);
SendSuccess(client);
foreach (string file in files)
{
string filename = file.Substring(file.LastIndexOf('\\') + 1);
byte[] data = Encoding.UTF8.GetBytes(filename);
byte[] fileSize = BitConverter.GetBytes(data.Length);
client.Send(fileSize, fileSize.Length, SocketFlags.None);
// Workaround:
// http://forums.netduino.com/index.php?/topic/4555-socket-error-10055-wsaenobufs/
Thread.Sleep(100);
client.Send(data, data.Length, SocketFlags.None);
// Workaround:
// http://forums.netduino.com/index.php?/topic/4555-socket-error-10055-wsaenobufs/
Thread.Sleep(100);
SendSuccess(client);
}
}
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_socket.Close();
_thread.Abort();
}
_disposed = true;
}
}
~FileServer()
{
Dispose(false);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class ConcurrentDictionaryTests
{
[Fact]
public static void TestBasicScenarios()
{
ConcurrentDictionary<int, int> cd = new ConcurrentDictionary<int, int>();
Task[] tks = new Task[2];
tks[0] = Task.Run(() =>
{
var ret = cd.TryAdd(1, 11);
if (!ret)
{
ret = cd.TryUpdate(1, 11, 111);
Assert.True(ret);
}
ret = cd.TryAdd(2, 22);
if (!ret)
{
ret = cd.TryUpdate(2, 22, 222);
Assert.True(ret);
}
});
tks[1] = Task.Run(() =>
{
var ret = cd.TryAdd(2, 222);
if (!ret)
{
ret = cd.TryUpdate(2, 222, 22);
Assert.True(ret);
}
ret = cd.TryAdd(1, 111);
if (!ret)
{
ret = cd.TryUpdate(1, 111, 11);
Assert.True(ret);
}
});
Task.WaitAll(tks);
}
[Fact]
public static void TestAdd1()
{
TestAdd1(1, 1, 1, 10000);
TestAdd1(5, 1, 1, 10000);
TestAdd1(1, 1, 2, 5000);
TestAdd1(1, 1, 5, 2000);
TestAdd1(4, 0, 4, 2000);
TestAdd1(16, 31, 4, 2000);
TestAdd1(64, 5, 5, 5000);
TestAdd1(5, 5, 5, 2500);
}
private static void TestAdd1(int cLevel, int initSize, int threads, int addsPerThread)
{
ConcurrentDictionary<int, int> dictConcurrent = new ConcurrentDictionary<int, int>(cLevel, 1);
IDictionary<int, int> dict = dictConcurrent;
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < addsPerThread; j++)
{
dict.Add(j + ii * addsPerThread, -(j + ii * addsPerThread));
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
int itemCount = threads * addsPerThread;
for (int i = 0; i < itemCount; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("The set of keys in the dictionary is are not the same as the expected" + Environment.NewLine +
"TestAdd1(cLevel={0}, initSize={1}, threads={2}, addsPerThread={3})", cLevel, initSize, threads, addsPerThread)
);
}
// Finally, let's verify that the count is reported correctly.
int expectedCount = threads * addsPerThread;
Assert.Equal(expectedCount, dict.Count);
Assert.Equal(expectedCount, dictConcurrent.ToArray().Length);
}
[Fact]
public static void TestUpdate1()
{
TestUpdate1(1, 1, 10000);
TestUpdate1(5, 1, 10000);
TestUpdate1(1, 2, 5000);
TestUpdate1(1, 5, 2001);
TestUpdate1(4, 4, 2001);
TestUpdate1(15, 5, 2001);
TestUpdate1(64, 5, 5000);
TestUpdate1(5, 5, 25000);
}
private static void TestUpdate1(int cLevel, int threads, int updatesPerThread)
{
IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
for (int i = 1; i <= updatesPerThread; i++) dict[i] = i;
int running = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 1; j <= updatesPerThread; j++)
{
dict[j] = (ii + 2) * j;
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
var div = pair.Value / pair.Key;
var rem = pair.Value % pair.Key;
Assert.Equal(0, rem);
Assert.True(div > 1 && div <= threads+1,
String.Format("* Invalid value={3}! TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread, div));
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 1; i <= updatesPerThread; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("The set of keys in the dictionary is are not the same as the expected." + Environment.NewLine +
"TestUpdate1(cLevel={0}, threads={1}, updatesPerThread={2})", cLevel, threads, updatesPerThread)
);
}
}
[Fact]
public static void TestRead1()
{
TestRead1(1, 1, 10000);
TestRead1(5, 1, 10000);
TestRead1(1, 2, 5000);
TestRead1(1, 5, 2001);
TestRead1(4, 4, 2001);
TestRead1(15, 5, 2001);
TestRead1(64, 5, 5000);
TestRead1(5, 5, 25000);
}
private static void TestRead1(int cLevel, int threads, int readsPerThread)
{
IDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
for (int i = 0; i < readsPerThread; i += 2) dict[i] = i;
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < readsPerThread; j++)
{
int val = 0;
if (dict.TryGetValue(j, out val))
{
Assert.Equal(0, j % 2);
Assert.Equal(j, val);
}
else
{
Assert.Equal(1, j % 2);
}
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
}
[Fact]
public static void TestRemove1()
{
TestRemove1(1, 1, 10000);
TestRemove1(5, 1, 1000);
TestRemove1(1, 5, 2001);
TestRemove1(4, 4, 2001);
TestRemove1(15, 5, 2001);
TestRemove1(64, 5, 5000);
}
private static void TestRemove1(int cLevel, int threads, int removesPerThread)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
string methodparameters = string.Format("* TestRemove1(cLevel={0}, threads={1}, removesPerThread={2})", cLevel, threads, removesPerThread);
int N = 2 * threads * removesPerThread;
for (int i = 0; i < N; i++) dict[i] = -i;
// The dictionary contains keys [0..N), each key mapped to a value equal to the key.
// Threads will cooperatively remove all even keys
int running = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < removesPerThread; j++)
{
int value;
int key = 2 * (ii + j * threads);
Assert.True(dict.TryRemove(key, out value), "Failed to remove an element! " + methodparameters);
Assert.Equal(-key, value);
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 0; i < (threads * removesPerThread); i++)
expectKeys.Add(2 * i + 1);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]), " > Unexpected key value! " + methodparameters);
}
// Finally, let's verify that the count is reported correctly.
Assert.Equal(expectKeys.Count, dict.Count);
Assert.Equal(expectKeys.Count, dict.ToArray().Length);
}
[Fact]
public static void TestRemove2()
{
TestRemove2(1);
TestRemove2(10);
TestRemove2(5000);
}
private static void TestRemove2(int removesPerThread)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>();
for (int i = 0; i < removesPerThread; i++) dict[i] = -i;
// The dictionary contains keys [0..N), each key mapped to a value equal to the key.
// Threads will cooperatively remove all even keys.
const int SIZE = 2;
int running = SIZE;
bool[][] seen = new bool[SIZE][];
for (int i = 0; i < SIZE; i++) seen[i] = new bool[removesPerThread];
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int t = 0; t < SIZE; t++)
{
int thread = t;
Task.Run(
() =>
{
for (int key = 0; key < removesPerThread; key++)
{
int value;
if (dict.TryRemove(key, out value))
{
seen[thread][key] = true;
Assert.Equal(-key, value);
}
}
if (Interlocked.Decrement(ref running) == 0) mre.Set();
});
}
mre.WaitOne();
}
Assert.Equal(0, dict.Count);
for (int i = 0; i < removesPerThread; i++)
{
Assert.False(seen[0][i] == seen[1][i],
String.Format("> FAILED. Two threads appear to have removed the same element. TestRemove2(removesPerThread={0})", removesPerThread)
);
}
}
[Fact]
public static void TestRemove3()
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>();
dict[99] = -99;
ICollection<KeyValuePair<int, int>> col = dict;
// Make sure we cannot "remove" a key/value pair which is not in the dictionary
for (int i = 0; i < 200; i++)
{
if (i != 99)
{
Assert.False(col.Remove(new KeyValuePair<int, int>(i, -99)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(i, -99)");
Assert.False(col.Remove(new KeyValuePair<int, int>(99, -i)), "Should not remove not existing a key/value pair - new KeyValuePair<int, int>(99, -i)");
}
}
// Can we remove a key/value pair successfully?
Assert.True(col.Remove(new KeyValuePair<int, int>(99, -99)), "Failed to remove existing key/value pair");
// Make sure the key/value pair is gone
Assert.False(col.Remove(new KeyValuePair<int, int>(99, -99)), "Should not remove the key/value pair which has been removed");
// And that the dictionary is empty. We will check the count in a few different ways:
Assert.Equal(0, dict.Count);
Assert.Equal(0, dict.ToArray().Length);
}
[Fact]
public static void TestGetOrAdd()
{
TestGetOrAddOrUpdate(1, 1, 1, 10000, true);
TestGetOrAddOrUpdate(5, 1, 1, 10000, true);
TestGetOrAddOrUpdate(1, 1, 2, 5000, true);
TestGetOrAddOrUpdate(1, 1, 5, 2000, true);
TestGetOrAddOrUpdate(4, 0, 4, 2000, true);
TestGetOrAddOrUpdate(16, 31, 4, 2000, true);
TestGetOrAddOrUpdate(64, 5, 5, 5000, true);
TestGetOrAddOrUpdate(5, 5, 5, 25000, true);
}
[Fact]
public static void TestAddOrUpdate()
{
TestGetOrAddOrUpdate(1, 1, 1, 10000, false);
TestGetOrAddOrUpdate(5, 1, 1, 10000, false);
TestGetOrAddOrUpdate(1, 1, 2, 5000, false);
TestGetOrAddOrUpdate(1, 1, 5, 2000, false);
TestGetOrAddOrUpdate(4, 0, 4, 2000, false);
TestGetOrAddOrUpdate(16, 31, 4, 2000, false);
TestGetOrAddOrUpdate(64, 5, 5, 5000, false);
TestGetOrAddOrUpdate(5, 5, 5, 25000, false);
}
private static void TestGetOrAddOrUpdate(int cLevel, int initSize, int threads, int addsPerThread, bool isAdd)
{
ConcurrentDictionary<int, int> dict = new ConcurrentDictionary<int, int>(cLevel, 1);
int count = threads;
using (ManualResetEvent mre = new ManualResetEvent(false))
{
for (int i = 0; i < threads; i++)
{
int ii = i;
Task.Run(
() =>
{
for (int j = 0; j < addsPerThread; j++)
{
if (isAdd)
{
//call either of the two overloads of GetOrAdd
if (j + ii % 2 == 0)
{
dict.GetOrAdd(j, -j);
}
else
{
dict.GetOrAdd(j, x => -x);
}
}
else
{
if (j + ii % 2 == 0)
{
dict.AddOrUpdate(j, -j, (k, v) => -j);
}
else
{
dict.AddOrUpdate(j, (k) => -k, (k, v) => -k);
}
}
}
if (Interlocked.Decrement(ref count) == 0) mre.Set();
});
}
mre.WaitOne();
}
foreach (var pair in dict)
{
Assert.Equal(pair.Key, -pair.Value);
}
List<int> gotKeys = new List<int>();
foreach (var pair in dict)
gotKeys.Add(pair.Key);
gotKeys.Sort();
List<int> expectKeys = new List<int>();
for (int i = 0; i < addsPerThread; i++)
expectKeys.Add(i);
Assert.Equal(expectKeys.Count, gotKeys.Count);
for (int i = 0; i < expectKeys.Count; i++)
{
Assert.True(expectKeys[i].Equals(gotKeys[i]),
String.Format("* Test '{4}': Level={0}, initSize={1}, threads={2}, addsPerThread={3})" + Environment.NewLine +
"> FAILED. The set of keys in the dictionary is are not the same as the expected.",
cLevel, initSize, threads, addsPerThread, isAdd ? "GetOrAdd" : "GetOrUpdate"));
}
// Finally, let's verify that the count is reported correctly.
Assert.Equal(addsPerThread, dict.Count);
Assert.Equal(addsPerThread, dict.ToArray().Length);
}
[Fact]
public static void TestBugFix669376()
{
var cd = new ConcurrentDictionary<string, int>(new OrdinalStringComparer());
cd["test"] = 10;
Assert.True(cd.ContainsKey("TEST"), "Customized comparer didn't work");
}
private class OrdinalStringComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
var xlower = x.ToLowerInvariant();
var ylower = y.ToLowerInvariant();
return string.CompareOrdinal(xlower, ylower) == 0;
}
public int GetHashCode(string obj)
{
return 0;
}
}
[Fact]
public static void TestConstructor()
{
var dictionary = new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) });
Assert.False(dictionary.IsEmpty);
Assert.Equal(1, dictionary.Keys.Count);
Assert.Equal(1, dictionary.Values.Count);
}
[Fact]
public static void TestDebuggerAttributes()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new ConcurrentDictionary<string, int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ConcurrentDictionary<string, int>());
}
[Fact]
public static void TestConstructor_Negative()
{
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((IEqualityComparer<int>)null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null IEqualityComparer is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>((ICollection<KeyValuePair<int, int>>)null, EqualityComparer<int>.Default));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection and non null IEqualityComparer passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1) }, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when non null collection and null IEqualityComparer passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<string, int>(new[] { new KeyValuePair<string, int>(null, 1) }));
// "TestConstructor: FAILED. Constructor didn't throw ANE when collection has null key passed");
Assert.Throws<ArgumentException>(
() => new ConcurrentDictionary<int, int>(new[] { new KeyValuePair<int, int>(1, 1), new KeyValuePair<int, int>(1, 2) }));
// "TestConstructor: FAILED. Constructor didn't throw AE when collection has duplicate keys passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, null, EqualityComparer<int>.Default));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null collection is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, new[] { new KeyValuePair<int, int>(1, 1) }, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed");
Assert.Throws<ArgumentNullException>(
() => new ConcurrentDictionary<int, int>(1, 1, null));
// "TestConstructor: FAILED. Constructor didn't throw ANE when null comparer is passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => new ConcurrentDictionary<int, int>(0, 10));
// "TestConstructor: FAILED. Constructor didn't throw AORE when <1 concurrencyLevel passed");
Assert.Throws<ArgumentOutOfRangeException>(
() => new ConcurrentDictionary<int, int>(-1, 0));
// "TestConstructor: FAILED. Constructor didn't throw AORE when < 0 capacity passed");
}
[Fact]
public static void TestExceptions()
{
var dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.TryAdd(null, 0));
// "TestExceptions: FAILED. TryAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.ContainsKey(null));
// "TestExceptions: FAILED. Contains didn't throw ANE when null key is passed");
int item;
Assert.Throws<ArgumentNullException>(
() => dictionary.TryRemove(null, out item));
// "TestExceptions: FAILED. TryRemove didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.TryGetValue(null, out item));
// "TestExceptions: FAILED. TryGetValue didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => { var x = dictionary[null]; });
// "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed");
Assert.Throws<KeyNotFoundException>(
() => { var x = dictionary["1"]; });
// "TestExceptions: FAILED. this[] TryGetValue didn't throw KeyNotFoundException!");
Assert.Throws<ArgumentNullException>(
() => dictionary[null] = 1);
// "TestExceptions: FAILED. this[] didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd(null, (k) => 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd("1", null));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null valueFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.GetOrAdd(null, 0));
// "TestExceptions: FAILED. GetOrAdd didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate(null, (k) => 0, (k, v) => 0));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate("1", null, (k, v) => 0));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null updateFactory is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.AddOrUpdate(null, (k) => 0, null));
// "TestExceptions: FAILED. AddOrUpdate didn't throw ANE when null addFactory is passed");
dictionary.TryAdd("1", 1);
Assert.Throws<ArgumentException>(
() => ((IDictionary<string, int>)dictionary).Add("1", 2));
// "TestExceptions: FAILED. IDictionary didn't throw AE when duplicate key is passed");
}
[Fact]
public static void TestIDictionary()
{
IDictionary dictionary = new ConcurrentDictionary<string, int>();
Assert.False(dictionary.IsReadOnly);
// Empty dictionary should not enumerate
Assert.Empty(dictionary);
const int SIZE = 10;
for (int i = 0; i < SIZE; i++)
dictionary.Add(i.ToString(), i);
Assert.Equal(SIZE, dictionary.Count);
//test contains
Assert.False(dictionary.Contains(1), "TestIDictionary: FAILED. Contain returned true for incorrect key type");
Assert.False(dictionary.Contains("100"), "TestIDictionary: FAILED. Contain returned true for incorrect key");
Assert.True(dictionary.Contains("1"), "TestIDictionary: FAILED. Contain returned false for correct key");
//test GetEnumerator
int count = 0;
foreach (var obj in dictionary)
{
DictionaryEntry entry = (DictionaryEntry)obj;
string key = (string)entry.Key;
int value = (int)entry.Value;
int expectedValue = int.Parse(key);
Assert.True(value == expectedValue,
String.Format("TestIDictionary: FAILED. Unexpected value returned from GetEnumerator, expected {0}, actual {1}", value, expectedValue));
count++;
}
Assert.Equal(SIZE, count);
Assert.Equal(SIZE, dictionary.Keys.Count);
Assert.Equal(SIZE, dictionary.Values.Count);
//Test Remove
dictionary.Remove("9");
Assert.Equal(SIZE - 1, dictionary.Count);
//Test this[]
for (int i = 0; i < dictionary.Count; i++)
Assert.Equal(i, (int)dictionary[i.ToString()]);
dictionary["1"] = 100; // try a valid setter
Assert.Equal(100, (int)dictionary["1"]);
//nonsexist key
Assert.Null(dictionary["NotAKey"]);
}
[Fact]
public static void TestIDictionary_Negative()
{
IDictionary dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.Add(null, 1));
// "TestIDictionary: FAILED. Add didn't throw ANE when null key is passed");
Assert.Throws<ArgumentException>(
() => dictionary.Add(1, 1));
// "TestIDictionary: FAILED. Add didn't throw AE when incorrect key type is passed");
Assert.Throws<ArgumentException>(
() => dictionary.Add("1", "1"));
// "TestIDictionary: FAILED. Add didn't throw AE when incorrect value type is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary.Contains(null));
// "TestIDictionary: FAILED. Contain didn't throw ANE when null key is passed");
//Test Remove
Assert.Throws<ArgumentNullException>(
() => dictionary.Remove(null));
// "TestIDictionary: FAILED. Remove didn't throw ANE when null key is passed");
//Test this[]
Assert.Throws<ArgumentNullException>(
() => { object val = dictionary[null]; });
// "TestIDictionary: FAILED. this[] getter didn't throw ANE when null key is passed");
Assert.Throws<ArgumentNullException>(
() => dictionary[null] = 0);
// "TestIDictionary: FAILED. this[] setter didn't throw ANE when null key is passed");
Assert.Throws<ArgumentException>(
() => dictionary[1] = 0);
// "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid key type is passed");
Assert.Throws<ArgumentException>(
() => dictionary["1"] = "0");
// "TestIDictionary: FAILED. this[] setter didn't throw AE when invalid value type is passed");
}
[Fact]
public static void TestICollection()
{
ICollection dictionary = new ConcurrentDictionary<int, int>();
Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!");
int key = -1;
int value = +1;
//add one item to the dictionary
((ConcurrentDictionary<int, int>)dictionary).TryAdd(key, value);
var objectArray = new Object[1];
dictionary.CopyTo(objectArray, 0);
Assert.Equal(key, ((KeyValuePair<int, int>)objectArray[0]).Key);
Assert.Equal(value, ((KeyValuePair<int, int>)objectArray[0]).Value);
var keyValueArray = new KeyValuePair<int, int>[1];
dictionary.CopyTo(keyValueArray, 0);
Assert.Equal(key, keyValueArray[0].Key);
Assert.Equal(value, keyValueArray[0].Value);
var entryArray = new DictionaryEntry[1];
dictionary.CopyTo(entryArray, 0);
Assert.Equal(key, (int)entryArray[0].Key);
Assert.Equal(value, (int)entryArray[0].Value);
}
[Fact]
public static void TestICollection_Negative()
{
ICollection dictionary = new ConcurrentDictionary<int, int>();
Assert.False(dictionary.IsSynchronized, "TestICollection: FAILED. IsSynchronized returned true!");
Assert.Throws<NotSupportedException>(() => { var obj = dictionary.SyncRoot; });
// "TestICollection: FAILED. SyncRoot property didn't throw");
Assert.Throws<ArgumentNullException>(() => dictionary.CopyTo(null, 0));
// "TestICollection: FAILED. CopyTo didn't throw ANE when null Array is passed");
Assert.Throws<ArgumentOutOfRangeException>(() => dictionary.CopyTo(new object[] { }, -1));
// "TestICollection: FAILED. CopyTo didn't throw AORE when negative index passed");
//add one item to the dictionary
((ConcurrentDictionary<int, int>)dictionary).TryAdd(1, 1);
Assert.Throws<ArgumentException>(() => dictionary.CopyTo(new object[] { }, 0));
// "TestICollection: FAILED. CopyTo didn't throw AE when the Array size is smaller than the dictionary count");
}
[Fact]
public static void TestClear()
{
var dictionary = new ConcurrentDictionary<int, int>();
for (int i = 0; i < 10; i++)
dictionary.TryAdd(i, i);
Assert.Equal(10, dictionary.Count);
dictionary.Clear();
Assert.Equal(0, dictionary.Count);
int item;
Assert.False(dictionary.TryRemove(1, out item), "TestClear: FAILED. TryRemove succeeded after Clear");
Assert.True(dictionary.IsEmpty, "TestClear: FAILED. IsEmpty returned false after Clear");
}
public static void TestTryUpdate()
{
var dictionary = new ConcurrentDictionary<string, int>();
Assert.Throws<ArgumentNullException>(
() => dictionary.TryUpdate(null, 0, 0));
// "TestTryUpdate: FAILED. TryUpdate didn't throw ANE when null key is passed");
for (int i = 0; i < 10; i++)
dictionary.TryAdd(i.ToString(), i);
for (int i = 0; i < 10; i++)
{
Assert.True(dictionary.TryUpdate(i.ToString(), i + 1, i), "TestTryUpdate: FAILED. TryUpdate failed!");
Assert.Equal(i + 1, dictionary[i.ToString()]);
}
//test TryUpdate concurrently
dictionary.Clear();
for (int i = 0; i < 1000; i++)
dictionary.TryAdd(i.ToString(), i);
var mres = new ManualResetEventSlim();
Task[] tasks = new Task[10];
ThreadLocal<ThreadData> updatedKeys = new ThreadLocal<ThreadData>(true);
for (int i = 0; i < tasks.Length; i++)
{
// We are creating the Task using TaskCreationOptions.LongRunning because...
// there is no guarantee that the Task will be created on another thread.
// There is also no guarantee that using this TaskCreationOption will force
// it to be run on another thread.
tasks[i] = Task.Factory.StartNew((obj) =>
{
mres.Wait();
int index = (((int)obj) + 1) + 1000;
updatedKeys.Value = new ThreadData();
updatedKeys.Value.ThreadIndex = index;
for (int j = 0; j < dictionary.Count; j++)
{
if (dictionary.TryUpdate(j.ToString(), index, j))
{
if (dictionary[j.ToString()] != index)
{
updatedKeys.Value.Succeeded = false;
return;
}
updatedKeys.Value.Keys.Add(j.ToString());
}
}
}, i, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
mres.Set();
Task.WaitAll(tasks);
int numberSucceeded = 0;
int totalKeysUpdated = 0;
foreach (var threadData in updatedKeys.Values)
{
totalKeysUpdated += threadData.Keys.Count;
if (threadData.Succeeded)
numberSucceeded++;
}
Assert.True(numberSucceeded == tasks.Length, "One or more threads failed!");
Assert.True(totalKeysUpdated == dictionary.Count,
String.Format("TestTryUpdate: FAILED. The updated keys count doesn't match the dictionary count, expected {0}, actual {1}", dictionary.Count, totalKeysUpdated));
foreach (var value in updatedKeys.Values)
{
for (int i = 0; i < value.Keys.Count; i++)
Assert.True(dictionary[value.Keys[i]] == value.ThreadIndex,
String.Format("TestTryUpdate: FAILED. The updated value doesn't match the thread index, expected {0} actual {1}", value.ThreadIndex, dictionary[value.Keys[i]]));
}
//test TryUpdate with non atomic values (intPtr > 8)
var dict = new ConcurrentDictionary<int, Struct16>();
dict.TryAdd(1, new Struct16(1, -1));
Assert.True(dict.TryUpdate(1, new Struct16(2, -2), new Struct16(1, -1)), "TestTryUpdate: FAILED. TryUpdate failed for non atomic values ( > 8 bytes)");
}
#region Helper Classes and Methods
private class ThreadData
{
public int ThreadIndex;
public bool Succeeded = true;
public List<string> Keys = new List<string>();
}
private struct Struct16 : IEqualityComparer<Struct16>
{
public long L1, L2;
public Struct16(long l1, long l2)
{
L1 = l1;
L2 = l2;
}
public bool Equals(Struct16 x, Struct16 y)
{
return x.L1 == y.L1 && x.L2 == y.L2;
}
public int GetHashCode(Struct16 obj)
{
return (int)L1;
}
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !NETSTANDARD
#define DISABLE_FILE_INTERNAL_LOGGING
namespace NLog.UnitTests.Targets
{
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using NLog.Config;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
using System.Collections.Generic;
using System.Linq;
using Xunit.Extensions;
public class ConcurrentFileTargetTests : NLogTestBase
{
private ILogger logger = LogManager.GetLogger("NLog.UnitTests.Targets.ConcurrentFileTargetTests");
private void ConfigureSharedFile(string mode, string fileName)
{
var modes = mode.Split('|');
FileTarget ft = new FileTarget();
ft.FileName = fileName;
ft.Layout = "${message}";
ft.KeepFileOpen = true;
ft.OpenFileCacheTimeout = 10;
ft.OpenFileCacheSize = 1;
ft.LineEnding = LineEndingMode.LF;
ft.KeepFileOpen = Array.IndexOf(modes, "retry") >= 0 ? false : true;
ft.ForceMutexConcurrentWrites = Array.IndexOf(modes, "mutex") >= 0 ? true : false;
ft.ArchiveAboveSize = Array.IndexOf(modes, "archive") >= 0 ? 50 : -1;
if (ft.ArchiveAboveSize > 0)
{
string archivePath = Path.Combine(Path.GetDirectoryName(fileName), "Archive");
ft.ArchiveFileName = Path.Combine(archivePath, "{####}_" + Path.GetFileName(fileName));
ft.MaxArchiveFiles = 10000;
}
var name = "ConfigureSharedFile_" + mode.Replace('|', '_') + "-wrapper";
switch (modes[0])
{
case "async":
SimpleConfigurator.ConfigureForTargetLogging(new AsyncTargetWrapper(ft, 100, AsyncTargetWrapperOverflowAction.Grow) { Name = name, TimeToSleepBetweenBatches = 10 }, LogLevel.Debug);
break;
case "buffered":
SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100) { Name = name }, LogLevel.Debug);
break;
case "buffered_timed_flush":
SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100, 10) { Name = name }, LogLevel.Debug);
break;
default:
SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
break;
}
}
#pragma warning disable xUnit1013 // Needed for test
public void Process(string processIndex, string fileName, string numLogsString, string mode)
#pragma warning restore xUnit1013
{
Thread.CurrentThread.Name = processIndex;
int numLogs = Convert.ToInt32(numLogsString);
int idxProcess = Convert.ToInt32(processIndex);
ConfigureSharedFile(mode, fileName);
string format = processIndex + " {0}";
// Having the internal logger enabled would just slow things down, reducing the
// likelyhood for uncovering racing conditions. Uncomment #define DISABLE_FILE_INTERNAL_LOGGING
#if !DISABLE_FILE_INTERNAL_LOGGING
var logWriter = new StringWriter { NewLine = Environment.NewLine };
NLog.Common.InternalLogger.LogLevel = LogLevel.Trace;
NLog.Common.InternalLogger.LogFile = Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex));
NLog.Common.InternalLogger.LogWriter = logWriter;
NLog.Common.InternalLogger.LogToConsole = true;
try
#endif
{
using (new NoThrowNLogExceptions())
{
Thread.Sleep(Math.Max((10 - idxProcess), 1) * 5); // Delay to wait for the other processes
for (int i = 0; i < numLogs; ++i)
{
logger.Debug(format, i);
}
LogManager.Configuration = null; // Flush + Close
}
}
#if !DISABLE_FILE_INTERNAL_LOGGING
catch (Exception ex)
{
using (var textWriter = File.AppendText(Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex))))
{
textWriter.WriteLine(ex.ToString());
textWriter.WriteLine(logWriter.GetStringBuilder().ToString());
}
throw;
}
using (var textWriter = File.AppendText(Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex))))
{
textWriter.WriteLine(logWriter.GetStringBuilder().ToString());
}
#endif
}
private string MakeFileName(int numProcesses, int numLogs, string mode)
{
// Having separate file names for the various tests makes debugging easier.
return $"test_{numProcesses}_{numLogs}_{mode.Replace('|', '_')}.txt";
}
private void DoConcurrentTest(int numProcesses, int numLogs, string mode)
{
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
string archivePath = Path.Combine(tempPath, "Archive");
try
{
Directory.CreateDirectory(tempPath);
Directory.CreateDirectory(archivePath);
string logFile = Path.Combine(tempPath, MakeFileName(numProcesses, numLogs, mode));
if (File.Exists(logFile))
{
throw new Exception($"file '{logFile}' already exists");
}
Process[] processes = new Process[numProcesses];
for (int i = 0; i < numProcesses; ++i)
{
processes[i] = ProcessRunner.SpawnMethod(
GetType(),
"Process",
i.ToString(),
logFile,
numLogs.ToString(),
mode);
}
// In case we'd like to capture stdout, we would need to drain it continuously.
// StandardOutput.ReadToEnd() wont work, since the other processes console only has limited buffer.
for (int i = 0; i < numProcesses; ++i)
{
processes[i].WaitForExit();
Assert.Equal(0, processes[i].ExitCode);
processes[i].Dispose();
processes[i] = null;
}
var files = new System.Collections.Generic.List<string>(Directory.GetFiles(archivePath));
files.Add(logFile);
bool verifyFileSize = files.Count > 1;
var receivedNumbersSet = new List<int>[numProcesses];
for (int i = 0; i < numProcesses; i++)
{
var receivedNumbers = new List<int>(numLogs);
receivedNumbersSet[i] = receivedNumbers;
}
//Console.WriteLine("Verifying output file {0}", logFile);
foreach (var file in files)
{
using (StreamReader sr = File.OpenText(file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] tokens = line.Split(' ');
Assert.Equal(2, tokens.Length);
int thread = Convert.ToInt32(tokens[0]);
int number = Convert.ToInt32(tokens[1]);
Assert.True(thread >= 0);
Assert.True(thread < numProcesses);
receivedNumbersSet[thread].Add(number);
}
if (verifyFileSize)
{
if (sr.BaseStream.Length > 100)
throw new InvalidOperationException(
$"Error when reading file {file}, size {sr.BaseStream.Length} is too large");
else if (sr.BaseStream.Length < 35 && files[files.Count - 1] != file)
throw new InvalidOperationException(
$"Error when reading file {file}, size {sr.BaseStream.Length} is too small");
}
}
}
var expected = Enumerable.Range(0, numLogs).ToList();
int currentProcess = 0;
bool? equalsWhenReorderd = null;
try
{
for (; currentProcess < numProcesses; currentProcess++)
{
var receivedNumbers = receivedNumbersSet[currentProcess];
var equalLength = expected.Count == receivedNumbers.Count;
var fastCheck = equalLength && expected.SequenceEqual(receivedNumbers);
if (!fastCheck)
//assert equals on two long lists in xUnit is lame. Not showing the difference.
{
if (equalLength)
{
var reodered = receivedNumbers.OrderBy(i => i);
equalsWhenReorderd = expected.SequenceEqual(reodered);
}
Assert.Equal(string.Join(",", expected), string.Join(",", receivedNumbers));
}
}
}
catch (Exception ex)
{
var reoderProblem = equalsWhenReorderd == null ? "Dunno" : (equalsWhenReorderd == true ? "Yes" : "No");
throw new InvalidOperationException($"Error when comparing path {tempPath} for process {currentProcess}. Is this a recording problem? {reoderProblem}", ex);
}
}
finally
{
try
{
if (Directory.Exists(archivePath))
Directory.Delete(archivePath, true);
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
catch
{
}
}
}
[Theory]
[InlineData(2, 10000, "none")]
[InlineData(5, 4000, "none")]
[InlineData(10, 2000, "none")]
#if !MONO
// MONO Doesn't work well with global mutex, and it is needed for successful concurrent archive operations
[InlineData(2, 500, "none|archive")]
[InlineData(2, 500, "none|mutex|archive")]
[InlineData(2, 10000, "none|mutex")]
[InlineData(5, 4000, "none|mutex")]
[InlineData(10, 2000, "none|mutex")]
#endif
public void SimpleConcurrentTest(int numProcesses, int numLogs, string mode)
{
RetryingIntegrationTest(3, () => DoConcurrentTest(numProcesses, numLogs, mode));
}
[Theory]
[InlineData("async")]
#if !MONO
[InlineData("async|mutex")]
#endif
public void AsyncConcurrentTest(string mode)
{
// Before 2 processes are running into concurrent writes,
// the first process typically already has written couple thousand events.
// Thus to have a meaningful test, at least 10K events are required.
// Due to the buffering it makes no big difference in runtime, whether we
// have 2 process writing 10K events each or couple more processes with even more events.
// Runtime is mostly defined by Runner.exe compilation and JITing the first.
DoConcurrentTest(5, 1000, mode);
}
[Theory]
[InlineData("buffered")]
#if !MONO
[InlineData("buffered|mutex")]
#endif
public void BufferedConcurrentTest(string mode)
{
DoConcurrentTest(5, 1000, mode);
}
[Theory]
[InlineData("buffered_timed_flush")]
#if !MONO
[InlineData("buffered_timed_flush|mutex")]
#endif
public void BufferedTimedFlushConcurrentTest(string mode)
{
DoConcurrentTest(5, 1000, mode);
}
}
}
#endif
| |
using System;
using System.Runtime.InteropServices;
namespace Daemaged.NTP
{
/// <summary>
/// The difference between two <see cref="T:Daemaged.NTP.NtpTimestamp" /> values.
/// This is a value type.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct NtpTimestampDifference : IComparable
{
readonly long _difference;
internal NtpTimestampDifference(long d)
{
_difference = d;
}
/// <summary>
/// Compares this instance to a specified object and returns an indication of their relative values.
/// </summary>
/// <param name="value">An object to compare, or null.</param>
/// <returns>A 32-bit signed integer that indicates the relative order of the objects being compared. See <see cref="M:System.IComparable.CompareTo(System.Object)" /> for details.</returns>
public int CompareTo(object value)
{
if (value is NtpTimestamp)
return _difference.CompareTo(((NtpTimestampDifference) value)._difference);
throw new ArgumentException($"must be of type {nameof(NtpTimestampDifference)}", nameof(value));
}
/// <summary>
/// Indicates whether the specified object is equal to the current object.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>true if <c>obj</c> is a NtpTimestampDifference that represents the same
/// time difference as this instance; otherwise, false.</returns>
public override bool Equals(object obj)
{
return ((obj is NtpTimestampDifference) && _difference.Equals(((NtpTimestampDifference) obj)._difference));
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>The 32 least significant bits of the time difference.</returns>
public override int GetHashCode()
{
return (int) (_difference & 0x7fffffffL);
}
/// <summary>
/// Accessor for the sign of the time difference.
/// </summary>
/// <value>True for positive differences and zero; false for negative
/// differences.</value>
public bool Positive => (_difference >= 0L);
internal long ToInt64()
{ return _difference; }
internal long ToTicks()
{
ulong unixDiff;
if (_difference >= 0L) {
unixDiff = (ulong) (_difference >> 32);
}
else
unixDiff = (ulong) (-_difference >> 32);
var fraction = GetFraction();
var ticks = (long)(unixDiff * (NtpTimestamp.TickToSecScale));
ticks += (long)((fraction * NtpTimestamp.TickToSecScale) >> 32);
if (_difference >= 0L) {
return ticks;
}
return -ticks;
}
/// <summary>
/// Gets the <see cref="T:System.TimeSpan" /> instance that represents the time difference.
/// </summary>
/// <value>A <see cref="T:System.TimeSpan" /> instance.</value>
public TimeSpan ToTimeSpan()
{ return new TimeSpan(ToTicks()); }
/// <summary>
/// Converts the value of this instance to its string representation.
/// </summary>
/// <returns>String representation of time difference.</returns>
public override string ToString()
{ return ToTimeSpan().ToString(); }
/// <summary>
/// Gets the value of this instance expressed in whole and fractional seconds.
/// </summary>
/// <remarks>The value of this instance expressed in whole and fractional seconds.</remarks>
public double TotalSeconds => ToTimeSpan().TotalSeconds;
/// <summary>
/// The sub-second part of the time difference, on microsecond scale.
/// </summary>
/// <value>A number between -10^6+1 and 10^6-1.</value>
public int Microsecond {
get {
var scaledFraction = GetScaledFraction(0xf4240L);
if (_difference >= 0L)
return scaledFraction;
return -scaledFraction;
}
}
ulong GetFraction()
{
ulong diff;
if (_difference >= 0L)
diff = (ulong) _difference;
else
diff = (ulong) -_difference;
return (diff & 0xffffffffL);
}
int GetScaledFraction(ulong scale)
{
return (int) (GetFraction()*scale >> 32);
}
/// <summary>
/// Divides the time difference by 2.
/// </summary>
/// <returns>A time difference with the same sign as this instance and an absolute
/// value one half of the absolute value of this instance.</returns>
internal NtpTimestampDifference Halve()
{ return new NtpTimestampDifference(_difference/2L); }
/// <summary>
/// Changes the sign of the time difference (positive to negative and vice-versa).
/// </summary>
/// <returns>A time difference with the same absolute
/// value as this instance and an opposite sign.</returns>
public NtpTimestampDifference Negate()
{ return new NtpTimestampDifference(-_difference); }
/// <summary>
/// Compare two instances of NtpTimestampDifference.
/// </summary>
/// <param name="a">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <param name="b">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <returns>True if equal; false if not equal.</returns>
public static bool operator ==(NtpTimestampDifference a, NtpTimestampDifference b)
{ return a.Equals(b); }
/// <summary>
/// Compare two instances of NtpTimestampDifference.
/// </summary>
/// <param name="a">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <param name="b">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <returns>Flase if equal; true if not equal.</returns>
public static bool operator !=(NtpTimestampDifference a, NtpTimestampDifference b)
{ return !a.Equals(b); }
/// <summary>
/// Indicates whether a specified NtpTimestampDifference is less than
/// another specified NtpTimestampDifference.
/// </summary>
/// <param name="a">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <param name="b">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <returns>true if the value of <c>a</c> is less than
/// the value of <c>b</c>; otherwise false.</returns>
public static bool operator <(NtpTimestampDifference a, NtpTimestampDifference b)
{ return (a._difference < b._difference); }
/// <summary>
/// Indicates whether a specified NtpTimestampDifference is greater than
/// another specified NtpTimestampDifference.
/// </summary>
/// <param name="a">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <param name="b">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <returns>true if the value of <c>a</c> is greater than
/// the value of <c>b</c>; otherwise false.</returns>
public static bool operator >(NtpTimestampDifference a, NtpTimestampDifference b)
{ return (a._difference > b._difference); }
/// <summary>
/// Indicates whether a specified NtpTimestampDifference is less than
/// or equal to another specified NtpTimestampDifference.
/// </summary>
/// <param name="a">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <param name="b">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <returns>true if the value of <c>a</c> is less than
/// or equal to the value of <c>b</c>; otherwise false.</returns>
public static bool operator <=(NtpTimestampDifference a, NtpTimestampDifference b)
{ return (a._difference <= b._difference); }
/// <summary>
/// Indicates whether a specified NtpTimestampDifference is greater than
/// or equal to another specified NtpTimestampDifference.
/// </summary>
/// <param name="a">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <param name="b">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <returns>true if the value of <c>a</c> is greater than
/// or equal to the value of <c>b</c>; otherwise false.</returns>
public static bool operator >=(NtpTimestampDifference a, NtpTimestampDifference b)
{ return (a._difference >= b._difference); }
/// <summary>
/// Adds a time difference to a timestamp.
/// </summary>
/// <param name="a">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <param name="b">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <returns>A timestamp plus a time difference.</returns>
public static NtpTimestampDifference operator +(NtpTimestampDifference a, NtpTimestampDifference b)
{ return a.Add(b); }
/// <summary>
/// Subtracts a time difference from a timestamp.
/// </summary>
/// <param name="a">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <param name="b">An <see cref="T:Daemaged.NTP.NtpTimestampDifference" />.</param>
/// <returns>A timestamp minus a time difference.</returns>
public static NtpTimestampDifference operator -(NtpTimestampDifference a, NtpTimestampDifference b)
{ return a.Subtract(b); }
/// <summary>
/// Adds the specified time difference to this instance.
/// </summary>
/// <param name="value">A time difference to add.</param>
/// <returns>A time difference plus a time difference.</returns>
public NtpTimestampDifference Add(NtpTimestampDifference value)
{
NtpTimestampDifference difference;
try {
difference = new NtpTimestampDifference(_difference + value._difference);
}
catch (OverflowException) {
throw new OverflowException(string.Format("Cannot add {1} to {0}.", this, value));
}
return difference;
}
/// <summary>
/// Subtracts the specified time difference from this instance.
/// </summary>
/// <param name="value">A time difference to subtract.</param>
/// <returns>A time difference plus a time difference.</returns>
public NtpTimestampDifference Subtract(NtpTimestampDifference value)
{
NtpTimestampDifference diff;
try {
diff = new NtpTimestampDifference(_difference - value._difference);
}
catch (OverflowException) {
throw new OverflowException(string.Format("Cannot subtract {1} from {0}.", this, value));
}
return diff;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Nohros.Resources;
namespace Nohros.Collections
{
/// <summary>
/// Represents a collections of parameters associated with a
/// <see cref="ParameterizedString"/>.
/// </summary>
/// <remarks>
/// A <see cref="ParameterizedStringPartParameterCollection"/> class was designed to
/// handle a small number of parameters and it uses classes that does not
/// performs well when the number of elements is greater than 10 elements.
/// </remarks>
public class ParameterizedStringPartParameterCollection :
ICollection<ParameterizedStringPartParameter>
{
readonly List<ParameterizedStringPartParameter> parameters_;
#region .ctor
/// <summary>
/// Initializes a new instance of the ParameterizedStringPartParameterCollection.
/// </summary>
internal ParameterizedStringPartParameterCollection() {
parameters_ = new List<ParameterizedStringPartParameter>();
}
#endregion
/// <summary>
/// Adds the specified <see cref="ParameterizedStringPartParameter"/>
/// object to this <see cref="ParameterizedStringPartParameterCollection"/>.
/// </summary>
/// <param name="part">
/// The <see cref="ParameterizedStringPartParameter"/> to add to the
/// collection.
/// </param>
/// <exception cref="ArgumentException">
/// The <see cref="ParameterizedStringPart"/> specified is already added to
/// this <see cref="ParameterizedStringPartParameterCollection"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="part"/> is <c>null</c>.
/// </exception>
public void Add(ParameterizedStringPartParameter part) {
if (part == null) {
throw new ArgumentNullException("part");
}
if (Contains(part))
throw new ArgumentException(
string.Format(
StringResources.Argument_AddingDuplicate, part.Name));
parameters_.Add(part);
}
/// <summary>
/// Removes all the <see cref="ParameterizedStringPart"/> objects from
/// the <see cref="ParameterizedStringPartParameterCollection"/>.
/// </summary>
public void Clear() {
parameters_.Clear();
}
/// <summary>
/// Determines whether the specified <see cref="ParameterizedStringPart"/>
/// is in the <see cref="ParameterizedStringPartParameterCollection"/>.
/// </summary>
/// <param name="part">
/// The <see cref="ParameterizedStringPart"/>value to verify.
/// </param>
/// <returns>
/// <c>true</c> if the <see cref="ParameterizedStringPartParameterCollection"/>
/// contains the <paramref name="part"/>; otherwise <c>false</c>.
/// </returns>
public bool Contains(ParameterizedStringPartParameter part) {
return (part != null && -1 != IndexOf(part.Name));
}
/// <summary>
/// Copies all elements of the current
/// <see cref="ParameterizedStringPartParameterCollection"/> to the specified
/// <see cref="ParameterizedStringPartParameterCollection"/> array starting at the
/// specified destination index.
/// </summary>
/// <param name="array">
/// The <see cref="ParameterizedStringPartParameterCollection"/> array that is the
/// destination of the elements copied from the current
/// <see cref="ParameterizedStringPartParameterCollection"/>
/// </param>
/// <param name="index">
/// A 32-bit integer that represents the index in the
/// <see cref="ParameterizedStringPartParameterCollection"/> at which copying
/// starts.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="array"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than 0.
/// </exception>
/// <exception cref="ArgumentException">
/// The number of elements in the source
/// <see cref="ParameterizedStringPartParameterCollection"/> is greater than the
/// available space from <paramref name="index"/> to the end of the
/// destination array.
/// </exception>
public void CopyTo(ParameterizedStringPartParameter[] array, int index) {
parameters_.CopyTo(array, index);
}
/// <summary>
/// Removes the specified <see cref="ParameterizedStringPart"/> from the
/// collection.
/// </summary>
/// <param name="part">
/// A <see cref="ParameterizedStringPart"/> object to remove from the
/// colletion.
/// </param>
/// <returns>
/// <c>true</c> if the parameter is successfully removed; othewise,
/// <c>false</c>.
/// </returns>
/// <remarks>
/// If part is not in the list, the
/// <see cref="Remove(ParameterizedStringPart)"/> method will do nothing.
/// In particular, it does not throws an exception.
/// </remarks>
public bool Remove(ParameterizedStringPartParameter part) {
if (part == null)
return false;
return Remove(part.Name);
}
/// <summary>
/// Returns an integer that contains the number of elements in the
/// <see cref="ParameterizedStringPartParameterCollection"/>.
/// </summary>
public int Count {
get { return parameters_.Count; }
}
/// <summary>
/// Gets a value that indicates whether the
/// <see cref="ParameterizedStringPartParameterCollection"/> is read-only.
/// </summary>
/// <value>
/// Returns true if the <see cref="ParameterizedStringPartParameterCollection"/>is
/// read only; otherwise, false.
/// </value>
bool ICollection<ParameterizedStringPartParameter>.IsReadOnly {
get { return false; }
}
/// <summary>
/// Returns an enumerator that iterates through the
/// <see cref="ParameterizedStringPartParameterCollection"/>
/// </summary>
/// <returns>
/// An IEnumerator of <see cref="ParameterizedStringPartParameterCollection"/>
/// </returns>
IEnumerator<ParameterizedStringPartParameter>
IEnumerable<ParameterizedStringPartParameter>.GetEnumerator() {
return parameters_.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the
/// <see cref="ParameterizedStringPartParameterCollection"/>
/// </summary>
/// <returns>
/// An IEnumerator of <see cref="ParameterizedStringPartParameterCollection"/>.
/// </returns>
IEnumerator IEnumerable.GetEnumerator() {
return parameters_.GetEnumerator();
}
/// <summary>
/// Adds the specified <see cref="ParameterizedStringPartParameter"/>
/// object to this <see cref="ParameterizedStringPartParameterCollection"/> if it
/// is not added yet.
/// </summary>
/// <param name="part">
/// The <see cref="ParameterizedStringPartParameter"/> to add to the
/// collection.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="part"/> is <c>null</c>.
/// </exception>
public void AddIfAbsent(ParameterizedStringPartParameter part) {
if (part == null) {
throw new ArgumentNullException("part");
}
if (!Contains(part)) {
parameters_.Add(part);
}
}
/// <summary>
/// Gets the location of the specified
/// <see cref="ParameterizedStringPart"/> with the specified name.
/// </summary>
/// <param name="name">
/// The case-insensitive name of the <see cref="ParameterizedStringPart"/>
/// to find.
/// </param>
/// <returns>
/// The zero-based location of the specified
/// <see cref="ParameterizedStringPart"/> with the specified
/// case-insensitive name. Returns -1 when the object does not exists in
/// the collection.
/// </returns>
public int IndexOf(string name) {
if (name == null)
return -1;
for (int i = 0, j = parameters_.Count; i < j; i++) {
if (string.Compare(
parameters_[i].Name, name,
StringComparison.OrdinalIgnoreCase) == 0) {
return i;
}
}
return -1;
}
/// <summary>
/// Removes a <see cref="ParameterizedStringPart"/> with name
/// <paramref name="name"/> from the collection.
/// </summary>
/// <param name="name">
/// The name of the parameter.
/// </param>
/// <returns><c>true</c> if the parameter is successfully removed;
/// othewise, <c>false</c>.
/// </returns>
/// <remarks>
/// If a parameter with name <paramref name="name"/> could not be found,
/// the <see cref="Remove(string)"/> method will
/// do nothing. In particular, it does not throws an exception, only
/// returns <c>false</c>.
/// </remarks>
public bool Remove(string name) {
int index = IndexOf(name);
if (index != -1) {
parameters_.RemoveAt(index);
return true;
}
return false;
}
/// <summary>
/// Gets the <see cref="ParameterizedStringPart"/> at the specified index.
/// </summary>
/// <param name="index">
/// The zero-based index of the parameter to retrieve.
/// </param>
/// <returns>
/// The <see cref="ParameterizedStringPart"/> at the specified index.
/// </returns>
/// <exception cref="IndexOutOfRangeException">
/// The specified index does not exists.
/// </exception>
public ParameterizedStringPartParameter this[int index] {
get { return parameters_[index]; }
}
/// <summary>
/// Gets the <see cref="ParameterizedStringPart"/> with the specified name.
/// </summary>
/// <param name="name">
/// The name of the parameter to retrieve.
/// </param>
/// <returns>
/// The <see cref="ParameterizedStringPart"/> with the specified name.
/// </returns>
/// <exception cref="IndexOutOfRangeException">
/// <paramref name="name"/> is not found or is invalid.
/// </exception>
/// <remarks>
/// The <paramref name="name"/> is used to look up the index
/// value in the underlying
/// <see cref="ParameterizedStringPartParameterCollection"/>. If the
/// <paramref name="name"/> is not found or if it is not valid,
/// an <see cref="IndexOutOfRangeException"/> will be throw.
/// </remarks>
public ParameterizedStringPartParameter this[string name] {
get {
int index = IndexOf(name);
if (index == -1)
throw new IndexOutOfRangeException("name");
return parameters_[index];
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Dbg = System.Management.Automation.Diagnostics;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
namespace Microsoft.PowerShell.Commands
{
#region BaseCsvWritingCommand
/// <summary>
/// This class implements the base for exportcsv and converttocsv commands.
/// </summary>
public abstract class BaseCsvWritingCommand : PSCmdlet
{
#region Command Line Parameters
/// <summary>
/// Property that sets delimiter.
/// </summary>
[Parameter(Position = 1, ParameterSetName = "Delimiter")]
[ValidateNotNull]
public char Delimiter { get; set; }
///<summary>
///Culture switch for csv conversion
///</summary>
[Parameter(ParameterSetName = "UseCulture")]
public SwitchParameter UseCulture { get; set; }
/// <summary>
/// Abstract Property - Input Object which is written in Csv format.
/// Derived as Different Attributes.In ConvertTo-CSV, This is a positional parameter. Export-CSV not a Positional behaviour.
/// </summary>
public abstract PSObject InputObject { get; set; }
/// <summary>
/// IncludeTypeInformation : The #TYPE line should be generated. Default is false. Cannot specify with NoTypeInformation.
/// </summary>
[Parameter]
[Alias("ITI")]
public SwitchParameter IncludeTypeInformation { get; set; }
/// <summary>
/// NoTypeInformation : The #TYPE line should not be generated. Default is true. Cannot specify with IncludeTypeInformation.
/// </summary>
[Parameter(DontShow = true)]
[Alias("NTI")]
public SwitchParameter NoTypeInformation { get; set; } = true;
#endregion Command Line Parameters
/// <summary>
/// Write the string to a file or pipeline.
/// </summary>
public virtual void WriteCsvLine(string line)
{
}
/// <summary>
/// BeginProcessing override.
/// </summary>
protected override void BeginProcessing()
{
if (this.MyInvocation.BoundParameters.ContainsKey(nameof(IncludeTypeInformation)) && this.MyInvocation.BoundParameters.ContainsKey(nameof(NoTypeInformation)))
{
InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyIncludeTypeInformationAndNoTypeInformation);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyIncludeTypeInformationAndNoTypeInformation", ErrorCategory.InvalidData, null);
this.ThrowTerminatingError(errorRecord);
}
if (this.MyInvocation.BoundParameters.ContainsKey(nameof(IncludeTypeInformation)))
{
NoTypeInformation = !IncludeTypeInformation;
}
Delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, Delimiter, UseCulture);
}
}
#endregion
#region Export-CSV Command
/// <summary>
/// Implementation for the Export-Csv command.
/// </summary>
[Cmdlet(VerbsData.Export, "Csv", SupportsShouldProcess = true, DefaultParameterSetName = "Delimiter", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113299")]
public sealed class ExportCsvCommand : BaseCsvWritingCommand, IDisposable
{
#region Command Line Parameters
// If a Passthru parameter is added, the ShouldProcess
// implementation will need to be changed.
/// <summary>
/// Input Object for CSV Writing.
/// </summary>
[Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true)]
public override PSObject InputObject { get; set; }
/// <summary>
/// Mandatory file name to write to.
/// </summary>
[Parameter(Position = 0)]
[ValidateNotNullOrEmpty]
public string Path
{
get
{
return _path;
}
set
{
_path = value;
_specifiedPath = true;
}
}
private string _path;
private bool _specifiedPath = false;
/// <summary>
/// The literal path of the mandatory file name to write to.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[Alias("PSPath", "LP")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string LiteralPath
{
get
{
return _path;
}
set
{
_path = value;
_isLiteralPath = true;
}
}
private bool _isLiteralPath = false;
/// <summary>
/// Gets or sets property that sets force parameter.
/// </summary>
[Parameter]
public SwitchParameter Force { get; set; }
/// <summary>
/// Gets or sets property that prevents file overwrite.
/// </summary>
[Parameter]
[Alias("NoOverwrite")]
public SwitchParameter NoClobber { get; set; }
/// <summary>
/// Gets or sets encoding optional flag.
/// </summary>
[Parameter]
[ArgumentToEncodingTransformationAttribute]
[ArgumentEncodingCompletionsAttribute]
[ValidateNotNullOrEmpty]
public Encoding Encoding { get; set; } = ClrFacade.GetDefaultEncoding();
/// <summary>
/// Gets or sets property that sets append parameter.
/// </summary>
[Parameter]
public SwitchParameter Append { get; set; }
// true if Append=true AND the file written was not empty (or nonexistent) when the cmdlet was invoked
private bool _isActuallyAppending;
#endregion
#region Overrides
private bool _shouldProcess;
private IList<string> _propertyNames;
private IList<string> _preexistingPropertyNames;
private ExportCsvHelper _helper;
/// <summary>
/// BeginProcessing override.
/// </summary>
protected override void BeginProcessing()
{
base.BeginProcessing();
// Validate that they don't provide both Path and LiteralPath, but have provided at least one.
if (!(_specifiedPath ^ _isLiteralPath))
{
InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null);
this.ThrowTerminatingError(errorRecord);
}
_shouldProcess = ShouldProcess(Path);
if (!_shouldProcess)
{
return;
}
CreateFileStream();
_helper = new ExportCsvHelper(this, base.Delimiter);
}
/// <summary>
/// Convert the current input object to Csv and write to file/WriteObject.
/// </summary>
protected override void ProcessRecord()
{
if (InputObject == null || _sw == null)
{
return;
}
if (!_shouldProcess)
{
return;
}
// Process first object
if (_propertyNames == null)
{
// figure out the column names (and lock-in their order)
_propertyNames = ExportCsvHelper.BuildPropertyNames(InputObject, _propertyNames);
if (_isActuallyAppending && _preexistingPropertyNames != null)
{
this.ReconcilePreexistingPropertyNames();
}
// write headers (row1: typename + row2: column names)
if (!_isActuallyAppending)
{
if (NoTypeInformation == false)
{
WriteCsvLine(ExportCsvHelper.GetTypeString(InputObject));
}
WriteCsvLine(_helper.ConvertPropertyNamesCSV(_propertyNames));
}
}
string csv = _helper.ConvertPSObjectToCSV(InputObject, _propertyNames);
WriteCsvLine(csv);
_sw.Flush();
}
/// <summary>
/// EndProcessing.
/// </summary>
protected override void EndProcessing()
{
CleanUp();
}
#endregion Overrides
#region file
/// <summary>
/// Handle to file stream.
/// </summary>
private FileStream _fs;
/// <summary>
/// Stream writer used to write to file.
/// </summary>
private StreamWriter _sw = null;
/// <summary>
/// Handle to file whose read-only attribute should be reset when we are done.
/// </summary>
private FileInfo _readOnlyFileInfo = null;
private void CreateFileStream()
{
if (_path == null)
{
throw new InvalidOperationException(CsvCommandStrings.FileNameIsAMandatoryParameter);
}
string resolvedFilePath = PathUtils.ResolveFilePath(this.Path, this, _isLiteralPath);
bool isCsvFileEmpty = true;
if (this.Append && File.Exists(resolvedFilePath))
{
using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, Encoding, _isLiteralPath))
{
isCsvFileEmpty = streamReader.Peek() == -1 ? true : false;
}
}
// If the csv file is empty then even append is treated as regular export (i.e., both header & values are added to the CSV file).
_isActuallyAppending = this.Append && File.Exists(resolvedFilePath) && !isCsvFileEmpty;
if (_isActuallyAppending)
{
Encoding encodingObject;
using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, Encoding, _isLiteralPath))
{
ImportCsvHelper readingHelper = new ImportCsvHelper(
this, this.Delimiter, null /* header */, null /* typeName */, streamReader);
readingHelper.ReadHeader();
_preexistingPropertyNames = readingHelper.Header;
encodingObject = streamReader.CurrentEncoding;
}
PathUtils.MasterStreamOpen(
this,
this.Path,
encodingObject,
defaultEncoding: false,
Append,
Force,
NoClobber,
out _fs,
out _sw,
out _readOnlyFileInfo,
_isLiteralPath);
}
else
{
PathUtils.MasterStreamOpen(
this,
this.Path,
Encoding,
defaultEncoding: false,
Append,
Force,
NoClobber,
out _fs,
out _sw,
out _readOnlyFileInfo,
_isLiteralPath);
}
}
private void CleanUp()
{
if (_fs != null)
{
if (_sw != null)
{
_sw.Flush();
_sw.Dispose();
_sw = null;
}
_fs.Dispose();
_fs = null;
// reset the read-only attribute
if (_readOnlyFileInfo != null)
_readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly;
}
if (_helper != null)
{
_helper.Dispose();
}
}
private void ReconcilePreexistingPropertyNames()
{
if (!_isActuallyAppending)
{
throw new InvalidOperationException(CsvCommandStrings.ReconcilePreexistingPropertyNamesMethodShouldOnlyGetCalledWhenAppending);
}
if (_preexistingPropertyNames == null)
{
throw new InvalidOperationException(CsvCommandStrings.ReconcilePreexistingPropertyNamesMethodShouldOnlyGetCalledWhenPreexistingPropertyNamesHaveBeenReadSuccessfully);
}
HashSet<string> appendedPropertyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string appendedPropertyName in _propertyNames)
{
appendedPropertyNames.Add(appendedPropertyName);
}
foreach (string preexistingPropertyName in _preexistingPropertyNames)
{
if (!appendedPropertyNames.Contains(preexistingPropertyName))
{
if (!Force)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture, // property names and file names are culture invariant
CsvCommandStrings.CannotAppendCsvWithMismatchedPropertyNames,
preexistingPropertyName,
this.Path);
InvalidOperationException exception = new InvalidOperationException(errorMessage);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotAppendCsvWithMismatchedPropertyNames", ErrorCategory.InvalidData, preexistingPropertyName);
this.ThrowTerminatingError(errorRecord);
}
}
}
_propertyNames = _preexistingPropertyNames;
_preexistingPropertyNames = null;
}
/// <summary>
/// Write the csv line to file.
/// </summary>
/// <param name="line">Line to write.</param>
public override void WriteCsvLine(string line)
{
// NTRAID#Windows Out Of Band Releases-915851-2005/09/13
if (_disposed)
{
throw PSTraceSource.NewObjectDisposedException("ExportCsvCommand");
}
_sw.WriteLine(line);
}
#endregion file
#region IDisposable Members
/// <summary>
/// Set to true when object is disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// Public dispose method.
/// </summary>
public void Dispose()
{
if (_disposed == false)
{
CleanUp();
}
_disposed = true;
}
#endregion IDisposable Members
}
#endregion Export-CSV Command
#region Import-CSV Command
/// <summary>
/// Implements Import-Csv command.
/// </summary>
[Cmdlet(VerbsData.Import, "Csv", DefaultParameterSetName = "DelimiterPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113341")]
public sealed class ImportCsvCommand : PSCmdlet
{
#region Command Line Parameters
/// <summary>
/// Gets or sets property that sets delimiter.
/// </summary>
[Parameter(Position = 1, ParameterSetName = "DelimiterPath")]
[Parameter(Position = 1, ParameterSetName = "DelimiterLiteralPath")]
[ValidateNotNull]
public char Delimiter { get; set; }
/// <summary>
/// Gets or sets mandatory file name to read from.
/// </summary>
[Parameter(Position = 0, ParameterSetName = "DelimiterPath", Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[Parameter(Position = 0, ParameterSetName = "CulturePath", Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public string[] Path
{
get
{
return _paths;
}
set
{
_paths = value;
_specifiedPath = true;
}
}
private string[] _paths;
private bool _specifiedPath = false;
/// <summary>
/// Gets or sets the literal path of the mandatory file name to read from.
/// </summary>
[Parameter(ParameterSetName = "DelimiterLiteralPath", Mandatory = true, ValueFromPipelineByPropertyName = true)]
[Parameter(ParameterSetName = "CultureLiteralPath", Mandatory = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[Alias("PSPath", "LP")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LiteralPath
{
get
{
return _paths;
}
set
{
_paths = value;
_isLiteralPath = true;
}
}
private bool _isLiteralPath = false;
/// <summary>
/// Gets or sets property that sets UseCulture parameter.
/// </summary>
[Parameter(ParameterSetName = "CulturePath", Mandatory = true)]
[Parameter(ParameterSetName = "CultureLiteralPath", Mandatory = true)]
[ValidateNotNull]
public SwitchParameter UseCulture { get; set; }
///<summary>
/// Gets or sets header property to customize the names.
///</summary>
[Parameter(Mandatory = false)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Header { get; set; }
/// <summary>
/// Gets or sets encoding optional flag.
/// </summary>
[Parameter]
[ArgumentToEncodingTransformationAttribute]
[ArgumentEncodingCompletionsAttribute]
[ValidateNotNullOrEmpty]
public Encoding Encoding { get; set; } = ClrFacade.GetDefaultEncoding();
/// <summary>
/// Avoid writing out duplicate warning messages when there are one or more unspecified names.
/// </summary>
private bool _alreadyWarnedUnspecifiedNames = false;
#endregion Command Line Parameters
#region Override Methods
/// <summary>
/// BeginProcessing override.
/// </summary>
protected override void BeginProcessing()
{
Delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, Delimiter, UseCulture);
}
/// <summary>
/// ProcessRecord overload.
/// </summary>
protected override void ProcessRecord()
{
// Validate that they don't provide both Path and LiteralPath, but have provided at least one.
if (!(_specifiedPath ^ _isLiteralPath))
{
InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath);
ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null);
this.ThrowTerminatingError(errorRecord);
}
if (_paths != null)
{
foreach (string path in _paths)
{
using (StreamReader streamReader = PathUtils.OpenStreamReader(this, path, this.Encoding, _isLiteralPath))
{
ImportCsvHelper helper = new ImportCsvHelper(this, Delimiter, Header, null /* typeName */, streamReader);
try
{
helper.Import(ref _alreadyWarnedUnspecifiedNames);
}
catch (ExtendedTypeSystemException exception)
{
ErrorRecord errorRecord = new ErrorRecord(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null);
this.ThrowTerminatingError(errorRecord);
}
}
}
}
}
}
#endregion Override Methods
#endregion Import-CSV Command
#region ConvertTo-CSV Command
/// <summary>
/// Implements ConvertTo-Csv command.
/// </summary>
[Cmdlet(VerbsData.ConvertTo, "Csv", DefaultParameterSetName = "DelimiterPath",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135203", RemotingCapability = RemotingCapability.None)]
[OutputType(typeof(string))]
public sealed class ConvertToCsvCommand : BaseCsvWritingCommand
{
#region Parameter
/// <summary>
/// Overrides Base InputObject.
/// </summary>
[Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)]
public override PSObject InputObject { get; set; }
#endregion Parameter
#region Overrides
/// <summary>
/// Stores Property Names.
/// </summary>
private IList<string> _propertyNames;
/// <summary>
/// </summary>
private ExportCsvHelper _helper;
/// <summary>
/// BeginProcessing override.
/// </summary>
protected override void BeginProcessing()
{
base.BeginProcessing();
_helper = new ExportCsvHelper(this, base.Delimiter);
}
/// <summary>
/// Convert the current input object to Csv and write to stream/WriteObject.
/// </summary>
protected override void ProcessRecord()
{
if (InputObject == null)
{
return;
}
// Process first object
if (_propertyNames == null)
{
_propertyNames = ExportCsvHelper.BuildPropertyNames(InputObject, _propertyNames);
if (NoTypeInformation == false)
{
WriteCsvLine(ExportCsvHelper.GetTypeString(InputObject));
}
// Write property information
string properties = _helper.ConvertPropertyNamesCSV(_propertyNames);
if (!properties.Equals(string.Empty))
WriteCsvLine(properties);
}
string csv = _helper.ConvertPSObjectToCSV(InputObject, _propertyNames);
// write to the console
if (csv != string.Empty)
WriteCsvLine(csv);
}
#endregion Overrides
#region CSV conversion
/// <summary>
/// Write the line to output.
/// </summary>
/// <param name="line">Line to write.</param>
public override void WriteCsvLine(string line)
{
WriteObject(line);
}
#endregion CSV conversion
}
#endregion ConvertTo-CSV Command
#region ConvertFrom-CSV Command
/// <summary>
/// Implements ConvertFrom-Csv command.
/// </summary>
[Cmdlet(VerbsData.ConvertFrom, "Csv", DefaultParameterSetName = "DelimiterPath",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135201", RemotingCapability = RemotingCapability.None)]
public sealed class ConvertFromCsvCommand : PSCmdlet
{
#region Command Line Parameters
/// <summary>
/// Property that sets delimiter.
/// </summary>
[Parameter(Position = 1, ParameterSetName = "DelimiterPath")]
[ValidateNotNull]
[ValidateNotNullOrEmpty]
public char Delimiter { get; set; }
///<summary>
///Culture switch for csv conversion
///</summary>
[Parameter(ParameterSetName = "CulturePath", Mandatory = true)]
[Parameter(ParameterSetName = "CultureLiteralPath", Mandatory = true)]
[ValidateNotNull]
[ValidateNotNullOrEmpty]
public SwitchParameter UseCulture { get; set; }
/// <summary>
/// Gets or sets input object which is written in Csv format.
/// </summary>
[Parameter(ValueFromPipeline = true, Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)]
[ValidateNotNull]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public PSObject[] InputObject { get; set; }
///<summary>
/// Gets or sets header property to customize the names.
///</summary>
[Parameter(Mandatory = false)]
[ValidateNotNull]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Header { get; set; }
/// <summary>
/// Avoid writing out duplicate warning messages when there are one or more unspecified names.
/// </summary>
private bool _alreadyWarnedUnspecifiedNames = false;
#endregion Command Line Parameters
#region Overrides
/// <summary>
/// BeginProcessing override.
/// </summary>
protected override void BeginProcessing()
{
Delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, Delimiter, UseCulture);
}
/// <summary>
/// Convert the current input object to Csv and write to stream/WriteObject.
/// </summary>
protected override void ProcessRecord()
{
foreach (PSObject inputObject in InputObject)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(inputObject.ToString())))
using (StreamReader streamReader = new StreamReader(memoryStream, System.Text.Encoding.Unicode))
{
ImportCsvHelper helper = new ImportCsvHelper(this, Delimiter, Header, _typeName, streamReader);
try
{
helper.Import(ref _alreadyWarnedUnspecifiedNames);
}
catch (ExtendedTypeSystemException exception)
{
ErrorRecord errorRecord = new ErrorRecord(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null);
this.ThrowTerminatingError(errorRecord);
}
if ((Header == null) && (helper.Header != null))
{
Header = helper.Header.ToArray();
}
if ((_typeName == null) && (helper.TypeName != null))
{
_typeName = helper.TypeName;
}
}
}
}
#endregion Overrides
private string _typeName;
}
#endregion ConvertFrom-CSV Command
#region CSV conversion
#region ExportHelperConversion
/// <summary>
/// Helper class for Export-Csvlper.
/// </summary>
internal class ExportCsvHelper : IDisposable
{
private PSCmdlet _cmdlet;
private char _delimiter;
/// <summary>
/// </summary>
/// <param name="cmdlet"></param>
/// <param name="delimiter"></param>
/// <exception cref="ArgumentNullException">Throw if cmdlet is null.</exception>
internal ExportCsvHelper(PSCmdlet cmdlet, char delimiter)
{
if (cmdlet == null)
{
throw new ArgumentNullException("cmdlet");
}
_cmdlet = cmdlet;
_delimiter = delimiter;
}
// Name of properties to be written in CSV format
/// <summary>
/// Get the name of properties from source PSObject and add them to _propertyNames.
/// </summary>
internal static IList<string> BuildPropertyNames(PSObject source, IList<string> propertyNames)
{
if (propertyNames != null)
{
throw new InvalidOperationException(CsvCommandStrings.BuildPropertyNamesMethodShouldBeCalledOnlyOncePerCmdletInstance);
}
// serialize only Extended and Adapted properties..
PSMemberInfoCollection<PSPropertyInfo> srcPropertiesToSearch =
new PSMemberInfoIntegratingCollection<PSPropertyInfo>(
source,
PSObject.GetPropertyCollection(PSMemberViewTypes.Extended | PSMemberViewTypes.Adapted));
propertyNames = new Collection<string>();
foreach (PSPropertyInfo prop in srcPropertiesToSearch)
{
propertyNames.Add(prop.Name);
}
return propertyNames;
}
/// <summary>
/// Converts PropertyNames in to a CSV string.
/// </summary>
/// <returns>Converted string.</returns>
internal string ConvertPropertyNamesCSV(IList<string> propertyNames)
{
if (propertyNames == null)
{
throw new ArgumentNullException("propertyNames");
}
StringBuilder dest = new StringBuilder();
bool first = true;
foreach (string propertyName in propertyNames)
{
if (first)
{
first = false;
}
else
{
// changed to delimiter
dest.Append(_delimiter);
}
EscapeAndAppendString(dest, propertyName);
}
return dest.ToString();
}
/// <summary>
/// Convert PSObject to CSV string.
/// </summary>
/// <param name="mshObject">PSObject to convert.</param>
/// <param name="propertyNames">Property names.</param>
/// <returns></returns>
internal string ConvertPSObjectToCSV(PSObject mshObject, IList<string> propertyNames)
{
if (propertyNames == null)
{
throw new ArgumentNullException("propertyNames");
}
StringBuilder dest = new StringBuilder();
bool first = true;
foreach (string propertyName in propertyNames)
{
if (first)
{
first = false;
}
else
{
dest.Append(_delimiter);
}
PSPropertyInfo property = mshObject.Properties[propertyName] as PSPropertyInfo;
string value = null;
// If property is not present, assume value is null
if (property != null)
{
value = GetToStringValueForProperty(property);
}
EscapeAndAppendString(dest, value);
}
return dest.ToString();
}
/// <summary>
/// Get value from property object.
/// </summary>
/// <param name="property"> Property to convert.</param>
/// <returns>ToString() value.</returns>
internal static string GetToStringValueForProperty(PSPropertyInfo property)
{
if (property == null)
{
throw new ArgumentNullException("property");
}
string value = null;
try
{
object temp = property.Value;
if (temp != null)
{
value = temp.ToString();
}
}
catch (Exception)
{
// If we cannot read some value, treat it as null.
}
return value;
}
/// <summary>
/// Prepares string for writing type information.
/// </summary>
/// <param name="source">PSObject whose type to determine.</param>
/// <returns>String with type information.</returns>
internal static string GetTypeString(PSObject source)
{
string type = null;
// get type of source
Collection<string> tnh = source.TypeNames;
if (tnh == null || tnh.Count == 0)
{
type = "#TYPE";
}
else
{
if (tnh[0] == null)
{
throw new InvalidOperationException(CsvCommandStrings.TypeHierarchyShouldNotHaveNullValues);
}
string temp = tnh[0];
// If type starts with CSV: remove it. This would happen when you export
// an imported object. import-csv adds CSV. prefix to the type.
if (temp.StartsWith(ImportExportCSVHelper.CSVTypePrefix, StringComparison.OrdinalIgnoreCase))
{
temp = temp.Substring(4);
}
type = string.Format(System.Globalization.CultureInfo.InvariantCulture, "#TYPE {0}", temp);
}
return type;
}
/// <summary>
/// Escapes the " in string if necessary.
/// Encloses the string in double quotes if necessary.
/// </summary>
internal static void EscapeAndAppendString(StringBuilder dest, string source)
{
if (source == null)
{
return;
}
// Adding Double quote to all strings
dest.Append('"');
for (int i = 0; i < source.Length; i++)
{
char c = source[i];
// Double quote in the string is escaped with double quote
if (c == '"')
{
dest.Append('"');
}
dest.Append(c);
}
dest.Append('"');
}
#region IDisposable Members
/// <summary>
/// Set to true when object is disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// Public dispose method.
/// </summary>
public void Dispose()
{
if (_disposed == false)
{
GC.SuppressFinalize(this);
}
_disposed = true;
}
#endregion IDisposable Members
}
#endregion ExportHelperConversion
#region ImportHelperConversion
/// <summary>
/// Helper class to import single CSV file.
/// </summary>
internal class ImportCsvHelper
{
#region constructor
/// <summary>
/// Reference to cmdlet which is using this helper class.
/// </summary>
private readonly PSCmdlet _cmdlet;
/// <summary>
/// CSV delimiter (default is the "comma" / "," character).
/// </summary>
private readonly char _delimiter;
/// <summary>
/// Use "UnspecifiedName" when the name is null or empty.
/// </summary>
private const string UnspecifiedName = "H";
/// <summary>
/// Avoid writing out duplicate warning messages when there are one or more unspecified names.
/// </summary>
private bool _alreadyWarnedUnspecifiedName = false;
/// <summary>
/// Gets reference to header values.
/// </summary>
internal IList<string> Header { get; private set; }
/// <summary>
/// Gets ETS type name from the first line / comment in the CSV.
/// </summary>
internal string TypeName { get; private set; }
/// <summary>
/// Reader of the csv content.
/// </summary>
private readonly StreamReader _sr;
// Initial sizes of the value list and the line stringbuilder.
// Set to reasonable initial sizes. They may grow beyond these,
// but this will prevent a few reallocations.
private const int ValueCountGuestimate = 16;
private const int LineLengthGuestimate = 256;
internal ImportCsvHelper(PSCmdlet cmdlet, char delimiter, IList<string> header, string typeName, StreamReader streamReader)
{
if (cmdlet == null)
{
throw new ArgumentNullException("cmdlet");
}
if (streamReader == null)
{
throw new ArgumentNullException("streamReader");
}
_cmdlet = cmdlet;
_delimiter = delimiter;
Header = header;
TypeName = typeName;
_sr = streamReader;
}
#endregion constructor
#region reading helpers
/// <summary>
/// This is set to true when end of file is reached.
/// </summary>
private bool EOF => _sr.EndOfStream;
private char ReadChar()
{
if (EOF)
{
throw new InvalidOperationException(CsvCommandStrings.EOFIsReached);
}
int i = _sr.Read();
return (char)i;
}
/// <summary>
/// Peeks the next character in the stream and returns true if it is same as passed in character.
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
private bool PeekNextChar(char c)
{
int i = _sr.Peek();
if (i == -1)
{
return false;
}
return c == (char)i;
}
/// <summary>
/// Reads a line from file. This consumes the end of line.
/// Only use it when end of line chars are not important.
/// </summary>
/// <returns>Line from file.</returns>
private string ReadLine() => _sr.ReadLine();
#endregion reading helpers
internal void ReadHeader()
{
// Read #Type record if available
if ((TypeName == null) && (!this.EOF))
{
TypeName = ReadTypeInformation();
}
var values = new List<string>(ValueCountGuestimate);
var builder = new StringBuilder(LineLengthGuestimate);
while ((Header == null) && (!this.EOF))
{
ParseNextRecord(values, builder);
// Trim all trailing blankspaces and delimiters ( single/multiple ).
// If there is only one element in the row and if its a blankspace we dont trim it.
// A trailing delimiter is represented as a blankspace while being added to result collection
// which is getting trimmed along with blankspaces supplied through the CSV in the below loop.
while (values.Count > 1 && values[values.Count - 1].Equals(string.Empty))
{
values.RemoveAt(values.Count - 1);
}
// File starts with '#' and contains '#Fields:' is W3C Extended Log File Format
if (values.Count != 0 && values[0].StartsWith("#Fields: "))
{
values[0] = values[0].Substring(9);
Header = values;
}
else if (values.Count != 0 && values[0].StartsWith("#"))
{
// Skip all lines starting with '#'
}
else
{
// This is not W3C Extended Log File Format
// By default first line is Header
Header = values;
}
}
if (Header != null && Header.Count > 0)
{
ValidatePropertyNames(Header);
}
}
internal void Import(ref bool alreadyWriteOutWarning)
{
_alreadyWarnedUnspecifiedName = alreadyWriteOutWarning;
ReadHeader();
var prevalidated = false;
var values = new List<string>(ValueCountGuestimate);
var builder = new StringBuilder(LineLengthGuestimate);
while (true)
{
ParseNextRecord(values, builder);
if (values.Count == 0)
break;
if (values.Count == 1 && string.IsNullOrEmpty(values[0]))
{
// skip the blank lines
continue;
}
PSObject result = BuildMshobject(TypeName, Header, values, _delimiter, prevalidated);
prevalidated = true;
_cmdlet.WriteObject(result);
}
alreadyWriteOutWarning = _alreadyWarnedUnspecifiedName;
}
/// <summary>
/// Validate the names of properties.
/// </summary>
/// <param name="names"></param>
private static void ValidatePropertyNames(IList<string> names)
{
if (names != null)
{
if (names.Count == 0)
{
// If there are no names, it is an error
}
else
{
HashSet<string> headers = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string currentHeader in names)
{
if (!string.IsNullOrEmpty(currentHeader))
{
if (!headers.Contains(currentHeader))
{
headers.Add(currentHeader);
}
else
{
// throw a terminating error as there are duplicate headers in the input.
string memberAlreadyPresentMsg =
string.Format(
CultureInfo.InvariantCulture,
ExtendedTypeSystem.MemberAlreadyPresent,
currentHeader);
ExtendedTypeSystemException exception = new ExtendedTypeSystemException(memberAlreadyPresentMsg);
throw exception;
}
}
}
}
}
}
/// <summary>
/// Read the type information, if present.
/// </summary>
/// <returns>Type string if present else null.</returns>
private string ReadTypeInformation()
{
string type = null;
if (PeekNextChar('#'))
{
string temp = ReadLine();
if (temp.StartsWith("#Type", StringComparison.OrdinalIgnoreCase))
{
type = temp.Substring(5);
type = type.Trim();
if (type.Length == 0)
{
type = null;
}
}
}
return type;
}
/// <summary>
/// Reads the next record from the file and returns parsed collection of string.
/// </summary>
/// <returns>
/// Parsed collection of strings.
/// </returns>
private void ParseNextRecord(List<string> result, StringBuilder current)
{
result.Clear();
// current string
current.Clear();
bool seenBeginQuote = false;
while (!EOF)
{
// Read the next character
char ch = ReadChar();
if (ch == _delimiter)
{
if (seenBeginQuote)
{
// Delimiter inside double quotes is part of string.
// Ex:
// "foo, bar"
// is parsed as
// ->foo, bar<-
current.Append(ch);
}
else
{
// Delimiter outside quotes is end of current word.
result.Add(current.ToString());
current.Remove(0, current.Length);
}
}
else if (ch == '"')
{
if (seenBeginQuote)
{
if (PeekNextChar('"'))
{
// "" inside double quote are single quote
// ex: "foo""bar"
// is read as
// ->foo"bar<-
// PeekNextChar only peeks. Read the next char.
ReadChar();
current.Append('"');
}
else
{
// We have seen a matching end quote.
seenBeginQuote = false;
// Read
// everything till we hit next delimiter.
// In correct CSV,1) end quote is followed by delimiter
// 2)end quote is followed some whitespaces and
// then delimiter.
// We eat the whitespaces seen after the ending quote.
// However if there are other characters, we add all of them
// to string.
// Ex: ->"foo bar"<- is read as ->foo bar<-
// ->"foo bar" <- is read as ->foo bar<-
// ->"foo bar" ab <- is read as ->"foo bar" ab <-
bool endofRecord = false;
ReadTillNextDelimiter(current, ref endofRecord, true);
result.Add(current.ToString());
current.Remove(0, current.Length);
if (endofRecord)
break;
}
}
else if (current.Length == 0)
{
// We are at the beginning of a new word.
// This quote is the first quote.
seenBeginQuote = true;
}
else
{
// We are seeing a quote after the start of
// the word. This is error, however we will be
// lenient here and do what excel does:
// Ex: foo "ba,r"
// In above example word read is ->foo "ba<-
// Basically we read till next delimiter
bool endOfRecord = false;
current.Append(ch);
ReadTillNextDelimiter(current, ref endOfRecord, false);
result.Add(current.ToString());
current.Remove(0, current.Length);
if (endOfRecord)
break;
}
}
else if (ch == ' ' || ch == '\t')
{
if (seenBeginQuote)
{
// Spaces in side quote are valid
current.Append(ch);
}
else if (current.Length == 0)
{
// ignore leading spaces
continue;
}
else
{
// We are not in quote and we are not at the
// beginning of a word. We should not be seeing
// spaces here. This is an error condition, however
// we will be lenient here and do what excel does,
// that is read till next delimiter.
// Ex: ->foo <- is read as ->foo<-
// Ex: ->foo bar<- is read as ->foo bar<-
// Ex: ->foo bar <- is read as ->foo bar <-
// Ex: ->foo bar "er,ror"<- is read as ->foo bar "er<-
bool endOfRecord = false;
current.Append(ch);
ReadTillNextDelimiter(current, ref endOfRecord, true);
result.Add(current.ToString());
current.Remove(0, current.Length);
if (endOfRecord)
{
break;
}
}
}
else if (IsNewLine(ch, out string newLine))
{
if (seenBeginQuote)
{
// newline inside quote are valid
current.Append(newLine);
}
else
{
result.Add(current.ToString());
current.Remove(0, current.Length);
// New line outside quote is end of word and end of record
break;
}
}
else
{
current.Append(ch);
}
}
if (current.Length != 0)
{
result.Add(current.ToString());
}
}
// If we detect a newline we return it as a string "\r", "\n" or "\r\n"
private bool IsNewLine(char ch, out string newLine)
{
newLine = string.Empty;
if (ch == '\r')
{
if (PeekNextChar('\n'))
{
ReadChar();
newLine = "\r\n";
}
else
{
newLine = "\r";
}
}
else if (ch == '\n')
{
newLine = "\n";
}
return newLine != string.Empty;
}
/// <summary>
/// This function reads the characters till next delimiter and adds them to current.
/// </summary>
/// <param name="current"></param>
/// <param name="endOfRecord">
/// This is true if end of record is reached
/// when delimiter is hit. This would be true if delimiter is NewLine.
/// </param>
/// <param name="eatTrailingBlanks">
/// If this is true, eat the trailing blanks. Note:if there are non
/// whitespace characters present, then trailing blanks are not consumed.
/// </param>
private void ReadTillNextDelimiter(StringBuilder current, ref bool endOfRecord, bool eatTrailingBlanks)
{
StringBuilder temp = new StringBuilder();
// Did we see any non-whitespace character
bool nonWhiteSpace = false;
while (true)
{
if (EOF)
{
endOfRecord = true;
break;
}
char ch = ReadChar();
if (ch == _delimiter)
{
break;
}
else if (IsNewLine(ch, out string newLine))
{
endOfRecord = true;
break;
}
else
{
temp.Append(ch);
if (ch != ' ' && ch != '\t')
{
nonWhiteSpace = true;
}
}
}
if (eatTrailingBlanks && !nonWhiteSpace)
{
string s = temp.ToString();
s = s.Trim();
current.Append(s);
}
else
{
current.Append(temp);
}
}
private PSObject BuildMshobject(string type, IList<string> names, List<string> values, char delimiter, bool preValidated = false)
{
PSObject result = new PSObject(names.Count);
char delimiterlocal = delimiter;
int unspecifiedNameIndex = 1;
for (int i = 0; i <= names.Count - 1; i++)
{
string name = names[i];
string value = null;
// if name is null and delimiter is '"', use a default property name 'UnspecifiedName'
if (name.Length == 0 && delimiterlocal == '"')
{
name = UnspecifiedName + unspecifiedNameIndex;
unspecifiedNameIndex++;
}
// if name is null and delimiter is not '"', use a default property name 'UnspecifiedName'
if (string.IsNullOrEmpty(name))
{
name = UnspecifiedName + unspecifiedNameIndex;
unspecifiedNameIndex++;
}
// If no value was present in CSV file, we write null.
if (i < values.Count)
{
value = values[i];
}
result.Properties.Add(new PSNoteProperty(name, value), preValidated);
}
if (!_alreadyWarnedUnspecifiedName && unspecifiedNameIndex != 1)
{
_cmdlet.WriteWarning(CsvCommandStrings.UseDefaultNameForUnspecifiedHeader);
_alreadyWarnedUnspecifiedName = true;
}
if (!string.IsNullOrEmpty(type))
{
result.TypeNames.Clear();
result.TypeNames.Add(type);
result.TypeNames.Add(ImportExportCSVHelper.CSVTypePrefix + type);
}
return result;
}
}
#endregion ImportHelperConversion
#region ExportImport Helper
/// <summary>
/// Helper class for CSV conversion.
/// </summary>
internal static class ImportExportCSVHelper
{
internal const char CSVDelimiter = ',';
internal const string CSVTypePrefix = "CSV:";
internal static char SetDelimiter(PSCmdlet cmdlet, string parameterSetName, char explicitDelimiter, bool useCulture)
{
char delimiter = explicitDelimiter;
switch (parameterSetName)
{
case "Delimiter":
case "DelimiterPath":
case "DelimiterLiteralPath":
// if delimiter is not given, it should take , as value
if (explicitDelimiter == '\0')
{
delimiter = ImportExportCSVHelper.CSVDelimiter;
}
break;
case "UseCulture":
case "CulturePath":
case "CultureLiteralPath":
if (useCulture == true)
{
// ListSeparator is apparently always a character even though the property returns a string, checked via:
// [CultureInfo]::GetCultures("AllCultures") | % { ([CultureInfo]($_.Name)).TextInfo.ListSeparator } | ? Length -ne 1
delimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator[0];
}
break;
default:
{
delimiter = ImportExportCSVHelper.CSVDelimiter;
}
break;
}
return delimiter;
}
}
#endregion ExportImport Helper
#endregion CSV conversion
}
| |
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Android;
using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android.Views;
using Android.Widget;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using Google.Android.Material.Snackbar;
using System;
using System.Linq;
namespace ArcGISRuntime.Samples.DisplayDeviceLocation
{
[Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Display device location with autopan modes",
category: "Location",
description: "Display your current position on the map, as well as switch between different types of auto pan Modes.",
instructions: "Select an autopan mode, then use the buttons to start and stop location display.",
tags: new[] { "GPS", "compass", "location", "map", "mobile", "navigation" })]
public class DisplayDeviceLocation : Activity, ActivityCompat.IOnRequestPermissionsResultCallback
{
// Constant for tracking permission request.
private const int LocationPermissionRequestCode = 99;
// Create and hold reference to the used MapView
private MapView _myMapView;
// String array to store the different device location options.
private readonly string[] _navigationTypes =
{
"On",
"Re-Center",
"Navigation",
"Compass"
};
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "Display device location";
CreateLayout();
Initialize();
}
private void Initialize()
{
// Create new Map with basemap
Map myMap = new Map(BasemapStyle.ArcGISImageryStandard);
// Provide used Map to the MapView
_myMapView.Map = myMap;
}
private void OnStopButtonClicked(object sender, EventArgs e) => _myMapView.LocationDisplay.IsEnabled = false;
private void OnStartButtonClicked(object sender, EventArgs e)
{
Button startButton = (Button)sender;
// Create menu to show navigation options
PopupMenu navigationMenu = new PopupMenu(this, startButton);
navigationMenu.MenuItemClick += OnNavigationMenuItemClicked;
// Create menu options
foreach (string navigationType in _navigationTypes)
{
navigationMenu.Menu.Add(navigationType);
}
// Show menu in the view
navigationMenu.Show();
}
private void OnNavigationMenuItemClicked(object sender, PopupMenu.MenuItemClickEventArgs e)
{
// Reset navigation display.
_myMapView.LocationDisplay.IsEnabled = false;
// Get title from the selected item
string selectedNavigationType = e.Item.TitleCondensedFormatted.ToString();
// Get index that is used to get the selected url
int selectedIndex = _navigationTypes.ToList().IndexOf(selectedNavigationType);
// Set location display automatic panning mode.
switch (selectedIndex)
{
case 0:
_myMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Off;
break;
case 1:
_myMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Recenter;
break;
case 2:
_myMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Navigation;
break;
case 3:
_myMapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.CompassNavigation;
break;
}
// Ask for location and enable location display when permission is granted.
AskForLocationPermission();
}
private async void AskForLocationPermission()
{
// Only check if permission hasn't been granted yet.
if (ContextCompat.CheckSelfPermission(this, LocationService) != Permission.Granted)
{
// The Fine location permission will be requested.
var requiredPermissions = new[] { Manifest.Permission.AccessFineLocation, Manifest.Permission.AccessCoarseLocation };
// Only prompt the user first if the system says to.
if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessFineLocation) || ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AccessCoarseLocation))
{
// A snackbar is a small notice that shows on the bottom of the view.
Snackbar.Make(_myMapView,
"Location permission is needed to display location on the map.",
Snackbar.LengthIndefinite)
.SetAction("OK",
delegate
{
// When the user presses 'OK', the system will show the standard permission dialog.
// Once the user has accepted or denied, OnRequestPermissionsResult is called with the result.
ActivityCompat.RequestPermissions(this, requiredPermissions, LocationPermissionRequestCode);
}
).Show();
}
else
{
// When the user presses 'OK', the system will show the standard permission dialog.
// Once the user has accepted or denied, OnRequestPermissionsResult is called with the result.
this.RequestPermissions(requiredPermissions, LocationPermissionRequestCode);
}
}
else
{
try
{
// Explicit DataSource.LoadAsync call is used to surface any errors that may arise.
await _myMapView.LocationDisplay.DataSource.StartAsync();
_myMapView.LocationDisplay.IsEnabled = true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
ShowMessage(ex.Message, "Failed to start location display.");
}
}
}
public override async void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
// Ignore other location requests.
if (requestCode != LocationPermissionRequestCode)
{
return;
}
// If the permissions were granted, enable location.
if (grantResults.Length == 2 && (grantResults[0] == Permission.Granted || grantResults[1] == Permission.Granted))
{
System.Diagnostics.Debug.WriteLine("User affirmatively gave permission to use location. Enabling location.");
try
{
// Explicit DataSource.LoadAsync call is used to surface any errors that may arise.
await _myMapView.LocationDisplay.DataSource.StartAsync();
_myMapView.LocationDisplay.IsEnabled = true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
ShowMessage(ex.Message, "Failed to start location display.");
}
}
else
{
ShowMessage("Location permissions not granted.", "Failed to start location display.");
}
}
private void ShowMessage(string message, string title = "Error") => new AlertDialog.Builder(this).SetTitle(title).SetMessage(message).Show();
private void CreateLayout()
{
// Create a new vertical layout for the app.
LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical };
// Create button to show possible navigation options.
Button startButton = new Button(this)
{
Text = "Start"
};
startButton.Click += OnStartButtonClicked;
// Create button to stop navigation.
Button stopButton = new Button(this)
{
Text = "Stop"
};
stopButton.Click += OnStopButtonClicked;
// Add start button to the layout.
layout.AddView(startButton);
// Add stop button to the layout.
layout.AddView(stopButton);
// Add the map view to the layout.
_myMapView = new MapView(this);
layout.AddView(_myMapView);
// Show the layout in the app.
SetContentView(layout);
}
protected override void OnDestroy()
{
// Stop the location data source.
_myMapView?.LocationDisplay?.DataSource?.StopAsync();
base.OnDestroy();
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
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;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// IntegrationLog
/// </summary>
[DataContract]
public partial class IntegrationLog : IEquatable<IntegrationLog>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="IntegrationLog" /> class.
/// </summary>
/// <param name="action">action.</param>
/// <param name="direction">direction.</param>
/// <param name="email">email.</param>
/// <param name="files">files.</param>
/// <param name="integrationLogOid">integrationLogOid.</param>
/// <param name="itemId">itemId.</param>
/// <param name="itemIpnOid">itemIpnOid.</param>
/// <param name="logDts">Date/time the integration log was created.</param>
/// <param name="logType">logType.</param>
/// <param name="loggerId">loggerId.</param>
/// <param name="loggerName">loggerName.</param>
/// <param name="logs">logs.</param>
/// <param name="omitLogMap">omitLogMap.</param>
/// <param name="orderIds">orderIds.</param>
/// <param name="pk">pk.</param>
/// <param name="sk">sk.</param>
/// <param name="status">status.</param>
/// <param name="statusCode">statusCode.</param>
public IntegrationLog(string action = default(string), string direction = default(string), string email = default(string), List<IntegrationLogFile> files = default(List<IntegrationLogFile>), int? integrationLogOid = default(int?), string itemId = default(string), int? itemIpnOid = default(int?), string logDts = default(string), string logType = default(string), string loggerId = default(string), string loggerName = default(string), List<IntegrationLogLog> logs = default(List<IntegrationLogLog>), bool? omitLogMap = default(bool?), List<string> orderIds = default(List<string>), string pk = default(string), string sk = default(string), string status = default(string), int? statusCode = default(int?))
{
this.Action = action;
this.Direction = direction;
this.Email = email;
this.Files = files;
this.IntegrationLogOid = integrationLogOid;
this.ItemId = itemId;
this.ItemIpnOid = itemIpnOid;
this.LogDts = logDts;
this.LogType = logType;
this.LoggerId = loggerId;
this.LoggerName = loggerName;
this.Logs = logs;
this.OmitLogMap = omitLogMap;
this.OrderIds = orderIds;
this.Pk = pk;
this.Sk = sk;
this.Status = status;
this.StatusCode = statusCode;
}
/// <summary>
/// Gets or Sets Action
/// </summary>
[DataMember(Name="action", EmitDefaultValue=false)]
public string Action { get; set; }
/// <summary>
/// Gets or Sets Direction
/// </summary>
[DataMember(Name="direction", EmitDefaultValue=false)]
public string Direction { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; }
/// <summary>
/// Gets or Sets Files
/// </summary>
[DataMember(Name="files", EmitDefaultValue=false)]
public List<IntegrationLogFile> Files { get; set; }
/// <summary>
/// Gets or Sets IntegrationLogOid
/// </summary>
[DataMember(Name="integration_log_oid", EmitDefaultValue=false)]
public int? IntegrationLogOid { get; set; }
/// <summary>
/// Gets or Sets ItemId
/// </summary>
[DataMember(Name="item_id", EmitDefaultValue=false)]
public string ItemId { get; set; }
/// <summary>
/// Gets or Sets ItemIpnOid
/// </summary>
[DataMember(Name="item_ipn_oid", EmitDefaultValue=false)]
public int? ItemIpnOid { get; set; }
/// <summary>
/// Date/time the integration log was created
/// </summary>
/// <value>Date/time the integration log was created</value>
[DataMember(Name="log_dts", EmitDefaultValue=false)]
public string LogDts { get; set; }
/// <summary>
/// Gets or Sets LogType
/// </summary>
[DataMember(Name="log_type", EmitDefaultValue=false)]
public string LogType { get; set; }
/// <summary>
/// Gets or Sets LoggerId
/// </summary>
[DataMember(Name="logger_id", EmitDefaultValue=false)]
public string LoggerId { get; set; }
/// <summary>
/// Gets or Sets LoggerName
/// </summary>
[DataMember(Name="logger_name", EmitDefaultValue=false)]
public string LoggerName { get; set; }
/// <summary>
/// Gets or Sets Logs
/// </summary>
[DataMember(Name="logs", EmitDefaultValue=false)]
public List<IntegrationLogLog> Logs { get; set; }
/// <summary>
/// Gets or Sets OmitLogMap
/// </summary>
[DataMember(Name="omit_log_map", EmitDefaultValue=false)]
public bool? OmitLogMap { get; set; }
/// <summary>
/// Gets or Sets OrderIds
/// </summary>
[DataMember(Name="order_ids", EmitDefaultValue=false)]
public List<string> OrderIds { get; set; }
/// <summary>
/// Gets or Sets Pk
/// </summary>
[DataMember(Name="pk", EmitDefaultValue=false)]
public string Pk { get; set; }
/// <summary>
/// Gets or Sets Sk
/// </summary>
[DataMember(Name="sk", EmitDefaultValue=false)]
public string Sk { get; set; }
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets StatusCode
/// </summary>
[DataMember(Name="status_code", EmitDefaultValue=false)]
public int? StatusCode { 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 IntegrationLog {\n");
sb.Append(" Action: ").Append(Action).Append("\n");
sb.Append(" Direction: ").Append(Direction).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" Files: ").Append(Files).Append("\n");
sb.Append(" IntegrationLogOid: ").Append(IntegrationLogOid).Append("\n");
sb.Append(" ItemId: ").Append(ItemId).Append("\n");
sb.Append(" ItemIpnOid: ").Append(ItemIpnOid).Append("\n");
sb.Append(" LogDts: ").Append(LogDts).Append("\n");
sb.Append(" LogType: ").Append(LogType).Append("\n");
sb.Append(" LoggerId: ").Append(LoggerId).Append("\n");
sb.Append(" LoggerName: ").Append(LoggerName).Append("\n");
sb.Append(" Logs: ").Append(Logs).Append("\n");
sb.Append(" OmitLogMap: ").Append(OmitLogMap).Append("\n");
sb.Append(" OrderIds: ").Append(OrderIds).Append("\n");
sb.Append(" Pk: ").Append(Pk).Append("\n");
sb.Append(" Sk: ").Append(Sk).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" StatusCode: ").Append(StatusCode).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 virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as IntegrationLog);
}
/// <summary>
/// Returns true if IntegrationLog instances are equal
/// </summary>
/// <param name="input">Instance of IntegrationLog to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(IntegrationLog input)
{
if (input == null)
return false;
return
(
this.Action == input.Action ||
(this.Action != null &&
this.Action.Equals(input.Action))
) &&
(
this.Direction == input.Direction ||
(this.Direction != null &&
this.Direction.Equals(input.Direction))
) &&
(
this.Email == input.Email ||
(this.Email != null &&
this.Email.Equals(input.Email))
) &&
(
this.Files == input.Files ||
this.Files != null &&
this.Files.SequenceEqual(input.Files)
) &&
(
this.IntegrationLogOid == input.IntegrationLogOid ||
(this.IntegrationLogOid != null &&
this.IntegrationLogOid.Equals(input.IntegrationLogOid))
) &&
(
this.ItemId == input.ItemId ||
(this.ItemId != null &&
this.ItemId.Equals(input.ItemId))
) &&
(
this.ItemIpnOid == input.ItemIpnOid ||
(this.ItemIpnOid != null &&
this.ItemIpnOid.Equals(input.ItemIpnOid))
) &&
(
this.LogDts == input.LogDts ||
(this.LogDts != null &&
this.LogDts.Equals(input.LogDts))
) &&
(
this.LogType == input.LogType ||
(this.LogType != null &&
this.LogType.Equals(input.LogType))
) &&
(
this.LoggerId == input.LoggerId ||
(this.LoggerId != null &&
this.LoggerId.Equals(input.LoggerId))
) &&
(
this.LoggerName == input.LoggerName ||
(this.LoggerName != null &&
this.LoggerName.Equals(input.LoggerName))
) &&
(
this.Logs == input.Logs ||
this.Logs != null &&
this.Logs.SequenceEqual(input.Logs)
) &&
(
this.OmitLogMap == input.OmitLogMap ||
(this.OmitLogMap != null &&
this.OmitLogMap.Equals(input.OmitLogMap))
) &&
(
this.OrderIds == input.OrderIds ||
this.OrderIds != null &&
this.OrderIds.SequenceEqual(input.OrderIds)
) &&
(
this.Pk == input.Pk ||
(this.Pk != null &&
this.Pk.Equals(input.Pk))
) &&
(
this.Sk == input.Sk ||
(this.Sk != null &&
this.Sk.Equals(input.Sk))
) &&
(
this.Status == input.Status ||
(this.Status != null &&
this.Status.Equals(input.Status))
) &&
(
this.StatusCode == input.StatusCode ||
(this.StatusCode != null &&
this.StatusCode.Equals(input.StatusCode))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Action != null)
hashCode = hashCode * 59 + this.Action.GetHashCode();
if (this.Direction != null)
hashCode = hashCode * 59 + this.Direction.GetHashCode();
if (this.Email != null)
hashCode = hashCode * 59 + this.Email.GetHashCode();
if (this.Files != null)
hashCode = hashCode * 59 + this.Files.GetHashCode();
if (this.IntegrationLogOid != null)
hashCode = hashCode * 59 + this.IntegrationLogOid.GetHashCode();
if (this.ItemId != null)
hashCode = hashCode * 59 + this.ItemId.GetHashCode();
if (this.ItemIpnOid != null)
hashCode = hashCode * 59 + this.ItemIpnOid.GetHashCode();
if (this.LogDts != null)
hashCode = hashCode * 59 + this.LogDts.GetHashCode();
if (this.LogType != null)
hashCode = hashCode * 59 + this.LogType.GetHashCode();
if (this.LoggerId != null)
hashCode = hashCode * 59 + this.LoggerId.GetHashCode();
if (this.LoggerName != null)
hashCode = hashCode * 59 + this.LoggerName.GetHashCode();
if (this.Logs != null)
hashCode = hashCode * 59 + this.Logs.GetHashCode();
if (this.OmitLogMap != null)
hashCode = hashCode * 59 + this.OmitLogMap.GetHashCode();
if (this.OrderIds != null)
hashCode = hashCode * 59 + this.OrderIds.GetHashCode();
if (this.Pk != null)
hashCode = hashCode * 59 + this.Pk.GetHashCode();
if (this.Sk != null)
hashCode = hashCode * 59 + this.Sk.GetHashCode();
if (this.Status != null)
hashCode = hashCode * 59 + this.Status.GetHashCode();
if (this.StatusCode != null)
hashCode = hashCode * 59 + this.StatusCode.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System.Collections.Generic;
namespace Lucene.Net.Util
{
/*
* 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.
*/
/// <summary>
/// Use by certain classes to match version compatibility
/// across releases of Lucene.
///
/// <p><b>WARNING</b>: When changing the version parameter
/// that you supply to components in Lucene, do not simply
/// change the version at search-time, but instead also adjust
/// your indexing code to match, and re-index.</p>
/// </summary>
public enum LuceneVersion
{
/// <summary>
/// Match settings and bugs in Lucene's 3.0 release. </summary>
/// @deprecated (4.0) Use latest
[System.Obsolete("(4.0) Use latest")]
LUCENE_30,
/// <summary>
/// Match settings and bugs in Lucene's 3.1 release. </summary>
/// @deprecated (4.0) Use latest
[System.Obsolete("(4.0) Use latest")]
LUCENE_31,
/// <summary>
/// Match settings and bugs in Lucene's 3.2 release. </summary>
/// @deprecated (4.0) Use latest
[System.Obsolete("(4.0) Use latest")]
LUCENE_32,
/// <summary>
/// Match settings and bugs in Lucene's 3.3 release. </summary>
/// @deprecated (4.0) Use latest
[System.Obsolete("(4.0) Use latest")]
LUCENE_33,
/// <summary>
/// Match settings and bugs in Lucene's 3.4 release. </summary>
/// @deprecated (4.0) Use latest
[System.Obsolete("(4.0) Use latest")]
LUCENE_34,
/// <summary>
/// Match settings and bugs in Lucene's 3.5 release. </summary>
/// @deprecated (4.0) Use latest
[System.Obsolete("(4.0) Use latest")]
LUCENE_35,
/// <summary>
/// Match settings and bugs in Lucene's 3.6 release. </summary>
/// @deprecated (4.0) Use latest
[System.Obsolete("(4.0) Use latest")]
LUCENE_36,
/// <summary>
/// Match settings and bugs in Lucene's 3.6 release. </summary>
/// @deprecated (4.1) Use latest
[System.Obsolete("(4.1) Use latest")]
LUCENE_40,
/// <summary>
/// Match settings and bugs in Lucene's 4.1 release. </summary>
/// @deprecated (4.2) Use latest
[System.Obsolete("(4.2) Use latest")]
LUCENE_41,
/// <summary>
/// Match settings and bugs in Lucene's 4.2 release. </summary>
/// @deprecated (4.3) Use latest
[System.Obsolete("(4.3) Use latest")]
LUCENE_42,
/// <summary>
/// Match settings and bugs in Lucene's 4.3 release. </summary>
/// @deprecated (4.4) Use latest
[System.Obsolete("(4.4) Use latest")]
LUCENE_43,
/// <summary>
/// Match settings and bugs in Lucene's 4.4 release. </summary>
/// @deprecated (4.5) Use latest
[System.Obsolete("(4.5) Use latest")]
LUCENE_44,
/// <summary>
/// Match settings and bugs in Lucene's 4.5 release. </summary>
/// @deprecated (4.6) Use latest
[System.Obsolete("(4.6) Use latest")]
LUCENE_45,
/// <summary>
/// Match settings and bugs in Lucene's 4.6 release. </summary>
/// @deprecated (4.7) Use latest
[System.Obsolete("(4.7) Use latest")]
LUCENE_46,
/// <summary>
/// Match settings and bugs in Lucene's 4.7 release. </summary>
/// @deprecated (4.8) Use latest
[System.Obsolete("(4.8) Use latest")]
LUCENE_47,
/// <summary>
/// Match settings and bugs in Lucene's 4.8 release.
/// <p>
/// Use this to get the latest & greatest settings, bug
/// fixes, etc, for Lucene.
/// </summary>
LUCENE_48,
/* Add new constants for later versions **here** to respect order! */
/// <summary>
/// <p><b>WARNING</b>: if you use this setting, and then
/// upgrade to a newer release of Lucene, sizable changes
/// may happen. If backwards compatibility is important
/// then you should instead explicitly specify an actual
/// version.
/// <p>
/// If you use this constant then you may need to
/// <b>re-index all of your documents</b> when upgrading
/// Lucene, as the way text is indexed may have changed.
/// Additionally, you may need to <b>re-test your entire
/// application</b> to ensure it behaves as expected, as
/// some defaults may have changed and may break functionality
/// in your application. </summary>
/// @deprecated Use an actual version instead.
[System.Obsolete("Use an actual version instead.")]
LUCENE_CURRENT
}
public static class LuceneVersionHelpers
{
private static readonly Dictionary<string, LuceneVersion> stringToEnum = new Dictionary<string, LuceneVersion>()
{
{"LUCENE_30", LuceneVersion.LUCENE_30},
{"LUCENE_31", LuceneVersion.LUCENE_31},
{"LUCENE_32", LuceneVersion.LUCENE_32},
{"LUCENE_33", LuceneVersion.LUCENE_33},
{"LUCENE_34", LuceneVersion.LUCENE_34},
{"LUCENE_35", LuceneVersion.LUCENE_35},
{"LUCENE_36", LuceneVersion.LUCENE_36},
{"LUCENE_40", LuceneVersion.LUCENE_40},
{"LUCENE_41", LuceneVersion.LUCENE_41},
{"LUCENE_42", LuceneVersion.LUCENE_42},
{"LUCENE_43", LuceneVersion.LUCENE_43},
{"LUCENE_44", LuceneVersion.LUCENE_44},
{"LUCENE_45", LuceneVersion.LUCENE_45},
{"LUCENE_46", LuceneVersion.LUCENE_46},
{"LUCENE_47", LuceneVersion.LUCENE_47},
{"LUCENE_48", LuceneVersion.LUCENE_48},
{"LUCENE_CURRENT", LuceneVersion.LUCENE_CURRENT}
};
private static readonly Dictionary<string, LuceneVersion> longToEnum = new Dictionary<string, LuceneVersion>()
{
{"3.0", LuceneVersion.LUCENE_30},
{"3.1", LuceneVersion.LUCENE_31},
{"3.2", LuceneVersion.LUCENE_32},
{"3.3", LuceneVersion.LUCENE_33},
{"3.4", LuceneVersion.LUCENE_34},
{"3.5", LuceneVersion.LUCENE_35},
{"3.6", LuceneVersion.LUCENE_36},
{"4.0", LuceneVersion.LUCENE_40},
{"4.1", LuceneVersion.LUCENE_41},
{"4.2", LuceneVersion.LUCENE_42},
{"4.3", LuceneVersion.LUCENE_43},
{"4.4", LuceneVersion.LUCENE_44},
{"4.5", LuceneVersion.LUCENE_45},
{"4.6", LuceneVersion.LUCENE_46},
{"4.7", LuceneVersion.LUCENE_47},
{"4.8", LuceneVersion.LUCENE_48}
};
public static bool OnOrAfter(this LuceneVersion instance, LuceneVersion other)
{
return other <= instance;
//return other >= 0; //LUCENENET TODO
}
public static LuceneVersion ParseLeniently(string version)
{
string upperVersionString = version.ToUpper();
LuceneVersion ret;
if (stringToEnum.TryGetValue(upperVersionString, out ret))
{
return ret;
}
else if (longToEnum.TryGetValue(upperVersionString, out ret))
{
return ret;
}
return ret;
}
}
}
| |
// MIT License
//
// Copyright (c) 2009-2017 Luca Piccioni
//
// 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.
//
// This file is automatically generated
#pragma warning disable 649, 1572, 1573
// ReSharper disable RedundantUsingDirective
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Khronos;
// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
// ReSharper disable JoinDeclarationAndInitializer
namespace OpenGL
{
public partial class Gl
{
/// <summary>
/// [GL] Value of GL_LGPU_SEPARATE_STORAGE_BIT_NVX symbol.
/// </summary>
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
[Log(BitmaskName = "GL")]
public const int LGPU_SEPARATE_STORAGE_BIT_NVX = 0x0800;
/// <summary>
/// [GL] Value of GL_MAX_LGPU_GPUS_NVX symbol.
/// </summary>
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
public const int MAX_LGPU_GPUS_NVX = 0x92BA;
/// <summary>
/// [GL] glLGPUNamedBufferSubDataNVX: Binding for glLGPUNamedBufferSubDataNVX.
/// </summary>
/// <param name="gpuMask">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="buffer">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="offset">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="size">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="data">
/// A <see cref="T:IntPtr"/>.
/// </param>
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
public static void LGPUNamedBufferSubDataNVX(uint gpuMask, uint buffer, IntPtr offset, uint size, IntPtr data)
{
Debug.Assert(Delegates.pglLGPUNamedBufferSubDataNVX != null, "pglLGPUNamedBufferSubDataNVX not implemented");
Delegates.pglLGPUNamedBufferSubDataNVX(gpuMask, buffer, offset, size, data);
LogCommand("glLGPUNamedBufferSubDataNVX", null, gpuMask, buffer, offset, size, data );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glLGPUNamedBufferSubDataNVX: Binding for glLGPUNamedBufferSubDataNVX.
/// </summary>
/// <param name="gpuMask">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="buffer">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="offset">
/// A <see cref="T:IntPtr"/>.
/// </param>
/// <param name="size">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="data">
/// A <see cref="T:object"/>.
/// </param>
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
public static void LGPUNamedBufferSubDataNVX(uint gpuMask, uint buffer, IntPtr offset, uint size, object data)
{
GCHandle pin_data = GCHandle.Alloc(data, GCHandleType.Pinned);
try {
LGPUNamedBufferSubDataNVX(gpuMask, buffer, offset, size, pin_data.AddrOfPinnedObject());
} finally {
pin_data.Free();
}
}
/// <summary>
/// [GL] glLGPUCopyImageSubDataNVX: Binding for glLGPUCopyImageSubDataNVX.
/// </summary>
/// <param name="sourceGpu">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="destinationGpuMask">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="srcName">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="srcTarget">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcLevel">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcX">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srxY">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="srcZ">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstName">
/// A <see cref="T:uint"/>.
/// </param>
/// <param name="dstTarget">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstLevel">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstX">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstY">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="dstZ">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="width">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="height">
/// A <see cref="T:int"/>.
/// </param>
/// <param name="depth">
/// A <see cref="T:int"/>.
/// </param>
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
public static void LGPUCopyImageSubDataNVX(uint sourceGpu, uint destinationGpuMask, uint srcName, int srcTarget, int srcLevel, int srcX, int srxY, int srcZ, uint dstName, int dstTarget, int dstLevel, int dstX, int dstY, int dstZ, int width, int height, int depth)
{
Debug.Assert(Delegates.pglLGPUCopyImageSubDataNVX != null, "pglLGPUCopyImageSubDataNVX not implemented");
Delegates.pglLGPUCopyImageSubDataNVX(sourceGpu, destinationGpuMask, srcName, srcTarget, srcLevel, srcX, srxY, srcZ, dstName, dstTarget, dstLevel, dstX, dstY, dstZ, width, height, depth);
LogCommand("glLGPUCopyImageSubDataNVX", null, sourceGpu, destinationGpuMask, srcName, srcTarget, srcLevel, srcX, srxY, srcZ, dstName, dstTarget, dstLevel, dstX, dstY, dstZ, width, height, depth );
DebugCheckErrors(null);
}
/// <summary>
/// [GL] glLGPUInterlockNVX: Binding for glLGPUInterlockNVX.
/// </summary>
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
public static void NVX()
{
Debug.Assert(Delegates.pglLGPUInterlockNVX != null, "pglLGPUInterlockNVX not implemented");
Delegates.pglLGPUInterlockNVX();
LogCommand("glLGPUInterlockNVX", null );
DebugCheckErrors(null);
}
internal static unsafe partial class Delegates
{
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glLGPUNamedBufferSubDataNVX(uint gpuMask, uint buffer, IntPtr offset, uint size, IntPtr data);
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
[ThreadStatic]
internal static glLGPUNamedBufferSubDataNVX pglLGPUNamedBufferSubDataNVX;
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glLGPUCopyImageSubDataNVX(uint sourceGpu, uint destinationGpuMask, uint srcName, int srcTarget, int srcLevel, int srcX, int srxY, int srcZ, uint dstName, int dstTarget, int dstLevel, int dstX, int dstY, int dstZ, int width, int height, int depth);
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
[ThreadStatic]
internal static glLGPUCopyImageSubDataNVX pglLGPUCopyImageSubDataNVX;
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
[SuppressUnmanagedCodeSecurity]
internal delegate void glLGPUInterlockNVX();
[RequiredByFeature("GL_NVX_linked_gpu_multicast")]
[ThreadStatic]
internal static glLGPUInterlockNVX pglLGPUInterlockNVX;
}
}
}
| |
/*
* 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.LowLevelAPI40;
using Net.Pkcs11Interop.LowLevelAPI40.MechanismParams;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI40
{
/// <summary>
/// C_EncryptInit, C_Encrypt, C_EncryptUpdate, C_EncryptFinish, C_DecryptInit, C_Decrypt, C_DecryptUpdate and C_DecryptFinish tests.
/// </summary>
[TestClass]
public class _20_EncryptAndDecryptTest
{
/// <summary>
/// C_EncryptInit, C_Encrypt, C_DecryptInit and C_Decrypt test.
/// </summary>
[TestMethod]
public void _01_EncryptAndDecryptSinglePartTest()
{
if (Platform.UnmanagedLongSize != 4 || 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.InitArgs40);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
uint slotId = Helpers.GetUsableSlot(pkcs11);
uint 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.ToUInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate symetric key
uint keyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKey(pkcs11, session, ref keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate random initialization vector
byte[] iv = new byte[8];
rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt32(iv.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify encryption mechanism with initialization vector as parameter.
// Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory.
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv);
// Initialize encryption operation
rv = pkcs11.C_EncryptInit(session, ref mechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password");
// Get length of encrypted data in first call
uint encryptedDataLen = 0;
rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt32(sourceData.Length), null, ref encryptedDataLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(encryptedDataLen > 0);
// Allocate array for encrypted data
byte[] encryptedData = new byte[encryptedDataLen];
// Get encrypted data in second call
rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt32(sourceData.Length), encryptedData, ref encryptedDataLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting with encrypted data
// Initialize decryption operation
rv = pkcs11.C_DecryptInit(session, ref mechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Get length of decrypted data in first call
uint decryptedDataLen = 0;
rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt32(encryptedData.Length), null, ref decryptedDataLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(decryptedDataLen > 0);
// Allocate array for decrypted data
byte[] decryptedData = new byte[decryptedDataLen];
// Get decrypted data in second call
rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt32(encryptedData.Length), decryptedData, ref decryptedDataLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting with decrypted data
Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));
// In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case)
UnmanagedMemory.Free(ref mechanism.Parameter);
mechanism.ParameterLen = 0;
rv = pkcs11.C_DestroyObject(session, keyId);
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_EncryptInit, C_EncryptUpdate, C_EncryptFinish, C_DecryptInit, C_DecryptUpdate and C_DecryptFinish test.
/// </summary>
[TestMethod]
public void _02_EncryptAndDecryptMultiPartTest()
{
if (Platform.UnmanagedLongSize != 4 || 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.InitArgs40);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
uint slotId = Helpers.GetUsableSlot(pkcs11);
uint 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.ToUInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate symetric key
uint keyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKey(pkcs11, session, ref keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate random initialization vector
byte[] iv = new byte[8];
rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt32(iv.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify encryption mechanism with initialization vector as parameter.
// Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory.
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password");
byte[] encryptedData = null;
byte[] decryptedData = null;
// Multipart encryption functions C_EncryptUpdate and C_EncryptFinal can be used i.e. for encryption of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream())
{
// Initialize encryption operation
rv = pkcs11.C_EncryptInit(session, ref mechanism, keyId);
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];
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
uint encryptedPartLen = Convert.ToUInt32(encryptedPart.Length);
// Read input stream with source data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
{
// Encrypt each individual source data part
encryptedPartLen = Convert.ToUInt32(encryptedPart.Length);
rv = pkcs11.C_EncryptUpdate(session, part, Convert.ToUInt32(bytesRead), encryptedPart, ref encryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append encrypted data part to the output stream
outputStream.Write(encryptedPart, 0, Convert.ToInt32(encryptedPartLen));
}
// Get the length of last encrypted data part in first call
byte[] lastEncryptedPart = null;
uint lastEncryptedPartLen = 0;
rv = pkcs11.C_EncryptFinal(session, null, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last encrypted data part
lastEncryptedPart = new byte[lastEncryptedPartLen];
// Get the last encrypted data part in second call
rv = pkcs11.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last encrypted data part to the output stream
outputStream.Write(lastEncryptedPart, 0, Convert.ToInt32(lastEncryptedPartLen));
// Read whole output stream to the byte array so we can compare results more easily
encryptedData = outputStream.ToArray();
}
// Do something interesting with encrypted data
// Multipart decryption functions C_DecryptUpdate and C_DecryptFinal can be used i.e. for decryption of streamed data
using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream())
{
// Initialize decryption operation
rv = pkcs11.C_DecryptInit(session, ref mechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
// Prepare buffer for decrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
uint partLen = Convert.ToUInt32(part.Length);
// Read input stream with encrypted data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0)
{
// Decrypt each individual encrypted data part
partLen = Convert.ToUInt32(part.Length);
rv = pkcs11.C_DecryptUpdate(session, encryptedPart, Convert.ToUInt32(bytesRead), part, ref partLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append decrypted data part to the output stream
outputStream.Write(part, 0, Convert.ToInt32(partLen));
}
// Get the length of last decrypted data part in first call
byte[] lastPart = null;
uint lastPartLen = 0;
rv = pkcs11.C_DecryptFinal(session, null, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last decrypted data part
lastPart = new byte[lastPartLen];
// Get the last decrypted data part in second call
rv = pkcs11.C_DecryptFinal(session, lastPart, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last decrypted data part to the output stream
outputStream.Write(lastPart, 0, Convert.ToInt32(lastPartLen));
// Read whole output stream to the byte array so we can compare results more easily
decryptedData = outputStream.ToArray();
}
// Do something interesting with decrypted data
Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));
// In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case)
UnmanagedMemory.Free(ref mechanism.Parameter);
mechanism.ParameterLen = 0;
rv = pkcs11.C_DestroyObject(session, keyId);
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_EncryptInit, C_Encrypt, C_DecryptInit and C_Decrypt test with CKM_RSA_PKCS_OAEP mechanism.
/// </summary>
[TestMethod]
public void _03_EncryptAndDecryptSinglePartOaepTest()
{
if (Platform.UnmanagedLongSize != 4 || 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.InitArgs40);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
uint slotId = Helpers.GetUsableSlot(pkcs11);
uint 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.ToUInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate asymetric key pair
uint pubKeyId = CK.CK_INVALID_HANDLE;
uint privKeyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKeyPair(pkcs11, session, ref pubKeyId, ref privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify mechanism parameters
CK_RSA_PKCS_OAEP_PARAMS mechanismParams = new CK_RSA_PKCS_OAEP_PARAMS();
mechanismParams.HashAlg = (uint)CKM.CKM_SHA_1;
mechanismParams.Mgf = (uint)CKG.CKG_MGF1_SHA1;
mechanismParams.Source = (uint)CKZ.CKZ_DATA_SPECIFIED;
mechanismParams.SourceData = IntPtr.Zero;
mechanismParams.SourceDataLen = 0;
// Specify encryption mechanism with parameters
// Note that CkmUtils.CreateMechanism() automaticaly copies mechanismParams into newly allocated unmanaged memory.
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_OAEP, mechanismParams);
// Initialize encryption operation
rv = pkcs11.C_EncryptInit(session, ref mechanism, pubKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world");
// Get length of encrypted data in first call
uint encryptedDataLen = 0;
rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt32(sourceData.Length), null, ref encryptedDataLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(encryptedDataLen > 0);
// Allocate array for encrypted data
byte[] encryptedData = new byte[encryptedDataLen];
// Get encrypted data in second call
rv = pkcs11.C_Encrypt(session, sourceData, Convert.ToUInt32(sourceData.Length), encryptedData, ref encryptedDataLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting with encrypted data
// Initialize decryption operation
rv = pkcs11.C_DecryptInit(session, ref mechanism, privKeyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Get length of decrypted data in first call
uint decryptedDataLen = 0;
rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt32(encryptedData.Length), null, ref decryptedDataLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(decryptedDataLen > 0);
// Allocate array for decrypted data
byte[] decryptedData = new byte[decryptedDataLen];
// Get decrypted data in second call
rv = pkcs11.C_Decrypt(session, encryptedData, Convert.ToUInt32(encryptedData.Length), decryptedData, ref decryptedDataLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Array may need to be shrinked
if (decryptedData.Length != decryptedDataLen)
Array.Resize(ref decryptedData, Convert.ToInt32(decryptedDataLen));
// Do something interesting with decrypted data
Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));
// In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter
UnmanagedMemory.Free(ref mechanism.Parameter);
mechanism.ParameterLen = 0;
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());
}
}
}
}
| |
// 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 TestZUInt64()
{
var test = new BooleanBinaryOpTest__TestZUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__TestZUInt64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt64[] inArray1, UInt64[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt64>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt64, 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 Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt64> _fld1;
public Vector256<UInt64> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__TestZUInt64 testClass)
{
var result = Avx.TestZ(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__TestZUInt64 testClass)
{
fixed (Vector256<UInt64>* pFld1 = &_fld1)
fixed (Vector256<UInt64>* pFld2 = &_fld2)
{
var result = Avx.TestZ(
Avx.LoadVector256((UInt64*)(pFld1)),
Avx.LoadVector256((UInt64*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector256<UInt64> _clsVar1;
private static Vector256<UInt64> _clsVar2;
private Vector256<UInt64> _fld1;
private Vector256<UInt64> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__TestZUInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
}
public BooleanBinaryOpTest__TestZUInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.TestZ(
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.TestZ(
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.TestZ(
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<UInt64>), typeof(Vector256<UInt64>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.TestZ(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt64>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt64>* pClsVar2 = &_clsVar2)
{
var result = Avx.TestZ(
Avx.LoadVector256((UInt64*)(pClsVar1)),
Avx.LoadVector256((UInt64*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt64>>(_dataTable.inArray2Ptr);
var result = Avx.TestZ(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt64*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx.TestZ(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt64*)(_dataTable.inArray2Ptr));
var result = Avx.TestZ(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__TestZUInt64();
var result = Avx.TestZ(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__TestZUInt64();
fixed (Vector256<UInt64>* pFld1 = &test._fld1)
fixed (Vector256<UInt64>* pFld2 = &test._fld2)
{
var result = Avx.TestZ(
Avx.LoadVector256((UInt64*)(pFld1)),
Avx.LoadVector256((UInt64*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.TestZ(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt64>* pFld1 = &_fld1)
fixed (Vector256<UInt64>* pFld2 = &_fld2)
{
var result = Avx.TestZ(
Avx.LoadVector256((UInt64*)(pFld1)),
Avx.LoadVector256((UInt64*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.TestZ(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx.TestZ(
Avx.LoadVector256((UInt64*)(&test._fld1)),
Avx.LoadVector256((UInt64*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt64> op1, Vector256<UInt64> op2, bool result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult &= ((left[i] & right[i]) == 0);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.TestZ)}<UInt64>(Vector256<UInt64>, Vector256<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = 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.
/******************************************************************************
* 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 MultiplySubtractNegatedSingle()
{
var test = new SimpleTernaryOpTest__MultiplySubtractNegatedSingle();
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();
if (Sse.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 (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 class works
test.RunClassLclFldScenario();
if (Sse.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 (Sse.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 (Sse.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 (Sse.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 SimpleTernaryOpTest__MultiplySubtractNegatedSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] inArray3;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle inHandle3;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] inArray3, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inArray3 = 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.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Single, byte>(ref inArray3[0]), (uint)sizeOfinArray3);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
inHandle3.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<Single> _fld1;
public Vector128<Single> _fld2;
public Vector128<Single> _fld3;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleTernaryOpTest__MultiplySubtractNegatedSingle testClass)
{
var result = Fma.MultiplySubtractNegated(_fld1, _fld2, _fld3);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplySubtractNegatedSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
fixed (Vector128<Single>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtractNegated(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2)),
Sse.LoadVector128((Single*)(pFld3))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Single[] _data3 = new Single[Op3ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private static Vector128<Single> _clsVar3;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private Vector128<Single> _fld3;
private DataTable _dataTable;
static SimpleTernaryOpTest__MultiplySubtractNegatedSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleTernaryOpTest__MultiplySubtractNegatedSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld3), ref Unsafe.As<Single, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, _data3, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Fma.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Fma.MultiplySubtractNegated(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Fma.MultiplySubtractNegated(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Fma.MultiplySubtractNegated(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegated), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegated), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Fma).GetMethod(nameof(Fma.MultiplySubtractNegated), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Fma.MultiplySubtractNegated(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
fixed (Vector128<Single>* pClsVar3 = &_clsVar3)
{
var result = Fma.MultiplySubtractNegated(
Sse.LoadVector128((Single*)(pClsVar1)),
Sse.LoadVector128((Single*)(pClsVar2)),
Sse.LoadVector128((Single*)(pClsVar3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var op3 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray3Ptr);
var result = Fma.MultiplySubtractNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var op3 = Sse.LoadVector128((Single*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtractNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var op3 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray3Ptr));
var result = Fma.MultiplySubtractNegated(op1, op2, op3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, op3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleTernaryOpTest__MultiplySubtractNegatedSingle();
var result = Fma.MultiplySubtractNegated(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleTernaryOpTest__MultiplySubtractNegatedSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
fixed (Vector128<Single>* pFld3 = &test._fld3)
{
var result = Fma.MultiplySubtractNegated(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2)),
Sse.LoadVector128((Single*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Fma.MultiplySubtractNegated(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
fixed (Vector128<Single>* pFld3 = &_fld3)
{
var result = Fma.MultiplySubtractNegated(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2)),
Sse.LoadVector128((Single*)(pFld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Fma.MultiplySubtractNegated(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Fma.MultiplySubtractNegated(
Sse.LoadVector128((Single*)(&test._fld1)),
Sse.LoadVector128((Single*)(&test._fld2)),
Sse.LoadVector128((Single*)(&test._fld3))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _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<Single> op1, Vector128<Single> op2, Vector128<Single> op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), op3);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] inArray3 = new Single[Op3ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] secondOp, Single[] thirdOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(MathF.Round(-(firstOp[0] * secondOp[0]) - thirdOp[0], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[0], 3)))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(MathF.Round(-(firstOp[i] * secondOp[i]) - thirdOp[i], 3)) != BitConverter.SingleToInt32Bits(MathF.Round(result[i], 3)))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Fma)}.{nameof(Fma.MultiplySubtractNegated)}<Single>(Vector128<Single>, Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})");
TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Common;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V10.Enums.AssetFieldTypeEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example adds sitelinks to a campaign using assets. Run AddCampaigns.cs to
/// create a campaign.
/// </summary>
public class AddSitelinksUsingAssets : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddSitelinksUsingAssets"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// ID of the campaign to which sitelinks are added.
/// </summary>
[Option("campaignId", Required = true, HelpText =
"ID of the campaign to which sitelinks are added.")]
public long CampaignId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// ID of the campaign to which sitelinks are added.
options.CampaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
return 0;
});
AddSitelinksUsingAssets codeExample = new AddSitelinksUsingAssets();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example adds sitelinks to a campaign using assets. Run AddCampaigns.cs " +
"to create a campaign.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="campaignId">ID of the campaign to which sitelinks are added.</param>
public void Run(GoogleAdsClient client, long customerId, long campaignId)
{
try
{
// Creates a sitelink asset.
List<string> siteLinkResourceNames = CreateSitelinkAssets(client, customerId);
// Associates the sitelinks at the campaign level.
LinkSitelinksToCampaign(client, customerId, campaignId, siteLinkResourceNames);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates a list of <see cref="SitelinkAsset"/> objects which can then be added
/// to campaigns.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <returns>The list of sitelink resource names.</returns>
private List<string> CreateSitelinkAssets(GoogleAdsClient client, long customerId)
{
AssetServiceClient assetService = client.GetService(Services.V10.AssetService);
// Creates some sitelink assets.
SitelinkAsset storeLocatorExtension = new SitelinkAsset()
{
Description1 = "Get in touch",
Description2 = "Find your local store",
LinkText = "Store locator"
};
SitelinkAsset storeExtension = new SitelinkAsset()
{
Description1 = "Buy some stuff",
Description2 = "It's really good",
LinkText = "Store"
};
SitelinkAsset storeAdditionalExtension = new SitelinkAsset()
{
Description1 = "Even more stuff",
Description2 = "There's never enough",
LinkText = "Store for more"
};
// Wraps the sitelinks in an Asset and sets the URLs.
List<Asset> assets = new List<Asset>()
{
new Asset()
{
SitelinkAsset = storeLocatorExtension,
FinalUrls = { "http://example.com/contact/store-finder" },
// Optionally sets a different URL for mobile.
FinalMobileUrls = { "http://example.com/mobile/contact/store-finder" }
},
new Asset()
{
SitelinkAsset = storeExtension,
FinalUrls = { "http://example.com/store" },
// Optionally sets a different URL for mobile.
FinalMobileUrls = {"http://example.com/mobile/store" }
},
new Asset()
{
SitelinkAsset = storeAdditionalExtension,
FinalUrls = { "http://example.com/store/more" },
// Optionally sets a different URL for mobile.
FinalMobileUrls = { "http://example.com/mobile/store/more" }
}
};
// Creates an operation to add each asset.
List<AssetOperation> operations = assets.Select(
asset => new AssetOperation()
{
Create = asset,
}).ToList();
// Sends the mutate request.
MutateAssetsResponse response = assetService.MutateAssets(
customerId.ToString(), operations);
// Prints some information about the result.
List<string> resourceNames = response.Results.Select(
result => result.ResourceName).ToList();
foreach (string resourceName in resourceNames)
{
Console.WriteLine($"Created sitelink asset with resource name '{resourceNames}'.");
}
return resourceNames;
}
/** Links the assets to a campaign. */
/// <summary>
/// Links the sitelinks to campaign.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="campaignId">ID of the campaign to which sitelinks are added.
/// </param>
/// <param name="sitelinkAssetResourceNames">The sitelink asset resource names.</param>
private void LinkSitelinksToCampaign(GoogleAdsClient client, long customerId,
long campaignId, List<string> sitelinkAssetResourceNames)
{
CampaignAssetServiceClient campaignAssetService = client.GetService(
Services.V10.CampaignAssetService);
string campaignResourceName = ResourceNames.Campaign(customerId, campaignId);
// Creates operations.
List<CampaignAssetOperation> campaignAssetOperations =
sitelinkAssetResourceNames.Select(resourceName =>
new CampaignAssetOperation()
{
// Creates CampaignAsset representing the association between sitelinks
// and campaign.
Create = new CampaignAsset()
{
Asset = resourceName,
Campaign = campaignResourceName,
FieldType = AssetFieldType.Sitelink
}
}).ToList();
// Sends the mutate request.
MutateCampaignAssetsResponse response = campaignAssetService.MutateCampaignAssets(
customerId.ToString(), campaignAssetOperations);
// Prints some information about the result.
foreach (MutateCampaignAssetResult result in response.Results)
{
Console.WriteLine($"Linked sitelink to campaign with resource " +
$"name '{result.ResourceName}'.");
}
}
}
}
| |
// 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.ComponentModel.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
[Export(typeof(MiscellaneousFilesWorkspace))]
internal sealed partial class MiscellaneousFilesWorkspace : Workspace, IVsRunningDocTableEvents2, IVisualStudioHostProjectContainer
{
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
private readonly IMetadataAsSourceFileService _fileTrackingMetadataAsSourceService;
private readonly IVsRunningDocumentTable4 _runningDocumentTable;
private readonly IVsTextManager _textManager;
private readonly RoslynDocumentProvider _documentProvider;
private readonly Dictionary<Guid, LanguageInformation> _languageInformationByLanguageGuid = new Dictionary<Guid, LanguageInformation>();
private readonly HashSet<DocumentKey> _filesInProjects = new HashSet<DocumentKey>();
private readonly Dictionary<ProjectId, HostProject> _hostProjects = new Dictionary<ProjectId, HostProject>();
private readonly Dictionary<uint, HostProject> _docCookiesToHostProject = new Dictionary<uint, HostProject>();
private readonly ImmutableArray<MetadataReference> _metadataReferences;
private uint _runningDocumentTableEventsCookie;
// document worker coordinator
private IWorkCoordinatorRegistrationService _workCoordinatorService;
[ImportingConstructor]
public MiscellaneousFilesWorkspace(
IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
IMetadataAsSourceFileService fileTrackingMetadataAsSourceService,
SaveEventsService saveEventsService,
VisualStudioWorkspace visualStudioWorkspace,
SVsServiceProvider serviceProvider) :
base(visualStudioWorkspace.Services.HostServices, "MiscellaneousFiles")
{
_editorAdaptersFactoryService = editorAdaptersFactoryService;
_fileTrackingMetadataAsSourceService = fileTrackingMetadataAsSourceService;
_runningDocumentTable = (IVsRunningDocumentTable4)serviceProvider.GetService(typeof(SVsRunningDocumentTable));
_textManager = (IVsTextManager)serviceProvider.GetService(typeof(SVsTextManager));
((IVsRunningDocumentTable)_runningDocumentTable).AdviseRunningDocTableEvents(this, out _runningDocumentTableEventsCookie);
_metadataReferences = ImmutableArray.CreateRange(CreateMetadataReferences());
_documentProvider = new RoslynDocumentProvider(this, serviceProvider);
saveEventsService.StartSendingSaveEvents();
}
public void RegisterLanguage(Guid languageGuid, string languageName, string scriptExtension, ParseOptions parseOptions)
{
_languageInformationByLanguageGuid.Add(languageGuid, new LanguageInformation(languageName, scriptExtension, parseOptions));
}
internal void StartSolutionCrawler()
{
if (_workCoordinatorService == null)
{
lock (this)
{
if (_workCoordinatorService == null)
{
_workCoordinatorService = this.Services.GetService<IWorkCoordinatorRegistrationService>();
_workCoordinatorService.Register(this);
}
}
}
}
internal void StopSolutionCrawler()
{
if (_workCoordinatorService != null)
{
lock (this)
{
if (_workCoordinatorService != null)
{
_workCoordinatorService.Unregister(this, blockingShutdown: true);
_workCoordinatorService = null;
}
}
}
}
private LanguageInformation TryGetLanguageInformation(string filename)
{
Guid fileLanguageGuid;
LanguageInformation languageInformation = null;
if (ErrorHandler.Succeeded(_textManager.MapFilenameToLanguageSID(filename, out fileLanguageGuid)))
{
_languageInformationByLanguageGuid.TryGetValue(fileLanguageGuid, out languageInformation);
}
return languageInformation;
}
private IEnumerable<MetadataReference> CreateMetadataReferences()
{
var manager = this.Services.GetService<VisualStudioMetadataReferenceManager>();
var searchPaths = ReferencePathUtilities.GetReferencePaths();
return from fileName in new[] { "mscorlib.dll", "System.dll", "System.Core.dll" }
let fullPath = FileUtilities.ResolveRelativePath(fileName, basePath: null, baseDirectory: null, searchPaths: searchPaths, fileExists: File.Exists)
where fullPath != null
select manager.CreateMetadataReferenceSnapshot(fullPath, MetadataReferenceProperties.Assembly);
}
internal void OnFileIncludedInProject(IVisualStudioHostDocument document)
{
uint docCookie;
if (_runningDocumentTable.TryGetCookieForInitializedDocument(document.FilePath, out docCookie))
{
TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, document.FilePath);
}
_filesInProjects.Add(document.Key);
}
internal void OnFileRemovedFromProject(IVisualStudioHostDocument document)
{
// Remove the document key from the filesInProjects map first because adding documents
// to the misc files workspace requires that they not appear in this map.
_filesInProjects.Remove(document.Key);
uint docCookie;
if (_runningDocumentTable.TryGetCookieForInitializedDocument(document.Key.Moniker, out docCookie))
{
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, document.Key.Moniker);
}
}
public int OnAfterAttributeChange(uint docCookie, uint grfAttribs)
{
return VSConstants.S_OK;
}
public int OnAfterAttributeChangeEx(uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
{
// Did we rename?
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_MkDocument) != 0)
{
// We want to consider this file to be added in one of two situations:
//
// 1) the old file already was a misc file, at which point we might just be doing a rename from
// one name to another with the same extension
// 2) the old file was a different extension that we weren't tracking, which may have now changed
if (TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, pszMkDocumentOld) || TryGetLanguageInformation(pszMkDocumentOld) == null)
{
// Add the new one, if appropriate.
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, pszMkDocumentNew);
}
}
// When starting a diff, the RDT doesn't call OnBeforeDocumentWindowShow, but it does call
// OnAfterAttributeChangeEx for the temporary buffer. The native IDE used this even to
// add misc files, so we'll do the same.
if ((grfAttribs & (uint)__VSRDTATTRIB.RDTA_DocDataReloaded) != 0)
{
var moniker = _runningDocumentTable.GetDocumentMoniker(docCookie);
if (moniker != null && TryGetLanguageInformation(moniker) != null && !_docCookiesToHostProject.ContainsKey(docCookie))
{
AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(docCookie, moniker);
}
}
return VSConstants.S_OK;
}
public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
return VSConstants.E_NOTIMPL;
}
public int OnAfterSave(uint docCookie)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame)
{
return VSConstants.E_NOTIMPL;
}
public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
{
if (dwReadLocksRemaining + dwEditLocksRemaining == 0)
{
TryRemoveDocumentFromMiscellaneousWorkspace(docCookie, _runningDocumentTable.GetDocumentMoniker(docCookie));
}
return VSConstants.S_OK;
}
private void AddDocumentToMiscellaneousOrMetadataAsSourceWorkspace(uint docCookie, string moniker)
{
var languageInformation = TryGetLanguageInformation(moniker);
if (languageInformation != null &&
!_filesInProjects.Any(d => StringComparer.OrdinalIgnoreCase.Equals(d.Moniker, moniker)) &&
!_docCookiesToHostProject.ContainsKey(docCookie))
{
// See if we should push to this to the metadata-to-source workspace instead.
if (_runningDocumentTable.IsDocumentInitialized(docCookie))
{
var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
var textBuffer = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);
if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
{
// We already added it, so we will keep it excluded from the misc files workspace
return;
}
}
var parseOptions = languageInformation.ParseOptions;
if (Path.GetExtension(moniker) == languageInformation.ScriptExtension)
{
parseOptions = parseOptions.WithKind(SourceCodeKind.Script);
}
// First, create the project
var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptions, _metadataReferences);
// Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
var document = _documentProvider.TryGetDocumentForFile(hostProject, (uint)VSConstants.VSITEMID.Nil, moniker, parseOptions.Kind, t => true);
// If the buffer has not yet been initialized, we won't get a document.
if (document == null)
{
return;
}
// Since we have a document, we can do the rest of the project setup.
_hostProjects.Add(hostProject.Id, hostProject);
OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());
OnDocumentAdded(document.GetInitialState());
hostProject.Document = document;
// Notify the document provider, so it knows the document is now open and a part of
// the project
_documentProvider.NotifyDocumentRegisteredToProject(document);
Contract.ThrowIfFalse(document.IsOpen);
var buffer = document.GetOpenTextBuffer();
OnDocumentOpened(document.Id, document.GetOpenTextContainer());
_docCookiesToHostProject.Add(docCookie, hostProject);
}
}
private bool TryRemoveDocumentFromMiscellaneousWorkspace(uint docCookie, string moniker)
{
HostProject hostProject;
if (_fileTrackingMetadataAsSourceService.TryRemoveDocumentFromWorkspace(moniker))
{
return true;
}
if (_docCookiesToHostProject.TryGetValue(docCookie, out hostProject))
{
var document = hostProject.Document;
OnDocumentClosed(document.Id, document.Loader);
OnDocumentRemoved(document.Id);
OnProjectRemoved(hostProject.Id);
_hostProjects.Remove(hostProject.Id);
_docCookiesToHostProject.Remove(docCookie);
return true;
}
return false;
}
protected override void Dispose(bool finalize)
{
StopSolutionCrawler();
var runningDocumentTableForEvents = (IVsRunningDocumentTable)_runningDocumentTable;
runningDocumentTableForEvents.UnadviseRunningDocTableEvents(_runningDocumentTableEventsCookie);
_runningDocumentTableEventsCookie = 0;
base.Dispose(finalize);
}
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.ChangeDocument:
return true;
default:
return false;
}
}
protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText)
{
var hostDocument = this.GetDocument(documentId);
hostDocument.UpdateText(newText);
}
private HostProject GetHostProject(ProjectId id)
{
HostProject project;
_hostProjects.TryGetValue(id, out project);
return project;
}
internal IVisualStudioHostDocument GetDocument(DocumentId id)
{
var project = GetHostProject(id.ProjectId);
if (project != null && project.Document.Id == id)
{
return project.Document;
}
return null;
}
IEnumerable<IVisualStudioHostProject> IVisualStudioHostProjectContainer.GetProjects()
{
return _hostProjects.Values;
}
private class LanguageInformation
{
public LanguageInformation(string languageName, string scriptExtension, ParseOptions parseOptions)
{
this.LanguageName = languageName;
this.ScriptExtension = scriptExtension;
this.ParseOptions = parseOptions;
}
public string LanguageName { get; private set; }
public string ScriptExtension { get; private set; }
public ParseOptions ParseOptions { get; private set; }
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Drawing;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.UI;
using OpenLiveWriter.Interop.Windows;
namespace OpenLiveWriter.ApplicationFramework.Skinning
{
/// <summary>
/// Summary description for ColorizedResources.
/// </summary>
public class ColorizedResources
{
[ThreadStatic]
private static ColorizedResources s_threadInstance;
public static ColorizedResources Instance
{
get
{
if (s_threadInstance == null)
s_threadInstance = new ColorizedResources();
return s_threadInstance;
}
}
internal static event EventHandler GlobalColorizationChanged;
private static void OnChange()
{
if (GlobalColorizationChanged != null)
GlobalColorizationChanged(null, EventArgs.Empty);
}
public static void FireColorChanged()
{
OnChange();
}
public static Color AppColor
{
get
{
if (UseSystemColors)
{
return SystemColors.Control;
}
else
{
if (ApplicationEnvironment.PreferencesSettingsRoot == null)
return Color.Empty;
string strColor = ApplicationEnvironment.PreferencesSettingsRoot.GetSubSettings("Appearance").GetString("AppColor", null);
if (strColor == null || strColor == string.Empty)
return Color.Empty;
else
return ColorHelper.StringToColor(strColor);
}
}
set
{
string strColor;
if (value == Color.Empty)
strColor = null;
else
strColor = ColorHelper.ColorToString(value);
ApplicationEnvironment.PreferencesSettingsRoot.GetSubSettings("Appearance").SetString("AppColor", strColor);
OnChange();
}
}
public static int AppColorScale
{
get
{
if (ApplicationEnvironment.PreferencesSettingsRoot == null)
return 128;
return ApplicationEnvironment.PreferencesSettingsRoot.GetSubSettings("Appearance").GetInt32("AppColorScale", 128);
}
set
{
ApplicationEnvironment.PreferencesSettingsRoot.GetSubSettings("Appearance").SetInt32("AppColorScale", value);
OnChange();
}
}
private Color _colorizeColor;
private int _colorizeScale;
private BorderPaint _borderAppFrameOutline;
private BorderPaint _borderFooterBackground;
private BorderPaint _borderToolbar;
private BorderPaint _viewSwitchingTabSelected;
private BorderPaint _viewSwitchingTabUnselected;
private Bitmap _imgFooterBackground;
private Bitmap _imgDropShadow;
private Color _frameGradientLightColor;
private Color _sidebarGradientTopColor;
private Color _sidebarGradientBottomColor;
private Color _sidebarTextColor;
private Color _borderDark;
private Color _borderLight;
private Color _sidebarHeaderBackgroundColor;
private Color _sidebarHeaderTextColor;
private Color _workspaceBackgroundColor;
private Color _menuGradientTopColor;
private Color _menuGradientBottomColor;
private Color _secondaryToolbarColor;
private Color _sidebarLinkColor;
private ColorizedResources()
{
Microsoft.Win32.SystemEvents.UserPreferenceChanged += new Microsoft.Win32.UserPreferenceChangedEventHandler(SystemEvents_UserPreferenceChanged);
Refresh();
}
public event EventHandler ColorizationChanged;
internal void FireColorizationChanged()
{
if (ColorizationChanged != null)
ColorizationChanged(this, EventArgs.Empty);
}
public static bool UseSystemColors
{
get
{
return SystemInformation.HighContrast;
}
}
private void ReplaceWithEmptyBitmap(Bitmap b, Color c)
{
using (Graphics g = Graphics.FromImage(b))
{
g.FillRectangle(new SolidBrush(c), 0, 0, b.Width, b.Height);
}
}
private Bitmap AdjustImageForSystemDPI(Bitmap b)
{
// see if we need to adjust our width for non-standard DPI (large fonts)
const double DESIGNTIME_DPI = 96;
double dpiX = Convert.ToDouble(DisplayHelper.PixelsPerLogicalInchX);
if (dpiX > DESIGNTIME_DPI)
{
// adjust scale ration for percentage of toolbar containing text
double scaleRatio = dpiX / DESIGNTIME_DPI;
// change width as appropriate
Bitmap adjustedBitmap = new Bitmap(b, Convert.ToInt32(Convert.ToDouble(b.Width) * scaleRatio), Convert.ToInt32(Convert.ToDouble(b.Height) * scaleRatio));
b.Dispose();
return adjustedBitmap;
}
return b;
}
private void RefreshImages()
{
_imgDropShadow = ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.DropShadow.png");
_imgFooterBackground = ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.FooterBackgroundBW.png");
Bitmap imgBorderAppFrameOutline = ColorizeBitmap(ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.AppFrameOutline.png"));
Bitmap imgBorderToolbar =
DisplayHelper.IsCompositionEnabled(false)
? AdjustImageForSystemDPI(ColorizeBitmap(ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.Toolbar.png")))
: AdjustImageForSystemDPI(ColorizeBitmap(ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.XPActionBarBottom.png")));
Bitmap imgSelectedTab = ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.TabSelected.png");
imgSelectedTab =
ColorizeBitmap(imgSelectedTab, new Rectangle(1, 0, imgSelectedTab.Width - 2, imgSelectedTab.Height - 1));
imgSelectedTab = AdjustImageForSystemDPI(imgSelectedTab);
Bitmap imgUnselectedTab = ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.TabUnselected.png");
imgUnselectedTab =
ColorizeBitmap(imgUnselectedTab, new Rectangle(1, 1, imgUnselectedTab.Width - 2, imgUnselectedTab.Height - 2));
imgUnselectedTab = AdjustImageForSystemDPI(imgUnselectedTab);
if (UseSystemColors)
{
ReplaceWithEmptyBitmap(_imgFooterBackground, SystemColors.Control);
ReplaceWithEmptyBitmap(imgBorderAppFrameOutline, SystemColors.Control);
ReplaceWithEmptyBitmap(imgBorderToolbar, SystemColors.Control);
ReplaceWithEmptyBitmap(imgUnselectedTab, SystemColors.Control);
ReplaceWithEmptyBitmap(imgSelectedTab, SystemColors.Control);
}
using (new QuickTimer("Colorize bitmaps"))
{
SwapAndDispose(ref _borderAppFrameOutline, new BorderPaint(
imgBorderAppFrameOutline,
true,
BorderPaintMode.GDI, 6, 9, 221, 222));
SwapAndDispose(ref _borderFooterBackground,
new BorderPaint(_imgFooterBackground, false, BorderPaintMode.GDI,
0, _imgFooterBackground.Width, _imgFooterBackground.Height, _imgFooterBackground.Height));
if (DisplayHelper.IsCompositionEnabled(false))
{
SwapAndDispose(ref _borderToolbar, new BorderPaint(
imgBorderToolbar,
true,
BorderPaintMode.StretchToFill | BorderPaintMode.Cached, 2, imgBorderToolbar.Width - 2, 0, 0));
}
else
{
SwapAndDispose(ref _borderToolbar, new BorderPaint(
imgBorderToolbar,
true,
BorderPaintMode.GDI, 0, imgBorderToolbar.Width - 1, 0, 0));
}
SwapAndDispose(ref _viewSwitchingTabSelected, new BorderPaint(imgSelectedTab, true, BorderPaintMode.StretchToFill | BorderPaintMode.Cached | BorderPaintMode.PaintMiddleCenter, 1, 8, 2, 8));
SwapAndDispose(ref _viewSwitchingTabUnselected, new BorderPaint(imgUnselectedTab, true, BorderPaintMode.StretchToFill | BorderPaintMode.Cached | BorderPaintMode.PaintMiddleCenter, 1, 9, 1, 9));
_sidebarLinkColor = SystemInformation.HighContrast ? SystemColors.HotTrack : Color.FromArgb(0, 134, 198);
/*
SwapAndDispose(ref _imgAppVapor,
ColorizeBitmap(ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.AppVapor.png")));
if (_hbAppVapor != IntPtr.Zero)
Gdi32.DeleteObject(_hbAppVapor);
_hbAppVapor = _imgAppVapor.GetHbitmap();
SwapAndDispose(ref _imgAppVaporFaded,
ColorizeBitmap(ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.AppVaporFaded.png")));
if (_hbAppVaporFaded != IntPtr.Zero)
Gdi32.DeleteObject(_hbAppVaporFaded);
_hbAppVaporFaded = _imgAppVaporFaded.GetHbitmap();
*/
}
}
internal void Refresh()
{
Color coolGray = Color.FromArgb(243, 243, 247);
bool useThemeColors = !UseSystemColors;
_colorizeColor = AppColor;
_colorizeScale = AppColorScale;
RefreshImages();
_borderDark = useThemeColors ? Color.FromArgb(188, 188, 188) : SystemColors.ControlDark;
_borderLight = useThemeColors ? Color.FromArgb(218, 229, 242) : SystemColors.ControlLight;
//_borderLight = Colorize(Color.FromArgb(62, 152, 180));
//_sidebarGradientTopColor = useThemeColors ? Colorize(Color.FromArgb(134, 209, 240)) : SystemColors.Control;
_sidebarGradientTopColor = useThemeColors ? Colorize(Color.FromArgb(255, 255, 255)) : SystemColors.Control;
_sidebarGradientBottomColor = useThemeColors ? Colorize(Color.FromArgb(255, 255, 255)) : SystemColors.Control;
_sidebarTextColor = SystemColors.HotTrack;
_sidebarHeaderBackgroundColor = !useThemeColors ? SystemColors.Control : Colorize(Color.FromArgb(255, 255, 255));
_sidebarHeaderTextColor = Color.FromArgb(53, 90, 136);
_frameGradientLightColor = useThemeColors ? Colorize(Color.FromArgb(255, 255, 255)) : SystemColors.Control;
_workspaceBackgroundColor = useThemeColors ? Colorize(coolGray) : SystemColors.Control;
_menuGradientTopColor = !useThemeColors ? SystemColors.Control :
DisplayHelper.IsCompositionEnabled(false) ? Colorize(Color.FromArgb(229, 238, 248)) :
Colorize(Color.FromArgb(229, 238, 248));
_menuGradientBottomColor = !useThemeColors ? SystemColors.Control :
DisplayHelper.IsCompositionEnabled(false) ? Colorize(Color.FromArgb(229, 238, 248)) :
_menuGradientTopColor;
_secondaryToolbarColor = useThemeColors ? Colorize(coolGray) : SystemColors.Control;
}
private void SwapAndDispose(ref Bitmap image, Bitmap newImage)
{
Bitmap oldImage = image;
image = newImage;
if (oldImage != null)
oldImage.Dispose();
}
private void SwapAndDispose(ref BorderPaint bd, BorderPaint newBd)
{
BorderPaint oldBd = bd;
bd = newBd;
if (oldBd != null)
oldBd.Dispose();
}
private Bitmap ColorizeBitmap(Bitmap bitmap)
{
return Colorizer.ColorizeBitmap(bitmap, _colorizeColor, _colorizeScale);
}
private Bitmap ColorizeBitmap(Bitmap bmp, Rectangle colorizeRectangle)
{
return Colorizer.ColorizeBitmap(bmp, _colorizeColor, _colorizeScale, colorizeRectangle);
}
public Bitmap FooterBackground
{
get { return _imgFooterBackground; }
}
public Bitmap DropShadowBitmap
{
get
{
return _imgDropShadow;
}
}
public BorderPaint AppOutlineBorder
{
get { return _borderAppFrameOutline; }
}
public BorderPaint AppFooterBackground
{
get { return _borderFooterBackground; }
}
public BorderPaint ToolbarBorder
{
get { return _borderToolbar; }
}
public BorderPaint ViewSwitchingTabSelected
{
get
{
return _viewSwitchingTabSelected;
}
}
public BorderPaint ViewSwitchingTabUnselected
{
get
{
return _viewSwitchingTabUnselected;
}
}
public Color SidebarLinkColor
{
get
{
return _sidebarLinkColor;
}
}
public Color FrameGradientLight
{
get { return _frameGradientLightColor; }
}
public Color SidebarGradientTopColor
{
get { return _sidebarGradientTopColor; }
}
public Color SidebarGradientBottomColor
{
get { return _sidebarGradientBottomColor; }
}
[Obsolete("This looks funny when juxtapositioned with GDI-drawn LinkLabel controls, which appear a little darker than they should.")]
public Color SidebarTextColor
{
get { return _sidebarTextColor; }
}
public Color SidebarDisabledTextColor
{
get { return SystemColors.GrayText; }
}
public Color BorderDarkColor
{
get { return _borderDark; }
}
public Color SecondaryToolbarColor
{
get
{
return _secondaryToolbarColor;
}
}
public Color BorderLightColor
{
get { return _borderLight; }
}
public Color SidebarHeaderBackgroundColor
{
get { return _sidebarHeaderBackgroundColor; }
}
public Color SidebarHeaderTextColor
{
get { return _sidebarHeaderTextColor; }
}
public Color WorkspaceBackgroundColor
{
get { return _workspaceBackgroundColor; }
}
public bool CustomMainMenuPainting
{
get
{
return !UseSystemColors;
}
}
public Color MainMenuGradientTopColor
{
get
{
return _menuGradientTopColor;
}
}
public Color MainMenuGradientBottomColor
{
get
{
return _menuGradientBottomColor;
}
}
public Color MainMenuHighlightColor
{
get
{
if (CustomMainMenuPainting)
return Color.FromArgb(160, 160, 160);
else
return SystemColors.Highlight;
}
}
public Color MainMenuTextColor
{
get
{
if (CustomMainMenuPainting)
return DisplayHelper.IsCompositionEnabled(false) && ColorHelper.GetLuminosity(_colorizeColor) > 128
? Color.FromArgb(99, 101, 99)
: Color.FromArgb(99, 101, 99);
else
return SystemColors.MenuText;
}
}
public Color Colorize(Color color)
{
return Colorizer.ColorizeARGB(color, _colorizeColor, _colorizeScale);
}
public Bitmap Colorize(Bitmap bmp)
{
return Colorizer.ColorizeBitmap(bmp, _colorizeColor, _colorizeScale);
}
public delegate void ControlUpdater<TControl>(ColorizedResources cr, TControl c) where TControl : Control;
public void RegisterControlForUpdates<TControl>(TControl control, ControlUpdater<TControl> updater) where TControl : Control
{
updater(Instance, control);
new ColorizationUpdateRegistrationHandle<TControl>(control, updater);
}
public void RegisterControlForBackColorUpdates(Control control)
{
RegisterControlForUpdates(control, delegate (ColorizedResources cr, Control c) { c.BackColor = cr.WorkspaceBackgroundColor; });
}
private class ColorizationUpdateRegistrationHandle<TControl> where TControl : Control
{
private readonly TControl control;
private readonly ControlUpdater<TControl> updater;
public ColorizationUpdateRegistrationHandle(TControl control, ControlUpdater<TControl> updater)
{
this.control = control;
this.updater = updater;
control.Disposed += new EventHandler(ControlDisposedHandler);
GlobalColorizationChanged += new EventHandler(Handler);
}
private void Handler(object sender, EventArgs e)
{
if (ControlHelper.ControlCanHandleInvoke(control))
{
control.BeginInvoke(new EventHandler(Handler2), new object[] { sender, e });
}
}
private void Handler2(object sender, EventArgs e)
{
updater(ColorizedResources.Instance, control);
}
private void ControlDisposedHandler(object sender, EventArgs e)
{
GlobalColorizationChanged -= new EventHandler(Handler);
}
}
private void SystemEvents_UserPreferenceChanged(object sender, Microsoft.Win32.UserPreferenceChangedEventArgs e)
{
OnChange();
}
}
class Colorizer
{
public static Color ColorizeRGB(Color crOld, Color crColorize, int wScale /*= 220*/)
{
// Convert special COL_GrayText value to the system's graytext color.
/*
if (crColorize == COL_GrayText)
{
crColorize = ::GetSysColor(COLOR_GRAYTEXT);
}
*/
// Is the colorize value a flag?
if (Color.Empty == crColorize)
{
// Yes! Then don't colorize. Return old value unchanged.
return crOld;
}
int wLumOld = (Math.Max(crOld.R, Math.Max(crOld.G, crOld.B)) +
Math.Min(crOld.R, Math.Min(crOld.G, crOld.B))) / 2;
if (wScale < wLumOld)
{
byte rColorizeHi = (byte)(255 - crColorize.R);
byte gColorizeHi = (byte)(255 - crColorize.G);
byte bColorizeHi = (byte)(255 - crColorize.B);
int wScaleHi = 255 - wScale;
wLumOld = wLumOld - wScale;
byte rNew = (byte)(crColorize.R + (byte)(rColorizeHi * wLumOld / wScaleHi));
byte gNew = (byte)(crColorize.G + (byte)(gColorizeHi * wLumOld / wScaleHi));
byte bNew = (byte)(crColorize.B + (byte)(bColorizeHi * wLumOld / wScaleHi));
return Color.FromArgb(rNew, gNew, bNew);
}
else
{
byte rNew = (byte)(crColorize.R * wLumOld / wScale);
byte gNew = (byte)(crColorize.G * wLumOld / wScale);
byte bNew = (byte)(crColorize.B * wLumOld / wScale);
return Color.FromArgb(rNew, gNew, bNew);
}
}
public static Color ColorizeARGB(Color crOld, Color crColorize, int wScale)
{
if (Color.Empty == crColorize)
return crOld;
int rNew = crColorize.R;
int gNew = crColorize.G;
int bNew = crColorize.B;
int rNewHi = 255 - rNew;
int gNewHi = 255 - gNew;
int bNewHi = 255 - bNew;
int wScaleHi = 255 - wScale;
// the pixel RGB has been prescaled with alpha
// we need to multiply the scale point and the new color by alpha as well
int wLumAlpha = (Math.Max(crOld.R, Math.Max(crOld.G, crOld.B)) +
Math.Min(crOld.R, Math.Min(crOld.G, crOld.B))) / 2;
int wScaleAlpha = wScale * crOld.A / 255;
if (wScaleAlpha < wLumAlpha)
{
wLumAlpha = wLumAlpha - wScaleAlpha;
// New needs to be scaled by alpha.
// NewHi does not as it is multiplied by the LumAlpha which includes the alpha scaling
return Color.FromArgb(
crOld.A,
(byte)((rNew * crOld.A / 255) + (rNewHi * wLumAlpha / wScaleHi)),
(byte)((gNew * crOld.A / 255) + (gNewHi * wLumAlpha / wScaleHi)),
(byte)((bNew * crOld.A / 255) + (bNewHi * wLumAlpha / wScaleHi)));
}
else
{
// New is multiplied by the LumAlpha which includes the alpha scaling
return Color.FromArgb(
(byte)(rNew * wLumAlpha / wScale),
(byte)(gNew * wLumAlpha / wScale),
(byte)(bNew * wLumAlpha / wScale));
}
}
public static Bitmap ColorizeBitmap(Bitmap bitmap, Color crColorize, int wScale)
{
return ColorizeBitmap(bitmap, crColorize, wScale, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
}
public static Bitmap ColorizeBitmap(Bitmap bitmap, Color crColorize, int wScale, Rectangle colorizeRect)
{
if (crColorize == Color.Empty)
return new Bitmap(bitmap);
Bitmap newBitmap = new Bitmap(bitmap.Width, bitmap.Height, bitmap.PixelFormat);
for (int x = 0; x < bitmap.Width; x++)
{
for (int y = 0; y < bitmap.Height; y++)
{
if (colorizeRect.Contains(x, y))
newBitmap.SetPixel(x, y, ColorizeARGB(bitmap.GetPixel(x, y), crColorize, wScale));
else
newBitmap.SetPixel(x, y, bitmap.GetPixel(x, y));
}
}
return newBitmap;
}
}
}
| |
using Loon.Core.Resource;
using System.IO;
using System.Collections.Generic;
using Loon.Utils.Xml;
using Loon.Utils;
using System;
using Loon.Action.Sprite;
namespace Loon.Core.Graphics.Opengl
{
public class LTextureList : LRelease
{
private readonly int width = LSystem.screenRect.width;
private readonly int height = LSystem.screenRect.height;
private class ImageData
{
public int index;
public int x;
public int y;
public int w;
public int h;
public float scale;
public int scaleType;
public LColor mask;
public string xref;
}
private System.Collections.Generic.Dictionary<string, ImageData> imageList;
public LTextureList(string res)
: this(Resources.OpenStream(res))
{
}
public LTextureList(Stream ins0)
{
this.imageList = new Dictionary<string, ImageData>(10);
this.autoExpand = false;
this.visible = true;
int index = 0;
string x = "x", y = "y", w = "w", h = "h";
string scale = "scale", src = "src", maskName = "mask", empty = "empty";
string name = "name", filterName = "filter", n = "nearest", l = "linear";
XMLDocument doc = XMLParser.Parse(ins0);
List<XMLElement> images = doc.GetRoot().Find("image");
if (images.Count > 0)
{
IEnumerator<XMLElement> it = images.GetEnumerator();
for (; it.MoveNext(); )
{
XMLElement ele = it.Current;
if (ele != null)
{
ImageData data = new ImageData();
data.x = ele.GetIntAttribute(x, 0);
data.y = ele.GetIntAttribute(y, 0);
data.w = ele.GetIntAttribute(w, 0);
data.h = ele.GetIntAttribute(h, 0);
data.scale = ele.GetFloatAttribute(scale, 0);
data.xref = ele.GetAttribute(src, empty);
XMLElement mask = ele.GetChildrenByName(maskName);
if (mask != null)
{
int r = mask.GetIntAttribute("r", 0);
int g = mask.GetIntAttribute("g", 0);
int b = mask.GetIntAttribute("b", 0);
int a = mask.GetIntAttribute("a", 0);
data.mask = new LColor(r, g, b, a);
}
else
{
data.mask = null;
}
string filter = ele.GetAttribute(filterName, n);
if (filter.Equals(n))
{
data.scaleType = 0;
}
if (filter.Equals(l))
{
data.scaleType = 1;
}
data.index = index;
XMLElement parent = ele.GetParent();
if (parent != null)
{
CollectionUtils.Put(imageList, parent.GetAttribute(name, empty), data);
index++;
}
}
}
}
this.count = imageList.Count;
this.values = new LTextureObject[count];
}
public LTexture LoadTexture(string name)
{
if (imageList == null)
{
throw new Exception("Xml data not loaded !");
}
ImageData data = (ImageData)CollectionUtils.Get(imageList, name);
if (data == null)
{
throw new Exception("No such image reference: '" + name
+ "'");
}
if (this.values[data.index] != null)
{
return this.values[data.index].texture;
}
LTexture img = null;
if (data.mask != null)
{
img = TextureUtils.FilterColor(data.xref, data.mask,
data.scaleType == 0 ? Loon.Core.Graphics.Opengl.LTexture.Format.DEFAULT : Loon.Core.Graphics.Opengl.LTexture.Format.LINEAR);
}
else
{
img = LTextures.LoadTexture(data.xref,
data.scaleType == 0 ? Loon.Core.Graphics.Opengl.LTexture.Format.DEFAULT : Loon.Core.Graphics.Opengl.LTexture.Format.LINEAR);
}
if ((data.w != 0) && (data.h != 0))
{
img = img.GetSubTexture(data.x, data.y, data.w, data.h);
}
if (data.scale != 0)
{
img = img.Scale(data.scale);
}
this.values[data.index] = new LTextureObject(img, 0, 0);
return img;
}
public int GetTextureX(string name)
{
return ((ImageData)CollectionUtils.Get(imageList, name)).x;
}
public int GetTextureY(string name)
{
return ((ImageData)CollectionUtils.Get(imageList, name)).y;
}
public int GetTextureWidth(string name)
{
return ((ImageData)CollectionUtils.Get(imageList, name)).w;
}
public int GetTextureHeight(string name)
{
return ((ImageData)CollectionUtils.Get(imageList, name)).h;
}
public float GetTextureScale(string name)
{
return ((ImageData)CollectionUtils.Get(imageList, name)).scale;
}
public sealed class LTextureObject
{
public LTexture texture;
public float x, y;
public int width, height;
public bool visible;
public LTextureObject(LTexture texture, float x, float y)
{
this.texture = texture;
this.x = x;
this.y = y;
this.width = texture.GetWidth();
this.height = texture.GetHeight();
this.visible = true;
}
}
private float alpha = 1;
private bool visible;
private int count = 0;
private readonly bool autoExpand;
internal LTextureObject[] values;
internal float nx, ny;
internal LTextureList(LTextureList tiles)
{
this.autoExpand = tiles.autoExpand;
this.values = (LTextureObject[])CollectionUtils.CopyOf(tiles.values);
this.count = tiles.count;
this.visible = tiles.visible;
}
public LTextureList()
: this(CollectionUtils.INITIAL_CAPACITY)
{
}
public LTextureList(int size)
: this(true, size)
{
}
public LTextureList(bool expand, int size)
{
this.autoExpand = expand;
this.values = new LTextureObject[size];
this.count = size;
this.visible = true;
}
public int add(LTexture tex2d, float x, float y)
{
return Add(new LTextureObject(tex2d, x, y));
}
public int Add(string res, float x, float y)
{
return Add(res, Loon.Core.Graphics.Opengl.LTexture.Format.SPEED, x, y);
}
public int Add(string res, Loon.Core.Graphics.Opengl.LTexture.Format format, float x, float y)
{
return Add(new LTextureObject(LTextures.LoadTexture(res, format), x, y));
}
public int Add(LTextureObject tex2d)
{
if (this.count == this.values.Length)
{
LTextureObject[] oldValue = this.values;
if (this.autoExpand)
this.values = new LTextureObject[(oldValue.Length << 1) + 1];
else
{
this.values = new LTextureObject[oldValue.Length + 1];
}
System.Array.Copy((Array)(oldValue), 0, (Array)(this.values), 0, oldValue.Length);
}
this.values[this.count] = tex2d;
return this.count++;
}
public LTextureObject Remove(int i)
{
if ((i >= this.count) || (i < 0))
{
throw new IndexOutOfRangeException("Referenced " + i + ", size = "
+ this.count.ToString());
}
LTextureObject ret = this.values[i];
if (i < this.count - 1)
{
System.Array.Copy((Array)(this.values), i + 1, (Array)(this.values), i, this.count - i
- 1);
}
this.count -= 1;
return ret;
}
public void AddAll(LTextureObject[] t)
{
Capacity(this.count + t.Length);
System.Array.Copy((Array)(t), 0, (Array)(this.values), this.count, t.Length);
this.count += t.Length;
}
public void AddAll(LTextureList t)
{
Capacity(this.count + t.count);
System.Array.Copy((Array)(t.values), 0, (Array)(this.values), this.count, t.count);
this.count += t.count;
}
public void Draw(GLEx g)
{
Draw(g, 0, 0, width, height);
}
private SpriteBatch batch = new SpriteBatch(1000);
public void Draw(GLEx g, int minX, int minY, int maxX, int maxY)
{
if (!visible)
{
return;
}
lock (values)
{
batch.Begin();
if (alpha > 0 && alpha < 1)
{
batch.SetAlpha(alpha);
}
for (int i = 0; i < count; i++)
{
LTextureObject tex2d = this.values[i];
if (tex2d == null || !tex2d.visible)
{
continue;
}
nx = minX + tex2d.x;
ny = minY + tex2d.y;
if (nx + tex2d.width < minX || nx > maxX
|| ny + tex2d.height < minY || ny > maxY)
{
continue;
}
LTexture texture = tex2d.texture;
if (texture == null)
{
continue;
}
if (tex2d.width != 0 && tex2d.height != 0)
{
batch.Draw(texture, tex2d.x, tex2d.y, tex2d.width,
tex2d.height);
}
else
{
batch.Draw(texture, tex2d.x, tex2d.y);
}
}
if (alpha > 0 && alpha < 1)
{
batch.ResetColor();
}
batch.End();
}
}
public void SetAlpha(float alpha)
{
this.alpha = alpha;
}
public float GetAlpha()
{
return alpha;
}
public bool IsVisible()
{
return visible;
}
public void SetVisible(bool visible)
{
this.visible = visible;
}
public LTextureObject[] Array()
{
return this.values;
}
public int Capacity()
{
return this.values.Length;
}
public void Clear()
{
this.count = 0;
}
public void Capacity(int size)
{
if (this.values.Length >= size)
{
return;
}
LTextureObject[] oldValue = this.values;
this.values = new LTextureObject[size];
System.Array.Copy((Array)(oldValue), 0, (Array)(this.values), 0, oldValue.Length);
}
public LTextureObject Get(int index)
{
return this.values[index];
}
public bool IsEmpty()
{
return this.count == 0;
}
public int Size()
{
return this.count;
}
public virtual LTextureList Clone()
{
return new LTextureList(this);
}
public void Update()
{
if (this.count == this.values.Length)
{
return;
}
LTextureObject[] oldValue = this.values;
this.values = new LTextureObject[this.count];
System.Array.Copy((Array)(oldValue), 0, (Array)(this.values), 0, this.count);
}
public LTextureObject[] ToArray(LTextureObject[] dest)
{
System.Array.Copy((Array)(this.values), 0, (Array)(dest), 0, this.count);
return dest;
}
public void Dispose()
{
this.visible = false;
foreach (LTextureObject tex2d in this.values)
{
if (tex2d != null)
{
if (tex2d.texture != null)
{
tex2d.texture.Destroy();
tex2d.texture = null;
}
}
}
if (batch != null)
{
batch.Dispose();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using DeOps.Implementation.Protocol;
using DeOps.Implementation.Protocol.Net;
using DeOps.Implementation.Dht;
namespace DeOps.Implementation.Transport
{
/// <summary>
/// Summary description for TcpHandler.
/// </summary>
public class TcpHandler
{
// super-classes
public OpCore Core;
public DhtNetwork Network;
Socket ListenSocket;
public ushort ListenPort;
public List<TcpConnect> SocketList = new List<TcpConnect>();
public List<TcpConnect> ProxyServers = new List<TcpConnect>();
public List<TcpConnect> ProxyClients = new List<TcpConnect>();
public Dictionary<ulong, TcpConnect> ProxyMap = new Dictionary<ulong, TcpConnect>();
DateTime LastProxyCheck = new DateTime(0);
int MaxProxyServers = 2;
int MaxProxyNATs = 12;
int MaxProxyBlocked = 6;
public TcpHandler(DhtNetwork network)
{
Network = network;
Core = Network.Core;
Initialize();
}
public void Initialize()
{
ListenPort = Network.IsLookup ? Network.Lookup.Ports.Tcp : Core.User.Settings.TcpPort;
if (Core.Sim != null)
return;
ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
bool bound = false;
int attempts = 0;
while( !bound && attempts < 5)
{
try
{
ListenSocket.Bind( new IPEndPoint( System.Net.IPAddress.Any, ListenPort) );
bound = true;
ListenSocket.Listen(10);
ListenSocket.BeginAccept(new AsyncCallback(ListenSocket_Accept), ListenSocket);
Network.UpdateLog("Core", "Listening for TCP on port " + ListenPort.ToString());
}
catch(Exception ex)
{
Network.UpdateLog("Exception", "TcpHandler::TcpHandler: " + ex.Message);
attempts++;
ListenPort++;
}
}
}
public void Shutdown()
{
if (Core.Sim != null)
return;
try
{
Socket oldSocket = ListenSocket; // do this to prevent listen exception
ListenSocket = null;
if(oldSocket != null)
oldSocket.Close();
lock(SocketList)
foreach(TcpConnect connection in SocketList)
connection.CleanClose("Client shutting down");
}
catch(Exception ex)
{
Network.UpdateLog("Exception", "TcpHandler::Shudown: " + ex.Message);
}
}
public void SecondTimer()
{
// if firewalled find closer proxy
if(Core.Firewall != FirewallType.Open)
if(NeedProxies(ProxyType.Server) || Core.TimeNow > LastProxyCheck.AddSeconds(30))
{
ConnectProxy();
LastProxyCheck = Core.TimeNow;
}
// Run through socket connections
ArrayList deadSockets = new ArrayList();
lock(SocketList)
foreach(TcpConnect socket in SocketList)
{
socket.SecondTimer();
// only let socket linger in connecting state for 10 secs
if( socket.State == TcpState.Closed )
deadSockets.Add(socket);
}
foreach (TcpConnect socket in deadSockets)
{
string message = "Connection to " + socket.ToString() + " Removed";
if (socket.ByeMessage != null)
message += ", Reason: " + socket.ByeMessage;
Network.UpdateLog("Tcp", message);
// socket.TcpSocket = null; causing endrecv to fail on disconnect
lock (SocketList)
SocketList.Remove(socket);
if (ProxyServers.Contains(socket))
ProxyServers.Remove(socket);
if (ProxyClients.Contains(socket))
ProxyClients.Remove(socket);
if (ProxyMap.ContainsKey(socket.RoutingID))
ProxyMap.Remove(socket.RoutingID);
ArrayList removeList = new ArrayList();
// iterate through searches
lock (Network.Searches.Active)
foreach (DhtSearch search in Network.Searches.Active)
// if proxytcp == connection
if (search.ProxyTcp != null && search.ProxyTcp == socket)
{
// if proxytcp == client blocked kill search
if (search.ProxyTcp.Proxy == ProxyType.ClientBlocked)
search.FinishSearch("Proxied client disconnected");
// else if proxy type is server add back to pending proxy list
if (search.ProxyTcp.Proxy == ProxyType.Server)
{
removeList.Add(search);
Network.Searches.Pending.Add(search);
search.Log("Back to Pending, TCP Disconnected");
}
search.ProxyTcp = null;
}
lock (Network.Searches.Active)
foreach (DhtSearch search in removeList)
Network.Searches.Active.Remove(search);
}
}
void ListenSocket_Accept(IAsyncResult asyncResult)
{
if(ListenSocket == null)
return;
try
{
Socket tempSocket = ListenSocket.EndAccept(asyncResult); // do first to catch
OnAccept(tempSocket, (IPEndPoint) tempSocket.RemoteEndPoint);
}
catch(Exception ex)
{
Network.UpdateLog("Exception", "TcpHandler::ListenSocket_Accept:1: " + ex.Message);
}
// exception handling not combined because endreceive can fail legit, still need begin receive to run
try
{
ListenSocket.BeginAccept(new AsyncCallback(ListenSocket_Accept), ListenSocket);
}
catch(Exception ex)
{
Network.UpdateLog("Exception", "TcpHandler::ListenSocket_Accept:2: " + ex.Message);
}
}
public TcpConnect OnAccept(Socket socket, IPEndPoint source)
{
TcpConnect inbound = new TcpConnect(this);
inbound.TcpSocket = socket;
inbound.RemoteIP = source.Address;
inbound.TcpPort = (ushort)source.Port; // zero if internet, actual value if sim
inbound.SetConnected();
// it's not until the host sends us traffic that we can send traffic back because we don't know
// connecting node's dhtID (and hence encryption key) until ping is sent
lock (SocketList)
SocketList.Add(inbound);
Network.UpdateLog("Tcp", "Accepted Connection from " + inbound.ToString());
return inbound;
}
public void MakeOutbound( DhtAddress address, ushort tcpPort, string reason)
{
try
{
int connecting = 0;
// check if already connected
lock(SocketList)
foreach (TcpConnect socket in SocketList)
{
if (socket.State == TcpState.Connecting)
connecting++;
if (socket.State != TcpState.Closed &&
address.IP.Equals(socket.RemoteIP) &&
tcpPort == socket.TcpPort &&
socket.Outbound) // allows check firewall to work
return;
}
if (connecting > 6)
{
Debug.Assert(true);
return;
}
TcpConnect outbound = new TcpConnect(this, address, tcpPort);
Network.UpdateLog("Tcp", "Attempting Connection to " + address.ToString() + ":" + tcpPort.ToString() + " (" + reason + ")");
lock(SocketList)
SocketList.Add(outbound);
}
catch(Exception ex)
{
Network.UpdateLog("Exception", "TcpHandler::MakeOutbound: " + ex.Message);
}
}
void ConnectProxy()
{
// Get cloest contacts and sort by distance to us
DhtContact attempt = null;
// no Dht contacts, use ip cache will be used to connect tcp/udp in DoBootstrap
// find if any contacts in list are worth trying (will be skipped if set already)
// get closest contact that is not already connected
foreach (DhtContact contact in Network.Routing.NearXor.Contacts)
// if havent tried in 10 minutes
if (Core.TimeNow > contact.NextTryProxy && contact.TunnelClient == null)
{
bool connected = false;
lock (SocketList)
foreach (TcpConnect socket in SocketList)
if (contact.UserID == socket.UserID && contact.ClientID == socket.ClientID)
{
connected = true;
break;
}
if(connected)
continue;
if (attempt == null || (contact.UserID ^ Network.Local.UserID) < (attempt.UserID ^ Network.Local.UserID))
attempt = contact;
}
if(attempt != null)
{
// take into account when making proxy request, disconnct furthest
if(Core.Firewall == FirewallType.Blocked)
{
// continue attempted to test nat with pings which are small
Network.Send_Ping(attempt);
MakeOutbound( attempt, attempt.TcpPort, "try proxy");
}
// if natted do udp proxy request first before connect
else if(Core.Firewall == FirewallType.NAT)
{
ProxyReq request = new ProxyReq();
request.SenderID = Network.Local.UserID;
request.Type = ProxyType.ClientNAT;
Network.UdpControl.SendTo( attempt, request);
}
attempt.NextTryProxy = Core.TimeNow.AddMinutes(10);
}
}
public bool NeedProxies(ProxyType type)
{
int count = 0;
lock(SocketList)
foreach(TcpConnect connection in SocketList)
if(connection.Proxy == type)
count++;
// count of proxy servers connected to, (we are firewalled)
if(type == ProxyType.Server && count < MaxProxyServers)
return true;
// count of proxy clients connected to, (we are open)
if(type == ProxyType.ClientBlocked && count < MaxProxyBlocked)
return true;
if(type == ProxyType.ClientNAT && count < MaxProxyNATs)
return true;
return false;
}
public bool ProxiesMaxed()
{
// we're not firewalled
if( Core.Firewall == FirewallType.Open)
{
if( NeedProxies(ProxyType.ClientBlocked) )
return false;
if( NeedProxies(ProxyType.ClientNAT) )
return false;
}
// we are firewalled
else
{
if( NeedProxies(ProxyType.Server) )
return false;
}
return true;
}
public bool AcceptProxy(ProxyType type, UInt64 targetID)
{
if( NeedProxies(type) )
return true;
// else go through proxies, determine if targetid is closer than proxies already hosted
lock(SocketList)
foreach(TcpConnect connection in SocketList)
if(connection.Proxy == type)
// if closer than at least 1 contact
if ((targetID ^ Network.Local.UserID) < (connection.UserID ^ Network.Local.UserID) || targetID == connection.UserID)
{
return true;
}
return false;
}
public void CheckProxies()
{
CheckProxies(ProxyType.Server, MaxProxyServers);
CheckProxies(ProxyType.ClientNAT, MaxProxyNATs);
CheckProxies(ProxyType.ClientBlocked, MaxProxyBlocked);
}
void CheckProxies(ProxyType type, int max)
{
/*if (type == ProxyType.Server && Core.Sim.RealFirewall != FirewallType.Open)
{
int x = 0;
// count number of connected servers, if too many break
foreach (TcpConnect connection in SocketList)
if (connection.Proxy == type)
x++;
if (x > 2)
{
int y = 0;
y++;
}
}*/
TcpConnect furthest = null;
UInt64 distance = 0;
int count = 0;
lock(SocketList)
foreach(TcpConnect connection in SocketList)
if (connection.State == TcpState.Connected && connection.Proxy == type)
{
count++;
if ((connection.UserID ^ Network.Local.UserID) > distance)
{
distance = connection.UserID ^ Network.Local.UserID;
furthest = connection;
}
}
// greater than max, disconnect furthest
if(count > max && furthest != null)
furthest.CleanClose("Too many proxies, disconnecting furthest");
}
public void Receive_Bye(G2ReceivedPacket packet)
{
Bye bye = Bye.Decode(packet);
foreach(DhtContact contact in bye.ContactList)
Network.Routing.Add(contact);
string message = (bye.Message != null) ? bye.Message : "";
packet.Tcp.ByeMessage = "Remote: " + message;
Network.UpdateLog("Tcp", "Bye Received from " + packet.Tcp.ToString() + " " + message);
// close connection
packet.Tcp.Disconnect();
// reconnect
if (bye.Reconnect && NeedProxies(ProxyType.Server))
MakeOutbound(packet.Source, packet.Tcp.TcpPort, "Reconnecting");
}
public TcpConnect GetRandomProxy()
{
if (ProxyServers.Count == 0)
return null;
return ProxyServers[Core.RndGen.Next(ProxyServers.Count)];
}
public int SendRandomProxy(G2Packet packet)
{
TcpConnect socket = GetRandomProxy();
return (socket != null) ? socket.SendPacket(packet) : 0;
}
public void AddProxy(TcpConnect socket)
{
if (ProxyMap.ContainsKey(socket.RoutingID))
return;
ProxyMap[socket.RoutingID] = socket;
if (socket.Proxy == ProxyType.Server)
ProxyServers.Add(socket);
else
ProxyClients.Add(socket);
}
public TcpConnect GetProxy(DhtClient client)
{
if (client == null)
return null;
return GetProxy(client.UserID, client.ClientID);
}
public TcpConnect GetProxy(ulong user, ushort client)
{
TcpConnect proxy;
if(ProxyMap.TryGetValue(user ^ client, out proxy))
if(proxy.State == TcpState.Connected && proxy.Proxy != ProxyType.Unset)
return proxy;
return null;
}
public TcpConnect GetProxyServer(IPAddress ip)
{
if (ip == null)
return null;
foreach (TcpConnect server in ProxyServers)
if (server.RemoteIP.Equals(ip))
return server;
return null;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
using osu.Framework.Development;
using osu.Framework.Threading;
namespace osu.Framework.Tests.Audio
{
[TestFixture]
public class TrackVirtualTest
{
private TrackVirtual track;
[SetUp]
public void Setup()
{
track = new TrackVirtual(60000);
updateTrack();
}
[Test]
public void TestStart()
{
track.Start();
updateTrack();
Thread.Sleep(50);
updateTrack();
Assert.IsTrue(track.IsRunning);
Assert.Greater(track.CurrentTime, 0);
}
[Test]
public void TestStartZeroLength()
{
// override default with custom length
track = new TrackVirtual(0);
track.Start();
updateTrack();
Thread.Sleep(50);
Assert.IsTrue(!track.IsRunning);
Assert.AreEqual(0, track.CurrentTime);
}
[Test]
public void TestStop()
{
track.Start();
track.Stop();
updateTrack();
Assert.IsFalse(track.IsRunning);
double expectedTime = track.CurrentTime;
Thread.Sleep(50);
Assert.AreEqual(expectedTime, track.CurrentTime);
}
[Test]
public void TestStopAtEnd()
{
startPlaybackAt(track.Length - 1);
Thread.Sleep(50);
updateTrack();
track.Stop();
updateTrack();
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(track.Length, track.CurrentTime);
}
[Test]
public void TestSeek()
{
track.Seek(1000);
updateTrack();
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(1000, track.CurrentTime);
}
[Test]
public void TestSeekWhileRunning()
{
track.Start();
track.Seek(1000);
updateTrack();
Assert.IsTrue(track.IsRunning);
Assert.GreaterOrEqual(track.CurrentTime, 1000);
}
[Test]
public void TestSeekBackToSamePosition()
{
track.Seek(1000);
track.Seek(0);
updateTrack();
Thread.Sleep(50);
updateTrack();
Assert.GreaterOrEqual(track.CurrentTime, 0);
Assert.Less(track.CurrentTime, 1000);
}
[Test]
public void TestPlaybackToEnd()
{
startPlaybackAt(track.Length - 1);
Thread.Sleep(50);
updateTrack();
Assert.IsFalse(track.IsRunning);
Assert.AreEqual(track.Length, track.CurrentTime);
}
/// <summary>
/// Bass restarts the track from the beginning if Start is called when the track has been completed.
/// This is blocked locally in <see cref="TrackVirtual"/>, so this test expects the track to not restart.
/// </summary>
[Test]
public void TestStartFromEndDoesNotRestart()
{
startPlaybackAt(track.Length - 1);
Thread.Sleep(50);
updateTrack();
track.Start();
updateTrack();
Assert.AreEqual(track.Length, track.CurrentTime);
}
[Test]
public void TestRestart()
{
startPlaybackAt(1000);
Thread.Sleep(50);
updateTrack();
restartTrack();
Assert.IsTrue(track.IsRunning);
Assert.Less(track.CurrentTime, 1000);
}
[Test]
public void TestRestartAtEnd()
{
startPlaybackAt(track.Length - 1);
Thread.Sleep(50);
updateTrack();
restartTrack();
Assert.IsTrue(track.IsRunning);
Assert.LessOrEqual(track.CurrentTime, 1000);
}
[Test]
public void TestRestartFromRestartPoint()
{
track.RestartPoint = 1000;
startPlaybackAt(3000);
restartTrack();
Assert.IsTrue(track.IsRunning);
Assert.GreaterOrEqual(track.CurrentTime, 1000);
Assert.Less(track.CurrentTime, 3000);
}
[Test]
public void TestLoopingRestart()
{
track.Looping = true;
startPlaybackAt(track.Length - 1);
Thread.Sleep(50);
// The first update brings the track to its end time and restarts it
updateTrack();
// The second update updates the IsRunning state
updateTrack();
// In a perfect world the track will be running after the update above, but during testing it's possible that the track is in
// a stalled state due to updates running on Bass' own thread, so we'll loop until the track starts running again
// Todo: This should be fixed in the future if/when we invoke Bass.Update() ourselves
int loopCount = 0;
while (++loopCount < 50 && !track.IsRunning)
{
updateTrack();
Thread.Sleep(10);
}
if (loopCount == 50)
throw new TimeoutException("Track failed to start in time.");
Assert.LessOrEqual(track.CurrentTime, 1000);
}
[Test]
public void TestSetTempoNegative()
{
Assert.IsFalse(track.IsReversed);
track.Tempo.Value = 0.05f;
Assert.IsFalse(track.IsReversed);
Assert.AreEqual(0.05f, track.Tempo.Value);
}
[Test]
public void TestRateWithAggregateTempoAdjustments()
{
track.AddAdjustment(AdjustableProperty.Tempo, new BindableDouble(1.5f));
Assert.AreEqual(1.5, track.Rate);
testPlaybackRate(1.5);
}
[Test]
public void TestRateWithAggregateFrequencyAdjustments()
{
track.AddAdjustment(AdjustableProperty.Frequency, new BindableDouble(1.5f));
Assert.AreEqual(1.5, track.Rate);
testPlaybackRate(1.5);
}
[Test]
public void TestCurrentTimeUpdatedAfterInlineSeek()
{
track.Start();
updateTrack();
RunOnAudioThread(() => track.Seek(20000));
Assert.That(track.CurrentTime, Is.EqualTo(20000).Within(100));
}
[Test]
public void TestSeekToCurrentTime()
{
track.Seek(5000);
bool seekSucceeded = false;
RunOnAudioThread(() => seekSucceeded = track.Seek(track.CurrentTime));
Assert.That(seekSucceeded, Is.True);
Assert.That(track.CurrentTime, Is.EqualTo(5000));
}
[Test]
public void TestSeekBeyondStartTime()
{
bool seekSucceeded = false;
RunOnAudioThread(() => seekSucceeded = track.Seek(-1000));
Assert.That(seekSucceeded, Is.False);
Assert.That(track.CurrentTime, Is.EqualTo(0));
}
[Test]
public void TestSeekBeyondEndTime()
{
bool seekSucceeded = false;
RunOnAudioThread(() => seekSucceeded = track.Seek(track.Length + 1000));
Assert.That(seekSucceeded, Is.False);
Assert.That(track.CurrentTime, Is.EqualTo(track.Length));
}
private void testPlaybackRate(double expectedRate)
{
const double play_time = 1000;
const double fudge = play_time * 0.1;
track.Start();
var sw = new Stopwatch();
sw.Start();
while (sw.ElapsedMilliseconds < play_time)
{
Thread.Sleep(50);
track.Update();
}
sw.Stop();
Assert.GreaterOrEqual(track.CurrentTime, sw.ElapsedMilliseconds * expectedRate - fudge);
Assert.LessOrEqual(track.CurrentTime, sw.ElapsedMilliseconds * expectedRate + fudge);
}
private void startPlaybackAt(double time)
{
track.Seek(time);
track.Start();
updateTrack();
}
private void updateTrack() => RunOnAudioThread(() => track.Update());
private void restartTrack()
{
RunOnAudioThread(() =>
{
track.Restart();
track.Update();
});
}
/// <summary>
/// Certain actions are invoked on the audio thread.
/// Here we simulate this process on a correctly named thread to avoid endless blocking.
/// </summary>
/// <param name="action">The action to perform.</param>
public static void RunOnAudioThread(Action action)
{
var resetEvent = new ManualResetEvent(false);
new Thread(() =>
{
ThreadSafety.IsAudioThread = true;
action();
resetEvent.Set();
})
{
Name = GameThread.PrefixedThreadNameFor("Audio")
}.Start();
if (!resetEvent.WaitOne(TimeSpan.FromSeconds(10)))
throw new TimeoutException();
}
}
}
| |
//
// Button sample in C#v
//
using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System.Drawing;
public partial class ButtonsViewController : UITableViewController {
//
// This datasource describes how the UITableView should render the
// contents. We have a number of sections determined by the
// samples in our container class, and 2 rows per section:
//
// Row 0: the actual styled button
// Row 1: the text information about the button
//
class DataSource : UITableViewDataSource {
ButtonsViewController bvc;
static NSString kDisplayCell_ID = new NSString ("DisplayCellID");
static NSString kSourceCell_ID = new NSString ("SourceCellID");
public DataSource (ButtonsViewController bvc)
{
this.bvc = bvc;
}
public override int NumberOfSections (UITableView tableView)
{
return bvc.samples.Length;
}
public override string TitleForHeader (UITableView tableView, int section)
{
return bvc.samples [section].Title;
}
public override int RowsInSection (UITableView tableView, int section)
{
return 2;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell;
if (indexPath.Row == 0){
cell = tableView.DequeueReusableCell (kDisplayCell_ID);
if (cell == null){
cell = new UITableViewCell (UITableViewCellStyle.Default, kDisplayCell_ID);
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
} else {
// The cell is being recycled, remove the old content
UIView viewToRemove = cell.ContentView.ViewWithTag (kViewTag);
if (viewToRemove != null)
viewToRemove.RemoveFromSuperview ();
}
cell.TextLabel.Text = bvc.samples [indexPath.Section].Label;
cell.ContentView.AddSubview (bvc.samples [indexPath.Section].Button);
} else {
cell = tableView.DequeueReusableCell (kSourceCell_ID);
if (cell == null){
// Construct the cell with reusability (the second argument is not null)
cell = new UITableViewCell (UITableViewCellStyle.Default, kSourceCell_ID);
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
var label = cell.TextLabel;
label.Opaque = false;
label.TextAlignment = UITextAlignment.Center;
label.TextColor = UIColor.Gray;
label.Lines = 2;
label.HighlightedTextColor = UIColor.Black;
label.Font = UIFont.SystemFontOfSize (12f);
}
cell.TextLabel.Text = bvc.samples [indexPath.Section].Source;
}
return cell;
}
}
class TableDelegate : UITableViewDelegate {
//
// Override to provide the sizing of the rows in our table
//
public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
// First row is always 50 pixes, second row 38
return indexPath.Row == 0 ? 50f : 38f;
}
}
// Load our definition from the NIB file
public ButtonsViewController () : base ("ButtonsViewController", null)
{
}
// For tagging our embedded controls at cell recylce time.
const int kViewTag = 1;
//
// Utility function that configures the various buttons that we create
//
static UIButton ButtonWithTitle (string title, RectangleF frame, UIImage image, UIImage imagePressed, bool darkTextColor)
{
var button = new UIButton (frame) {
VerticalAlignment = UIControlContentVerticalAlignment.Center,
HorizontalAlignment = UIControlContentHorizontalAlignment.Center,
BackgroundColor = UIColor.Clear
};
button.SetTitle (title, UIControlState.Normal);
if (darkTextColor)
button.SetTitleColor (UIColor.Black, UIControlState.Normal);
else
button.SetTitleColor (UIColor.White, UIControlState.Normal);
var newImage = image.StretchableImage (12, 0);
button.SetBackgroundImage (newImage, UIControlState.Normal);
var newPressedImage = image.StretchableImage (12, 0);
button.SetBackgroundImage (newPressedImage, UIControlState.Highlighted);
button.Tag = kViewTag; // To support reusable cells
button.TouchDown += delegate {
Console.WriteLine ("The button has been touched");
};
return button;
}
UIButton GrayButton ()
{
var background = UIImage.FromFile ("whiteButton.png");
var backgroundPressed = UIImage.FromFile ("blueButton.png");
var frame = new RectangleF (182f, 5f, 106f, 40f);
return ButtonWithTitle ("Gray", frame, background, backgroundPressed, true);
}
UIButton ImageButton ()
{
var background = UIImage.FromFile ("whiteButton.png");
var backgroundPressed = UIImage.FromFile ("blueButton.png");
var frame = new RectangleF (182f, 5f, 106f, 40f);
var button = ButtonWithTitle ("", frame, background, backgroundPressed, true);
button.SetImage (UIImage.FromFile ("UIButton_custom.png"), UIControlState.Normal);
return button;
}
UIButton RoundedButtonType ()
{
var button = UIButton.FromType (UIButtonType.RoundedRect);
button.Frame = new RectangleF (182f, 5f, 106f, 40f);
button.BackgroundColor = UIColor.Clear;
button.SetTitle ("Rounded", UIControlState.Normal);
button.Tag = kViewTag; // To support reusable cells
return button;
}
UIButton DetailDisclosureButton ()
{
var button = UIButton.FromType (UIButtonType.DetailDisclosure);
button.Frame = new RectangleF (250f, 8f, 25f, 25f);
button.BackgroundColor = UIColor.Clear;
button.SetTitle ("Detail Disclosure", UIControlState.Normal);
button.Tag = kViewTag; // To support reusable cells
return button;
}
UIButton InfoDarkButtonType ()
{
var button = UIButton.FromType (UIButtonType.InfoDark);
button.Frame = new RectangleF (250, 8f, 25f, 25f);
button.BackgroundColor = UIColor.Clear;
button.SetTitle ("Detail Disclosure", UIControlState.Normal);
button.Tag = kViewTag; // To support reusable cells
return button;
}
UIButton InfoLightButtonType ()
{
var button = UIButton.FromType (UIButtonType.InfoLight);
button.Frame = new RectangleF (250, 8f, 25f, 25f);
button.BackgroundColor = UIColor.Gray;
button.SetTitle ("Detail Disclosure", UIControlState.Normal);
button.Tag = kViewTag; // To support reusable cells
return button;
}
UIButton ContactAddButtonType ()
{
var button = UIButton.FromType (UIButtonType.ContactAdd);
button.Frame = new RectangleF (250, 8f, 25f, 25f);
button.BackgroundColor = UIColor.Clear;
button.SetTitle ("Detail Disclosure", UIControlState.Normal);
button.Tag = kViewTag; // To support reusable cells
return button;
}
struct ButtonSample {
public string Title, Label, Source;
public UIButton Button;
public ButtonSample (string t, string l, string s, UIButton b)
{
Title = t;
Label = l;
Source = s;
Button = b;
}
}
ButtonSample [] samples;
public override void ViewDidLoad ()
{
Console.WriteLine ("Buttons: View Did Load - FIrst");
base.ViewDidLoad ();
Title = "Buttons";
samples = new ButtonSample [] {
new ButtonSample ("UIButton", "Background image", "buttons.cs:\rUIButton GrayButton ()", GrayButton ()),
new ButtonSample ("UIButton", "Button with image", "buttons.cs:\rUIButton ImageButton ()", ImageButton ()),
new ButtonSample ("UIButtonRoundedRect", "Rounded Button", "buttons.cs:\rUIButton RoundedButtonType ()", RoundedButtonType ()),
new ButtonSample ("UIButtonTypeDetailDisclosure", "Detail disclosure", "buttons.cs:\rUIButton DetailDisclosureButton ()", DetailDisclosureButton ()),
new ButtonSample ("UIButtonTypeInfoLight", "Info light", "buttons.cs:\rUIButton InfoLightButtonType ()", InfoLightButtonType ()),
new ButtonSample ("UIButtonTypeInfoDark", "Info dark", "buttons.cs:\rUIButton InfoLightButtonType ()", InfoDarkButtonType ()),
new ButtonSample ("UIButtonTypeContactAdd", "Contact Add", "buttons.cs:\rUIButton ContactAddButtonType ()", ContactAddButtonType ())
};
TableView.DataSource = new DataSource (this);
TableView.Delegate = new TableDelegate ();
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace BotSuite.ImageLibrary
{
/// <summary>
/// collection of common functions
/// </summary>
public static class CommonFunctions
{
/// <summary>
/// Tests if the colors are similar.
/// </summary>
/// <remarks>
/// the tolerance has to be within the interval 0..255 and no bigger difference in each color channel is allowed
/// </remarks>
/// <example>
/// <code>
/// <![CDATA[
/// Color A = Color.White;
/// Color B = Color.Blue;
/// bool similar = CommonFunctions.ColorsSimilar(A,B,50);
/// bool match = CommonFunctions.ColorsSimilar(A,B,0);
/// ]]>
/// </code>
/// </example>
/// <param name="one">Color A</param>
/// <param name="two">Color B</param>
/// <param name="tolerance">Tolerance (0,...,255)</param>
/// <returns>Similar or not</returns>
public static Boolean ColorsSimilar(Color one, Color two, uint tolerance)
{
if (Math.Abs(one.R - two.R) > tolerance)
return false;
if (Math.Abs(one.G - two.G) > tolerance)
return false;
if (Math.Abs(one.B - two.B) > tolerance)
return false;
return true;
}
/// <summary>
/// Gets the average RGB values from a given rectangle in an image
/// By default the average RGB values from the whole image are calculated
/// </summary>
/// <remarks>
/// to detect the color of bubbles or coins this function can be helpful in connection with IdentifyColor()
/// </remarks>
/// <example>
/// <code>
/// <![CDATA[
/// ImageData Img = new ImageData(...);
/// // average color in whole image
/// double[] AverageColor = CommonFunctions.AverageRGBValues(img);
/// int left = 0;
/// int top = 5;
/// // average color in clipped image
/// double[] AverageColorShifted = CommonFunctions.AverageRGBValues(img,left,top);
/// int width = 50;
/// int height = 100;
/// // average color in predefined rectangle
/// double[] AverageColorRectangle = CommonFunctions.AverageRGBValues(img,left,top,width,height);
/// ]]>
/// </code>
/// </example>
/// <param name="img">The image to process</param>
/// <param name="left">The left of the rectangle (default=0)</param>
/// <param name="top">The top of the rectangle (default=0)</param>
/// <param name="width">The width of the rectangle (default=full width)</param>
/// <param name="height">The height of the rectangle (default=full height)</param>
/// <returns>The average RGB values</returns>
public static double[] AverageRGBValues(ImageData img, int left = 0, int top = 0, int width = -1,
int height = -1)
{
long[] totals = {0, 0, 0};
if (width == -1)
width = img.Width;
if (height == -1)
height = img.Height;
for (int x = left; x < left + width; x++)
{
for (int y = top; y < top + height; y++)
{
Color currentColor = img.GetPixel(x, y);
totals[0] += currentColor.R;
totals[1] += currentColor.G;
totals[2] += currentColor.B;
}
}
int count = width*height;
double[] retvar = {(totals[0]/(double) count), (totals[1]/(double) count), (totals[2]/(double) count)};
return retvar;
}
/// <summary>
/// Gets the average color from an image in a given rectangle
/// By default the the average color from the whole image is calculated
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ImageData Img = new ImageData(...);
/// // average color in whole image
/// double[] AverageColor = CommonFunctions.AverageRGBValues(img);
/// // average color in predefined rectangle
/// Color AverageColorInRectangle = CommonFunctions.AverageRGBValues(img,left,top,width,height);
/// ]]>
/// </code>
/// </example>
/// <param name="img">The image to process</param>
/// <param name="left">The left of the rectangle (default=0)</param>
/// <param name="top">The top of the rectangle (default=0)</param>
/// <param name="width">The width of the rectangle (default=full width)</param>
/// <param name="height">The height of the rectangle (default=full height)</param>
/// <returns>average color</returns>
public static Color AverageColor(ImageData img, int left = 0, int top = 0, int width = -1, int height = -1)
{
double[] retvar = AverageRGBValues(img, left, top, width, height);
return Color.FromArgb(Convert.ToInt32(retvar[0]), Convert.ToInt32(retvar[1]), Convert.ToInt32(retvar[2]));
}
/// <summary>
/// Calculates the similarity of image "img" in a given rectangle and a reference image "reference"
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ImageData Screenshot = new ImageData(...);
/// ImageData Coin = new ImageData(...);
/// // do magic or using a clipped region of screenshot (500px from left and 100px from top)
/// int left_region = 500;
/// int top_region = 100;
/// double measure = Similarity(Screenshot,Coin,left_region,top_region);
/// ]]>
/// </code>
/// </example>
/// <param name="img">Image A</param>
/// <param name="reference">Image B</param>
/// <param name="left">The offset from left of image A</param>
/// <param name="top">The offset from top of image A</param>
/// <param name="width">The width of the rectangle (default: full width)</param>
/// <param name="height">The height of the rectangle (default: full height)</param>
/// <param name="offsetLeft">The left offset</param>
/// <param name="offsetTop">The top offset</param>
/// <returns>The similarity result (1=exact, 0=none)</returns>
public static double Similarity(ImageData img, ImageData reference, int left = 0, int top = 0, int width = -1,
int height = -1, int offsetLeft = 0, int offsetTop = 0)
{
double sim = 0.0;
width = (width == -1) ? img.Width - left : width;
height = (height == -1) ? img.Height - top : height;
if ((img.Width == reference.Width) && (img.Height == reference.Height))
{
for (Int32 column = left; column < left + width; column++)
{
for (Int32 row = top; row < top + height; row++)
{
Color a = img.GetPixel(offsetLeft + column, offsetTop + row);
Color b = reference.GetPixel(column, row);
int cr = Math.Abs(a.R - b.R);
int cg = Math.Abs(a.G - b.G);
int cb = Math.Abs(a.B - b.B);
sim += (cr + cg + cb)/3; //TODO: Fix possible loss of fraction
}
}
sim /= 255.0;
sim /= (img.Height*img.Width);
}
return 1 - sim;
}
/// <summary>
/// Identifies the colors of the pixels in a rectangle from an image by a given list of
/// reference colors (root means square error
/// from average)
/// </summary>
/// <remarks>
/// if the color differs sometimes you can use this function to find the best matching colors in a dictionary list.
/// In most you do not need to know the exact rgb values. You only wants to know whether the rectangle is more likely to the color
/// red, blue, rgb(?,?,?), ....
///
/// this functions maps the result to the correct color. If the image contains a pale red and you want to identify this as #ff0000
/// you have to add the pair (#FF8C8C "pale red", #FF0000)
///
/// This uses the RMSE root mean square error to find the best color.
/// Attention! If there are some pixel that have to complete other colors, they can destroy the accurately
/// see: IdentifyColorByVoting
/// </remarks>
/// <example>
/// <code>
/// <![CDATA[
/// ImageData Screenshot = new ImageData(...);
/// Dictionary<Color, List<double>> Choose = new Dictionary<Color, List<double>> ();
/// Choose.Add(Color.Red, new List<double> { 255, 144.23, 140.89 });
/// Choose.Add(Color.White, new List<double> { 218, 219, 222 });
/// Choose.Add(Color.Blue, new List<double> { 21, 108, 182 });
/// Choose.Add(Color.Green, new List<double> { 86, 191, 50 });
/// Choose.Add(Color.Yellow, new List<double> { 233, 203, 118 });
/// Choose.Add(Color.Orange, new List<double> { 246, 122, 11 });
/// Choose.Add(Color.Black, new List<double> { 94, 98, 98 });
/// Choose.Add(Color.Violet, new List<double> { 223, 80, 195 });
/// Choose.Add(Color.MediumSeaGreen, new List<double> { 106, 227, 216 });
/// // ...
/// Color PieceColor = CommonFunctions.IdentifyColor(Screenshot,Choose,leftoffset,topoffset,width,height);
/// ]]>
/// </code>
/// </example>
/// <param name="img">The image that should be analyzed</param>
/// <param name="statReference">The list of possible colors</param>
/// <param name="left">The left of the rectangle (default: 0)</param>
/// <param name="top">The top of the rectangle (default: 0)</param>
/// <param name="width">The width of the rectangle (default: full width)</param>
/// <param name="height">The height of the rectangle (default: full height)</param>
/// <returns>The best matching color</returns>
public static Color IdentifyColor(ImageData img, Dictionary<Color, List<double>> statReference, int left = 0,
int top = 0, int width = -1, int height = -1)
{
double[] av = AverageRGBValues(img, left, top, width, height);
double bestScore = 255;
Color foo = Color.White;
foreach (var item in statReference)
{
double currentScore = Math.Pow((item.Value[0]/255.0) - (av[0]/255.0), 2)
+ Math.Pow((item.Value[1]/255.0) - (av[1]/255.0), 2)
+ Math.Pow((item.Value[2]/255.0) - (av[2]/255.0), 2);
if (currentScore < bestScore)
{
foo = item.Key;
bestScore = currentScore;
}
}
return foo;
}
/// <summary>
/// Identifies the colors of the pixels in a rectangle and compares them with those from an image by a given list of
/// reference colors (majority vote)
/// </summary>
/// <remarks>
/// This tests every pixel in the given rectangle and majority votes the color from the given dictionary of possible
/// colors. Each pixel votes for a color.
///
/// if the image patch is
///
/// " red red "
/// " red blue "
///
/// then 4 pixels vote for similary colors to red and one pixel votes for a similar color to blue
///
/// </remarks>
/// <example>
/// <code>
/// <![CDATA[
/// ImageData Screenshot = new ImageData(...);
/// Dictionary<Color, List<double>> Choose = new Dictionary<Color, List<double>> ();
/// Choose.Add(Color.Red, new List<double> { 255, 144.23, 140.89 });
/// Choose.Add(Color.White, new List<double> { 218, 219, 222 });
/// Choose.Add(Color.Blue, new List<double> { 21, 108, 182 });
/// Choose.Add(Color.Green, new List<double> { 86, 191, 50 });
/// Choose.Add(Color.Yellow, new List<double> { 233, 203, 118 });
/// Choose.Add(Color.Orange, new List<double> { 246, 122, 11 });
/// Choose.Add(Color.Black, new List<double> { 94, 98, 98 });
/// Choose.Add(Color.Violet, new List<double> { 223, 80, 195 });
/// Choose.Add(Color.MediumSeaGreen, new List<double> { 106, 227, 216 });
/// // ...
/// Color PieceColor = CommonFunctions.IdentifyColorByVoting(Screenshot,Choose,leftoffset,topoffset,width,height);
/// ]]>
/// </code>
/// </example>
/// <param name="img">The image to look in</param>
/// <param name="statReference">The list of possible colors</param>
/// <param name="left">The left of the rectangle (default: 0)</param>
/// <param name="top">The top of the rectangle (default: 0)</param>
/// <param name="width">The width of the rectangle (default: full width)</param>
/// <param name="height">The height of the rectangle (default: full height)</param>
/// <returns>The best matching color</returns>
public static Color IdentifyColorByVoting(ImageData img, Dictionary<Color, List<double>> statReference,
int left = 0, int top = 0, int width = -1, int height = -1)
{
int[] votes = Enumerable.Repeat(0, statReference.Count).ToArray();
if (width == -1)
width = img.Width;
if (height == -1)
height = img.Height;
for (int x = left; x < left + width; x++)
{
for (int y = top; y < top + height; y++)
{
// color from image
Color currentColor = img.GetPixel(x, y);
int bestDist = 255*50;
int bestIndex = 0;
for (int i = 0; i < statReference.Count; i++)
{
List<double> RGB = statReference.ElementAt(i).Value;
// from from dictionary
Color cCol = Color.FromArgb(Convert.ToInt32(RGB.ElementAt(0)), Convert.ToInt32(RGB.ElementAt(1)),
Convert.ToInt32(RGB.ElementAt(2)));
// distance
int currentDist = Math.Abs(cCol.R - currentColor.R) + Math.Abs(cCol.G - currentColor.G) +
Math.Abs(cCol.B - currentColor.B);
if (currentDist < bestDist)
{
bestDist = currentDist;
bestIndex = i;
}
}
votes[bestIndex]++;
}
}
// this is faster than LINQ
int m = -1;
int ans = 0;
for (int i = 0; i < votes.Length; i++)
{
if (votes[i] > m)
{
m = votes[i];
ans = i;
}
}
return statReference.ElementAt(ans).Key;
}
/// <summary>
/// Identifies the best matching color from a list of colors
/// </summary>
/// <remarks>
/// In the example the color #FF8C8C "pale red" would be identify as red
/// </remarks>
/// <example>
/// <code>
/// <![CDATA[
/// Dictionary<Color, List<double>> Choose = new Dictionary<Color, List<double>> ();
/// Choose.Add(Color.Red, new List<double> { 255, 0, 0 });
/// Choose.Add(Color.White, new List<double> { 218, 219, 222 });
/// Choose.Add(Color.Blue, new List<double> { 21, 108, 182 });
/// Choose.Add(Color.Green, new List<double> { 86, 191, 50 });
/// Choose.Add(Color.Yellow, new List<double> { 233, 203, 118 });
/// Choose.Add(Color.Orange, new List<double> { 246, 122, 11 });
/// Choose.Add(Color.Black, new List<double> { 94, 98, 98 });
/// Choose.Add(Color.Violet, new List<double> { 223, 80, 195 });
/// Choose.Add(Color.MediumSeaGreen, new List<double> { 106, 227, 216 });
/// // ...
/// Color PieceColor = CommonFunctions.IdentifyColor(Color.FromArgb(255,140,140),Choose);
/// ]]>
/// </code>
/// </example>
/// <param name="givenColor">The color to look for</param>
/// <param name="statReference">The list of colors</param>
/// <returns>The best matching color from the list</returns>
public static Color IdentifyColor(Color givenColor, Dictionary<Color, List<double>> statReference)
{
var av = new double[] {givenColor.R, givenColor.G, givenColor.B};
double bestScore = 255;
Color foo = Color.White;
foreach (var item in statReference)
{
double currentScore = Math.Abs((item.Value[0]/255.0) - (av[0]/255.0))
+ Math.Abs((item.Value[1]/255.0) - (av[1]/255.0))
+ Math.Abs((item.Value[2]/255.0) - (av[2]/255.0));
if (currentScore < bestScore)
{
foo = item.Key;
bestScore = currentScore;
}
}
return foo;
}
/// <summary>
/// Identifies the best matching image from a list of images
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// Dictionary<string, ImageData> Choose = new Dictionary<string, ImageData> ();
/// Choose.Add("coin", new ImageData("coin.bmp"));
/// Choose.Add("enemy", new ImageData("warrior.bmp"));
/// Choose.Add("water", new ImageData("blue_piece.bmp"));
/// // ...
/// string PieceColor = CommonFunctions.IdentifyImage(new ImageData("unkown.bmp"),Choose);
/// ]]>
/// </code>
/// </example>
/// <remarks>
/// If you want to compare an image patch to a collection of interesting images, you can use this
/// function to find the best matching from the given list
/// </remarks>
/// <param name="img">The image to look for</param>
/// <param name="statReference">The list of images</param>
/// <returns>The name of the best matching image in the list</returns>
public static string IdentifyImage(ImageData img, Dictionary<string, ImageData> statReference)
{
double similar = 0.0;
string keyword = "";
foreach (var item in statReference)
{
// exact size match cause easier way of compare the image
if ((img.Width == item.Value.Width) && (img.Height == item.Value.Height))
{
double s = Similarity(img, item.Value);
if (s > similar)
{
keyword = item.Key;
similar = s;
}
}
else
{
if ((img.Width > item.Value.Width) && (img.Height > item.Value.Height))
{
// search within the greater image
for (int column = 0; column < img.Width - item.Value.Width; column++)
{
for (int row = 0; row < img.Height - item.Value.Height; row++)
{
double s = Similarity(img, item.Value, 0, 0, item.Value.Width, item.Value.Height, column,
row);
if (s > similar)
{
keyword = item.Key;
similar = s;
}
}
}
}
}
}
return keyword;
}
/// <summary>
/// Calculates the difference between two colors (a-b)
/// </summary>
/// <param name="a">Color a</param>
/// <param name="b">Color b</param>
/// <returns></returns>
public static Color ColorDifference(Color a, Color b)
{
int cr = a.R - b.R;
int cg = a.G - b.G;
int cb = a.B - b.B;
if (cr < 0)
cr += 255;
if (cg < 0)
cg += 255;
if (cb < 0)
cb += 255;
return Color.FromArgb(cr, cg, cb);
}
/// <summary>
/// Retrieves the red channel as an array
/// </summary>
/// <param name="img">image</param>
/// <returns>The red channel as an array</returns>
public static uint[,] ExtractRedChannel(ImageData img)
{
var red = new uint[img.Width, img.Height];
for (Int32 column = 0; column < img.Width; column++)
{
for (Int32 row = 0; row < img.Height; row++)
{
Color c = img.GetPixel(column, row);
red[column, row] = c.R;
}
}
return red;
}
/// <summary>
/// Finds all pixels matching a specified color
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// List<Point> WaterPixel = CommonFunctions.FindColors(ScreenShot.create(),Color.Blue,20);
/// ]]>
/// </code>
/// </example>
/// <param name="img">The image to look in</param>
/// <param name="searchColor">The color to look for</param>
/// <param name="tolerance">The tolerance to use</param>
/// <returns></returns>
public static List<Point> FindColors(ImageData img, Color searchColor, uint tolerance)
{
var collection = new List<Point>();
for (int column = 0; column < img.Width; column++)
{
for (int row = 0; row < img.Height; row++)
{
if (ColorsSimilar(img.GetPixel(column, row), searchColor, tolerance))
{
collection.Add(new Point(column, row));
}
}
}
return collection;
}
/// <summary>
/// Finds all pixels matching a specified color
/// /accelerated/
/// </summary>
/// <remarks>
/// this function skips in both dimension (x and y) a predefined amount of pixels in each iteration.
/// You can use this function to test every n-th pixel
/// </remarks>
/// <param name="img">The image to look in</param>
/// <param name="searchColor">The color to look for</param>
/// <param name="skipX">The X pixels to skip each time</param>
/// <param name="skipY">The Y pixels to skip each time</param>
/// <param name="tolerance">The tolerance to use</param>
/// <returns></returns>
public static List<Point> FindColors(ImageData img, Color searchColor, uint tolerance, int skipX = 1, int skipY = 1)
{
if (skipX < 1 && skipY < 1) return null; // Cannot be non-positive numbers
var collection = new List<Point>();
for (int column = 0; column < img.Width; column = column + skipX)
{
for (int row = 0; row < img.Height; row = row + skipY)
{
if (ColorsSimilar(img.GetPixel(column, row), searchColor, tolerance))
{
collection.Add(new Point(column, row));
}
}
}
return collection;
}
}
}
| |
/*
* CP1143.cs - IBM EBCDIC (Finland/Sweden with Euro) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ibm-1143.ucm".
namespace I18N.Rare
{
using System;
using I18N.Common;
public class CP1143 : ByteEncoding
{
public CP1143()
: base(1143, ToChars, "IBM EBCDIC (Finland/Sweden with Euro)",
"IBM01143", "IBM01143", "IBM01143",
false, false, false, false, 1252)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009',
'\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087',
'\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D',
'\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083',
'\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089',
'\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007',
'\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095',
'\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B',
'\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0',
'\u00E2', '\u007B', '\u00E0', '\u00E1', '\u00E3', '\u007D',
'\u00E7', '\u00F1', '\u00A7', '\u002E', '\u003C', '\u0028',
'\u002B', '\u0021', '\u0026', '\u0060', '\u00EA', '\u00EB',
'\u00E8', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF',
'\u20AC', '\u00C5', '\u002A', '\u0029', '\u003B', '\u005E',
'\u002D', '\u002F', '\u00C2', '\u0023', '\u00C0', '\u00C1',
'\u00C3', '\u0024', '\u00C7', '\u00D1', '\u00F6', '\u002C',
'\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u005C',
'\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF',
'\u00CC', '\u00E9', '\u003A', '\u00C4', '\u00D6', '\u0027',
'\u003D', '\u0022', '\u00D8', '\u0061', '\u0062', '\u0063',
'\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069',
'\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1',
'\u00B0', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E',
'\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA',
'\u00E6', '\u00B8', '\u00C6', '\u005D', '\u00B5', '\u00FC',
'\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078',
'\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD',
'\u00DE', '\u00AE', '\u00A2', '\u00A3', '\u00A5', '\u00B7',
'\u00A9', '\u005B', '\u00B6', '\u00BC', '\u00BD', '\u00BE',
'\u00AC', '\u007C', '\u00AF', '\u00A8', '\u00B4', '\u00D7',
'\u00E4', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045',
'\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4',
'\u00A6', '\u00F2', '\u00F3', '\u00F5', '\u00E5', '\u004A',
'\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050',
'\u0051', '\u0052', '\u00B9', '\u00FB', '\u007E', '\u00F9',
'\u00FA', '\u00FF', '\u00C9', '\u00F7', '\u0053', '\u0054',
'\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A',
'\u00B2', '\u00D4', '\u0040', '\u00D2', '\u00D3', '\u00D5',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB',
'\u00DC', '\u00D9', '\u00DA', '\u009F',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x4F; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x63; break;
case 0x0024: ch = 0x67; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0xEC; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0xB5; break;
case 0x005C: ch = 0x71; break;
case 0x005D: ch = 0x9F; break;
case 0x005E: ch = 0x5F; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x51; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0x43; break;
case 0x007C: ch = 0xBB; break;
case 0x007D: ch = 0x47; break;
case 0x007E: ch = 0xDC; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0xCC; break;
case 0x00A7: ch = 0x4A; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0xBA; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x7B; break;
case 0x00C5: ch = 0x5B; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0xE0; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0x7C; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0xC0; break;
case 0x00E5: ch = 0xD0; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x79; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0x6A; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xA1; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x203E: ch = 0xBC; break;
case 0x20AC: ch = 0x5A; break;
case 0xFF01: ch = 0x4F; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x63; break;
case 0xFF04: ch = 0x67; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0xEC; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0xB5; break;
case 0xFF3C: ch = 0x71; break;
case 0xFF3D: ch = 0x9F; break;
case 0xFF3E: ch = 0x5F; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x51; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0x43; break;
case 0xFF5C: ch = 0xBB; break;
case 0xFF5D: ch = 0x47; break;
case 0xFF5E: ch = 0xDC; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 4) switch(ch)
{
case 0x000B:
case 0x000C:
case 0x000D:
case 0x000E:
case 0x000F:
case 0x0010:
case 0x0011:
case 0x0012:
case 0x0013:
case 0x0018:
case 0x0019:
case 0x001C:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x00B6:
break;
case 0x0004: ch = 0x37; break;
case 0x0005: ch = 0x2D; break;
case 0x0006: ch = 0x2E; break;
case 0x0007: ch = 0x2F; break;
case 0x0008: ch = 0x16; break;
case 0x0009: ch = 0x05; break;
case 0x000A: ch = 0x25; break;
case 0x0014: ch = 0x3C; break;
case 0x0015: ch = 0x3D; break;
case 0x0016: ch = 0x32; break;
case 0x0017: ch = 0x26; break;
case 0x001A: ch = 0x3F; break;
case 0x001B: ch = 0x27; break;
case 0x0020: ch = 0x40; break;
case 0x0021: ch = 0x4F; break;
case 0x0022: ch = 0x7F; break;
case 0x0023: ch = 0x63; break;
case 0x0024: ch = 0x67; break;
case 0x0025: ch = 0x6C; break;
case 0x0026: ch = 0x50; break;
case 0x0027: ch = 0x7D; break;
case 0x0028: ch = 0x4D; break;
case 0x0029: ch = 0x5D; break;
case 0x002A: ch = 0x5C; break;
case 0x002B: ch = 0x4E; break;
case 0x002C: ch = 0x6B; break;
case 0x002D: ch = 0x60; break;
case 0x002E: ch = 0x4B; break;
case 0x002F: ch = 0x61; break;
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
ch += 0x00C0;
break;
case 0x003A: ch = 0x7A; break;
case 0x003B: ch = 0x5E; break;
case 0x003C: ch = 0x4C; break;
case 0x003D: ch = 0x7E; break;
case 0x003E: ch = 0x6E; break;
case 0x003F: ch = 0x6F; break;
case 0x0040: ch = 0xEC; break;
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
ch += 0x0080;
break;
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
ch += 0x0087;
break;
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
ch += 0x008F;
break;
case 0x005B: ch = 0xB5; break;
case 0x005C: ch = 0x71; break;
case 0x005D: ch = 0x9F; break;
case 0x005E: ch = 0x5F; break;
case 0x005F: ch = 0x6D; break;
case 0x0060: ch = 0x51; break;
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
ch += 0x0020;
break;
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
ch += 0x0027;
break;
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
ch += 0x002F;
break;
case 0x007B: ch = 0x43; break;
case 0x007C: ch = 0xBB; break;
case 0x007D: ch = 0x47; break;
case 0x007E: ch = 0xDC; break;
case 0x007F: ch = 0x07; break;
case 0x0080:
case 0x0081:
case 0x0082:
case 0x0083:
case 0x0084:
ch -= 0x0060;
break;
case 0x0085: ch = 0x15; break;
case 0x0086: ch = 0x06; break;
case 0x0087: ch = 0x17; break;
case 0x0088:
case 0x0089:
case 0x008A:
case 0x008B:
case 0x008C:
ch -= 0x0060;
break;
case 0x008D: ch = 0x09; break;
case 0x008E: ch = 0x0A; break;
case 0x008F: ch = 0x1B; break;
case 0x0090: ch = 0x30; break;
case 0x0091: ch = 0x31; break;
case 0x0092: ch = 0x1A; break;
case 0x0093:
case 0x0094:
case 0x0095:
case 0x0096:
ch -= 0x0060;
break;
case 0x0097: ch = 0x08; break;
case 0x0098:
case 0x0099:
case 0x009A:
case 0x009B:
ch -= 0x0060;
break;
case 0x009C: ch = 0x04; break;
case 0x009D: ch = 0x14; break;
case 0x009E: ch = 0x3E; break;
case 0x009F: ch = 0xFF; break;
case 0x00A0: ch = 0x41; break;
case 0x00A1: ch = 0xAA; break;
case 0x00A2: ch = 0xB0; break;
case 0x00A3: ch = 0xB1; break;
case 0x00A5: ch = 0xB2; break;
case 0x00A6: ch = 0xCC; break;
case 0x00A7: ch = 0x4A; break;
case 0x00A8: ch = 0xBD; break;
case 0x00A9: ch = 0xB4; break;
case 0x00AA: ch = 0x9A; break;
case 0x00AB: ch = 0x8A; break;
case 0x00AC: ch = 0xBA; break;
case 0x00AD: ch = 0xCA; break;
case 0x00AE: ch = 0xAF; break;
case 0x00AF: ch = 0xBC; break;
case 0x00B0: ch = 0x90; break;
case 0x00B1: ch = 0x8F; break;
case 0x00B2: ch = 0xEA; break;
case 0x00B3: ch = 0xFA; break;
case 0x00B4: ch = 0xBE; break;
case 0x00B5: ch = 0xA0; break;
case 0x00B7: ch = 0xB3; break;
case 0x00B8: ch = 0x9D; break;
case 0x00B9: ch = 0xDA; break;
case 0x00BA: ch = 0x9B; break;
case 0x00BB: ch = 0x8B; break;
case 0x00BC: ch = 0xB7; break;
case 0x00BD: ch = 0xB8; break;
case 0x00BE: ch = 0xB9; break;
case 0x00BF: ch = 0xAB; break;
case 0x00C0: ch = 0x64; break;
case 0x00C1: ch = 0x65; break;
case 0x00C2: ch = 0x62; break;
case 0x00C3: ch = 0x66; break;
case 0x00C4: ch = 0x7B; break;
case 0x00C5: ch = 0x5B; break;
case 0x00C6: ch = 0x9E; break;
case 0x00C7: ch = 0x68; break;
case 0x00C8: ch = 0x74; break;
case 0x00C9: ch = 0xE0; break;
case 0x00CA: ch = 0x72; break;
case 0x00CB: ch = 0x73; break;
case 0x00CC: ch = 0x78; break;
case 0x00CD: ch = 0x75; break;
case 0x00CE: ch = 0x76; break;
case 0x00CF: ch = 0x77; break;
case 0x00D0: ch = 0xAC; break;
case 0x00D1: ch = 0x69; break;
case 0x00D2: ch = 0xED; break;
case 0x00D3: ch = 0xEE; break;
case 0x00D4: ch = 0xEB; break;
case 0x00D5: ch = 0xEF; break;
case 0x00D6: ch = 0x7C; break;
case 0x00D7: ch = 0xBF; break;
case 0x00D8: ch = 0x80; break;
case 0x00D9: ch = 0xFD; break;
case 0x00DA: ch = 0xFE; break;
case 0x00DB: ch = 0xFB; break;
case 0x00DC: ch = 0xFC; break;
case 0x00DD: ch = 0xAD; break;
case 0x00DE: ch = 0xAE; break;
case 0x00DF: ch = 0x59; break;
case 0x00E0: ch = 0x44; break;
case 0x00E1: ch = 0x45; break;
case 0x00E2: ch = 0x42; break;
case 0x00E3: ch = 0x46; break;
case 0x00E4: ch = 0xC0; break;
case 0x00E5: ch = 0xD0; break;
case 0x00E6: ch = 0x9C; break;
case 0x00E7: ch = 0x48; break;
case 0x00E8: ch = 0x54; break;
case 0x00E9: ch = 0x79; break;
case 0x00EA: ch = 0x52; break;
case 0x00EB: ch = 0x53; break;
case 0x00EC: ch = 0x58; break;
case 0x00ED: ch = 0x55; break;
case 0x00EE: ch = 0x56; break;
case 0x00EF: ch = 0x57; break;
case 0x00F0: ch = 0x8C; break;
case 0x00F1: ch = 0x49; break;
case 0x00F2: ch = 0xCD; break;
case 0x00F3: ch = 0xCE; break;
case 0x00F4: ch = 0xCB; break;
case 0x00F5: ch = 0xCF; break;
case 0x00F6: ch = 0x6A; break;
case 0x00F7: ch = 0xE1; break;
case 0x00F8: ch = 0x70; break;
case 0x00F9: ch = 0xDD; break;
case 0x00FA: ch = 0xDE; break;
case 0x00FB: ch = 0xDB; break;
case 0x00FC: ch = 0xA1; break;
case 0x00FD: ch = 0x8D; break;
case 0x00FE: ch = 0x8E; break;
case 0x00FF: ch = 0xDF; break;
case 0x203E: ch = 0xBC; break;
case 0x20AC: ch = 0x5A; break;
case 0xFF01: ch = 0x4F; break;
case 0xFF02: ch = 0x7F; break;
case 0xFF03: ch = 0x63; break;
case 0xFF04: ch = 0x67; break;
case 0xFF05: ch = 0x6C; break;
case 0xFF06: ch = 0x50; break;
case 0xFF07: ch = 0x7D; break;
case 0xFF08: ch = 0x4D; break;
case 0xFF09: ch = 0x5D; break;
case 0xFF0A: ch = 0x5C; break;
case 0xFF0B: ch = 0x4E; break;
case 0xFF0C: ch = 0x6B; break;
case 0xFF0D: ch = 0x60; break;
case 0xFF0E: ch = 0x4B; break;
case 0xFF0F: ch = 0x61; break;
case 0xFF10:
case 0xFF11:
case 0xFF12:
case 0xFF13:
case 0xFF14:
case 0xFF15:
case 0xFF16:
case 0xFF17:
case 0xFF18:
case 0xFF19:
ch -= 0xFE20;
break;
case 0xFF1A: ch = 0x7A; break;
case 0xFF1B: ch = 0x5E; break;
case 0xFF1C: ch = 0x4C; break;
case 0xFF1D: ch = 0x7E; break;
case 0xFF1E: ch = 0x6E; break;
case 0xFF1F: ch = 0x6F; break;
case 0xFF20: ch = 0xEC; break;
case 0xFF21:
case 0xFF22:
case 0xFF23:
case 0xFF24:
case 0xFF25:
case 0xFF26:
case 0xFF27:
case 0xFF28:
case 0xFF29:
ch -= 0xFE60;
break;
case 0xFF2A:
case 0xFF2B:
case 0xFF2C:
case 0xFF2D:
case 0xFF2E:
case 0xFF2F:
case 0xFF30:
case 0xFF31:
case 0xFF32:
ch -= 0xFE59;
break;
case 0xFF33:
case 0xFF34:
case 0xFF35:
case 0xFF36:
case 0xFF37:
case 0xFF38:
case 0xFF39:
case 0xFF3A:
ch -= 0xFE51;
break;
case 0xFF3B: ch = 0xB5; break;
case 0xFF3C: ch = 0x71; break;
case 0xFF3D: ch = 0x9F; break;
case 0xFF3E: ch = 0x5F; break;
case 0xFF3F: ch = 0x6D; break;
case 0xFF40: ch = 0x51; break;
case 0xFF41:
case 0xFF42:
case 0xFF43:
case 0xFF44:
case 0xFF45:
case 0xFF46:
case 0xFF47:
case 0xFF48:
case 0xFF49:
ch -= 0xFEC0;
break;
case 0xFF4A:
case 0xFF4B:
case 0xFF4C:
case 0xFF4D:
case 0xFF4E:
case 0xFF4F:
case 0xFF50:
case 0xFF51:
case 0xFF52:
ch -= 0xFEB9;
break;
case 0xFF53:
case 0xFF54:
case 0xFF55:
case 0xFF56:
case 0xFF57:
case 0xFF58:
case 0xFF59:
case 0xFF5A:
ch -= 0xFEB1;
break;
case 0xFF5B: ch = 0x43; break;
case 0xFF5C: ch = 0xBB; break;
case 0xFF5D: ch = 0x47; break;
case 0xFF5E: ch = 0xDC; break;
default: ch = 0x3F; break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP1143
public class ENCibm01143 : CP1143
{
public ENCibm01143() : base() {}
}; // class ENCibm01143
}; // namespace I18N.Rare
| |
/*
* 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.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Threading;
using System.Reflection;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Serialization.External;
using OpenSim.Framework.Console;
using OpenSim.Server.Base;
using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
using Nini.Config;
using log4net;
using OpenMetaverse;
using System.Security.Cryptography;
namespace OpenSim.Services.FSAssetService
{
public class FSAssetConnector : ServiceBase, IAssetService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
static SHA256CryptoServiceProvider SHA256 = new SHA256CryptoServiceProvider();
static byte[] ToCString(string s)
{
byte[] ret = enc.GetBytes(s);
Array.Resize(ref ret, ret.Length + 1);
ret[ret.Length - 1] = 0;
return ret;
}
protected IAssetLoader m_AssetLoader = null;
protected IFSAssetDataPlugin m_DataConnector = null;
protected IAssetService m_FallbackService;
protected Thread m_WriterThread;
protected Thread m_StatsThread;
protected string m_SpoolDirectory;
protected object m_readLock = new object();
protected object m_statsLock = new object();
protected int m_readCount = 0;
protected int m_readTicks = 0;
protected int m_missingAssets = 0;
protected int m_missingAssetsFS = 0;
protected string m_FSBase;
protected bool m_useOsgridFormat = false;
protected bool m_showStats = true;
private static bool m_Initialized;
private bool m_MainInstance;
public FSAssetConnector(IConfigSource config)
: this(config, "AssetService")
{
}
public FSAssetConnector(IConfigSource config, string configName) : base(config)
{
if (!m_Initialized)
{
m_Initialized = true;
m_MainInstance = true;
MainConsole.Instance.Commands.AddCommand("fs", false,
"show assets", "show assets", "Show asset stats",
HandleShowAssets);
MainConsole.Instance.Commands.AddCommand("fs", false,
"show digest", "show digest <ID>", "Show asset digest",
HandleShowDigest);
MainConsole.Instance.Commands.AddCommand("fs", false,
"delete asset", "delete asset <ID>",
"Delete asset from database",
HandleDeleteAsset);
MainConsole.Instance.Commands.AddCommand("fs", false,
"import", "import <conn> <table> [<start> <count>]",
"Import legacy assets",
HandleImportAssets);
MainConsole.Instance.Commands.AddCommand("fs", false,
"force import", "force import <conn> <table> [<start> <count>]",
"Import legacy assets, overwriting current content",
HandleImportAssets);
}
IConfig assetConfig = config.Configs[configName];
if (assetConfig == null)
throw new Exception("No AssetService configuration");
// Get Database Connector from Asset Config (If present)
string dllName = assetConfig.GetString("StorageProvider", string.Empty);
string connectionString = assetConfig.GetString("ConnectionString", string.Empty);
string realm = assetConfig.GetString("Realm", "fsassets");
int SkipAccessTimeDays = assetConfig.GetInt("DaysBetweenAccessTimeUpdates", 0);
// If not found above, fallback to Database defaults
IConfig dbConfig = config.Configs["DatabaseService"];
if (dbConfig != null)
{
if (dllName == String.Empty)
dllName = dbConfig.GetString("StorageProvider", String.Empty);
if (connectionString == String.Empty)
connectionString = dbConfig.GetString("ConnectionString", String.Empty);
}
// No databse connection found in either config
if (dllName.Equals(String.Empty))
throw new Exception("No StorageProvider configured");
if (connectionString.Equals(String.Empty))
throw new Exception("Missing database connection string");
// Create Storage Provider
m_DataConnector = LoadPlugin<IFSAssetDataPlugin>(dllName);
if (m_DataConnector == null)
throw new Exception(string.Format("Could not find a storage interface in the module {0}", dllName));
// Initialize DB And perform any migrations required
m_DataConnector.Initialise(connectionString, realm, SkipAccessTimeDays);
// Setup Fallback Service
string str = assetConfig.GetString("FallbackService", string.Empty);
if (str != string.Empty)
{
object[] args = new object[] { config };
m_FallbackService = LoadPlugin<IAssetService>(str, args);
if (m_FallbackService != null)
{
m_log.Info("[FSASSETS]: Fallback service loaded");
}
else
{
m_log.Error("[FSASSETS]: Failed to load fallback service");
}
}
// Setup directory structure including temp directory
m_SpoolDirectory = assetConfig.GetString("SpoolDirectory", "/tmp");
string spoolTmp = Path.Combine(m_SpoolDirectory, "spool");
Directory.CreateDirectory(spoolTmp);
m_FSBase = assetConfig.GetString("BaseDirectory", String.Empty);
if (m_FSBase == String.Empty)
{
m_log.ErrorFormat("[FSASSETS]: BaseDirectory not specified");
throw new Exception("Configuration error");
}
m_useOsgridFormat = assetConfig.GetBoolean("UseOsgridFormat", m_useOsgridFormat);
// Default is to show stats to retain original behaviour
m_showStats = assetConfig.GetBoolean("ShowConsoleStats", m_showStats);
if (m_MainInstance)
{
string loader = assetConfig.GetString("DefaultAssetLoader", string.Empty);
if (loader != string.Empty)
{
m_AssetLoader = LoadPlugin<IAssetLoader>(loader);
string loaderArgs = assetConfig.GetString("AssetLoaderArgs", string.Empty);
m_log.InfoFormat("[FSASSETS]: Loading default asset set from {0}", loaderArgs);
m_AssetLoader.ForEachDefaultXmlAsset(loaderArgs,
delegate(AssetBase a)
{
Store(a, false);
});
}
m_WriterThread = new Thread(Writer);
m_WriterThread.Start();
if (m_showStats)
{
m_StatsThread = new Thread(Stats);
m_StatsThread.Start();
}
}
m_log.Info("[FSASSETS]: FS asset service enabled");
}
private void Stats()
{
while (true)
{
Thread.Sleep(60000);
lock (m_statsLock)
{
if (m_readCount > 0)
{
double avg = (double)m_readTicks / (double)m_readCount;
// if (avg > 10000)
// Environment.Exit(0);
m_log.InfoFormat("[FSASSETS]: Read stats: {0} files, {1} ticks, avg {2:F2}, missing {3}, FS {4}", m_readCount, m_readTicks, (double)m_readTicks / (double)m_readCount, m_missingAssets, m_missingAssetsFS);
}
m_readCount = 0;
m_readTicks = 0;
m_missingAssets = 0;
m_missingAssetsFS = 0;
}
}
}
private void Writer()
{
m_log.Info("[ASSET]: Writer started");
while (true)
{
string[] files = Directory.GetFiles(m_SpoolDirectory);
if (files.Length > 0)
{
int tickCount = Environment.TickCount;
for (int i = 0 ; i < files.Length ; i++)
{
string hash = Path.GetFileNameWithoutExtension(files[i]);
string s = HashToFile(hash);
string diskFile = Path.Combine(m_FSBase, s);
bool pathOk = false;
// The cure for chicken bones!
while(true)
{
try
{
// Try to make the directory we need for this file
Directory.CreateDirectory(Path.GetDirectoryName(diskFile));
pathOk = true;
break;
}
catch (System.IO.IOException)
{
// Creating the directory failed. This can't happen unless
// a part of the path already exists as a file. Sadly the
// SRAS data contains such files.
string d = Path.GetDirectoryName(diskFile);
// Test each path component in turn. If we can successfully
// make a directory, the level below must be the chicken bone.
while (d.Length > 0)
{
Console.WriteLine(d);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(d));
}
catch (System.IO.IOException)
{
d = Path.GetDirectoryName(d);
// We failed making the directory and need to
// go up a bit more
continue;
}
// We succeeded in making the directory and (d) is
// the chicken bone
break;
}
// Is the chicken alive?
if (d.Length > 0)
{
Console.WriteLine(d);
FileAttributes attr = File.GetAttributes(d);
if ((attr & FileAttributes.Directory) == 0)
{
// The chicken bone should be resolved.
// Return to writing the file.
File.Delete(d);
continue;
}
}
}
// Could not resolve, skipping
m_log.ErrorFormat("[ASSET]: Could not resolve path creation error for {0}", diskFile);
break;
}
if (pathOk)
{
try
{
byte[] data = File.ReadAllBytes(files[i]);
using (GZipStream gz = new GZipStream(new FileStream(diskFile + ".gz", FileMode.Create), CompressionMode.Compress))
{
gz.Write(data, 0, data.Length);
gz.Close();
}
File.Delete(files[i]);
//File.Move(files[i], diskFile);
}
catch(System.IO.IOException e)
{
if (e.Message.StartsWith("Win32 IO returned ERROR_ALREADY_EXISTS"))
File.Delete(files[i]);
else
throw;
}
}
}
int totalTicks = System.Environment.TickCount - tickCount;
if (totalTicks > 0) // Wrap?
{
m_log.InfoFormat("[ASSET]: Write cycle complete, {0} files, {1} ticks, avg {2:F2}", files.Length, totalTicks, (double)totalTicks / (double)files.Length);
}
}
Thread.Sleep(1000);
}
}
string GetSHA256Hash(byte[] data)
{
byte[] hash = SHA256.ComputeHash(data);
return BitConverter.ToString(hash).Replace("-", String.Empty);
}
public string HashToPath(string hash)
{
if (hash == null || hash.Length < 10)
return "junkyard";
if (m_useOsgridFormat)
{
/*
* The code below is the OSGrid code.
*/
return Path.Combine(hash.Substring(0, 3),
Path.Combine(hash.Substring(3, 3)));
}
else
{
/*
* The below is what core would normally use.
* This is modified to work in OSGrid, as seen
* above, because the SRAS data is structured
* that way.
*/
return Path.Combine(hash.Substring(0, 2),
Path.Combine(hash.Substring(2, 2),
Path.Combine(hash.Substring(4, 2),
hash.Substring(6, 4))));
}
}
private bool AssetExists(string hash)
{
string s = HashToFile(hash);
string diskFile = Path.Combine(m_FSBase, s);
if (File.Exists(diskFile + ".gz") || File.Exists(diskFile))
return true;
return false;
}
public virtual bool[] AssetsExist(string[] ids)
{
UUID[] uuid = Array.ConvertAll(ids, id => UUID.Parse(id));
return m_DataConnector.AssetsExist(uuid);
}
public string HashToFile(string hash)
{
return Path.Combine(HashToPath(hash), hash);
}
public virtual AssetBase Get(string id)
{
string hash;
return Get(id, out hash);
}
private AssetBase Get(string id, out string sha)
{
string hash = string.Empty;
int startTime = System.Environment.TickCount;
AssetMetadata metadata;
lock (m_readLock)
{
metadata = m_DataConnector.Get(id, out hash);
}
sha = hash;
if (metadata == null)
{
AssetBase asset = null;
if (m_FallbackService != null)
{
asset = m_FallbackService.Get(id);
if (asset != null)
{
asset.Metadata.ContentType =
SLUtil.SLAssetTypeToContentType((int)asset.Type);
sha = GetSHA256Hash(asset.Data);
m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id);
Store(asset);
}
}
if (asset == null && m_showStats)
{
// m_log.InfoFormat("[FSASSETS]: Asset {0} not found", id);
m_missingAssets++;
}
return asset;
}
AssetBase newAsset = new AssetBase();
newAsset.Metadata = metadata;
try
{
newAsset.Data = GetFsData(hash);
if (newAsset.Data.Length == 0)
{
AssetBase asset = null;
if (m_FallbackService != null)
{
asset = m_FallbackService.Get(id);
if (asset != null)
{
asset.Metadata.ContentType =
SLUtil.SLAssetTypeToContentType((int)asset.Type);
sha = GetSHA256Hash(asset.Data);
m_log.InfoFormat("[FSASSETS]: Added asset {0} from fallback to local store", id);
Store(asset);
}
}
if (asset == null)
{
if (m_showStats)
m_missingAssetsFS++;
// m_log.InfoFormat("[FSASSETS]: Asset {0}, hash {1} not found in FS", id, hash);
}
else
{
// Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
// Fix bad assets before sending them elsewhere
if (asset.Type == (int)AssetType.Object && asset.Data != null)
{
string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(asset.Data));
asset.Data = Utils.StringToBytes(xml);
}
return asset;
}
}
if (m_showStats)
{
lock (m_statsLock)
{
m_readTicks += Environment.TickCount - startTime;
m_readCount++;
}
}
// Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
// Fix bad assets before sending them elsewhere
if (newAsset.Type == (int)AssetType.Object && newAsset.Data != null)
{
string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(newAsset.Data));
newAsset.Data = Utils.StringToBytes(xml);
}
return newAsset;
}
catch (Exception exception)
{
m_log.Error(exception.ToString());
Thread.Sleep(5000);
Environment.Exit(1);
return null;
}
}
public virtual AssetMetadata GetMetadata(string id)
{
string hash;
return m_DataConnector.Get(id, out hash);
}
public virtual byte[] GetData(string id)
{
string hash;
if (m_DataConnector.Get(id, out hash) == null)
return null;
return GetFsData(hash);
}
public bool Get(string id, Object sender, AssetRetrieved handler)
{
AssetBase asset = Get(id);
handler(id, sender, asset);
return true;
}
public byte[] GetFsData(string hash)
{
string spoolFile = Path.Combine(m_SpoolDirectory, hash + ".asset");
if (File.Exists(spoolFile))
{
try
{
byte[] content = File.ReadAllBytes(spoolFile);
return content;
}
catch
{
}
}
string file = HashToFile(hash);
string diskFile = Path.Combine(m_FSBase, file);
if (File.Exists(diskFile + ".gz"))
{
try
{
using (GZipStream gz = new GZipStream(new FileStream(diskFile + ".gz", FileMode.Open, FileAccess.Read), CompressionMode.Decompress))
{
using (MemoryStream ms = new MemoryStream())
{
byte[] data = new byte[32768];
int bytesRead;
do
{
bytesRead = gz.Read(data, 0, 32768);
if (bytesRead > 0)
ms.Write(data, 0, bytesRead);
} while (bytesRead > 0);
return ms.ToArray();
}
}
}
catch (Exception)
{
return new Byte[0];
}
}
else if (File.Exists(diskFile))
{
try
{
byte[] content = File.ReadAllBytes(diskFile);
return content;
}
catch
{
}
}
return new Byte[0];
}
public virtual string Store(AssetBase asset)
{
return Store(asset, false);
}
private string Store(AssetBase asset, bool force)
{
int tickCount = Environment.TickCount;
string hash = GetSHA256Hash(asset.Data);
if (!AssetExists(hash))
{
string tempFile = Path.Combine(Path.Combine(m_SpoolDirectory, "spool"), hash + ".asset");
string finalFile = Path.Combine(m_SpoolDirectory, hash + ".asset");
if (!File.Exists(finalFile))
{
// Deal with bug introduced in Oct. 20 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
// Fix bad assets before storing on this server
if (asset.Type == (int)AssetType.Object && asset.Data != null)
{
string xml = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(asset.Data));
asset.Data = Utils.StringToBytes(xml);
}
FileStream fs = File.Create(tempFile);
fs.Write(asset.Data, 0, asset.Data.Length);
fs.Close();
File.Move(tempFile, finalFile);
}
}
if (asset.ID == string.Empty)
{
if (asset.FullID == UUID.Zero)
{
asset.FullID = UUID.Random();
}
asset.ID = asset.FullID.ToString();
}
else if (asset.FullID == UUID.Zero)
{
UUID uuid = UUID.Zero;
if (UUID.TryParse(asset.ID, out uuid))
{
asset.FullID = uuid;
}
else
{
asset.FullID = UUID.Random();
}
}
if (!m_DataConnector.Store(asset.Metadata, hash))
{
if (asset.Metadata.Type == -2)
return asset.ID;
return UUID.Zero.ToString();
}
else
{
return asset.ID;
}
}
public bool UpdateContent(string id, byte[] data)
{
return false;
// string oldhash;
// AssetMetadata meta = m_DataConnector.Get(id, out oldhash);
//
// if (meta == null)
// return false;
//
// AssetBase asset = new AssetBase();
// asset.Metadata = meta;
// asset.Data = data;
//
// Store(asset);
//
// return true;
}
public virtual bool Delete(string id)
{
m_DataConnector.Delete(id);
return true;
}
private void HandleShowAssets(string module, string[] args)
{
int num = m_DataConnector.Count();
MainConsole.Instance.Output(string.Format("Total asset count: {0}", num));
}
private void HandleShowDigest(string module, string[] args)
{
if (args.Length < 3)
{
MainConsole.Instance.Output("Syntax: show digest <ID>");
return;
}
string hash;
AssetBase asset = Get(args[2], out hash);
if (asset == null || asset.Data.Length == 0)
{
MainConsole.Instance.Output("Asset not found");
return;
}
int i;
MainConsole.Instance.Output(String.Format("Name: {0}", asset.Name));
MainConsole.Instance.Output(String.Format("Description: {0}", asset.Description));
MainConsole.Instance.Output(String.Format("Type: {0}", asset.Type));
MainConsole.Instance.Output(String.Format("Content-type: {0}", asset.Metadata.ContentType));
MainConsole.Instance.Output(String.Format("Flags: {0}", asset.Metadata.Flags.ToString()));
MainConsole.Instance.Output(String.Format("FS file: {0}", HashToFile(hash)));
for (i = 0 ; i < 5 ; i++)
{
int off = i * 16;
if (asset.Data.Length <= off)
break;
int len = 16;
if (asset.Data.Length < off + len)
len = asset.Data.Length - off;
byte[] line = new byte[len];
Array.Copy(asset.Data, off, line, 0, len);
string text = BitConverter.ToString(line);
MainConsole.Instance.Output(String.Format("{0:x4}: {1}", off, text));
}
}
private void HandleDeleteAsset(string module, string[] args)
{
if (args.Length < 3)
{
MainConsole.Instance.Output("Syntax: delete asset <ID>");
return;
}
AssetBase asset = Get(args[2]);
if (asset == null || asset.Data.Length == 0)
{
MainConsole.Instance.Output("Asset not found");
return;
}
m_DataConnector.Delete(args[2]);
MainConsole.Instance.Output("Asset deleted");
}
private void HandleImportAssets(string module, string[] args)
{
bool force = false;
if (args[0] == "force")
{
force = true;
List<string> list = new List<string>(args);
list.RemoveAt(0);
args = list.ToArray();
}
if (args.Length < 3)
{
MainConsole.Instance.Output("Syntax: import <conn> <table> [<start> <count>]");
}
else
{
string conn = args[1];
string table = args[2];
int start = 0;
int count = -1;
if (args.Length > 3)
{
start = Convert.ToInt32(args[3]);
}
if (args.Length > 4)
{
count = Convert.ToInt32(args[4]);
}
m_DataConnector.Import(conn, table, start, count, force, new FSStoreDelegate(Store));
}
}
public AssetBase GetCached(string id)
{
return Get(id);
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeQuality.Analyzers.Maintainability
{
/// <summary>
/// CA1812: Avoid uninstantiated internal classes
/// </summary>
public abstract class AvoidUninstantiatedInternalClassesAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1812";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.AvoidUninstantiatedInternalClassesTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.AvoidUninstantiatedInternalClassesMessage), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.AvoidUninstantiatedInternalClassesDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources));
internal static DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessage,
DiagnosticCategory.Performance,
RuleLevel.Disabled, // Code coverage tools provide superior results when done correctly.
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false,
isReportedAtCompilationEnd: true);
public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public abstract void RegisterLanguageSpecificChecks(CompilationStartAnalysisContext context, ConcurrentDictionary<INamedTypeSymbol, object?> instantiatedTypes);
public sealed override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze);
context.RegisterCompilationStartAction(startContext =>
{
ConcurrentDictionary<INamedTypeSymbol, object?> instantiatedTypes = new ConcurrentDictionary<INamedTypeSymbol, object?>();
var internalTypes = new ConcurrentDictionary<INamedTypeSymbol, object?>();
var compilation = startContext.Compilation;
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilation);
// If the assembly being built by this compilation exposes its internals to
// any other assembly, don't report any "uninstantiated internal class" errors.
// If we were to report an error for an internal type that is not instantiated
// by this assembly, and then it turned out that the friend assembly did
// instantiate the type, that would be a false positive. We've decided it's
// better to have false negatives (which would happen if the type were *not*
// instantiated by any friend assembly, but we didn't report the issue) than
// to have false positives.
var internalsVisibleToAttributeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeCompilerServicesInternalsVisibleToAttribute);
if (compilation.Assembly.HasAttribute(internalsVisibleToAttributeSymbol))
{
return;
}
var systemAttributeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute);
var iConfigurationSectionHandlerSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemConfigurationIConfigurationSectionHandler);
var configurationSectionSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemConfigurationConfigurationSection);
var safeHandleSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesSafeHandle);
var traceListenerSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsTraceListener);
var mef1ExportAttributeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute);
var mef2ExportAttributeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute);
var coClassAttributeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesCoClassAttribute);
var designerAttributeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelDesignerAttribute);
var debuggerTypeProxyAttributeSymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsDebuggerTypeProxyAttribute);
var instantiatingAttributeChecker = new List<(Func<INamedTypeSymbol, bool> isAttributeTarget, Func<AttributeData, Compilation, INamedTypeSymbol?> findTypeOrDefault)>
{
(type => CanBeCoClassAttributeContext(type), (attribute, _) => FindTypeIfCoClassAttribute(attribute)),
(type => CanBeDesignerAttributeContext(type), (attribute, compilation) => FindTypeIfDesignerAttribute(attribute, compilation)),
(type => CanBeDebuggerTypeProxyAttributeContext(type), (attribute, compilation) => FindTypeIfDebuggerTypeProxyAttribute(attribute, compilation)),
};
RegisterLanguageSpecificChecks(startContext, instantiatedTypes);
startContext.RegisterOperationAction(context =>
{
var expr = (IObjectCreationOperation)context.Operation;
if (expr.Type is INamedTypeSymbol namedType)
{
instantiatedTypes.TryAdd(namedType, null);
}
}, OperationKind.ObjectCreation);
startContext.RegisterSymbolAction(context =>
{
var type = (INamedTypeSymbol)context.Symbol;
if (!type.IsExternallyVisible() &&
!IsOkToBeUninstantiated(type, compilation,
systemAttributeSymbol,
iConfigurationSectionHandlerSymbol,
configurationSectionSymbol,
safeHandleSymbol,
traceListenerSymbol,
mef1ExportAttributeSymbol,
mef2ExportAttributeSymbol))
{
internalTypes.TryAdd(type, null);
}
// Instantiation from the subtype constructor initializer.
if (type.BaseType != null)
{
instantiatedTypes.TryAdd(type.BaseType, null);
}
// Some attributes are known to behave as type activator so we want to check them
var applicableAttributes = instantiatingAttributeChecker.Where(tuple => tuple.isAttributeTarget(type)).ToArray();
foreach (var attribute in type.GetAttributes())
{
foreach (var (_, findTypeOrDefault) in applicableAttributes)
{
if (findTypeOrDefault(attribute, context.Compilation) is INamedTypeSymbol namedType)
{
instantiatedTypes.TryAdd(namedType, null);
break;
}
}
}
}, SymbolKind.NamedType);
startContext.RegisterOperationAction(context =>
{
var expr = (IObjectCreationOperation)context.Operation;
var constructedClass = (INamedTypeSymbol)expr.Type;
if (!constructedClass.IsGenericType || constructedClass.IsUnboundGenericType)
{
return;
}
var generics = constructedClass.TypeParameters.Zip(constructedClass.TypeArguments, (parameter, argument) => (parameter, argument));
ProcessGenericTypes(generics, instantiatedTypes);
}, OperationKind.ObjectCreation);
startContext.RegisterOperationAction(context =>
{
var expr = (IInvocationOperation)context.Operation;
var methodType = expr.TargetMethod;
if (!methodType.IsGenericMethod)
{
return;
}
var generics = methodType.TypeParameters.Zip(methodType.TypeArguments, (parameter, argument) => (parameter, argument));
ProcessGenericTypes(generics, instantiatedTypes);
}, OperationKind.Invocation);
startContext.RegisterCompilationEndAction(context =>
{
var uninstantiatedInternalTypes = internalTypes
.Select(it => it.Key.OriginalDefinition)
.Except(instantiatedTypes.Select(it => it.Key.OriginalDefinition))
.Where(type => !HasInstantiatedNestedType(type, instantiatedTypes.Keys));
foreach (var type in uninstantiatedInternalTypes)
{
context.ReportDiagnostic(type.CreateDiagnostic(Rule, type.FormatMemberName()));
}
});
return;
// Local functions
bool CanBeCoClassAttributeContext(INamedTypeSymbol type)
=> coClassAttributeSymbol != null && type.TypeKind == TypeKind.Interface;
INamedTypeSymbol? FindTypeIfCoClassAttribute(AttributeData attribute)
{
RoslynDebug.Assert(coClassAttributeSymbol != null);
if (attribute.AttributeClass.Equals(coClassAttributeSymbol) &&
attribute.ConstructorArguments.Length == 1 &&
attribute.ConstructorArguments[0].Kind == TypedConstantKind.Type &&
attribute.ConstructorArguments[0].Value is INamedTypeSymbol typeSymbol &&
typeSymbol.TypeKind == TypeKind.Class)
{
return typeSymbol;
}
return null;
}
bool CanBeDesignerAttributeContext(INamedTypeSymbol type)
=> designerAttributeSymbol != null && (type.TypeKind == TypeKind.Interface || type.TypeKind == TypeKind.Class);
INamedTypeSymbol? FindTypeIfDesignerAttribute(AttributeData attribute, Compilation compilation)
{
RoslynDebug.Assert(designerAttributeSymbol != null);
if (attribute.ConstructorArguments.Length is not (1 or 2) ||
!attribute.AttributeClass.Equals(designerAttributeSymbol))
{
return null;
}
switch (attribute.ConstructorArguments[0].Value)
{
case string designerTypeName:
{
if (IsTypeInCurrentAssembly(designerTypeName, compilation, out var namedType))
{
return namedType;
}
break;
}
case INamedTypeSymbol namedType:
return namedType;
}
return null;
}
bool CanBeDebuggerTypeProxyAttributeContext(INamedTypeSymbol type)
=> debuggerTypeProxyAttributeSymbol != null && (type.TypeKind == TypeKind.Struct || type.TypeKind == TypeKind.Class);
INamedTypeSymbol? FindTypeIfDebuggerTypeProxyAttribute(AttributeData attribute, Compilation compilation)
{
RoslynDebug.Assert(debuggerTypeProxyAttributeSymbol != null);
if (!attribute.AttributeClass.Equals(debuggerTypeProxyAttributeSymbol))
{
return null;
}
switch (attribute.ConstructorArguments[0].Value)
{
case string typeName:
{
if (IsTypeInCurrentAssembly(typeName, compilation, out var namedType))
{
return namedType;
}
break;
}
case INamedTypeSymbol namedType:
return namedType;
}
return null;
}
});
}
private bool HasInstantiatedNestedType(INamedTypeSymbol type, IEnumerable<INamedTypeSymbol> instantiatedTypes)
{
// We don't care whether a private nested type is instantiated, because if it
// is, it can only have happened within the type itself.
var nestedTypes = type.GetTypeMembers().Where(member => member.DeclaredAccessibility != Accessibility.Private);
foreach (var nestedType in nestedTypes)
{
if (instantiatedTypes.Contains(nestedType))
{
return true;
}
if (HasInstantiatedNestedType(nestedType, instantiatedTypes))
{
return true;
}
}
return false;
}
private static bool IsOkToBeUninstantiated(
INamedTypeSymbol type,
Compilation compilation,
INamedTypeSymbol? systemAttributeSymbol,
INamedTypeSymbol? iConfigurationSectionHandlerSymbol,
INamedTypeSymbol? configurationSectionSymbol,
INamedTypeSymbol? safeHandleSymbol,
INamedTypeSymbol? traceListenerSymbol,
INamedTypeSymbol? mef1ExportAttributeSymbol,
INamedTypeSymbol? mef2ExportAttributeSymbol)
{
if (type.TypeKind != TypeKind.Class || type.IsAbstract || type.IsStatic)
{
return true;
}
// Attributes are not instantiated in IL but are created by reflection.
if (type.Inherits(systemAttributeSymbol))
{
return true;
}
// Ignore type generated for holding top level statements
if (type.IsTopLevelStatementsEntryPointType())
{
return true;
}
// The type containing the assembly's entry point is OK.
if (ContainsEntryPoint(type, compilation))
{
return true;
}
// MEF exported classes are instantiated by MEF, by reflection.
if (IsMefExported(type, mef1ExportAttributeSymbol, mef2ExportAttributeSymbol))
{
return true;
}
// Types implementing the (deprecated) IConfigurationSectionHandler interface
// are OK because they are instantiated by the configuration system.
if (type.Inherits(iConfigurationSectionHandlerSymbol))
{
return true;
}
// Likewise for types derived from ConfigurationSection.
if (type.Inherits(configurationSectionSymbol))
{
return true;
}
// SafeHandles can be created from within the type itself by native code.
if (type.Inherits(safeHandleSymbol))
{
return true;
}
if (type.Inherits(traceListenerSymbol))
{
return true;
}
if (type.IsStaticHolderType())
{
return true;
}
return false;
}
public static bool IsMefExported(
INamedTypeSymbol type,
INamedTypeSymbol? mef1ExportAttributeSymbol,
INamedTypeSymbol? mef2ExportAttributeSymbol)
{
return (mef1ExportAttributeSymbol != null && type.HasAttribute(mef1ExportAttributeSymbol))
|| (mef2ExportAttributeSymbol != null && type.HasAttribute(mef2ExportAttributeSymbol));
}
private static bool ContainsEntryPoint(INamedTypeSymbol type, Compilation compilation)
{
// If this type doesn't live in an application assembly (.exe), it can't contain
// the entry point.
if (compilation.Options.OutputKind is not OutputKind.ConsoleApplication and
not OutputKind.WindowsApplication and
not OutputKind.WindowsRuntimeApplication)
{
return false;
}
var wellKnowTypeProvider = WellKnownTypeProvider.GetOrCreate(compilation);
var taskSymbol = wellKnowTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask);
var genericTaskSymbol = wellKnowTypeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask1);
// TODO: Handle the case where Compilation.Options.MainTypeName matches this type.
// TODO: Test: can't have type parameters.
// TODO: Main in nested class? If allowed, what name does it have?
// TODO: Test that parameter is array of int.
return type.GetMembers("Main")
.Where(m => m is IMethodSymbol)
.Cast<IMethodSymbol>()
.Any(m => IsEntryPoint(m, taskSymbol, genericTaskSymbol));
}
private static bool IsEntryPoint(IMethodSymbol method, ITypeSymbol? taskSymbol, ITypeSymbol? genericTaskSymbol)
{
if (!method.IsStatic)
{
return false;
}
if (!IsSupportedReturnType(method, taskSymbol, genericTaskSymbol))
{
return false;
}
if (!method.Parameters.Any())
{
return true;
}
if (method.Parameters.HasMoreThan(1))
{
return false;
}
return true;
}
private static bool IsSupportedReturnType(IMethodSymbol method, ITypeSymbol? taskSymbol, ITypeSymbol? genericTaskSymbol)
{
if (method.ReturnType.SpecialType == SpecialType.System_Int32)
{
return true;
}
if (method.ReturnsVoid)
{
return true;
}
if (taskSymbol != null && Equals(method.ReturnType, taskSymbol))
{
return true;
}
if (genericTaskSymbol != null && Equals(method.ReturnType.OriginalDefinition, genericTaskSymbol) && ((INamedTypeSymbol)method.ReturnType).TypeArguments.Single().SpecialType == SpecialType.System_Int32)
{
return true;
}
return false;
}
/// <summary>
/// If a type is passed a generic argument to another type or a method that specifies that the type must have a constructor,
/// we presume that the method will be constructing the type, and add it to the list of instantiated types.
/// </summary>
protected void ProcessGenericTypes(IEnumerable<(ITypeParameterSymbol param, ITypeSymbol arg)> generics, ConcurrentDictionary<INamedTypeSymbol, object?> instantiatedTypes)
{
foreach (var (typeParam, typeArg) in generics)
{
if (typeParam.HasConstructorConstraint)
{
void ProcessNamedTypeParamConstraint(INamedTypeSymbol namedTypeArg)
{
if (!instantiatedTypes.TryAdd(namedTypeArg, null))
{
// Already processed.
return;
}
// We need to handle if this type param also has type params that have a generic constraint. Take the following example:
// new Factory1<Factory2<InstantiatedType>>();
// In this example, Factory1 and Factory2 have type params with constructor constraints. Therefore, we need to add all 3
// types to the list of types that have actually been instantiated. However, in the following example:
// new List<Factory<InstantiatedType>>();
// List does not have a constructor constraint, so we can't reasonably infer anything about its type parameters.
if (namedTypeArg.IsGenericType)
{
var newGenerics = namedTypeArg.TypeParameters.Zip(namedTypeArg.TypeArguments, (parameter, argument) => (parameter, argument));
ProcessGenericTypes(newGenerics, instantiatedTypes);
}
}
if (typeArg is INamedTypeSymbol namedType)
{
ProcessNamedTypeParamConstraint(namedType);
}
else if (typeArg is ITypeParameterSymbol typeParameterArg && !typeParameterArg.ConstraintTypes.IsEmpty)
{
static IEnumerable<INamedTypeSymbol> GetAllNamedTypeConstraints(ITypeParameterSymbol t)
{
var directConstraints = t.ConstraintTypes.OfType<INamedTypeSymbol>();
var inheritedConstraints = t.ConstraintTypes.OfType<ITypeParameterSymbol>()
.SelectMany(constraintT => GetAllNamedTypeConstraints(constraintT));
return directConstraints.Concat(inheritedConstraints);
}
var constraints = GetAllNamedTypeConstraints(typeParameterArg);
foreach (INamedTypeSymbol constraint in constraints)
{
ProcessNamedTypeParamConstraint(constraint);
}
}
}
}
}
private static bool IsTypeInCurrentAssembly(string typeName, Compilation compilation, out INamedTypeSymbol? namedType)
{
namedType = null;
var nameParts = typeName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return nameParts.Length >= 2 &&
nameParts[1].Trim().Equals(compilation.AssemblyName, StringComparison.Ordinal) &&
compilation.TryGetOrCreateTypeByMetadataName(nameParts[0].Trim(), out namedType) &&
namedType.ContainingAssembly.Equals(compilation.Assembly);
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 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;
using System.Collections.Generic;
namespace XenAPI
{
public enum API_Version
{
/// <summary>XenServer 4.0 (rio)</summary>
API_1_1 = 1,
/// <summary>XenServer 4.1 (miami)</summary>
API_1_2 = 2,
/// <summary>XenServer 5.0 (orlando)</summary>
API_1_3 = 3,
/// <summary>Unreleased ()</summary>
API_1_4 = 4,
/// <summary>XenServer 5.0 update 3 ()</summary>
API_1_5 = 5,
/// <summary>XenServer 5.5 (george)</summary>
API_1_6 = 6,
/// <summary>XenServer 5.6 (midnight-ride)</summary>
API_1_7 = 7,
/// <summary>XenServer 5.6 FP1 (cowley)</summary>
API_1_8 = 8,
/// <summary>XenServer 6.0 (boston)</summary>
API_1_9 = 9,
/// <summary>XenServer 6.1 (tampa)</summary>
API_1_10 = 10,
/// <summary>XenServer 6.2 (clearwater)</summary>
API_2_0 = 11,
/// <summary>XenServer 6.2 SP1 (vgpu-productisation)</summary>
API_2_1 = 12,
/// <summary>XenServer 6.2 SP1 Hotfix 4 (clearwater-felton)</summary>
API_2_2 = 13,
/// <summary>XenServer 6.5 (creedence)</summary>
API_2_3 = 14,
/// <summary>XenServer 6.5 SP1 (cream)</summary>
API_2_4 = 15,
/// <summary>XenServer 7.0 (dundee)</summary>
API_2_5 = 16,
/// <summary>XenServer 7.1 (ely)</summary>
API_2_6 = 17,
/// <summary>XenServer 7.2 (falcon)</summary>
API_2_7 = 18,
/// <summary>XenServer 7.3 (inverness)</summary>
API_2_8 = 19,
/// <summary>XenServer 7.4 (jura)</summary>
API_2_9 = 20,
/// <summary>XenServer 7.5 (kolkata)</summary>
API_2_10 = 21,
/// <summary>XenServer 7.6 (lima)</summary>
API_2_11 = 22,
/// <summary>Citrix Hypervisor 8.0 (naples)</summary>
API_2_12 = 23,
/// <summary>Unreleased (oslo)</summary>
API_2_13 = 24,
/// <summary>Citrix Hypervisor 8.1 (quebec)</summary>
API_2_14 = 25,
/// <summary>Citrix Hypervisor 8.2 (stockholm)</summary>
API_2_15 = 26,
/// <summary>Unreleased (next)</summary>
API_2_20 = 27,
LATEST = 27,
UNKNOWN = 99
}
public static partial class Helper
{
public static string APIVersionString(API_Version v)
{
switch (v)
{
case API_Version.API_1_1:
return "1.1";
case API_Version.API_1_2:
return "1.2";
case API_Version.API_1_3:
return "1.3";
case API_Version.API_1_4:
return "1.4";
case API_Version.API_1_5:
return "1.5";
case API_Version.API_1_6:
return "1.6";
case API_Version.API_1_7:
return "1.7";
case API_Version.API_1_8:
return "1.8";
case API_Version.API_1_9:
return "1.9";
case API_Version.API_1_10:
return "1.10";
case API_Version.API_2_0:
return "2.0";
case API_Version.API_2_1:
return "2.1";
case API_Version.API_2_2:
return "2.2";
case API_Version.API_2_3:
return "2.3";
case API_Version.API_2_4:
return "2.4";
case API_Version.API_2_5:
return "2.5";
case API_Version.API_2_6:
return "2.6";
case API_Version.API_2_7:
return "2.7";
case API_Version.API_2_8:
return "2.8";
case API_Version.API_2_9:
return "2.9";
case API_Version.API_2_10:
return "2.10";
case API_Version.API_2_11:
return "2.11";
case API_Version.API_2_12:
return "2.12";
case API_Version.API_2_13:
return "2.13";
case API_Version.API_2_14:
return "2.14";
case API_Version.API_2_15:
return "2.15";
case API_Version.API_2_20:
return "2.20";
default:
return "Unknown";
}
}
public static API_Version GetAPIVersion(long major, long minor)
{
try
{
return (API_Version)Enum.Parse(typeof(API_Version),
string.Format("API_{0}_{1}", major, minor));
}
catch (ArgumentException)
{
return API_Version.UNKNOWN;
}
}
/// <summary>
/// Converts the string representation of an API version number to its API_Version equivalent.
/// This function assumes that API version numbers are of form a.b
/// </summary>
public static API_Version GetAPIVersion(string version)
{
if (version != null)
{
string[] tokens = version.Split('.');
int major, minor;
if (tokens.Length == 2 && int.TryParse(tokens[0], out major) && int.TryParse(tokens[1], out minor))
{
return GetAPIVersion(major, minor);
}
}
return API_Version.UNKNOWN;
}
/// <summary>
/// Return a positive number if the given session's API version is greater than the given
/// API_version, negative if it is less, and 0 if they are equal.
/// </summary>
internal static int APIVersionCompare(Session session, API_Version v)
{
return (int)session.APIVersion - (int)v;
}
/// <summary>
/// Return true if the given session's API version is greater than or equal to the given
/// API_version.
/// </summary>
internal static bool APIVersionMeets(Session session, API_Version v)
{
return APIVersionCompare(session, v) >= 0;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcwcv = Google.Cloud.Workflows.Common.V1Beta;
using gcwev = Google.Cloud.Workflows.Executions.V1Beta;
using sys = System;
namespace Google.Cloud.Workflows.Executions.V1Beta
{
/// <summary>Resource name for the <c>Execution</c> resource.</summary>
public sealed partial class ExecutionName : gax::IResourceName, sys::IEquatable<ExecutionName>
{
/// <summary>The possible contents of <see cref="ExecutionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}</c>.
/// </summary>
ProjectLocationWorkflowExecution = 1,
}
private static gax::PathTemplate s_projectLocationWorkflowExecution = new gax::PathTemplate("projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}");
/// <summary>Creates a <see cref="ExecutionName"/> 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="ExecutionName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ExecutionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ExecutionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ExecutionName"/> with the pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}</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="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="executionId">The <c>Execution</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ExecutionName"/> constructed from the provided ids.</returns>
public static ExecutionName FromProjectLocationWorkflowExecution(string projectId, string locationId, string workflowId, string executionId) =>
new ExecutionName(ResourceNameType.ProjectLocationWorkflowExecution, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), workflowId: gax::GaxPreconditions.CheckNotNullOrEmpty(workflowId, nameof(workflowId)), executionId: gax::GaxPreconditions.CheckNotNullOrEmpty(executionId, nameof(executionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ExecutionName"/> with pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}</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="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="executionId">The <c>Execution</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ExecutionName"/> with pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string workflowId, string executionId) =>
FormatProjectLocationWorkflowExecution(projectId, locationId, workflowId, executionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ExecutionName"/> with pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}</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="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="executionId">The <c>Execution</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ExecutionName"/> with pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}</c>.
/// </returns>
public static string FormatProjectLocationWorkflowExecution(string projectId, string locationId, string workflowId, string executionId) =>
s_projectLocationWorkflowExecution.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(workflowId, nameof(workflowId)), gax::GaxPreconditions.CheckNotNullOrEmpty(executionId, nameof(executionId)));
/// <summary>Parses the given resource name string into a new <see cref="ExecutionName"/> 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}/workflows/{workflow}/executions/{execution}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="executionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ExecutionName"/> if successful.</returns>
public static ExecutionName Parse(string executionName) => Parse(executionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ExecutionName"/> 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}/workflows/{workflow}/executions/{execution}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="executionName">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="ExecutionName"/> if successful.</returns>
public static ExecutionName Parse(string executionName, bool allowUnparsed) =>
TryParse(executionName, allowUnparsed, out ExecutionName 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="ExecutionName"/> 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}/workflows/{workflow}/executions/{execution}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="executionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ExecutionName"/>, 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 executionName, out ExecutionName result) => TryParse(executionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ExecutionName"/> 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}/workflows/{workflow}/executions/{execution}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="executionName">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="ExecutionName"/>, 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 executionName, bool allowUnparsed, out ExecutionName result)
{
gax::GaxPreconditions.CheckNotNull(executionName, nameof(executionName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationWorkflowExecution.TryParseName(executionName, out resourceName))
{
result = FromProjectLocationWorkflowExecution(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(executionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ExecutionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string executionId = null, string locationId = null, string projectId = null, string workflowId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ExecutionId = executionId;
LocationId = locationId;
ProjectId = projectId;
WorkflowId = workflowId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ExecutionName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/workflows/{workflow}/executions/{execution}</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="workflowId">The <c>Workflow</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="executionId">The <c>Execution</c> ID. Must not be <c>null</c> or empty.</param>
public ExecutionName(string projectId, string locationId, string workflowId, string executionId) : this(ResourceNameType.ProjectLocationWorkflowExecution, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), workflowId: gax::GaxPreconditions.CheckNotNullOrEmpty(workflowId, nameof(workflowId)), executionId: gax::GaxPreconditions.CheckNotNullOrEmpty(executionId, nameof(executionId)))
{
}
/// <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>Execution</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ExecutionId { 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>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Workflow</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string WorkflowId { 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.ProjectLocationWorkflowExecution: return s_projectLocationWorkflowExecution.Expand(ProjectId, LocationId, WorkflowId, ExecutionId);
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 ExecutionName);
/// <inheritdoc/>
public bool Equals(ExecutionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ExecutionName a, ExecutionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ExecutionName a, ExecutionName b) => !(a == b);
}
public partial class Execution
{
/// <summary>
/// <see cref="gcwev::ExecutionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcwev::ExecutionName ExecutionName
{
get => string.IsNullOrEmpty(Name) ? null : gcwev::ExecutionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListExecutionsRequest
{
/// <summary>
/// <see cref="gcwcv::WorkflowName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gcwcv::WorkflowName ParentAsWorkflowName
{
get => string.IsNullOrEmpty(Parent) ? null : gcwcv::WorkflowName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class CreateExecutionRequest
{
/// <summary>
/// <see cref="gcwcv::WorkflowName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gcwcv::WorkflowName ParentAsWorkflowName
{
get => string.IsNullOrEmpty(Parent) ? null : gcwcv::WorkflowName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetExecutionRequest
{
/// <summary>
/// <see cref="gcwev::ExecutionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcwev::ExecutionName ExecutionName
{
get => string.IsNullOrEmpty(Name) ? null : gcwev::ExecutionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CancelExecutionRequest
{
/// <summary>
/// <see cref="gcwev::ExecutionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcwev::ExecutionName ExecutionName
{
get => string.IsNullOrEmpty(Name) ? null : gcwev::ExecutionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Reflection
{
using System;
using System.Reflection;
////using System.Reflection.Cache;
////using System.Reflection.Emit;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
////using System.Security.Permissions;
////using System.Collections;
////using System.Security;
////using System.Text;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
////using System.Runtime.InteropServices;
////using System.Runtime.Serialization;
////using System.Runtime.Versioning;
////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
////using CorElementType = System.Reflection.CorElementType;
////using MdToken = System.Reflection.MetadataToken;
[Serializable]
public unsafe class ParameterInfo /*: ICustomAttributeProvider*/
{
#region Static Members
//// internal unsafe static ParameterInfo[] GetParameters( MethodBase method, MemberInfo member, Signature sig )
//// {
//// ParameterInfo dummy;
////
//// return GetParameters( method, member, sig, out dummy, false );
//// }
////
//// internal unsafe static ParameterInfo GetReturnParameter( MethodBase method, MemberInfo member, Signature sig )
//// {
//// ParameterInfo returnParameter;
////
//// GetParameters( method, member, sig, out returnParameter, true );
////
//// return returnParameter;
//// }
////
//// internal unsafe static ParameterInfo[] GetParameters( MethodBase method ,
//// MemberInfo member ,
//// Signature sig ,
//// out ParameterInfo returnParameter ,
//// bool fetchReturnParameter )
//// {
//// returnParameter = null;
////
//// RuntimeMethodHandle methodHandle = method.GetMethodHandle();
//// int sigArgCount = sig.Arguments.Length;
//// ParameterInfo[] args = fetchReturnParameter ? null : new ParameterInfo[sigArgCount];
////
//// int tkMethodDef = methodHandle.GetMethodDef();
//// int cParamDefs = 0;
////
//// // Not all methods have tokens. Arrays, pointers and byRef types do not have tokens as they
//// // are generated on the fly by the runtime.
//// if(!MdToken.IsNullToken( tkMethodDef ))
//// {
//// MetadataImport scope = methodHandle.GetDeclaringType().GetModuleHandle().GetMetadataImport();
////
//// cParamDefs = scope.EnumParamsCount( tkMethodDef );
////
//// int* tkParamDefs = stackalloc int[cParamDefs];
////
//// scope.EnumParams( tkMethodDef, tkParamDefs, cParamDefs );
////
//// // Not all parameters have tokens. Parameters may have no token
//// // if they have no name and no attributes.
//// ASSERT.CONSISTENCY_CHECK( cParamDefs <= sigArgCount + 1 /* return type */);
////
////
//// for(uint i = 0; i < cParamDefs; i++)
//// {
//// #region Populate ParameterInfos
//// ParameterAttributes attr;
//// int position;
//// int tkParamDef = tkParamDefs[i];
////
//// scope.GetParamDefProps( tkParamDef, out position, out attr );
////
//// position--;
////
//// if(fetchReturnParameter == true && position == -1)
//// {
//// ASSERT.CONSISTENCY_CHECK( returnParameter == null );
//// returnParameter = new ParameterInfo( sig, scope, tkParamDef, position, attr, member );
//// }
//// else if(fetchReturnParameter == false && position >= 0)
//// {
//// ASSERT.CONSISTENCY_CHECK( position < sigArgCount );
//// args[position] = new ParameterInfo( sig, scope, tkParamDef, position, attr, member );
//// }
//// #endregion
//// }
//// }
////
//// // Fill in empty ParameterInfos for those without tokens
//// if(fetchReturnParameter)
//// {
//// if(returnParameter == null)
//// {
//// returnParameter = new ParameterInfo( sig, MetadataImport.EmptyImport, 0, -1, (ParameterAttributes)0, member );
//// }
//// }
//// else
//// {
//// if(cParamDefs < args.Length + 1)
//// {
//// for(int i = 0; i < args.Length; i++)
//// {
//// if(args[i] != null)
//// {
//// continue;
//// }
////
//// args[i] = new ParameterInfo( sig, MetadataImport.EmptyImport, 0, i, (ParameterAttributes)0, member );
//// }
//// }
//// }
////
//// return args;
//// }
#endregion
#region Private Statics
//// private static readonly Type s_DecimalConstantAttributeType = typeof( DecimalConstantAttribute );
//// private static readonly Type s_CustomConstantAttributeType = typeof( CustomConstantAttribute );
//// private static Type ParameterInfoType = typeof( System.Reflection.ParameterInfo );
#endregion
#region Definitions
//// [Flags]
//// private enum WhatIsCached
//// {
//// Nothing = 0x0,
//// Name = 0x1,
//// ParameterType = 0x2,
//// DefaultValue = 0x4,
//// All = Name | ParameterType | DefaultValue
//// }
#endregion
#region Legacy Protected Members
//// protected String NameImpl;
//// protected Type ClassImpl;
//// protected int PositionImpl;
//// protected ParameterAttributes AttrsImpl;
//// protected Object DefaultValueImpl; // cannot cache this as it may be non agile user defined enum
//// protected MemberInfo MemberImpl;
#endregion
#region Legacy Private Members
// These are here only for backwards compatibility -- they are not set
// until this instance is serialized, so don't rely on their values from
// arbitrary code.
#pragma warning disable 414
//// private IntPtr _importer;
//// private int _token;
//// private bool bExtraConstChecked;
#pragma warning restore 414
#endregion
#region Private Data Members
//// // These are new in Whidbey, so we cannot serialize them directly or we break backwards compatibility.
//// [NonSerialized]
//// private int m_tkParamDef;
//// [NonSerialized]
//// private MetadataImport m_scope;
//// [NonSerialized]
//// private Signature m_signature;
//// [NonSerialized]
//// private volatile bool m_nameIsCached = false;
//// [NonSerialized]
//// private readonly bool m_noDefaultValue = false;
#endregion
#region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints.
//// [OnSerializing]
//// private void OnSerializing( StreamingContext context )
//// {
//// // We could be serializing for consumption by a pre-Whidbey
//// // endpoint. Therefore we set up all the serialized fields to look
//// // just like a v1.0/v1.1 instance.
////
//// // First force all the protected fields (*Impl) which are computed
//// // to be set if they aren't already.
//// Object dummy;
//// dummy = ParameterType;
//// dummy = Name;
//// DefaultValueImpl = DefaultValue;
////
//// // Now set the legacy fields that the current implementation doesn't
//// // use any more. Note that _importer is a raw pointer that should
//// // never have been serialized in V1. We set it to zero here; if the
//// // deserializer uses it (by calling GetCustomAttributes() on this
//// // instance) they'll AV, but at least it will be a well defined
//// // exception and not a random AV.
//// _importer = IntPtr.Zero;
//// _token = m_tkParamDef;
//// bExtraConstChecked = false;
//// }
////
//// [OnDeserialized]
//// private void OnDeserialized( StreamingContext context )
//// {
//// // Once all the serializable fields have come in we can setup this
//// // instance based on just two of them (MemberImpl and PositionImpl).
//// // Use these members to lookup a template ParameterInfo then clone
//// // that instance into this one.
////
//// ParameterInfo targetInfo = null;
////
//// if(MemberImpl == null)
//// {
//// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_InsufficientState ) );
//// }
////
//// ParameterInfo[] args = null;
////
//// switch(MemberImpl.MemberType)
//// {
//// case MemberTypes.Constructor:
//// case MemberTypes.Method:
//// if(PositionImpl == -1)
//// {
//// if(MemberImpl.MemberType == MemberTypes.Method)
//// {
//// targetInfo = ((MethodInfo)MemberImpl).ReturnParameter;
//// }
//// else
//// {
//// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_BadParameterInfo ) );
//// }
//// }
//// else
//// {
//// args = ((MethodBase)MemberImpl).GetParametersNoCopy();
////
//// if(args != null && PositionImpl < args.Length)
//// {
//// targetInfo = args[PositionImpl];
//// }
//// else
//// {
//// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_BadParameterInfo ) );
//// }
//// }
//// break;
////
//// case MemberTypes.Property:
//// args = ((PropertyInfo)MemberImpl).GetIndexParameters();
////
//// if(args != null && PositionImpl > -1 && PositionImpl < args.Length)
//// {
//// targetInfo = args[PositionImpl];
//// }
//// else
//// {
//// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_BadParameterInfo ) );
//// }
//// break;
////
//// default:
//// throw new SerializationException( Environment.GetResourceString( ResId.Serialization_NoParameterInfo ) );
//// }
////
//// // We've got a ParameterInfo that matches the incoming information,
//// // clone it into ourselves. We really only need to copy the private
//// // members we didn't receive via serialization.
//// ASSERT.PRECONDITION( targetInfo != null );
////
//// m_tkParamDef = targetInfo.m_tkParamDef;
//// m_scope = targetInfo.m_scope;
//// m_signature = targetInfo.m_signature;
//// m_nameIsCached = true;
//// }
#endregion
#region Constructor
//// protected ParameterInfo()
//// {
//// m_nameIsCached = true;
//// m_noDefaultValue = true;
//// }
////
//// internal ParameterInfo( ParameterInfo accessor, RuntimePropertyInfo property ) : this( accessor, (MemberInfo)property )
//// {
//// m_signature = property.Signature;
//// }
////
//// internal ParameterInfo( ParameterInfo accessor, MethodBuilderInstantiation method ) : this( accessor, (MemberInfo)method )
//// {
//// m_signature = accessor.m_signature;
////
//// if(ClassImpl.IsGenericParameter)
//// {
//// ClassImpl = method.GetGenericArguments()[ClassImpl.GenericParameterPosition];
//// }
//// }
////
//// private ParameterInfo( ParameterInfo accessor, MemberInfo member )
//// {
//// // Change ownership
//// MemberImpl = member;
////
//// // Populate all the caches -- we inherit this behavior from RTM
//// NameImpl = accessor.Name;
//// m_nameIsCached = true;
//// ClassImpl = accessor.ParameterType;
//// PositionImpl = accessor.Position;
//// AttrsImpl = accessor.Attributes;
////
//// // Strictly speeking, property's don't contain paramter tokens
//// // However we need this to make ca's work... oh well...
//// m_tkParamDef = MdToken.IsNullToken( accessor.MetadataToken ) ? (int)MetadataTokenType.ParamDef : accessor.MetadataToken;
//// m_scope = accessor.m_scope;
//// }
////
//// private ParameterInfo( Signature signature ,
//// MetadataImport scope ,
//// int tkParamDef,
//// int position ,
//// ParameterAttributes attributes,
//// MemberInfo member )
//// {
//// ASSERT.PRECONDITION( member != null );
//// ASSERT.PRECONDITION( LOGIC.BIJECTION( MdToken.IsNullToken( tkParamDef ), scope.Equals( null ) ) );
//// ASSERT.PRECONDITION( LOGIC.IMPLIES( !MdToken.IsNullToken( tkParamDef ), MdToken.IsTokenOfType( tkParamDef, MetadataTokenType.ParamDef ) ) );
////
//// PositionImpl = position;
//// MemberImpl = member;
//// m_signature = signature;
//// m_tkParamDef = MdToken.IsNullToken( tkParamDef ) ? (int)MetadataTokenType.ParamDef : tkParamDef;
//// m_scope = scope;
//// AttrsImpl = attributes;
////
//// ClassImpl = null;
//// NameImpl = null;
//// }
////
//// // ctor for no metadata MethodInfo
//// internal ParameterInfo( MethodInfo owner, String name, RuntimeType parameterType, int position )
//// {
//// MemberImpl = owner;
//// NameImpl = name;
//// m_nameIsCached = true;
//// m_noDefaultValue = true;
//// ClassImpl = parameterType;
//// PositionImpl = position;
//// AttrsImpl = ParameterAttributes.None;
//// m_tkParamDef = (int)MetadataTokenType.ParamDef;
//// m_scope = MetadataImport.EmptyImport;
//// }
#endregion
#region Private Members
//// private bool IsLegacyParameterInfo
//// {
//// get
//// {
//// return GetType() != typeof( ParameterInfo );
//// }
//// }
#endregion
#region Internal Members
//// // this is an internal api for DynamicMethod. A better solution is to change the relationship
//// // between ParameterInfo and ParameterBuilder so that a ParameterBuilder can be seen as a writer
//// // api over a ParameterInfo. However that is a possible breaking change so it needs to go through some process first
//// internal void SetName( String name )
//// {
//// NameImpl = name;
//// }
////
//// internal void SetAttributes( ParameterAttributes attributes )
//// {
//// AttrsImpl = attributes;
//// }
#endregion
#region Public Methods
public extern virtual Type ParameterType
{
[MethodImpl( MethodImplOptions.InternalCall )]
get;
//// {
//// // only instance of ParameterInfo has ClassImpl, all its subclasses don't
//// if(ClassImpl == null && this.GetType() == typeof( ParameterInfo ))
//// {
//// RuntimeTypeHandle parameterTypeHandle;
//// if(PositionImpl == -1)
//// {
//// parameterTypeHandle = m_signature.ReturnTypeHandle;
//// }
//// else
//// {
//// parameterTypeHandle = m_signature.Arguments[PositionImpl];
//// }
////
//// ASSERT.CONSISTENCY_CHECK( !parameterTypeHandle.IsNullHandle() );
//// // different thread could only write ClassImpl to the same value, so race is not a problem here
//// ClassImpl = parameterTypeHandle.GetRuntimeType();
//// }
////
//// BCLDebug.Assert( ClassImpl != null || this.GetType() != typeof( ParameterInfo ), "ClassImple should already be initialized for ParameterInfo class" );
////
//// return ClassImpl;
//// }
}
public virtual String Name
{
get
{
//////if(!m_nameIsCached)
//////{
////// if(!MdToken.IsNullToken( m_tkParamDef ))
////// {
////// string name = m_scope.GetName( m_tkParamDef ).ToString();
////// NameImpl = name;
////// }
////// // other threads could only write it to true, so race is OK
////// // this field is volatile, so the write ordering is guaranteed
////// m_nameIsCached = true;
//////}
//////// name may be null
//////return NameImpl;
return String.Empty;
}
}
//// public virtual Object DefaultValue
//// {
//// get
//// {
//// return GetDefaultValue( false );
//// }
//// }
////
//// public virtual Object RawDefaultValue
//// {
//// get
//// {
//// return GetDefaultValue( true );
//// }
//// }
////
//// internal Object GetDefaultValue( bool raw )
//// {
//// // Cannot cache because default value could be non-agile user defined enumeration.
//// object defaultValue = null;
////
//// // for dynamic method we pretend to have cached the value so we do not go to metadata
//// if(!m_noDefaultValue)
//// {
//// if(ParameterType == typeof( DateTime ))
//// {
//// if(raw)
//// {
//// CustomAttributeTypedArgument value = CustomAttributeData.Filter( CustomAttributeData.GetCustomAttributes( this ), typeof( DateTimeConstantAttribute ), 0 );
////
//// if(value.ArgumentType != null)
//// {
//// return new DateTime( (long)value.Value );
//// }
//// }
//// else
//// {
//// object[] dt = GetCustomAttributes( typeof( DateTimeConstantAttribute ), false );
////
//// if(dt != null && dt.Length != 0)
//// {
//// return ((DateTimeConstantAttribute)dt[0]).Value;
//// }
//// }
//// }
////
//// #region Look for a default value in metadata
//// if(!MdToken.IsNullToken( m_tkParamDef ))
//// {
//// defaultValue = MdConstant.GetValue( m_scope, m_tkParamDef, ParameterType.GetTypeHandleInternal(), raw );
//// }
//// #endregion
////
//// if(defaultValue == DBNull.Value)
//// {
//// #region Look for a default value in the custom attributes
//// if(raw)
//// {
//// System.Collections.Generic.IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes( this );
//// CustomAttributeTypedArgument value = CustomAttributeData.Filter( attrs, s_CustomConstantAttributeType, "Value" );
////
//// if(value.ArgumentType == null)
//// {
//// value = CustomAttributeData.Filter( attrs, s_DecimalConstantAttributeType, "Value" );
////
////
//// if(value.ArgumentType == null)
//// {
//// for(int i = 0; i < attrs.Count; i++)
//// {
//// if(attrs[i].Constructor.DeclaringType == s_DecimalConstantAttributeType)
//// {
//// ParameterInfo[] parameters = attrs[i].Constructor.GetParameters();
////
//// if(parameters.Length != 0)
//// {
//// if(parameters[2].ParameterType == typeof( uint ))
//// {
//// System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attrs[i].ConstructorArguments;
////
//// int low = (int)(UInt32)args[4].Value;
//// int mid = (int)(UInt32)args[3].Value;
//// int hi = (int)(UInt32)args[2].Value;
//// byte sign = (byte)args[1].Value;
//// byte scale = (byte)args[0].Value;
////
//// value = new CustomAttributeTypedArgument( new System.Decimal( low, mid, hi, (sign != 0), scale ) );
//// }
//// else
//// {
//// System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attrs[i].ConstructorArguments;
////
//// int low = (int)args[4].Value;
//// int mid = (int)args[3].Value;
//// int hi = (int)args[2].Value;
//// byte sign = (byte)args[1].Value;
//// byte scale = (byte)args[0].Value;
////
//// value = new CustomAttributeTypedArgument( new System.Decimal( low, mid, hi, (sign != 0), scale ) );
//// }
//// }
//// }
//// }
//// }
//// }
////
//// if(value.ArgumentType != null)
//// {
//// defaultValue = value.Value;
//// }
//// }
//// else
//// {
//// Object[] CustomAttrs = GetCustomAttributes( s_CustomConstantAttributeType, false );
//// if(CustomAttrs.Length != 0)
//// {
//// defaultValue = ((CustomConstantAttribute)CustomAttrs[0]).Value;
//// }
//// else
//// {
//// CustomAttrs = GetCustomAttributes( s_DecimalConstantAttributeType, false );
//// if(CustomAttrs.Length != 0)
//// {
//// defaultValue = ((DecimalConstantAttribute)CustomAttrs[0]).Value;
//// }
//// }
//// }
//// #endregion
//// }
////
//// if(defaultValue == DBNull.Value)
//// {
//// #region Handle case if no default value was found
//// if(IsOptional)
//// {
//// // If the argument is marked as optional then the default value is Missing.Value.
//// defaultValue = Type.Missing;
//// }
//// #endregion
//// }
//// }
////
//// return defaultValue;
//// }
////
//// public virtual int Position
//// {
//// get
//// {
//// return PositionImpl;
//// }
//// }
////
//// public virtual ParameterAttributes Attributes
//// {
//// get
//// {
//// return AttrsImpl;
//// }
//// }
////
//// public virtual MemberInfo Member
//// {
//// get
//// {
//// return MemberImpl;
//// }
//// }
////
//// public bool IsIn
//// {
//// get
//// {
//// return ((Attributes & ParameterAttributes.In) != 0);
//// }
//// }
////
//// public bool IsOut
//// {
//// get
//// {
//// return ((Attributes & ParameterAttributes.Out) != 0);
//// }
//// }
////
//// public bool IsLcid
//// {
//// get
//// {
//// return ((Attributes & ParameterAttributes.Lcid) != 0);
//// }
//// }
////
//// public bool IsRetval
//// {
//// get
//// {
//// return ((Attributes & ParameterAttributes.Retval) != 0);
//// }
//// }
////
//// public bool IsOptional
//// {
//// get
//// {
//// return ((Attributes & ParameterAttributes.Optional) != 0);
//// }
//// }
////
//// public int MetadataToken
//// {
//// get
//// {
//// return m_tkParamDef;
//// }
//// }
////
//// public virtual Type[] GetRequiredCustomModifiers()
//// {
//// if(IsLegacyParameterInfo)
//// {
//// return new Type[0];
//// }
////
//// return m_signature.GetCustomModifiers( PositionImpl + 1, true );
//// }
////
//// public virtual Type[] GetOptionalCustomModifiers()
//// {
//// if(IsLegacyParameterInfo)
//// {
//// return new Type[0];
//// }
////
//// return m_signature.GetCustomModifiers( PositionImpl + 1, false );
//// }
////
#endregion
#region Object Overrides
//// public override String ToString()
//// {
//// return ParameterType.SigToString() + " " + Name;
//// }
#endregion
#region ICustomAttributeProvider
//// public virtual Object[] GetCustomAttributes( bool inherit )
//// {
//// if(IsLegacyParameterInfo)
//// {
//// return null;
//// }
////
//// if(MdToken.IsNullToken( m_tkParamDef ))
//// {
//// return new object[0];
//// }
////
//// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType );
//// }
////
//// public virtual Object[] GetCustomAttributes( Type attributeType, bool inherit )
//// {
//// if(IsLegacyParameterInfo)
//// {
//// return null;
//// }
////
//// if(attributeType == null)
//// {
//// throw new ArgumentNullException( "attributeType" );
//// }
////
//// if(MdToken.IsNullToken( m_tkParamDef ))
//// {
//// return new object[0];
//// }
////
//// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
////
//// if(attributeRuntimeType == null)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" );
//// }
////
//// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType );
//// }
////
//// public virtual bool IsDefined( Type attributeType, bool inherit )
//// {
//// if(IsLegacyParameterInfo)
//// {
//// return false;
//// }
////
//// if(attributeType == null)
//// {
//// throw new ArgumentNullException( "attributeType" );
//// }
////
//// if(MdToken.IsNullToken( m_tkParamDef ))
//// {
//// return false;
//// }
////
//// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
////
//// if(attributeRuntimeType == null)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" );
//// }
////
//// return CustomAttribute.IsDefined( this, attributeRuntimeType );
//// }
#endregion
#region Remoting Cache
//// private InternalCache m_cachedData;
////
//// internal InternalCache Cache
//// {
//// get
//// {
//// // This grabs an internal copy of m_cachedData and uses
//// // that instead of looking at m_cachedData directly because
//// // the cache may get cleared asynchronously. This prevents
//// // us from having to take a lock.
//// InternalCache cache = m_cachedData;
//// if(cache == null)
//// {
//// cache = new InternalCache( "ParameterInfo" );
//// InternalCache ret = Interlocked.CompareExchange( ref m_cachedData, cache, null );
//// if(ret != null)
//// {
//// cache = ret;
//// }
////
//// GC.ClearCache += new ClearCacheHandler( OnCacheClear );
//// }
////
//// return cache;
//// }
//// }
////
//// internal void OnCacheClear( Object sender, ClearCacheEventArgs cacheEventArgs )
//// {
//// m_cachedData = null;
//// }
#endregion
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Drawing;
using System.Threading;
using System.Linq;
using Gallio.Common.Markup;
using Gallio.Common.Media;
using Gallio.Common.Reflection;
using Gallio.Framework;
using Gallio.Runner.Reports.Schema;
using MbUnit.Framework;
namespace Gallio.Tests.Framework
{
[TestFixture]
[TestsOn(typeof(Capture))]
[RunSample(typeof(AutoEmbedScreenshotSamples))]
[RunSample(typeof(AutoEmbedRecordingSamples))]
public class CaptureTest : BaseTestWithSampleRunner
{
[Test]
public void ScreenSize_ReturnsSensibleResult()
{
Size screenSize = Capture.GetScreenSize();
Assert.Multiple(() =>
{
Assert.GreaterThan(screenSize.Width, 0);
Assert.GreaterThan(screenSize.Height, 0);
});
}
[Test]
[Row("A caption.")]
[Row(null)]
public void Screenshot_CapturesScreenshot(string caption)
{
Size screenSize = Capture.GetScreenSize();
if (Capture.CanCaptureScreenshot())
{
if (caption != null)
Capture.SetCaption(caption);
using (Bitmap bitmap = Capture.Screenshot())
{
TestLog.EmbedImage("Screenshot", bitmap);
Assert.Multiple(() =>
{
Assert.AreEqual(screenSize.Width, bitmap.Width);
Assert.AreEqual(screenSize.Height, bitmap.Height);
});
}
}
else
{
Assert.Throws<ScreenshotNotAvailableException>(() => Capture.Screenshot(),
"CanCaptureScreenshot returned false so expected an exception to be thrown.");
}
}
[Test]
public void Screenshot_WhenCaptureParametersIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() => Capture.Screenshot(null));
}
[Test]
[Row("A caption.")]
[Row(null)]
public void Screenshot_WithCaptureParametersIncludingZoomFactor_CapturesZoomedScreenshot(string caption)
{
Size screenSize = Capture.GetScreenSize();
if (Capture.CanCaptureScreenshot())
{
if (caption != null)
Capture.SetCaption(caption);
using (Bitmap bitmap = Capture.Screenshot(new CaptureParameters() {Zoom = 0.25}))
{
TestLog.EmbedImage("Screenshot with 0.25x zoom", bitmap);
Assert.Multiple(() =>
{
Assert.AreApproximatelyEqual(screenSize.Width / 2, bitmap.Width, 1);
Assert.AreApproximatelyEqual(screenSize.Height / 2, bitmap.Height, 1);
});
}
}
else
{
Assert.Throws<ScreenshotNotAvailableException>(() => Capture.Screenshot(new CaptureParameters() { Zoom = 0.25 }),
"CanCaptureScreenshot returned false so expected an exception to be thrown.");
}
}
[Test]
[Row("A caption.")]
[Row(null)]
public void StartRecording_CapturesVideo(string caption)
{
Size screenSize = Capture.GetScreenSize();
if (Capture.CanCaptureScreenshot())
{
if (caption != null)
Capture.SetCaption(caption);
using (ScreenRecorder recorder = Capture.StartRecording())
{
Thread.Sleep(2000);
recorder.Stop();
TestLog.EmbedVideo("Video", recorder.Video);
Assert.Multiple(() =>
{
Assert.AreEqual(screenSize.Width, recorder.Video.Parameters.Width);
Assert.AreEqual(screenSize.Height, recorder.Video.Parameters.Height);
});
}
}
else
{
Assert.Throws<ScreenshotNotAvailableException>(() => Capture.StartRecording(),
"CanCaptureScreenshot returned false so expected an exception to be thrown.");
}
}
[Test]
public void StartRecording_WhenCaptureParametersIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() => Capture.StartRecording(null, 5.0));
}
[Test]
[Row("A caption.")]
[Row(null)]
public void StartRecording_WithCaptureParametersIncludingZoomFactor_CapturesZoomedVideo(string caption)
{
Size screenSize = Capture.GetScreenSize();
if (Capture.CanCaptureScreenshot())
{
if (caption != null)
Capture.SetCaption(caption);
using (ScreenRecorder recorder = Capture.StartRecording(new CaptureParameters() {Zoom = 0.25}, 5))
{
Thread.Sleep(2000);
recorder.Stop();
TestLog.EmbedVideo("Video", recorder.Video);
Assert.Multiple(() =>
{
Assert.AreApproximatelyEqual(screenSize.Width / 2, recorder.Video.Parameters.Width, 1);
Assert.AreApproximatelyEqual(screenSize.Height / 2, recorder.Video.Parameters.Height, 1);
});
}
}
else
{
Assert.Throws<ScreenshotNotAvailableException>(() => Capture.StartRecording(new CaptureParameters() { Zoom = 0.25 }, 5),
"CanCaptureScreenshot returned false so expected an exception to be thrown.");
}
}
[Test]
public void AutoEmbedScreenshot_WhenCaptureParametersIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() => Capture.AutoEmbedScreenshot(TriggerEvent.TestFinished, "name", null));
}
[Test]
[Row("Triggered", true)]
[Row("NotTriggered", false)]
public void AutoEmbedScreenshot_EmbedsImageWhenTriggered(string testName, bool triggered)
{
TestStepRun run = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromMember(typeof(AutoEmbedScreenshotSamples).GetMethod(testName)));
if (Capture.CanCaptureScreenshot())
{
if (triggered)
{
Assert.Count(1, run.TestLog.Attachments);
Assert.AreEqual(MimeTypes.Png, run.TestLog.Attachments[0].ContentType);
}
else
{
Assert.Count(0, run.TestLog.Attachments);
}
}
else
{
if (triggered)
{
Assert.Contains(run.TestLog.ToString(), "Screenshot not available.");
}
else
{
Assert.DoesNotContain(run.TestLog.ToString(), "Screenshot not available.");
}
}
}
[Test]
public void AutoEmbedRecording_WhenCaptureParametersIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() => Capture.AutoEmbedRecording(TriggerEvent.TestFinished, "name", null, 5));
}
[Test]
[Row("Triggered", true)]
[Row("NotTriggered", false)]
public void AutoEmbedRecording_EmbedsVideoWhenTriggered(string testName, bool triggered)
{
TestStepRun run = Runner.GetPrimaryTestStepRun(CodeReference.CreateFromMember(typeof(AutoEmbedRecordingSamples).GetMethod(testName)));
if (Capture.CanCaptureScreenshot())
{
if (triggered)
{
Assert.Count(1, run.TestLog.Attachments);
Assert.AreEqual(MimeTypes.FlashVideo, run.TestLog.Attachments[0].ContentType);
}
else
{
Assert.Count(0, run.TestLog.Attachments);
}
}
else
{
if (triggered)
{
Assert.Contains(run.TestLog.ToString(), "Recording not available.");
}
else
{
Assert.DoesNotContain(run.TestLog.ToString(), "Recording not available.");
}
}
}
[Test]
public void GetOverlayManager_ReturnsSameOverlayManagerEachTime()
{
var first = Capture.GetOverlayManager();
var second = Capture.GetOverlayManager();
Assert.Multiple(() =>
{
Assert.IsNotNull(first);
Assert.AreSame(first, second);
});
}
[Test]
public void GetOverlayManager_WhenContextIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() => Capture.GetOverlayManager(null));
}
[Test]
public void AddOverlay_WhenOverlayIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() => Capture.AddOverlay(null));
}
[Test]
public void AddOverlay_WhenOverlayIsValid_AddsTheOverlayToTheOverlayManager()
{
var overlay = new CaptionOverlay();
Capture.AddOverlay(overlay);
Assert.Contains(Capture.GetOverlayManager().Overlays, overlay);
}
[Test]
public void SetCaption_WhenTextIsNull_Throws()
{
Assert.Throws<ArgumentNullException>(() => Capture.SetCaption(null));
}
[Test]
public void SetCaption_WhenTextIsNotNullAndNotEmpty_AddsACaptionOverlay()
{
Capture.SetCaption("A caption.");
var captionOverlay = Capture.GetCaptionOverlay();
Assert.Multiple(() =>
{
Assert.IsNotNull(captionOverlay);
Assert.AreEqual("A caption.", captionOverlay.Text);
});
}
[Test]
public void SetCaption_WhenTextIsNotNullAndNotEmptyAndThereIsAPreviousCaption_ReplacesExistingCaptionOverlay()
{
Capture.SetCaption("A caption.");
Capture.SetCaption("Another caption.");
var overlays = Capture.GetOverlayManager().Overlays.Where(x => x is CaptionOverlay).ToArray();
Assert.Multiple(() =>
{
Assert.Count(1, overlays);
var captionOverlay = (CaptionOverlay)overlays[0];
Assert.AreEqual("Another caption.", captionOverlay.Text);
Assert.AreSame(captionOverlay, Capture.GetCaptionOverlay());
});
}
[Test]
public void SetCaption_WhenTextIsEmptyAndThereIsNoPreviousCaption_CaptionRemainsEmpty()
{
Capture.SetCaption("");
var captionOverlay = Capture.GetCaptionOverlay();
Assert.AreEqual("", captionOverlay.Text);
}
[Test]
public void SetCaption_WhenTextIsEmptyAndThereIsAPreviousCaption_CaptionBecomesEmpty()
{
Capture.SetCaption("A caption.");
Capture.SetCaption("");
var captionOverlay = Capture.GetCaptionOverlay();
Assert.AreEqual("", captionOverlay.Text);
}
[Test]
public void SetCaptionFontSize_WhenFontSizeIsLessThan1_Throws()
{
Assert.Throws<ArgumentOutOfRangeException>(() => Capture.SetCaptionFontSize(0));
Assert.Throws<ArgumentOutOfRangeException>(() => Capture.SetCaptionFontSize(-1));
}
[Test]
public void SetCaptionFontSize_WhenFontSizeIsValid_SetsTheCaptionFontSize()
{
Capture.SetCaptionFontSize(5);
Assert.AreEqual(5, Capture.GetCaptionOverlay().FontSize);
}
[Test]
public void SetCaptionAlignment_SetsTheCaptionHoriontalAndVerticalAlignment()
{
Capture.SetCaptionAlignment(HorizontalAlignment.Right, VerticalAlignment.Middle);
Assert.Multiple(() =>
{
var captionOverlay = Capture.GetCaptionOverlay();
Assert.AreEqual(HorizontalAlignment.Right, captionOverlay.HorizontalAlignment);
Assert.AreEqual(VerticalAlignment.Middle, captionOverlay.VerticalAlignment);
});
}
[Explicit("Sample")]
public class AutoEmbedScreenshotSamples
{
[Test]
public void Triggered()
{
Register(TriggerEvent.TestPassed);
}
[Test]
public void NotTriggered()
{
Register(TriggerEvent.TestPassed);
Assert.Fail();
}
private static void Register(TriggerEvent triggerEvent)
{
Capture.AutoEmbedScreenshot(triggerEvent, null, new CaptureParameters() { Zoom = 0.25 });
}
}
[Explicit("Sample")]
public class AutoEmbedRecordingSamples
{
[Test]
public void Triggered()
{
Register(TriggerEvent.TestPassed);
Thread.Sleep(1000);
}
[Test]
public void NotTriggered()
{
Register(TriggerEvent.TestPassed);
Thread.Sleep(1000);
Assert.Fail();
}
private static void Register(TriggerEvent triggerEvent)
{
Capture.AutoEmbedRecording(triggerEvent, null, new CaptureParameters() { Zoom = 0.25 }, 5);
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A musical group, such as a band, an orchestra, or a choir. Can also be a solo musician.
/// </summary>
public class MusicGroup_Core : TypeCore, IPerformingGroup
{
public MusicGroup_Core()
{
this._TypeId = 176;
this._Id = "MusicGroup";
this._Schema_Org_Url = "http://schema.org/MusicGroup";
string label = "";
GetLabel(out label, "MusicGroup", typeof(MusicGroup_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,200};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{200};
this._Properties = new int[]{67,108,143,229,5,10,47,75,77,85,91,94,95,115,130,137,199,196,11,142,223};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// A collection of music albums.
/// </summary>
private Albums_Core albums;
public Albums_Core Albums
{
get
{
return albums;
}
set
{
albums = value;
SetPropertyInstance(albums);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// A member of the music group\u2014for example, John, Paul, George, or Ringo.
/// </summary>
private MusicGroupMember_Core musicGroupMember;
public MusicGroupMember_Core MusicGroupMember
{
get
{
return musicGroupMember;
}
set
{
musicGroupMember = value;
SetPropertyInstance(musicGroupMember);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// A music recording (track)\u2014usually a single song.
/// </summary>
private Tracks_Core tracks;
public Tracks_Core Tracks
{
get
{
return tracks;
}
set
{
tracks = value;
SetPropertyInstance(tracks);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TMDbLib.Objects.Exceptions;
using TMDbLib.Utilities.Serializer;
namespace TMDbLib.Rest
{
internal class RestRequest
{
private readonly RestClient _client;
private readonly string _endpoint;
private object _bodyObj;
private List<KeyValuePair<string, string>> _queryString;
private List<KeyValuePair<string, string>> _urlSegment;
public RestRequest(RestClient client, string endpoint)
{
_client = client;
_endpoint = endpoint;
}
public RestRequest AddParameter(KeyValuePair<string, string> pair, ParameterType type = ParameterType.QueryString)
{
AddParameter(pair.Key, pair.Value, type);
return this;
}
public RestRequest AddParameter(string key, string value, ParameterType type = ParameterType.QueryString)
{
switch (type)
{
case ParameterType.QueryString:
return AddQueryString(key, value);
case ParameterType.UrlSegment:
return AddUrlSegment(key, value);
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
}
public RestRequest AddQueryString(string key, string value)
{
if (_queryString == null)
_queryString = new List<KeyValuePair<string, string>>();
_queryString.Add(new KeyValuePair<string, string>(key, value));
return this;
}
public RestRequest AddUrlSegment(string key, string value)
{
if (_urlSegment == null)
_urlSegment = new List<KeyValuePair<string, string>>();
_urlSegment.Add(new KeyValuePair<string, string>(key, value));
return this;
}
private void AppendQueryString(StringBuilder sb, string key, string value)
{
if (sb.Length > 0)
sb.Append("&");
sb.Append(key);
sb.Append("=");
sb.Append(WebUtility.UrlEncode(value));
}
private void AppendQueryString(StringBuilder sb, KeyValuePair<string, string> value)
{
AppendQueryString(sb, value.Key, value.Value);
}
public async Task<RestResponse> Delete(CancellationToken cancellationToken)
{
HttpResponseMessage resp = await SendInternal(HttpMethod.Delete, cancellationToken).ConfigureAwait(false);
return new RestResponse(resp);
}
[SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP001:Dispose created", Justification = "resp is disposed by RestResponse<>()")]
public async Task<RestResponse<T>> Delete<T>(CancellationToken cancellationToken)
{
HttpResponseMessage resp = await SendInternal(HttpMethod.Delete, cancellationToken).ConfigureAwait(false);
return new RestResponse<T>(resp, _client);
}
public async Task<RestResponse> Get(CancellationToken cancellationToken)
{
HttpResponseMessage resp = await SendInternal(HttpMethod.Get, cancellationToken).ConfigureAwait(false);
return new RestResponse(resp);
}
[SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP001:Dispose created", Justification = "resp is disposed by RestResponse<>()")]
public async Task<RestResponse<T>> Get<T>(CancellationToken cancellationToken)
{
HttpResponseMessage resp = await SendInternal(HttpMethod.Get, cancellationToken).ConfigureAwait(false);
return new RestResponse<T>(resp, _client);
}
public async Task<RestResponse> Post(CancellationToken cancellationToken)
{
HttpResponseMessage resp = await SendInternal(HttpMethod.Post, cancellationToken).ConfigureAwait(false);
return new RestResponse(resp);
}
[SuppressMessage("IDisposableAnalyzers.Correctness", "IDISP001:Dispose created", Justification = "resp is disposed by RestResponse<>()")]
public async Task<RestResponse<T>> Post<T>(CancellationToken cancellationToken)
{
HttpResponseMessage resp = await SendInternal(HttpMethod.Post, cancellationToken).ConfigureAwait(false);
return new RestResponse<T>(resp, _client);
}
private HttpRequestMessage PrepRequest(HttpMethod method)
{
StringBuilder queryStringSb = new StringBuilder();
// Query String
if (_queryString != null)
{
foreach (KeyValuePair<string, string> pair in _queryString)
AppendQueryString(queryStringSb, pair);
}
foreach (KeyValuePair<string, string> pair in _client.DefaultQueryString)
AppendQueryString(queryStringSb, pair);
// Url
string endpoint = _endpoint;
if (_urlSegment != null)
{
foreach (KeyValuePair<string, string> pair in _urlSegment)
endpoint = endpoint.Replace("{" + pair.Key + "}", pair.Value);
}
// Build
UriBuilder builder = new UriBuilder(new Uri(_client.BaseUrl, endpoint));
builder.Query = queryStringSb.ToString();
HttpRequestMessage req = new HttpRequestMessage(method, builder.Uri);
// Body
if (method == HttpMethod.Post && _bodyObj != null)
{
byte[] bodyBytes = _client.Serializer.SerializeToBytes(_bodyObj);
req.Content = new ByteArrayContent(bodyBytes);
req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
return req;
}
private async Task<HttpResponseMessage> SendInternal(HttpMethod method, CancellationToken cancellationToken)
{
// Account for the following settings:
// - MaxRetryCount Max times to retry
int timesToTry = _client.MaxRetryCount + 1;
RetryConditionHeaderValue retryHeader;
TMDbStatusMessage statusMessage;
Debug.Assert(timesToTry >= 1);
do
{
using HttpRequestMessage req = PrepRequest(method);
HttpResponseMessage resp = await _client.HttpClient.SendAsync(req, cancellationToken).ConfigureAwait(false);
bool isJson = resp.Content.Headers.ContentType.MediaType.Equals("application/json");
if (resp.IsSuccessStatusCode && isJson)
#pragma warning disable IDISP011 // Don't return disposed instance
return resp;
#pragma warning restore IDISP011 // Don't return disposed instance
try
{
if (isJson)
statusMessage = JsonConvert.DeserializeObject<TMDbStatusMessage>(await resp.Content.ReadAsStringAsync().ConfigureAwait(false));
else
statusMessage = null;
switch (resp.StatusCode)
{
case (HttpStatusCode)429:
// The previous result was a ratelimit, read the Retry-After header and wait the allotted time
retryHeader = resp.Headers.RetryAfter;
TimeSpan? retryAfter = retryHeader?.Delta.Value;
if (retryAfter.HasValue && retryAfter.Value.TotalSeconds > 0)
await Task.Delay(retryAfter.Value, cancellationToken).ConfigureAwait(false);
else
// TMDb sometimes gives us 0-second waits, which can lead to rapid succession of requests
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ConfigureAwait(false);
continue;
case HttpStatusCode.Unauthorized:
throw new UnauthorizedAccessException(
"Call to TMDb returned unauthorized. Most likely the provided API key is invalid.");
case HttpStatusCode.NotFound:
if (_client.ThrowApiExceptions)
{
throw new NotFoundException(statusMessage);
}
else
{
return null;
}
}
throw new GeneralHttpException(resp.StatusCode);
}
finally
{
resp.Dispose();
}
} while (timesToTry-- > 0);
// We never reached a success
throw new RequestLimitExceededException(statusMessage, retryHeader?.Date, retryHeader?.Delta);
}
public RestRequest SetBody(object obj)
{
_bodyObj = obj;
return this;
}
}
}
| |
using System;
using System.Data.Common;
using System.Threading.Tasks;
using MySqlConnector;
using Xunit;
using Xunit.Abstractions;
using YesSql.Provider.MySql;
using YesSql.Sql;
using YesSql.Tests.Indexes;
using YesSql.Tests.Models;
namespace YesSql.Tests
{
/// <summary>
/// To run MySQL inside Docker, use this command:
/// docker run --name mysql -e MYSQL_DATABASE=yessql -e MYSQL_USER=user1 -e MYSQL_PASSWORD=Password12! -e MYSQL_ALLOW_EMPTY_PASSWORD=1 -d -p 3306:3306 mysql:8
/// </summary>
public class MySqlTests : CoreTests
{
public static string ConnectionString => Environment.GetEnvironmentVariable("MYSQL_CONNECTION_STRING") ?? @"server=localhost;uid=user1;pwd=Password12!;database=yessql;";
protected override string DecimalColumnDefinitionFormatString => "decimal({0}, {1})";
public MySqlTests(ITestOutputHelper output) : base(output)
{
}
protected override IConfiguration CreateConfiguration()
{
return new Configuration()
.UseMySql(ConnectionString)
.SetTablePrefix(TablePrefix)
.UseBlockIdGenerator()
;
}
[Fact]
public async Task ForeignKeyOfIndexesMustBe_DeleteCascated()
{
var configuration = CreateConfiguration();
_store = await StoreFactory.CreateAndInitializeAsync(configuration);
// First store register the index
_store.RegisterIndexes<PersonIndexProvider>();
var bill = new Person
{
Firstname = "Bill",
Lastname = "Gates"
};
using (var session = _store.CreateSession())
{
session.Save(bill);
await session.SaveChangesAsync();
}
// second store, don't register the index
_store = await StoreFactory.CreateAndInitializeAsync(configuration);
using (var session = _store.CreateSession())
{
var person = await session.Query().For<Person>().FirstOrDefaultAsync();
Assert.NotNull(person);
session.Delete(person);
}
}
[Fact(Skip = "The syntax used for MySQL only works since MySQL 8.0 which is not available on appveyor")]
public override void ShouldRenameColumn()
{
base.ShouldRenameColumn();
}
[Fact]
public async Task ThrowsWhenIndexKeyLengthExceeded()
{
using (var connection = _store.Configuration.ConnectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel))
{
var builder = new SchemaBuilder(_store.Configuration, transaction);
builder
.DropMapIndexTable<PropertyIndex>();
builder
.CreateMapIndexTable<PropertyIndex>(column => column
.Column<string>(nameof(PropertyIndex.Name), col => col.WithLength(769))
.Column<bool>(nameof(PropertyIndex.ForRent))
.Column<bool>(nameof(PropertyIndex.IsOccupied))
.Column<string>(nameof(PropertyIndex.Location), col => col.WithLength(768))
);
Assert.Throws<MySqlException>(() => builder
.AlterTable(nameof(PropertyIndex), table => table
.CreateIndex("IDX_Property", "Name")));
}
}
}
[Fact]
public async Task ThrowsWhenIndexKeysWithBitsLengthExceeded()
{
using (var connection = _store.Configuration.ConnectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel))
{
var builder = new SchemaBuilder(_store.Configuration, transaction);
builder
.DropMapIndexTable<PropertyIndex>();
builder
.CreateMapIndexTable<PropertyIndex>(column => column
.Column<string>(nameof(PropertyIndex.Name), col => col.WithLength(384))
.Column<bool>(nameof(PropertyIndex.ForRent))
.Column<bool>(nameof(PropertyIndex.IsOccupied))
.Column<string>(nameof(PropertyIndex.Location), col => col.WithLength(384))
);
Assert.Throws<MySqlException>(() => builder
.AlterTable(nameof(PropertyIndex), table => table
.CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied", "Location")));
}
}
}
[Fact]
public async Task ThrowsWhenIndexKeysLengthExceeded()
{
using (var connection = _store.Configuration.ConnectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel))
{
var builder = new SchemaBuilder(_store.Configuration, transaction);
builder
.DropMapIndexTable<PropertyIndex>();
builder
.CreateMapIndexTable<PropertyIndex>(column => column
.Column<string>(nameof(PropertyIndex.Name), col => col.WithLength(385))
.Column<bool>(nameof(PropertyIndex.ForRent))
.Column<bool>(nameof(PropertyIndex.IsOccupied))
.Column<string>(nameof(PropertyIndex.Location), col => col.WithLength(384))
);
Assert.Throws<MySqlException>(() => builder
.AlterTable(nameof(PropertyIndex), table => table
.CreateIndex("IDX_Property", "Name", "Location")));
}
}
}
[Fact]
public async Task ShouldCreatePropertyIndexWithMaxKey()
{
using (var connection = _store.Configuration.ConnectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel))
{
var builder = new SchemaBuilder(_store.Configuration, transaction);
builder
.DropMapIndexTable<PropertyIndex>();
builder
.CreateMapIndexTable<PropertyIndex>(column => column
.Column<string>(nameof(PropertyIndex.Name), col => col.WithLength(768))
.Column<bool>(nameof(PropertyIndex.ForRent))
.Column<bool>(nameof(PropertyIndex.IsOccupied))
.Column<string>(nameof(PropertyIndex.Location), col => col.WithLength(768))
);
builder
.AlterTable(nameof(PropertyIndex), table => table
.CreateIndex("IDX_Property", "Name"));
transaction.Commit();
}
}
}
[Fact]
public async Task ShouldCreateIndexPropertyWithMaxKeys()
{
using (var connection = _store.Configuration.ConnectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel))
{
var builder = new SchemaBuilder(_store.Configuration, transaction);
builder
.DropMapIndexTable<PropertyIndex>();
builder
.CreateMapIndexTable<PropertyIndex>(column => column
.Column<string>(nameof(PropertyIndex.Name), col => col.WithLength(384))
.Column<bool>(nameof(PropertyIndex.ForRent))
.Column<bool>(nameof(PropertyIndex.IsOccupied))
.Column<string>(nameof(PropertyIndex.Location), col => col.WithLength(384))
);
builder
.AlterTable(nameof(PropertyIndex), table => table
.CreateIndex("IDX_Property", "Name", "Location"));
transaction.Commit();
}
}
}
[Fact]
public async Task ShouldCreateIndexPropertyWithMaxBitKeys()
{
using (var connection = _store.Configuration.ConnectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel))
{
var builder = new SchemaBuilder(_store.Configuration, transaction);
builder
.DropMapIndexTable<PropertyIndex>();
builder
.CreateMapIndexTable<PropertyIndex>(column => column
.Column<string>(nameof(PropertyIndex.Name), col => col.WithLength(767))
.Column<bool>(nameof(PropertyIndex.ForRent))
.Column<bool>(nameof(PropertyIndex.IsOccupied))
.Column<string>(nameof(PropertyIndex.Location), col => col.WithLength(384))
);
builder
.AlterTable(nameof(PropertyIndex), table => table
.CreateIndex("IDX_Property", "Name", "ForRent", "IsOccupied"));
transaction.Commit();
}
}
}
[Fact]
public async Task ShouldCreateHashedIndexKeyName()
{
await _store.InitializeCollectionAsync("LongCollection");
using (var connection = _store.Configuration.ConnectionFactory.CreateConnection())
{
await connection.OpenAsync();
using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel))
{
var builder = new SchemaBuilder(_store.Configuration, transaction);
// tpFK_LongCollection_PersonsByNameCol_LongCollection_Document_Id : 64 chars. Throws exception if not hashed.
builder.CreateReduceIndexTable<PersonsByNameCol>(column => column
.Column<string>(nameof(PersonsByNameCol.Name))
.Column<int>(nameof(PersonsByNameCol.Count)),
"LongCollection"
);
transaction.Commit();
}
using (var transaction = connection.BeginTransaction(_store.Configuration.IsolationLevel))
{
var builder = new SchemaBuilder(_store.Configuration, transaction);
builder.DropReduceIndexTable<PersonsByNameCol>("LongCollection");
transaction.Commit();
}
}
}
}
}
| |
// 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.Text;
using System.Diagnostics;
namespace System.Xml
{
internal class UTF16Decoder : System.Text.Decoder
{
private bool _bigEndian;
private int _lastByte;
private const int CharSize = 2;
public UTF16Decoder(bool bigEndian)
{
_lastByte = -1;
_bigEndian = bigEndian;
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return GetCharCount(bytes, index, count, false);
}
public override int GetCharCount(byte[] bytes, int index, int count, bool flush)
{
int byteCount = count + ((_lastByte >= 0) ? 1 : 0);
if (flush && (byteCount % CharSize != 0))
{
throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, -1), (string)null);
}
return byteCount / CharSize;
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
int charCount = GetCharCount(bytes, byteIndex, byteCount);
if (_lastByte >= 0)
{
if (byteCount == 0)
{
return charCount;
}
int nextByte = bytes[byteIndex++];
byteCount--;
chars[charIndex++] = _bigEndian
? (char)(_lastByte << 8 | nextByte)
: (char)(nextByte << 8 | _lastByte);
_lastByte = -1;
}
if ((byteCount & 1) != 0)
{
_lastByte = bytes[byteIndex + --byteCount];
}
// use the fast BlockCopy if possible
if (_bigEndian == BitConverter.IsLittleEndian)
{
int byteEnd = byteIndex + byteCount;
if (_bigEndian)
{
while (byteIndex < byteEnd)
{
int hi = bytes[byteIndex++];
int lo = bytes[byteIndex++];
chars[charIndex++] = (char)(hi << 8 | lo);
}
}
else
{
while (byteIndex < byteEnd)
{
int lo = bytes[byteIndex++];
int hi = bytes[byteIndex++];
chars[charIndex++] = (char)(hi << 8 | lo);
}
}
}
else
{
Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, byteCount);
}
return charCount;
}
public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
{
charsUsed = 0;
bytesUsed = 0;
if (_lastByte >= 0)
{
if (byteCount == 0)
{
completed = true;
return;
}
int nextByte = bytes[byteIndex++];
byteCount--;
bytesUsed++;
chars[charIndex++] = _bigEndian
? (char)(_lastByte << 8 | nextByte)
: (char)(nextByte << 8 | _lastByte);
charCount--;
charsUsed++;
_lastByte = -1;
}
if (charCount * CharSize < byteCount)
{
byteCount = charCount * CharSize;
completed = false;
}
else
{
completed = true;
}
if (_bigEndian == BitConverter.IsLittleEndian)
{
int i = byteIndex;
int byteEnd = i + (byteCount & ~0x1);
if (_bigEndian)
{
while (i < byteEnd)
{
int hi = bytes[i++];
int lo = bytes[i++];
chars[charIndex++] = (char)(hi << 8 | lo);
}
}
else
{
while (i < byteEnd)
{
int lo = bytes[i++];
int hi = bytes[i++];
chars[charIndex++] = (char)(hi << 8 | lo);
}
}
}
else
{
Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, (int)(byteCount & ~0x1));
}
charsUsed += byteCount / CharSize;
bytesUsed += byteCount;
if ((byteCount & 1) != 0)
{
_lastByte = bytes[byteIndex + byteCount - 1];
}
}
}
internal class SafeAsciiDecoder : Decoder
{
public SafeAsciiDecoder()
{
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return count;
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
int i = byteIndex;
int j = charIndex;
while (i < byteIndex + byteCount)
{
chars[j++] = (char)bytes[i++];
}
return byteCount;
}
public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
{
if (charCount < byteCount)
{
byteCount = charCount;
completed = false;
}
else
{
completed = true;
}
int i = byteIndex;
int j = charIndex;
int byteEndIndex = byteIndex + byteCount;
while (i < byteEndIndex)
{
chars[j++] = (char)bytes[i++];
}
charsUsed = byteCount;
bytesUsed = byteCount;
}
}
internal class Ucs4Encoding : Encoding
{
internal Ucs4Decoder ucs4Decoder;
public override string WebName
{
get
{
return this.EncodingName;
}
}
public override Decoder GetDecoder()
{
return ucs4Decoder;
}
public override int GetByteCount(char[] chars, int index, int count)
{
return checked(count * 4);
}
public override int GetByteCount(char[] chars)
{
return chars.Length * 4;
}
public override byte[] GetBytes(string s)
{
return null; //ucs4Decoder.GetByteCount(chars, index, count);
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
return 0;
}
public override int GetMaxByteCount(int charCount)
{
return 0;
}
public override int GetCharCount(byte[] bytes, int index, int count)
{
return ucs4Decoder.GetCharCount(bytes, index, count);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
return ucs4Decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
}
public override int GetMaxCharCount(int byteCount)
{
return (byteCount + 3) / 4;
}
public override int CodePage
{
get
{
return 0;
}
}
public override int GetCharCount(byte[] bytes)
{
return bytes.Length / 4;
}
public override Encoder GetEncoder()
{
return null;
}
internal static Encoding UCS4_Littleendian
{
get
{
return new Ucs4Encoding4321();
}
}
internal static Encoding UCS4_Bigendian
{
get
{
return new Ucs4Encoding1234();
}
}
internal static Encoding UCS4_2143
{
get
{
return new Ucs4Encoding2143();
}
}
internal static Encoding UCS4_3412
{
get
{
return new Ucs4Encoding3412();
}
}
}
internal class Ucs4Encoding1234 : Ucs4Encoding
{
public Ucs4Encoding1234()
{
ucs4Decoder = new Ucs4Decoder1234();
}
public override string EncodingName
{
get
{
return "ucs-4 (Bigendian)";
}
}
public override byte[] GetPreamble()
{
return new byte[4] { 0x00, 0x00, 0xfe, 0xff };
}
}
internal class Ucs4Encoding4321 : Ucs4Encoding
{
public Ucs4Encoding4321()
{
ucs4Decoder = new Ucs4Decoder4321();
}
public override string EncodingName
{
get
{
return "ucs-4";
}
}
public override byte[] GetPreamble()
{
return new byte[4] { 0xff, 0xfe, 0x00, 0x00 };
}
}
internal class Ucs4Encoding2143 : Ucs4Encoding
{
public Ucs4Encoding2143()
{
ucs4Decoder = new Ucs4Decoder2143();
}
public override string EncodingName
{
get
{
return "ucs-4 (order 2143)";
}
}
public override byte[] GetPreamble()
{
return new byte[4] { 0x00, 0x00, 0xff, 0xfe };
}
}
internal class Ucs4Encoding3412 : Ucs4Encoding
{
public Ucs4Encoding3412()
{
ucs4Decoder = new Ucs4Decoder3412();
}
public override string EncodingName
{
get
{
return "ucs-4 (order 3412)";
}
}
public override byte[] GetPreamble()
{
return new byte[4] { 0xfe, 0xff, 0x00, 0x00 };
}
}
internal abstract class Ucs4Decoder : Decoder
{
internal byte[] lastBytes = new byte[4];
internal int lastBytesCount = 0;
public override int GetCharCount(byte[] bytes, int index, int count)
{
return (count + lastBytesCount) / 4;
}
internal abstract int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex);
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
// finish a character from the bytes that were cached last time
int i = lastBytesCount;
if (lastBytesCount > 0)
{
// copy remaining bytes into the cache
for (; lastBytesCount < 4 && byteCount > 0; lastBytesCount++)
{
lastBytes[lastBytesCount] = bytes[byteIndex];
byteIndex++;
byteCount--;
}
// still not enough bytes -> return
if (lastBytesCount < 4)
{
return 0;
}
// decode 1 character from the byte cache
i = GetFullChars(lastBytes, 0, 4, chars, charIndex);
Debug.Assert(i == 1);
charIndex += i;
lastBytesCount = 0;
}
else
{
i = 0;
}
// decode block of byte quadruplets
i = GetFullChars(bytes, byteIndex, byteCount, chars, charIndex) + i;
// cache remaining bytes that does not make up a character
int bytesLeft = (byteCount & 0x3);
if (bytesLeft >= 0)
{
for (int j = 0; j < bytesLeft; j++)
{
lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j];
}
lastBytesCount = bytesLeft;
}
return i;
}
public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
{
bytesUsed = 0;
charsUsed = 0;
// finish a character from the bytes that were cached last time
int i = 0;
int lbc = lastBytesCount;
if (lbc > 0)
{
// copy remaining bytes into the cache
for (; lbc < 4 && byteCount > 0; lbc++)
{
lastBytes[lbc] = bytes[byteIndex];
byteIndex++;
byteCount--;
bytesUsed++;
}
// still not enough bytes -> return
if (lbc < 4)
{
lastBytesCount = lbc;
completed = true;
return;
}
// decode 1 character from the byte cache
i = GetFullChars(lastBytes, 0, 4, chars, charIndex);
Debug.Assert(i == 1);
charIndex += i;
charCount -= i;
charsUsed = i;
lastBytesCount = 0;
// if that's all that was requested -> return
if (charCount == 0)
{
completed = (byteCount == 0);
return;
}
}
else
{
i = 0;
}
// modify the byte count for GetFullChars depending on how many characters were requested
if (charCount * 4 < byteCount)
{
byteCount = charCount * 4;
completed = false;
}
else
{
completed = true;
}
bytesUsed += byteCount;
// decode block of byte quadruplets
charsUsed = GetFullChars(bytes, byteIndex, byteCount, chars, charIndex) + i;
// cache remaining bytes that does not make up a character
int bytesLeft = (byteCount & 0x3);
if (bytesLeft >= 0)
{
for (int j = 0; j < bytesLeft; j++)
{
lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j];
}
lastBytesCount = bytesLeft;
}
}
internal void Ucs4ToUTF16(uint code, char[] chars, int charIndex)
{
chars[charIndex] = (char)(XmlCharType.SurHighStart + (char)((code >> 16) - 1) + (char)((code >> 10) & 0x3F));
chars[charIndex + 1] = (char)(XmlCharType.SurLowStart + (char)(code & 0x3FF));
}
}
internal class Ucs4Decoder4321 : Ucs4Decoder
{
internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
uint code;
int i, j;
byteCount += byteIndex;
for (i = byteIndex, j = charIndex; i + 3 < byteCount;)
{
code = (uint)((bytes[i + 3] << 24) | (bytes[i + 2] << 16) | (bytes[i + 1] << 8) | bytes[i]);
if (code > 0x10FFFF)
{
throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null);
}
else if (code > 0xFFFF)
{
Ucs4ToUTF16(code, chars, j);
j++;
}
else
{
if (XmlCharType.IsSurrogate((int)code))
{
throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty);
}
else
{
chars[j] = (char)code;
}
}
j++;
i += 4;
}
return j - charIndex;
}
};
internal class Ucs4Decoder1234 : Ucs4Decoder
{
internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
uint code;
int i, j;
byteCount += byteIndex;
for (i = byteIndex, j = charIndex; i + 3 < byteCount;)
{
code = (uint)((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]);
if (code > 0x10FFFF)
{
throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null);
}
else if (code > 0xFFFF)
{
Ucs4ToUTF16(code, chars, j);
j++;
}
else
{
if (XmlCharType.IsSurrogate((int)code))
{
throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty);
}
else
{
chars[j] = (char)code;
}
}
j++;
i += 4;
}
return j - charIndex;
}
}
internal class Ucs4Decoder2143 : Ucs4Decoder
{
internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
uint code;
int i, j;
byteCount += byteIndex;
for (i = byteIndex, j = charIndex; i + 3 < byteCount;)
{
code = (uint)((bytes[i + 1] << 24) | (bytes[i] << 16) | (bytes[i + 3] << 8) | bytes[i + 2]);
if (code > 0x10FFFF)
{
throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null);
}
else if (code > 0xFFFF)
{
Ucs4ToUTF16(code, chars, j);
j++;
}
else
{
if (XmlCharType.IsSurrogate((int)code))
{
throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty);
}
else
{
chars[j] = (char)code;
}
}
j++;
i += 4;
}
return j - charIndex;
}
}
internal class Ucs4Decoder3412 : Ucs4Decoder
{
internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
{
uint code;
int i, j;
byteCount += byteIndex;
for (i = byteIndex, j = charIndex; i + 3 < byteCount;)
{
code = (uint)((bytes[i + 2] << 24) | (bytes[i + 3] << 16) | (bytes[i] << 8) | bytes[i + 1]);
if (code > 0x10FFFF)
{
throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null);
}
else if (code > 0xFFFF)
{
Ucs4ToUTF16(code, chars, j);
j++;
}
else
{
if (XmlCharType.IsSurrogate((int)code))
{
throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty);
}
else
{
chars[j] = (char)code;
}
}
j++;
i += 4;
}
return j - charIndex;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using LinkFuture.Extensions;
namespace LinkFuture.Library
{
#region EntryInfo
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable")]
public class EntryInfo : Dictionary<string, ColumnMemberInfo>
{
public Type EntryType { get; set; }
private static readonly ConcurrentDictionary<Guid, object> CachedEntryList = new ConcurrentDictionary<Guid, object>();
#region ReadDB
public void ReadDB<T>(IDataRecord reader, T entry) where T : class
{
if (reader != null)
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (this.ContainsKey(reader.GetName(i).ToLower()))
{
ColumnMemberInfo cachedProperty = this[reader.GetName(i).ToLower()];
if (!cachedProperty.IsEntry)
{
if (reader[i] != DBNull.Value && reader[i]!=null)
{
cachedProperty.SetValue(entry, reader[i]);
}
}
}
}
foreach (var item in this.Values)
{
if (item.IsEntry)
{
var subEntryValue = Activator.CreateInstance(item.PropertyType);
item.Entry.ReadDB(reader, subEntryValue);
item.SetAction.DynamicInvoke(entry, subEntryValue);
}
}
}
}
public T ReadDB<T>(IDataRecord reader) where T : class,new()
{
if (reader == null)
{
return default(T);
}
var entry = new T();
this.ReadDB(reader, entry);
return entry;
}
public void ReadDBList<T>(SqlDataReader reader, IList<T> list) where T : class,new()
{
while (reader.Read())
{
var entry = new T();
this.ReadDB(reader, entry);
list.Add(entry);
}
}
public IList<T> ReadDBList<T>(SqlDataReader reader) where T : class,new()
{
IList<T> list = new List<T>();
ReadDBList(reader, list);
return list;
}
#endregion
/// <summary>
/// read value from parameters, and set value to entry if have same column name
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="paramList"></param>
/// <param name="entry"></param>
public void ReadOutputParameters<T>(SqlParameterCollection paramList, T entry) where T:class
{
foreach (SqlParameter param in paramList)
{
if (param.Direction == ParameterDirection.Output || param.Direction == ParameterDirection.InputOutput)
{
if (this.ContainsKey(param.ColumnName().ToLower()))
{
var item = this[param.ColumnName().ToLower()];
if (!item.IsEntry)
{
if (param.Value != DBNull.Value && param.Value!=null)
{
item.SetValue(entry,param.Value);
}
}
}
}
}
}
/// <summary>
/// fill sql parameters from entry if have same column name
/// it is case insensitive.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="paramList"></param>
/// <param name="entry"></param>
public void FillParameters<T>(SqlParameterCollection paramList, T entry) where T : class
{
foreach (var item in this.Values)
{
if (!item.IsEntry)
{
if (paramList.Contains(item.SqlParamName))
{
SqlParameter param = paramList[item.SqlParamName];
if (param.Direction == ParameterDirection.Input || param.Direction == ParameterDirection.InputOutput)
{
var paramValue = item.GetValue(entry);
//special case, it is limiation at MSSQL, check RemoveXmlDeclaration for detail
if (param.DbType == DbType.Xml && paramValue is string)
{
param.Value = ((string)paramValue).RemoveXmlDeclaration();
}
else
{
param.Value = paramValue;
}
}
}
}
else
{
//FillParameters into sub Entry
var subEntryValue = item.GetAction.DynamicInvoke(entry);
if (subEntryValue != null)
{
item.Entry.FillParameters(paramList, subEntryValue);
}
}
}
}
public static EntryInfo FindEntry(Type myType)
{
if (!CachedEntryList.ContainsKey(myType.GUID))
{
EventLogger.TraceLine("Build Entry List:{0}",null, myType.FullName);
var entryAttributeList = myType.ReteriveAttributeList<ColumnMemberAttribute>();
var entry = new EntryInfo {EntryType = myType};
foreach (var attribute in entryAttributeList)
{
string columnName = string.IsNullOrWhiteSpace(attribute.Attribute.ColumnName) ? attribute.Property.Name : attribute.Attribute.ColumnName;
if (!entry.ContainsKey(columnName.ToLower()))
{
if (attribute.Attribute.IsEntry)
{
EntryInfo subEntry = FindEntry(attribute.Property.PropertyType);
entry.Add(columnName.ToLower(), new ColumnMemberInfo
{
SetAction = attribute.SetAction,
GetAction = attribute.GetAction,
ColumnName = columnName,
PropertyType = attribute.Property.PropertyType,
Entry = subEntry,
IsEntry = true,
Attribute = attribute.Attribute,
PropertyName = attribute.Property.Name
});
}
else
{
entry.Add(columnName.ToLower(), new ColumnMemberInfo
{
SetAction = attribute.SetAction,
GetAction = attribute.GetAction,
ColumnName = columnName,
PropertyType = attribute.Property.PropertyType,
Entry = entry,
IsEntry = false,
Attribute = attribute.Attribute,
PropertyName = attribute.Property.Name
});
}
}
}
CachedEntryList[myType.GUID] = entry;
}
return CachedEntryList[myType.GUID] as EntryInfo;
}
/// <summary>
/// throw EntryValidationException if valid failed
/// please specific Validation on your attribute
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entry"></param>
public void Valid<T>(T entry) where T : class
{
foreach (var item in this.Values)
{
//skip if no validation
if (item.IsEntry)
{
var subEntryValue = item.GetAction.DynamicInvoke(entry);
if (subEntryValue != null)
{
item.Entry.Valid(subEntryValue);
}
}
else
{
if (!string.IsNullOrWhiteSpace(item.Attribute.Validation))
{
var getValue = item.GetAction.DynamicInvoke(entry);
if(getValue==null)
{
continue;
}
string value = getValue.ToString();
if(!System.Text.RegularExpressions.Regex.IsMatch(value, item.Attribute.Validation, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
var errorMessage = string.IsNullOrWhiteSpace(item.Attribute.ErrorMessage) ?
"Invalid " + item.PropertyName : item.Attribute.ErrorMessage;
throw new EntryValidationException(errorMessage)
{
ColumnName = item.ColumnName,
PropertyName = item.PropertyName
};
}
}
}
}
}
}
#endregion
#region EntryValidationException
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable")]
public class EntryValidationException : Exception
{
public string ColumnName { get; set; }
public string PropertyName { get; set; }
public EntryValidationException(string message)
: base(message)
{
}
public override string ToString()
{
return this.PropertyName + " " + this.Message;
}
}
#endregion
#region ColumnMemberInfo
public class ColumnMemberInfo : PropertyAttributeInfo<ColumnMemberAttribute>
{
/// <summary>
/// DB Column Name
/// </summary>
public string ColumnName { get; set; }
/// <summary>
/// Property name in code
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// Type of property
/// </summary>
public Type PropertyType { get; set; }
/// <summary>
/// specific whether this property is entry(class)
///
/// </summary>
public bool IsEntry { get; set; }
/// <summary>
/// if it is entry you will have entry info
/// </summary>
public EntryInfo Entry { get; set; }
/// <summary>
/// Name in sql parameter, always have pre "@"
/// </summary>
public string SqlParamName
{
get
{
if (this.ColumnName.IndexOf("@", StringComparison.Ordinal) < 0)
{
return "@" + this.ColumnName;
}
return this.ColumnName;
}
}
public object GetValue<T>(T entry) where T : class
{
var obj = this.GetAction.DynamicInvoke(entry);
if (obj == null)
{
return null;
}
if (this.Attribute.Type == ColumnMemberType.DataContractXml && !(obj is string))
{
return obj.DataContractToXmlString();
}
if (this.Attribute.Type == ColumnMemberType.Xml && !(obj is string))
{
return obj.ToXmlString();
}
if (obj is DateTime && ((DateTime)obj == DateTime.MinValue
|| (DateTime)obj == DateTime.MaxValue
|| (DateTime)obj == DateTime.MinValue.ToUniversalTime()
|| (DateTime)obj == DateTime.MaxValue.ToUniversalTime()))
{
return null;
}
if (obj is Guid && (Guid)obj == Guid.Empty)
{
return null;
}
if (this.PropertyType.IsEnum)
{
return Convert.ToInt32(obj);
}
return obj;
}
public void SetValue<T>(T entry,object value) where T : class
{
this.SetAction.DynamicInvoke(entry, GetDefaultValueFromDB(value));
}
private object GetDefaultValueFromDB(object value)
{
if (value == null || value == DBNull.Value)
{
return default(object);
}
if (this.Attribute.Type == ColumnMemberType.DataContractXml && this.PropertyType != typeof(string))
{
return value.ToString().DataContractFromXml(this.PropertyType);
}
if (this.Attribute.Type == ColumnMemberType.Xml && this.PropertyType != typeof(string))
{
return value.ToString().FromXml(this.PropertyType);
}
return value.ChangeType(this.PropertyType);
}
}
#endregion
}
| |
/*
* Copyright (c) 2007-2009, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
//#define DEBUG_VOICE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenMetaverse.Voice
{
public partial class VoiceGateway : IDisposable
{
// These states should be in increasing order of 'completeness'
// so that the (int) values can drive a progress bar.
public enum ConnectionState
{
None = 0,
Provisioned,
DaemonStarted,
DaemonConnected,
ConnectorConnected,
AccountLogin,
RegionCapAvailable,
SessionRunning
}
internal string sipServer = "";
private string acctServer = "https://www.bhr.vivox.com/api2/";
private string connectionHandle;
private string accountHandle;
private string sessionHandle;
// Parameters to Vivox daemon
private string slvoicePath = "";
private string slvoiceArgs = "-ll 5";
private string daemonNode = "127.0.0.1";
private int daemonPort = 37331;
private string voiceUser;
private string voicePassword;
private string spatialUri;
private string spatialCredentials;
// Session management
private Dictionary<string, VoiceSession> sessions;
private VoiceSession spatialSession;
private Uri currentParcelCap;
private Uri nextParcelCap;
private string regionName;
// Position update thread
private Thread posThread;
private ManualResetEvent posRestart;
public GridClient Client;
private VoicePosition position;
private Vector3d oldPosition;
private Vector3d oldAt;
// Audio interfaces
private List<string> inputDevices;
/// <summary>
/// List of audio input devices
/// </summary>
public List<string> CaptureDevices { get { return inputDevices; } }
private List<string> outputDevices;
/// <summary>
/// List of audio output devices
/// </summary>
public List<string> PlaybackDevices { get { return outputDevices; } }
private string currentCaptureDevice;
private string currentPlaybackDevice;
private bool testing = false;
public event EventHandler OnSessionCreate;
public event EventHandler OnSessionRemove;
public delegate void VoiceConnectionChangeCallback(ConnectionState state);
public event VoiceConnectionChangeCallback OnVoiceConnectionChange;
public delegate void VoiceMicTestCallback(float level);
public event VoiceMicTestCallback OnVoiceMicTest;
public VoiceGateway(GridClient c)
{
Random rand = new Random();
daemonPort = rand.Next(34000, 44000);
Client = c;
sessions = new Dictionary<string, VoiceSession>();
position = new VoicePosition();
position.UpOrientation = new Vector3d(0.0, 1.0, 0.0);
position.Velocity = new Vector3d(0.0, 0.0, 0.0);
oldPosition = new Vector3d(0, 0, 0);
oldAt = new Vector3d(1, 0, 0);
slvoiceArgs = " -ll -1"; // Min logging
slvoiceArgs += " -i 127.0.0.1:" + daemonPort.ToString();
// slvoiceArgs += " -lf " + control.instance.ClientDir;
}
/// <summary>
/// Start up the Voice service.
/// </summary>
public void Start()
{
// Start the background thread
if (posThread != null && posThread.IsAlive)
posThread.Abort();
posThread = new Thread(new ThreadStart(PositionThreadBody));
posThread.Name = "VoicePositionUpdate";
posThread.IsBackground = true;
posRestart = new ManualResetEvent(false);
posThread.Start();
Client.Network.EventQueueRunning += new EventHandler<EventQueueRunningEventArgs>(Network_EventQueueRunning);
// Connection events
OnDaemonRunning +=
new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning);
OnDaemonCouldntRun +=
new VoiceGateway.DaemonCouldntRunCallback(connector_OnDaemonCouldntRun);
OnConnectorCreateResponse +=
new EventHandler<VoiceGateway.VoiceConnectorEventArgs>(connector_OnConnectorCreateResponse);
OnDaemonConnected +=
new DaemonConnectedCallback(connector_OnDaemonConnected);
OnDaemonCouldntConnect +=
new DaemonCouldntConnectCallback(connector_OnDaemonCouldntConnect);
OnAuxAudioPropertiesEvent +=
new EventHandler<AudioPropertiesEventArgs>(connector_OnAuxAudioPropertiesEvent);
// Session events
OnSessionStateChangeEvent +=
new EventHandler<SessionStateChangeEventArgs>(connector_OnSessionStateChangeEvent);
OnSessionAddedEvent +=
new EventHandler<SessionAddedEventArgs>(connector_OnSessionAddedEvent);
// Session Participants events
OnSessionParticipantUpdatedEvent +=
new EventHandler<ParticipantUpdatedEventArgs>(connector_OnSessionParticipantUpdatedEvent);
OnSessionParticipantAddedEvent +=
new EventHandler<ParticipantAddedEventArgs>(connector_OnSessionParticipantAddedEvent);
// Device events
OnAuxGetCaptureDevicesResponse +=
new EventHandler<VoiceDevicesEventArgs>(connector_OnAuxGetCaptureDevicesResponse);
OnAuxGetRenderDevicesResponse +=
new EventHandler<VoiceDevicesEventArgs>(connector_OnAuxGetRenderDevicesResponse);
// Generic status response
OnVoiceResponse += new EventHandler<VoiceResponseEventArgs>(connector_OnVoiceResponse);
// Account events
OnAccountLoginResponse +=
new EventHandler<VoiceAccountEventArgs>(connector_OnAccountLoginResponse);
Logger.Log("Voice initialized", Helpers.LogLevel.Info);
// If voice provisioning capability is already available,
// proceed with voice startup. Otherwise the EventQueueRunning
// event will do it.
System.Uri vCap =
Client.Network.CurrentSim.Caps.CapabilityURI("ProvisionVoiceAccountRequest");
if (vCap != null)
RequestVoiceProvision(vCap);
}
/// <summary>
/// Handle miscellaneous request status
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// ///<remarks>If something goes wrong, we log it.</remarks>
void connector_OnVoiceResponse(object sender, VoiceGateway.VoiceResponseEventArgs e)
{
if (e.StatusCode == 0)
return;
Logger.Log(e.Message + " on " + sender as string, Helpers.LogLevel.Error);
}
public void Stop()
{
Client.Network.EventQueueRunning -= new EventHandler<EventQueueRunningEventArgs>(Network_EventQueueRunning);
// Connection events
OnDaemonRunning -=
new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning);
OnDaemonCouldntRun -=
new VoiceGateway.DaemonCouldntRunCallback(connector_OnDaemonCouldntRun);
OnConnectorCreateResponse -=
new EventHandler<VoiceGateway.VoiceConnectorEventArgs>(connector_OnConnectorCreateResponse);
OnDaemonConnected -=
new VoiceGateway.DaemonConnectedCallback(connector_OnDaemonConnected);
OnDaemonCouldntConnect -=
new VoiceGateway.DaemonCouldntConnectCallback(connector_OnDaemonCouldntConnect);
OnAuxAudioPropertiesEvent -=
new EventHandler<AudioPropertiesEventArgs>(connector_OnAuxAudioPropertiesEvent);
// Session events
OnSessionStateChangeEvent -=
new EventHandler<SessionStateChangeEventArgs>(connector_OnSessionStateChangeEvent);
OnSessionAddedEvent -=
new EventHandler<SessionAddedEventArgs>(connector_OnSessionAddedEvent);
// Session Participants events
OnSessionParticipantUpdatedEvent -=
new EventHandler<ParticipantUpdatedEventArgs>(connector_OnSessionParticipantUpdatedEvent);
OnSessionParticipantAddedEvent -=
new EventHandler<ParticipantAddedEventArgs>(connector_OnSessionParticipantAddedEvent);
OnSessionParticipantRemovedEvent -=
new EventHandler<ParticipantRemovedEventArgs>(connector_OnSessionParticipantRemovedEvent);
// Tuning events
OnAuxGetCaptureDevicesResponse -=
new EventHandler<VoiceGateway.VoiceDevicesEventArgs>(connector_OnAuxGetCaptureDevicesResponse);
OnAuxGetRenderDevicesResponse -=
new EventHandler<VoiceGateway.VoiceDevicesEventArgs>(connector_OnAuxGetRenderDevicesResponse);
// Account events
OnAccountLoginResponse -=
new EventHandler<VoiceGateway.VoiceAccountEventArgs>(connector_OnAccountLoginResponse);
// Stop the background thread
if (posThread != null)
{
PosUpdating(false);
if (posThread.IsAlive)
posThread.Abort();
posThread = null;
}
// Close all sessions
foreach (VoiceSession s in sessions.Values)
{
if (OnSessionRemove != null)
OnSessionRemove(s, EventArgs.Empty);
s.Close();
}
// Clear out lots of state so in case of restart we begin at the beginning.
currentParcelCap = null;
sessions.Clear();
accountHandle = null;
voiceUser = null;
voicePassword = null;
SessionTerminate(sessionHandle);
sessionHandle = null;
AccountLogout(accountHandle);
accountHandle = null;
ConnectorInitiateShutdown(connectionHandle);
connectionHandle = null;
StopDaemon();
}
/// <summary>
/// Cleanup oject resources
/// </summary>
public void Dispose()
{
Stop();
}
internal string GetVoiceDaemonPath()
{
string myDir =
Path.GetDirectoryName(
(System.Reflection.Assembly.GetEntryAssembly() ?? typeof (VoiceGateway).Assembly).Location);
if (Environment.OSVersion.Platform != PlatformID.MacOSX &&
Environment.OSVersion.Platform != PlatformID.Unix)
{
string localDaemon = Path.Combine(myDir, Path.Combine("voice", "SLVoice.exe"));
if (File.Exists(localDaemon))
return localDaemon;
string progFiles;
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ProgramFiles(x86)")))
{
progFiles = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
else
{
progFiles = Environment.GetEnvironmentVariable("ProgramFiles");
}
if (System.IO.File.Exists(Path.Combine(progFiles, @"SecondLife" + Path.DirectorySeparatorChar + @"SLVoice.exe")))
{
return Path.Combine(progFiles, @"SecondLife" + Path.DirectorySeparatorChar + @"SLVoice.exe");
}
return Path.Combine(myDir, @"SLVoice.exe");
}
else
{
string localDaemon = Path.Combine(myDir, Path.Combine("voice", "SLVoice"));
if (File.Exists(localDaemon))
return localDaemon;
return Path.Combine(myDir,"SLVoice");
}
}
void RequestVoiceProvision(System.Uri cap)
{
OpenMetaverse.Http.CapsClient capClient =
new OpenMetaverse.Http.CapsClient(cap);
capClient.OnComplete +=
new OpenMetaverse.Http.CapsClient.CompleteCallback(cClient_OnComplete);
OSD postData = new OSD();
// STEP 0
Logger.Log("Requesting voice capability", Helpers.LogLevel.Info);
capClient.BeginGetResponse(postData, OSDFormat.Xml, 10000);
}
/// <summary>
/// Request voice cap when changing regions
/// </summary>
void Network_EventQueueRunning(object sender, EventQueueRunningEventArgs e)
{
// We only care about the sim we are in.
if (e.Simulator != Client.Network.CurrentSim)
return;
// Did we provision voice login info?
if (string.IsNullOrEmpty(voiceUser))
{
// The startup steps are
// 0. Get voice account info
// 1. Start Daemon
// 2. Create TCP connection
// 3. Create Connector
// 4. Account login
// 5. Create session
// Get the voice provisioning data
System.Uri vCap =
Client.Network.CurrentSim.Caps.CapabilityURI("ProvisionVoiceAccountRequest");
// Do we have voice capability?
if (vCap == null)
{
Logger.Log("Null voice capability after event queue running", Helpers.LogLevel.Warning);
}
else
{
RequestVoiceProvision(vCap);
}
return;
}
else
{
// Change voice session for this region.
ParcelChanged();
}
}
#region Participants
void connector_OnSessionParticipantUpdatedEvent(object sender, ParticipantUpdatedEventArgs e)
{
VoiceSession s = FindSession(e.SessionHandle, false);
if (s == null) return;
s.ParticipantUpdate(e.URI, e.IsMuted, e.IsSpeaking, e.Volume, e.Energy);
}
public string SIPFromUUID(UUID id)
{
return "sip:" +
nameFromID(id) +
"@" +
sipServer;
}
private static string nameFromID(UUID id)
{
string result = null;
if (id == UUID.Zero)
return result;
// Prepending this apparently prevents conflicts with reserved names inside the vivox and diamondware code.
result = "x";
// Base64 encode and replace the pieces of base64 that are less compatible
// with e-mail local-parts.
// See RFC-4648 "Base 64 Encoding with URL and Filename Safe Alphabet"
byte[] encbuff = id.GetBytes();
result += Convert.ToBase64String(encbuff);
result = result.Replace('+', '-');
result = result.Replace('/', '_');
return result;
}
void connector_OnSessionParticipantAddedEvent(object sender, ParticipantAddedEventArgs e)
{
VoiceSession s = FindSession(e.SessionHandle, false);
if (s == null)
{
Logger.Log("Orphan participant", Helpers.LogLevel.Error);
return;
}
s.AddParticipant(e.URI);
}
void connector_OnSessionParticipantRemovedEvent(object sender, ParticipantRemovedEventArgs e)
{
VoiceSession s = FindSession(e.SessionHandle, false);
if (s == null) return;
s.RemoveParticipant(e.URI);
}
#endregion
#region Sessions
void connector_OnSessionAddedEvent(object sender, SessionAddedEventArgs e)
{
sessionHandle = e.SessionHandle;
// Create our session context.
VoiceSession s = FindSession(sessionHandle, true);
s.RegionName = regionName;
spatialSession = s;
// Tell any user-facing code.
if (OnSessionCreate != null)
OnSessionCreate(s, null);
Logger.Log("Added voice session in " + regionName, Helpers.LogLevel.Info);
}
/// <summary>
/// Handle a change in session state
/// </summary>
void connector_OnSessionStateChangeEvent(object sender, SessionStateChangeEventArgs e)
{
VoiceSession s;
switch (e.State)
{
case VoiceGateway.SessionState.Connected:
s = FindSession(e.SessionHandle, true);
sessionHandle = e.SessionHandle;
s.RegionName = regionName;
spatialSession = s;
Logger.Log("Voice connected in " + regionName, Helpers.LogLevel.Info);
// Tell any user-facing code.
if (OnSessionCreate != null)
OnSessionCreate(s, null);
break;
case VoiceGateway.SessionState.Disconnected:
s = FindSession(sessionHandle, false);
sessions.Remove(sessionHandle);
if (s != null)
{
Logger.Log("Voice disconnected in " + s.RegionName, Helpers.LogLevel.Info);
// Inform interested parties
if (OnSessionRemove != null)
OnSessionRemove(s, null);
if (s == spatialSession)
spatialSession = null;
}
// The previous session is now ended. Check for a new one and
// start it going.
if (nextParcelCap != null)
{
currentParcelCap = nextParcelCap;
nextParcelCap = null;
RequestParcelInfo(currentParcelCap);
}
break;
}
}
/// <summary>
/// Close a voice session
/// </summary>
/// <param name="sessionHandle"></param>
internal void CloseSession(string sessionHandle)
{
if (!sessions.ContainsKey(sessionHandle))
return;
PosUpdating(false);
ReportConnectionState(ConnectionState.AccountLogin);
// Clean up spatial pointers.
VoiceSession s = sessions[sessionHandle];
if (s.IsSpatial)
{
spatialSession = null;
currentParcelCap = null;
}
// Remove this session from the master session list
sessions.Remove(sessionHandle);
// Let any user-facing code clean up.
if (OnSessionRemove != null)
OnSessionRemove(s, null);
// Tell SLVoice to clean it up as well.
SessionTerminate(sessionHandle);
}
/// <summary>
/// Locate a Session context from its handle
/// </summary>
/// <remarks>Creates the session context if it does not exist.</remarks>
VoiceSession FindSession(string sessionHandle, bool make)
{
if (sessions.ContainsKey(sessionHandle))
return sessions[sessionHandle];
if (!make) return null;
// Create a new session and add it to the sessions list.
VoiceSession s = new VoiceSession(this, sessionHandle);
// Turn on position updating for spatial sessions
// (For now, only spatial sessions are supported)
if (s.IsSpatial)
PosUpdating(true);
// Register the session by its handle
sessions.Add(sessionHandle, s);
return s;
}
#endregion
#region MinorResponses
void connector_OnAuxAudioPropertiesEvent(object sender, AudioPropertiesEventArgs e)
{
if (OnVoiceMicTest != null)
OnVoiceMicTest(e.MicEnergy);
}
#endregion
private void ReportConnectionState(ConnectionState s)
{
if (OnVoiceConnectionChange == null) return;
OnVoiceConnectionChange(s);
}
/// <summary>
/// Handle completion of main voice cap request.
/// </summary>
/// <param name="client"></param>
/// <param name="result"></param>
/// <param name="error"></param>
void cClient_OnComplete(OpenMetaverse.Http.CapsClient client,
OpenMetaverse.StructuredData.OSD result,
Exception error)
{
if (error != null)
{
Logger.Log("Voice cap error " + error.Message, Helpers.LogLevel.Error);
return;
}
Logger.Log("Voice provisioned", Helpers.LogLevel.Info);
ReportConnectionState(ConnectionState.Provisioned);
OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap;
// We can get back 4 interesting values:
// voice_sip_uri_hostname
// voice_account_server_name (actually a full URI)
// username
// password
if (pMap.ContainsKey("voice_sip_uri_hostname"))
sipServer = pMap["voice_sip_uri_hostname"].AsString();
if (pMap.ContainsKey("voice_account_server_name"))
acctServer = pMap["voice_account_server_name"].AsString();
voiceUser = pMap["username"].AsString();
voicePassword = pMap["password"].AsString();
// Start the SLVoice daemon
slvoicePath = GetVoiceDaemonPath();
// Test if the executable exists
if (!System.IO.File.Exists(slvoicePath))
{
Logger.Log("SLVoice is missing", Helpers.LogLevel.Error);
return;
}
// STEP 1
StartDaemon(slvoicePath, slvoiceArgs);
}
#region Daemon
void connector_OnDaemonCouldntConnect()
{
Logger.Log("No voice daemon connect", Helpers.LogLevel.Error);
}
void connector_OnDaemonCouldntRun()
{
Logger.Log("Daemon not started", Helpers.LogLevel.Error);
}
/// <summary>
/// Daemon has started so connect to it.
/// </summary>
void connector_OnDaemonRunning()
{
OnDaemonRunning -=
new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning);
Logger.Log("Daemon started", Helpers.LogLevel.Info);
ReportConnectionState(ConnectionState.DaemonStarted);
// STEP 2
ConnectToDaemon(daemonNode, daemonPort);
}
/// <summary>
/// The daemon TCP connection is open.
/// </summary>
void connector_OnDaemonConnected()
{
Logger.Log("Daemon connected", Helpers.LogLevel.Info);
ReportConnectionState(ConnectionState.DaemonConnected);
// The connector is what does the logging.
VoiceGateway.VoiceLoggingSettings vLog =
new VoiceGateway.VoiceLoggingSettings();
#if DEBUG_VOICE
vLog.Enabled = true;
vLog.FileNamePrefix = "OpenmetaverseVoice";
vLog.FileNameSuffix = ".log";
vLog.LogLevel = 4;
#endif
// STEP 3
int reqId = ConnectorCreate(
"V2 SDK", // Magic value keeps SLVoice happy
acctServer, // Account manager server
30000, 30099, // port range
vLog);
if (reqId < 0)
{
Logger.Log("No voice connector request", Helpers.LogLevel.Error);
}
}
/// <summary>
/// Handle creation of the Connector.
/// </summary>
void connector_OnConnectorCreateResponse(
object sender,
VoiceGateway.VoiceConnectorEventArgs e)
{
Logger.Log("Voice daemon protocol started " + e.Message, Helpers.LogLevel.Info);
connectionHandle = e.Handle;
if (e.StatusCode != 0)
return;
// STEP 4
AccountLogin(
connectionHandle,
voiceUser,
voicePassword,
"VerifyAnswer", // This can also be "AutoAnswer"
"", // Default account management server URI
10, // Throttle state changes
true); // Enable buddies and presence
}
#endregion
void connector_OnAccountLoginResponse(
object sender,
VoiceGateway.VoiceAccountEventArgs e)
{
Logger.Log("Account Login " + e.Message, Helpers.LogLevel.Info);
accountHandle = e.AccountHandle;
ReportConnectionState(ConnectionState.AccountLogin);
ParcelChanged();
}
#region Audio devices
/// <summary>
/// Handle response to audio output device query
/// </summary>
void connector_OnAuxGetRenderDevicesResponse(
object sender,
VoiceGateway.VoiceDevicesEventArgs e)
{
outputDevices = e.Devices;
currentPlaybackDevice = e.CurrentDevice;
}
/// <summary>
/// Handle response to audio input device query
/// </summary>
void connector_OnAuxGetCaptureDevicesResponse(
object sender,
VoiceGateway.VoiceDevicesEventArgs e)
{
inputDevices = e.Devices;
currentCaptureDevice = e.CurrentDevice;
}
public string CurrentCaptureDevice
{
get { return currentCaptureDevice; }
set
{
currentCaptureDevice = value;
AuxSetCaptureDevice(value);
}
}
public string PlaybackDevice
{
get { return currentPlaybackDevice; }
set
{
currentPlaybackDevice = value;
AuxSetRenderDevice(value);
}
}
public int MicLevel
{
set
{
ConnectorSetLocalMicVolume(connectionHandle, value);
}
}
public int SpkrLevel
{
set
{
ConnectorSetLocalSpeakerVolume(connectionHandle, value);
}
}
public bool MicMute
{
set
{
ConnectorMuteLocalMic(connectionHandle, value);
}
}
public bool SpkrMute
{
set
{
ConnectorMuteLocalSpeaker(connectionHandle, value);
}
}
/// <summary>
/// Set audio test mode
/// </summary>
public bool TestMode
{
get { return testing; }
set
{
testing = value;
if (testing)
{
if (spatialSession != null)
{
spatialSession.Close();
spatialSession = null;
}
AuxCaptureAudioStart(0);
}
else
{
AuxCaptureAudioStop();
ParcelChanged();
}
}
}
#endregion
/// <summary>
/// Set voice channel for new parcel
/// </summary>
///
internal void ParcelChanged()
{
// Get the capability for this parcel.
Caps c = Client.Network.CurrentSim.Caps;
System.Uri pCap = c.CapabilityURI("ParcelVoiceInfoRequest");
if (pCap == null)
{
Logger.Log("Null voice capability", Helpers.LogLevel.Error);
return;
}
// Parcel has changed. If we were already in a spatial session, we have to close it first.
if (spatialSession != null)
{
nextParcelCap = pCap;
CloseSession(spatialSession.Handle);
}
// Not already in a session, so can start the new one.
RequestParcelInfo(pCap);
}
private OpenMetaverse.Http.CapsClient parcelCap;
/// <summary>
/// Request info from a parcel capability Uri.
/// </summary>
/// <param name="cap"></param>
void RequestParcelInfo(Uri cap)
{
Logger.Log("Requesting region voice info", Helpers.LogLevel.Info);
parcelCap = new OpenMetaverse.Http.CapsClient(cap);
parcelCap.OnComplete +=
new OpenMetaverse.Http.CapsClient.CompleteCallback(pCap_OnComplete);
OSD postData = new OSD();
currentParcelCap = cap;
parcelCap.BeginGetResponse(postData, OSDFormat.Xml, 10000);
}
/// <summary>
/// Receive parcel voice cap
/// </summary>
/// <param name="client"></param>
/// <param name="result"></param>
/// <param name="error"></param>
void pCap_OnComplete(OpenMetaverse.Http.CapsClient client,
OpenMetaverse.StructuredData.OSD result,
Exception error)
{
parcelCap.OnComplete -=
new OpenMetaverse.Http.CapsClient.CompleteCallback(pCap_OnComplete);
parcelCap = null;
if (error != null)
{
Logger.Log("Region voice cap " + error.Message, Helpers.LogLevel.Error);
return;
}
OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap;
regionName = pMap["region_name"].AsString();
ReportConnectionState(ConnectionState.RegionCapAvailable);
if (pMap.ContainsKey("voice_credentials"))
{
OpenMetaverse.StructuredData.OSDMap cred =
pMap["voice_credentials"] as OpenMetaverse.StructuredData.OSDMap;
if (cred.ContainsKey("channel_uri"))
spatialUri = cred["channel_uri"].AsString();
if (cred.ContainsKey("channel_credentials"))
spatialCredentials = cred["channel_credentials"].AsString();
}
if (spatialUri == null || spatialUri == "")
{
// "No voice chat allowed here");
return;
}
Logger.Log("Voice connecting for region " + regionName, Helpers.LogLevel.Info);
// STEP 5
int reqId = SessionCreate(
accountHandle,
spatialUri, // uri
"", // Channel name seems to be always null
spatialCredentials, // spatialCredentials, // session password
true, // Join Audio
false, // Join Text
"");
if (reqId < 0)
{
Logger.Log("Voice Session ReqID " + reqId.ToString(), Helpers.LogLevel.Error);
}
}
#region Location Update
/// <summary>
/// Tell Vivox where we are standing
/// </summary>
/// <remarks>This has to be called when we move or turn.</remarks>
internal void UpdatePosition(AgentManager self)
{
// Get position in Global coordinates
Vector3d OMVpos = new Vector3d(self.GlobalPosition);
// Do not send trivial updates.
if (OMVpos.ApproxEquals(oldPosition, 1.0))
return;
oldPosition = OMVpos;
// Convert to the coordinate space that Vivox uses
// OMV X is East, Y is North, Z is up
// VVX X is East, Y is up, Z is South
position.Position = new Vector3d(OMVpos.X, OMVpos.Z, -OMVpos.Y);
// TODO Rotate these two vectors
// Get azimuth from the facing Quaternion.
// By definition, facing.W = Cos( angle/2 )
double angle = 2.0 * Math.Acos(self.Movement.BodyRotation.W);
position.LeftOrientation = new Vector3d(-1.0, 0.0, 0.0);
position.AtOrientation = new Vector3d((float)Math.Acos(angle), 0.0, -(float)Math.Asin(angle));
SessionSet3DPosition(
sessionHandle,
position,
position);
}
/// <summary>
/// Start and stop updating out position.
/// </summary>
/// <param name="go"></param>
internal void PosUpdating(bool go)
{
if (go)
posRestart.Set();
else
posRestart.Reset();
}
private void PositionThreadBody()
{
while (true)
{
posRestart.WaitOne();
Thread.Sleep(1500);
UpdatePosition(Client.Self);
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using FileHelpers.Events;
using FileHelpers.Helpers;
using FileHelpers.Streams;
namespace FileHelpers
{
/// <summary>
/// Async engine, reads records from file in background,
/// returns them record by record in foreground
/// </summary>
public sealed class FileHelperAsyncEngine :
FileHelperAsyncEngine<object>
{
#region " Constructor "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/>
public FileHelperAsyncEngine(Type recordType)
: base(recordType) {}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/>
/// <param name="encoding">The encoding used by the Engine.</param>
public FileHelperAsyncEngine(Type recordType, Encoding encoding)
: base(recordType, encoding) {}
#endregion
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngine/*'/>
/// <include file='Examples.xml' path='doc/examples/FileHelperAsyncEngine/*'/>
/// <typeparam name="T">The record type.</typeparam>
[DebuggerDisplay(
"FileHelperAsyncEngine for type: {RecordType.Name}. ErrorMode: {ErrorManager.ErrorMode.ToString()}. Encoding: {Encoding.EncodingName}"
)]
public class FileHelperAsyncEngine<T>
:
EventEngineBase<T>,
IFileHelperAsyncEngine<T>
where T : class
{
#region " Constructor "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/>
public FileHelperAsyncEngine()
: base(typeof (T))
{
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtr/*'/>
protected FileHelperAsyncEngine(Type recordType)
: base(recordType)
{
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/>
/// <param name="encoding">The encoding used by the Engine.</param>
public FileHelperAsyncEngine(Encoding encoding)
: base(typeof (T), encoding)
{
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/FileHelperAsyncEngineCtrG/*'/>
/// <param name="encoding">The encoding used by the Engine.</param>
/// <param name="recordType">Type of record to read</param>
protected FileHelperAsyncEngine(Type recordType, Encoding encoding)
: base(recordType, encoding)
{
}
#endregion
#region " Readers and Writters "
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private ForwardReader mAsyncReader;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private TextWriter mAsyncWriter;
#endregion
#region " LastRecord "
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private T mLastRecord;
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/LastRecord/*'/>
public T LastRecord
{
get { return mLastRecord; }
}
private object[] mLastRecordValues;
/// <summary>
/// An array with the values of each field of the current record
/// </summary>
public object[] LastRecordValues
{
get { return mLastRecordValues; }
}
/// <summary>
/// Get a field value of the current records.
/// </summary>
/// <param name="fieldIndex" >The index of the field.</param>
public object this[int fieldIndex]
{
get
{
if (mLastRecordValues == null)
{
//?NoBeginReadFileCall"You must be reading something to access this property. Try calling BeginReadFile first."
throw new BadUsageException("FileHelperMsg_NoBeginReadFileCall", null);
}
return mLastRecordValues[fieldIndex];
}
set
{
if (mAsyncWriter == null)
{
//?NoBeginWriteFileCall"You must be writing something to set a record value. Try calling BeginWriteFile first."
throw new BadUsageException("FileHelperMsg_NoBeginWriteFileCall", null);
}
if (mLastRecordValues == null)
mLastRecordValues = new object[RecordInfo.FieldCount];
if (value == null)
{
if (RecordInfo.Fields[fieldIndex].FieldType.IsValueType)
//?NullAssigned"You can't assign null to a value type."
throw new BadUsageException("FileHelperMsg_NullAssigned", null);
mLastRecordValues[fieldIndex] = null;
}
else
{
if (!RecordInfo.Fields[fieldIndex].FieldType.IsInstanceOfType(value))
{
//?TypeNotExpected"Invalid type: {0}. Expected: {1}"
throw new BadUsageException("FileHelperMsg_TypeNotExpected", new List<string>() { value.GetType().Name, RecordInfo.Fields[fieldIndex].FieldType.Name });
}
mLastRecordValues[fieldIndex] = value;
}
}
}
/// <summary>
/// Get a field value of the current records.
/// </summary>
/// <param name="fieldName" >The name of the field (case sensitive)</param>
public object this[string fieldName]
{
get
{
if (mLastRecordValues == null)
{
//?NoBeginReadFileCall"You must be reading something to access this property. Try calling BeginReadFile first."
throw new BadUsageException("FileHelperMsg_NoBeginReadFileCall", null);
}
int index = RecordInfo.GetFieldIndex(fieldName);
return mLastRecordValues[index];
}
set
{
int index = RecordInfo.GetFieldIndex(fieldName);
this[index] = value;
}
}
#endregion
#region " BeginReadStream"
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadStream/*'/>
public IDisposable BeginReadStream(TextReader reader)
{
if (reader == null)
//?TextReaderIsNull"The TextReader can't be null."
throw new FileHelpersException("FileHelperMsg_TextReaderIsNull", null);
if (mAsyncWriter != null)
//?ReadWhileWriting"You can't start to read while you are writing."
throw new BadUsageException("FileHelperMsg_ReadWhileWriting", null);
var recordReader = new NewLineDelimitedRecordReader(reader);
ResetFields();
HeaderText = String.Empty;
mFooterText = String.Empty;
if (RecordInfo.IgnoreFirst > 0)
{
for (int i = 0; i < RecordInfo.IgnoreFirst; i++)
{
string temp = recordReader.ReadRecordString();
mLineNumber++;
if (temp != null)
HeaderText += temp + StringHelper.NewLine;
else
break;
}
}
mAsyncReader = new ForwardReader(recordReader, RecordInfo.IgnoreLast, mLineNumber)
{
DiscardForward = true
};
State = EngineState.Reading;
mStreamInfo = new StreamInfoProvider(reader);
mCurrentRecord = 0;
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, -1, mStreamInfo.Position, mStreamInfo.TotalBytes));
return this;
}
#endregion
#region " BeginReadFile "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadFile/*'/>
public IDisposable BeginReadFile(string fileName)
{
BeginReadFile(fileName, DefaultReadBufferSize);
return this;
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadFile/*'/>
/// <param name="bufferSize">Buffer size to read</param>
public IDisposable BeginReadFile(string fileName, int bufferSize)
{
BeginReadStream(new InternalStreamReader(fileName, mEncoding, true, bufferSize));
return this;
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginReadString/*'/>
public IDisposable BeginReadString(string sourceData)
{
if (sourceData == null)
sourceData = String.Empty;
BeginReadStream(new InternalStringReader(sourceData));
return this;
}
#endregion
#region " ReadNext "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/ReadNext/*'/>
public T ReadNext()
{
if (mAsyncReader == null)
//?ReadNotStarted"Before call ReadNext you must call BeginReadFile or BeginReadStream."
throw new BadUsageException("FileHelperMsg_ReadNotStarted", null);
ReadNextRecord();
return mLastRecord;
}
private int mCurrentRecord = 0;
private void ReadNextRecord()
{
string currentLine = mAsyncReader.ReadNextLine();
mLineNumber++;
bool byPass = false;
mLastRecord = default(T);
var line = new LineInfo(string.Empty)
{
mReader = mAsyncReader
};
if (mLastRecordValues == null)
mLastRecordValues = new object[RecordInfo.FieldCount];
while (true)
{
if (currentLine != null)
{
try
{
mTotalRecords++;
mCurrentRecord++;
line.ReLoad(currentLine);
bool skip = false;
mLastRecord = (T) RecordInfo.Operations.CreateRecordHandler();
if (MustNotifyProgress) // Avoid object creation
{
OnProgress(new ProgressEventArgs(mCurrentRecord,
-1,
mStreamInfo.Position,
mStreamInfo.TotalBytes));
}
BeforeReadEventArgs<T> e = null;
if (MustNotifyRead) // Avoid object creation
{
e = new BeforeReadEventArgs<T>(this, mLastRecord, currentLine, LineNumber);
skip = OnBeforeReadRecord(e);
if (e.RecordLineChanged)
line.ReLoad(e.RecordLine);
}
if (skip == false)
{
if (RecordInfo.Operations.StringToRecord(mLastRecord, line, mLastRecordValues, ErrorManager, -1, out var valuesPosition))
{
if (MustNotifyRead) // Avoid object creation
skip = OnAfterReadRecord(currentLine, mLastRecord, valuesPosition, e.RecordLineChanged, LineNumber);
if (skip == false)
{
byPass = true;
return;
}
}
}
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
byPass = true;
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo
{
mLineNumber = mAsyncReader.LineNumber,
mExceptionInfo = ex,
mRecordString = currentLine,
mRecordTypeName = RecordInfo.RecordType.Name
};
mErrorManager.AddError(err);
break;
}
}
finally
{
if (byPass == false)
{
currentLine = mAsyncReader.ReadNextLine();
mLineNumber = mAsyncReader.LineNumber;
}
}
}
else
{
mLastRecordValues = null;
mLastRecord = default(T);
if (RecordInfo.IgnoreLast > 0)
mFooterText = mAsyncReader.RemainingText;
try
{
mAsyncReader.Close();
//mAsyncReader = null;
}
catch {}
return;
}
}
}
/// <summary>
/// Return array of object for all data to end of the file
/// </summary>
/// <returns>Array of objects created from data on file</returns>
public T[] ReadToEnd()
{
return ReadNexts(int.MaxValue);
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/ReadNexts/*'/>
public T[] ReadNexts(int numberOfRecords)
{
if (mAsyncReader == null)
//?ReadNotStarted"Before call ReadNext you must call BeginReadFile or BeginReadStream."
throw new BadUsageException("FileHelperMsg_ReadNotStarted", null);
var arr = new List<T>(numberOfRecords);
for (int i = 0; i < numberOfRecords; i++)
{
ReadNextRecord();
if (mLastRecord != null)
arr.Add(mLastRecord);
else
break;
}
return arr.ToArray();
}
#endregion
#region " Close "
/// <summary>
/// Save all the buffered data for write to the disk.
/// Useful to opened async engines that wants to save pending values to
/// disk or for engines used for logging.
/// </summary>
public void Flush()
{
if (mAsyncWriter != null)
mAsyncWriter.Flush();
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/Close/*'/>
public void Close()
{
lock (this)
{
State = EngineState.Closed;
try
{
mLastRecordValues = null;
mLastRecord = default(T);
var reader = mAsyncReader;
if (reader != null)
{
reader.Close();
mAsyncReader = null;
}
}
catch {}
try
{
var writer = mAsyncWriter;
if (writer != null)
{
WriteFooter(writer);
writer.Close();
mAsyncWriter = null;
}
}
catch {}
}
}
#endregion
#region " BeginWriteStream"
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteStream/*'/>
public IDisposable BeginWriteStream(TextWriter writer)
{
if (writer == null)
//?TextWriterIsNull"The TextWriter can't be null."
throw new FileHelpersException("FileHelperMsg_TextWriterIsNull", null);
if (mAsyncReader != null)
//?WriteWhileReading"You can't start to write while you are reading."
throw new BadUsageException("FileHelperMsg_WriteWhileReading", null);
State = EngineState.Writing;
ResetFields();
writer.NewLine = NewLineForWrite;
mAsyncWriter = writer;
WriteHeader(mAsyncWriter);
mStreamInfo = new StreamInfoProvider(mAsyncWriter);
mCurrentRecord = 0;
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, -1, mStreamInfo.Position, mStreamInfo.TotalBytes));
return this;
}
#endregion
#region " BeginWriteFile "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteFile/*'/>
public IDisposable BeginWriteFile(string fileName)
{
return BeginWriteFile(fileName, DefaultWriteBufferSize);
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginWriteFile/*'/>
/// <param name="bufferSize">Size of the write buffer</param>
public IDisposable BeginWriteFile(string fileName, int bufferSize)
{
BeginWriteStream(new StreamWriter(fileName, false, mEncoding, bufferSize));
return this;
}
#endregion
#region " BeginAppendToFile "
/// <summary>
/// Begin the append to an existing file
/// </summary>
/// <param name="fileName">Filename to append to</param>
/// <returns>Object to append TODO: ???</returns>
public IDisposable BeginAppendToFile(string fileName)
{
return BeginAppendToFile(fileName, DefaultWriteBufferSize);
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/BeginAppendToFile/*'/>
/// <param name="bufferSize">Size of the buffer for writing</param>
public IDisposable BeginAppendToFile(string fileName, int bufferSize)
{
if (mAsyncReader != null)
//?WriteWhileReading"You can't start to write while you are reading."
throw new BadUsageException("FileHelperMsg_WriteWhileReading", null);
mAsyncWriter = StreamHelper.CreateFileAppender(fileName, mEncoding, false, true, bufferSize);
HeaderText = String.Empty;
mFooterText = String.Empty;
State = EngineState.Writing;
mStreamInfo = new StreamInfoProvider(mAsyncWriter);
mCurrentRecord = 0;
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, -1, mStreamInfo.Position, mStreamInfo.TotalBytes));
return this;
}
#endregion
#region " WriteNext "
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/WriteNext/*'/>
public void WriteNext(T record)
{
if (mAsyncWriter == null)
//?WriteNotStarted"Before call WriteNext you must call BeginWriteFile or BeginWriteStream."
throw new BadUsageException("FileHelperMsg_WriteNotStarted", null);
if (record == null)
//?WriteRecordIsNull"The record to write can't be null."
throw new BadUsageException("FileHelperMsg_WriteRecordIsNull", null);
if (RecordType.IsAssignableFrom(record.GetType()) == false)
//?WrongRecordType"The record must be of type: {0}"
throw new BadUsageException("FileHelperMsg_WrongRecordType", new List<string>() { RecordType.Name });
WriteRecord(record);
}
private void WriteRecord(T record)
{
string currentLine = null;
try
{
mLineNumber++;
mTotalRecords++;
mCurrentRecord++;
bool skip = false;
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(mCurrentRecord, -1, mStreamInfo.Position, mStreamInfo.TotalBytes));
if (MustNotifyWrite)
skip = OnBeforeWriteRecord(record, LineNumber);
if (skip == false)
{
currentLine = RecordInfo.Operations.RecordToString(record);
if (MustNotifyWrite)
currentLine = OnAfterWriteRecord(currentLine, record);
mAsyncWriter.WriteLine(currentLine);
}
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo
{
mLineNumber = mLineNumber,
mExceptionInfo = ex,
mRecordString = currentLine,
mRecordTypeName = RecordInfo.RecordType.Name
};
mErrorManager.AddError(err);
break;
}
}
}
/// <include file='FileHelperAsyncEngine.docs.xml' path='doc/WriteNexts/*'/>
public void WriteNexts(IEnumerable<T> records)
{
if (mAsyncWriter == null)
//?WriteNotStarted"Before call WriteNext you must call BeginWriteFile or BeginWriteStream."
throw new BadUsageException("FileHelperMsg_WriteNotStarted", null);
if (records == null)
//?WriteRecordIsNull"The record to write can't be null."
throw new FileHelpersException("FileHelperMsg_WriteRecordIsNull", null);
bool first = true;
foreach (var rec in records)
{
if (first)
{
if (RecordType.IsAssignableFrom(rec.GetType()) == false)
//?WrongRecordType"The record must be of type: {0}"
throw new BadUsageException("FileHelperMsg_WrongRecordType", new List<string>() { RecordType.Name });
first = false;
}
WriteRecord(rec);
}
}
#endregion
#region " WriteNext for LastRecordValues "
/// <summary>
/// Write the current record values in the buffer. You can use
/// engine[0] or engine["YourField"] to set the values.
/// </summary>
public void WriteNextValues()
{
if (mAsyncWriter == null)
//?WriteNotStarted"Before call WriteNext you must call BeginWriteFile or BeginWriteStream."
throw new BadUsageException("FileHelperMsg_WriteNotStarted", null);
if (mLastRecordValues == null)
{
//?RecordWithoutValues"You must set some values of the record before call this method, or use the overload that has a record as argument."
throw new BadUsageException("FileHelperMsg_RecordWithoutValues", null);
}
string currentLine = null;
try
{
mLineNumber++;
mTotalRecords++;
currentLine = RecordInfo.Operations.RecordValuesToString(mLastRecordValues);
mAsyncWriter.WriteLine(currentLine);
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo
{
mLineNumber = mLineNumber,
mExceptionInfo = ex,
mRecordString = currentLine,
mRecordTypeName = RecordInfo.RecordType.Name
};
mErrorManager.AddError(err);
break;
}
}
finally
{
mLastRecordValues = null;
}
}
#endregion
#region " IEnumerable implementation "
/// <summary>Allows to loop record by record in the engine</summary>
/// <returns>The enumerator</returns>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
if (mAsyncReader == null)
//!"You must call BeginRead before use the engine in a for each loop."
throw new FileHelpersException("FileHelperMsg_MustCallBeginReadBeforeLoop", null);
return new AsyncEnumerator(this);
}
///<summary>
///Returns an enumerator that iterates through a collection.
///</summary>
///
///<returns>
///An <see cref="T:System.Collections.IEnumerator"></see> object that can be used to iterate through the collection.
///</returns>
IEnumerator IEnumerable.GetEnumerator()
{
if (mAsyncReader == null)
//!"You must call BeginRead before use the engine in a for each loop."
throw new FileHelpersException("FileHelperMsg_MustCallBeginReadBeforeLoop", null);
return new AsyncEnumerator(this);
}
private class AsyncEnumerator : IEnumerator<T>
{
T IEnumerator<T>.Current
{
get { return mEngine.mLastRecord; }
}
void IDisposable.Dispose()
{
mEngine.Close();
}
private readonly FileHelperAsyncEngine<T> mEngine;
public AsyncEnumerator(FileHelperAsyncEngine<T> engine)
{
mEngine = engine;
}
public bool MoveNext()
{
if (mEngine.State == EngineState.Closed)
return false;
object res = mEngine.ReadNext();
if (res == null)
{
mEngine.Close();
return false;
}
return true;
}
public object Current
{
get { return mEngine.mLastRecord; }
}
public void Reset()
{
// No needed
}
}
#endregion
#region " IDisposable implementation "
/// <summary>Release Resources</summary>
void IDisposable.Dispose()
{
Close();
GC.SuppressFinalize(this);
}
/// <summary>Destructor</summary>
~FileHelperAsyncEngine()
{
Close();
}
#endregion
#region " State "
private StreamInfoProvider mStreamInfo;
/// <summary>
/// Indicates the current state of the engine.
/// </summary>
private EngineState State { get; set; }
/// <summary>
/// Indicates the State of an engine
/// </summary>
private enum EngineState
{
/// <summary>The Engine is closed</summary>
Closed = 0,
/// <summary>The Engine is reading a file, string or stream</summary>
Reading,
/// <summary>The Engine is writing a file, string or stream</summary>
Writing
}
#endregion
}
}
| |
#region Using Directives
using System;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Services;
using EnvDTE;
using Microsoft.VisualStudio.SharePoint;
#endregion
namespace SPALM.SPSF.Library.Actions
{
/// <summary>
/// </summary>
[ServiceDependency(typeof(DTE))]
public class ShowProperties : ConfigurableAction
{
private ProjectItem projectItem;
private Project project;
[Input(Required = false)]
public ProjectItem SelectedItem
{
get { return projectItem; }
set { projectItem = value; }
}
[Input(Required = false)]
public Project SelectedProject
{
get { return project; }
set { project = value; }
}
protected string GetBasePath()
{
return base.GetService<IConfigurationService>(true).BasePath;
}
public object GetService(object serviceProvider, System.Type type)
{
return GetService(serviceProvider, type.GUID);
}
public object GetService(object serviceProviderObject, System.Guid guid)
{
object service = null;
Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider = null;
IntPtr serviceIntPtr;
int hr = 0;
Guid SIDGuid;
Guid IIDGuid;
SIDGuid = guid;
IIDGuid = SIDGuid;
serviceProvider = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)serviceProviderObject;
hr = serviceProvider.QueryService(ref SIDGuid, ref IIDGuid, out serviceIntPtr);
if (hr != 0)
{
System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(hr);
}
else if (!serviceIntPtr.Equals(IntPtr.Zero))
{
service = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(serviceIntPtr);
System.Runtime.InteropServices.Marshal.Release(serviceIntPtr);
}
return service;
}
public override void Execute()
{
DTE service = (DTE)this.GetService(typeof(DTE));
try
{
if (projectItem != null)
{
Helpers.LogMessage(service, this, "*********** SharePointService Properties ********************");
try
{
ISharePointProjectService projectService = Helpers2.GetSharePointProjectService(service);
ISharePointProject sharePointProject = projectService.Convert<EnvDTE.Project, ISharePointProject>(project);
try
{ //is it a feature
ISharePointProjectFeature sharePointFeature = projectService.Convert<EnvDTE.ProjectItem, ISharePointProjectFeature>(projectItem);
}
catch { }
try
{ //is it a feature
ISharePointProjectItem sharePointItem = projectService.Convert<EnvDTE.ProjectItem, ISharePointProjectItem>(projectItem);
}
catch { }
try
{ //is it a feature
ISharePointProjectItemFile sharePointItemFile = projectService.Convert<EnvDTE.ProjectItem, ISharePointProjectItemFile>(projectItem);
}
catch { }
try
{ //is it a mapped folder
IMappedFolder sharePointMappedFolder = projectService.Convert<EnvDTE.ProjectItem, IMappedFolder>(projectItem);
}
catch { }
try
{ //is it a mapped folder
ISharePointProjectPackage sharePointProjectPackage = projectService.Convert<EnvDTE.ProjectItem, ISharePointProjectPackage>(projectItem);
}
catch { }
}
catch{}
//codelements
Helpers.LogMessage(service, this, "*********** EnvDTE CodeElements ********************");
foreach (CodeElement codeElement in projectItem.FileCodeModel.CodeElements)
{
try
{
Helpers.LogMessage(service, this, "codeElement.FullName: " + codeElement.FullName);
Helpers.LogMessage(service, this, "codeElement.Type: " + codeElement.GetType().ToString());
Helpers.LogMessage(service, this, "codeElement.Kind: " + codeElement.Kind.ToString());
}
catch {}
}
Helpers.LogMessage(service, this, "*********** EnvDTE Properties ********************");
for (int i = 0; i < projectItem.Properties.Count; i++)
{
try
{
string name = projectItem.Properties.Item(i).Name;
string value = "";
try
{
value = projectItem.Properties.Item(i).Value.ToString();
}
catch (Exception)
{
}
Helpers.LogMessage(service, this, name + "=" + value);
}
catch (Exception)
{
}
}
}
else if (project != null)
{
for (int i = 0; i < project.Properties.Count; i++)
{
try
{
string name = project.Properties.Item(i).Name;
string value = "";
try
{
value = project.Properties.Item(i).Value.ToString();
}
catch (Exception)
{
}
Helpers.LogMessage(service, this, name + "=" + value);
if (project.Properties.Item(i).Collection.Count > 0)
{
}
}
catch (Exception)
{
}
}
}
}
catch (Exception ex)
{
Helpers.LogMessage(service, this, ex.ToString());
}
}
/// <summary>
/// Removes the previously added reference, if it was created
/// </summary>
public override void Undo()
{
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.ProviderBase
{
internal abstract class DbConnectionFactory
{
private Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> _connectionPoolGroups;
private readonly List<DbConnectionPool> _poolsToRelease;
private readonly List<DbConnectionPoolGroup> _poolGroupsToRelease;
private readonly DbConnectionPoolCounters _performanceCounters;
private readonly Timer _pruningTimer;
private const int PruningDueTime = 4 * 60 * 1000; // 4 minutes
private const int PruningPeriod = 30 * 1000; // thirty seconds
// s_pendingOpenNonPooled is an array of tasks used to throttle creation of non-pooled connections to
// a maximum of Environment.ProcessorCount at a time.
private static int s_pendingOpenNonPooledNext = 0;
private static readonly Task<DbConnectionInternal>[] s_pendingOpenNonPooled = new Task<DbConnectionInternal>[Environment.ProcessorCount];
private static Task<DbConnectionInternal> s_completedTask;
protected DbConnectionFactory() : this(DbConnectionPoolCountersNoCounters.SingletonInstance) { }
protected DbConnectionFactory(DbConnectionPoolCounters performanceCounters)
{
_performanceCounters = performanceCounters;
_connectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>();
_poolsToRelease = new List<DbConnectionPool>();
_poolGroupsToRelease = new List<DbConnectionPoolGroup>();
_pruningTimer = CreatePruningTimer();
}
internal DbConnectionPoolCounters PerformanceCounters
{
get { return _performanceCounters; }
}
public abstract DbProviderFactory ProviderFactory
{
get;
}
public void ClearAllPools()
{
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
DbConnectionPoolGroup poolGroup = entry.Value;
if (null != poolGroup)
{
poolGroup.Clear();
}
}
}
protected virtual DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory)
{
// providers that support GetSchema must override this with a method that creates a meta data
// factory appropriate for them.
cacheMetaDataFactory = false;
throw ADP.NotSupported();
}
internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
{
Debug.Assert(null != owningConnection, "null owningConnection?");
Debug.Assert(null != poolGroup, "null poolGroup?");
DbConnectionOptions connectionOptions = poolGroup.ConnectionOptions;
DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo;
DbConnectionPoolKey poolKey = poolGroup.PoolKey;
DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions);
if (null != newConnection)
{
PerformanceCounters.HardConnectsPerSecond.Increment();
newConnection.MakeNonPooledObject(owningConnection, PerformanceCounters);
}
return newConnection;
}
internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
{
Debug.Assert(null != pool, "null pool?");
DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo;
DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions);
if (null != newConnection)
{
PerformanceCounters.HardConnectsPerSecond.Increment();
newConnection.MakePooledConnection(pool);
}
return newConnection;
}
internal virtual DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions)
{
return null;
}
private Timer CreatePruningTimer()
{
TimerCallback callback = new TimerCallback(PruneConnectionPoolGroups);
return new Timer(callback, null, PruningDueTime, PruningPeriod);
}
// GetCompletedTask must be called from within s_pendingOpenPooled lock
private static Task<DbConnectionInternal> GetCompletedTask()
{
if (s_completedTask == null)
{
TaskCompletionSource<DbConnectionInternal> source = new TaskCompletionSource<DbConnectionInternal>();
source.SetResult(null);
s_completedTask = source.Task;
}
return s_completedTask;
}
internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
{
Debug.Assert(null != owningConnection, "null owningConnection?");
DbConnectionPoolGroup poolGroup;
DbConnectionPool connectionPool;
connection = null;
// Work around race condition with clearing the pool between GetConnectionPool obtaining pool
// and GetConnection on the pool checking the pool state. Clearing the pool in this window
// will switch the pool into the ShuttingDown state, and GetConnection will return null.
// There is probably a better solution involving locking the pool/group, but that entails a major
// re-design of the connection pooling synchronization, so is post-poned for now.
// use retriesLeft to prevent CPU spikes with incremental sleep
// start with one msec, double the time every retry
// max time is: 1 + 2 + 4 + ... + 2^(retries-1) == 2^retries -1 == 1023ms (for 10 retries)
int retriesLeft = 10;
int timeBetweenRetriesMilliseconds = 1;
do
{
poolGroup = GetConnectionPoolGroup(owningConnection);
// Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread.
connectionPool = GetConnectionPool(owningConnection, poolGroup);
if (null == connectionPool)
{
// If GetConnectionPool returns null, we can be certain that
// this connection should not be pooled via DbConnectionPool
// or have a disabled pool entry.
poolGroup = GetConnectionPoolGroup(owningConnection); // previous entry have been disabled
if (retry != null)
{
Task<DbConnectionInternal> newTask;
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
lock (s_pendingOpenNonPooled)
{
// look for an available task slot (completed or empty)
int idx;
for (idx = 0; idx < s_pendingOpenNonPooled.Length; idx++)
{
Task task = s_pendingOpenNonPooled[idx];
if (task == null)
{
s_pendingOpenNonPooled[idx] = GetCompletedTask();
break;
}
else if (task.IsCompleted)
{
break;
}
}
// if didn't find one, pick the next one in round-robbin fashion
if (idx == s_pendingOpenNonPooled.Length)
{
idx = s_pendingOpenNonPooledNext++ % s_pendingOpenNonPooled.Length;
}
// now that we have an antecedent task, schedule our work when it is completed.
// If it is a new slot or a compelted task, this continuation will start right away.
// BUG? : If we have timed out task on top of running task, then new task could be started
// on top of that, since we are only checking the top task. This will lead to starting more threads
// than intended.
newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) =>
{
Transactions.Transaction originalTransaction = ADP.GetCurrentTransaction();
try
{
ADP.SetCurrentTransaction(retry.Task.AsyncState as Transactions.Transaction);
var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open))
{
oldConnection.PrepareForReplaceConnection();
oldConnection.Dispose();
}
return newConnection;
}
finally
{
ADP.SetCurrentTransaction(originalTransaction);
}
}, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
// Place this new task in the slot so any future work will be queued behind it
s_pendingOpenNonPooled[idx] = newTask;
}
// Set up the timeout (if needed)
if (owningConnection.ConnectionTimeout > 0)
{
int connectionTimeoutMilliseconds = owningConnection.ConnectionTimeout * 1000;
cancellationTokenSource.CancelAfter(connectionTimeoutMilliseconds);
}
// once the task is done, propagate the final results to the original caller
newTask.ContinueWith((task) =>
{
cancellationTokenSource.Dispose();
if (task.IsCanceled)
{
retry.TrySetException(ADP.ExceptionWithStackTrace(ADP.NonPooledOpenTimeout()));
}
else if (task.IsFaulted)
{
retry.TrySetException(task.Exception.InnerException);
}
else
{
if (retry.TrySetResult(task.Result))
{
PerformanceCounters.NumberOfNonPooledConnections.Increment();
}
else
{
// The outer TaskCompletionSource was already completed
// Which means that we don't know if someone has messed with the outer connection in the middle of creation
// So the best thing to do now is to destroy the newly created connection
task.Result.DoomThisConnection();
task.Result.Dispose();
}
}
}, TaskScheduler.Default);
return false;
}
connection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
PerformanceCounters.NumberOfNonPooledConnections.Increment();
}
else
{
if (((System.Data.OleDb.OleDbConnection)owningConnection).ForceNewConnection)
{
Debug.Assert(!(oldConnection is DbConnectionClosed), "Force new connection, but there is no old connection");
connection = connectionPool.ReplaceConnection(owningConnection, userOptions, oldConnection);
}
else
{
if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection))
{
return false;
}
}
if (connection == null)
{
// connection creation failed on semaphore waiting or if max pool reached
if (connectionPool.IsRunning)
{
// If GetConnection failed while the pool is running, the pool timeout occurred.
throw ADP.PooledOpenTimeout();
}
else
{
// We've hit the race condition, where the pool was shut down after we got it from the group.
// Yield time slice to allow shut down activities to complete and a new, running pool to be instantiated
// before retrying.
Threading.Thread.Sleep(timeBetweenRetriesMilliseconds);
timeBetweenRetriesMilliseconds *= 2; // double the wait time for next iteration
}
}
}
} while (connection == null && retriesLeft-- > 0);
if (connection == null)
{
// exhausted all retries or timed out - give up
throw ADP.PooledOpenTimeout();
}
return true;
}
private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup)
{
// if poolgroup is disabled, it will be replaced with a new entry
Debug.Assert(null != owningObject, "null owningObject?");
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?");
// It is possible that while the outer connection object has
// been sitting around in a closed and unused state in some long
// running app, the pruner may have come along and remove this
// the pool entry from the master list. If we were to use a
// pool entry in this state, we would create "unmanaged" pools,
// which would be bad. To avoid this problem, we automagically
// re-create the pool entry whenever it's disabled.
// however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work
if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))
{
// reusing existing pool option in case user originally used SetConnectionPoolOptions
DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions;
// get the string to hash on again
DbConnectionOptions connectionOptions = connectionPoolGroup.ConnectionOptions;
Debug.Assert(null != connectionOptions, "prevent expansion of connectionString");
connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions);
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?");
SetConnectionPoolGroup(owningObject, connectionPoolGroup);
}
DbConnectionPool connectionPool = connectionPoolGroup.GetConnectionPool(this);
return connectionPool;
}
internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions)
{
if (ADP.IsEmpty(key.ConnectionString))
{
return (DbConnectionPoolGroup)null;
}
DbConnectionPoolGroup connectionPoolGroup;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)))
{
// If we can't find an entry for the connection string in
// our collection of pool entries, then we need to create a
// new pool entry and add it to our collection.
DbConnectionOptions connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions);
if (null == connectionOptions)
{
throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing);
}
string expandedConnectionString = key.ConnectionString;
if (null == userConnectionOptions)
{ // we only allow one expansion on the connection string
userConnectionOptions = connectionOptions;
expandedConnectionString = connectionOptions.Expand();
// if the expanded string is same instance (default implementation), the use the already created options
if ((object)expandedConnectionString != (object)key.ConnectionString)
{
// CONSIDER: caching the original string to reduce future parsing
DbConnectionPoolKey newKey = (DbConnectionPoolKey)((ICloneable)key).Clone();
newKey.ConnectionString = expandedConnectionString;
return GetConnectionPoolGroup(newKey, null, ref userConnectionOptions);
}
}
// We don't support connection pooling on Win9x; it lacks too many of the APIs we require.
if ((null == poolOptions) && ADP.IsWindowsNT)
{
if (null != connectionPoolGroup)
{
// reusing existing pool option in case user originally used SetConnectionPoolOptions
poolOptions = connectionPoolGroup.PoolGroupOptions;
}
else
{
// Note: may return null for non-pooled connections
poolOptions = CreateConnectionPoolGroupOptions(connectionOptions);
}
}
lock (this)
{
connectionPoolGroups = _connectionPoolGroups;
if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup))
{
DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions);
newConnectionPoolGroup.ProviderInfo = CreateConnectionPoolGroupProviderInfo(connectionOptions);
// build new dictionary with space for new connection string
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(1 + connectionPoolGroups.Count);
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
newConnectionPoolGroups.Add(entry.Key, entry.Value);
}
// lock prevents race condition with PruneConnectionPoolGroups
newConnectionPoolGroups.Add(key, newConnectionPoolGroup);
PerformanceCounters.NumberOfActiveConnectionPoolGroups.Increment();
connectionPoolGroup = newConnectionPoolGroup;
_connectionPoolGroups = newConnectionPoolGroups;
}
else
{
Debug.Assert(!connectionPoolGroup.IsDisabled, "Disabled pool entry discovered");
}
}
Debug.Assert(null != connectionPoolGroup, "how did we not create a pool entry?");
Debug.Assert(null != userConnectionOptions, "how did we not have user connection options?");
}
else if (null == userConnectionOptions)
{
userConnectionOptions = connectionPoolGroup.ConnectionOptions;
}
return connectionPoolGroup;
}
internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPoolGroup, DbConnectionInternal internalConnection)
{
Debug.Assert(connectionPoolGroup != null, "connectionPoolGroup may not be null.");
// get the matadatafactory from the pool entry. If it does not already have one
// create one and save it on the pool entry
DbMetaDataFactory metaDataFactory = connectionPoolGroup.MetaDataFactory;
// consider serializing this so we don't construct multiple metadata factories
// if two threads happen to hit this at the same time. One will be GC'd
if (metaDataFactory == null)
{
bool allowCache = false;
metaDataFactory = CreateMetaDataFactory(internalConnection, out allowCache);
if (allowCache)
{
connectionPoolGroup.MetaDataFactory = metaDataFactory;
}
}
return metaDataFactory;
}
private void PruneConnectionPoolGroups(object state)
{
// when debugging this method, expect multiple threads at the same time
// First, walk the pool release list and attempt to clear each
// pool, when the pool is finally empty, we dispose of it. If the
// pool isn't empty, it's because there are active connections or
// distributed transactions that need it.
lock (_poolsToRelease)
{
if (0 != _poolsToRelease.Count)
{
DbConnectionPool[] poolsToRelease = _poolsToRelease.ToArray();
foreach (DbConnectionPool pool in poolsToRelease)
{
if (null != pool)
{
pool.Clear();
if (0 == pool.Count)
{
_poolsToRelease.Remove(pool);
PerformanceCounters.NumberOfInactiveConnectionPools.Decrement();
}
}
}
}
}
// Next, walk the pool entry release list and dispose of each
// pool entry when it is finally empty. If the pool entry isn't
// empty, it's because there are active pools that need it.
lock (_poolGroupsToRelease)
{
if (0 != _poolGroupsToRelease.Count)
{
DbConnectionPoolGroup[] poolGroupsToRelease = _poolGroupsToRelease.ToArray();
foreach (DbConnectionPoolGroup poolGroup in poolGroupsToRelease)
{
if (null != poolGroup)
{
int poolsLeft = poolGroup.Clear(); // may add entries to _poolsToRelease
if (0 == poolsLeft)
{
_poolGroupsToRelease.Remove(poolGroup);
PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Decrement();
}
}
}
}
}
// Finally, we walk through the collection of connection pool entries
// and prune each one. This will cause any empty pools to be put
// into the release list.
lock (this)
{
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(connectionPoolGroups.Count);
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
if (null != entry.Value)
{
Debug.Assert(!entry.Value.IsDisabled, "Disabled pool entry discovered");
// entries start active and go idle during prune if all pools are gone
// move idle entries from last prune pass to a queue for pending release
// otherwise process entry which may move it from active to idle
if (entry.Value.Prune())
{ // may add entries to _poolsToRelease
PerformanceCounters.NumberOfActiveConnectionPoolGroups.Decrement();
QueuePoolGroupForRelease(entry.Value);
}
else
{
newConnectionPoolGroups.Add(entry.Key, entry.Value);
}
}
}
_connectionPoolGroups = newConnectionPoolGroups;
}
}
internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing)
{
// Queue the pool up for release -- we'll clear it out and dispose
// of it as the last part of the pruning timer callback so we don't
// do it with the pool entry or the pool collection locked.
Debug.Assert(null != pool, "null pool?");
// set the pool to the shutdown state to force all active
// connections to be automatically disposed when they
// are returned to the pool
pool.Shutdown();
lock (_poolsToRelease)
{
if (clearing)
{
pool.Clear();
}
_poolsToRelease.Add(pool);
}
PerformanceCounters.NumberOfInactiveConnectionPools.Increment();
}
internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup)
{
Debug.Assert(null != poolGroup, "null poolGroup?");
lock (_poolGroupsToRelease)
{
_poolGroupsToRelease.Add(poolGroup);
}
PerformanceCounters.NumberOfInactiveConnectionPoolGroups.Increment();
}
protected virtual DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
{
return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection);
}
protected abstract DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection);
protected abstract DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous);
protected abstract DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions options);
internal abstract DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection);
internal abstract void PermissionDemand(DbConnection outerConnection);
internal abstract void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup);
internal abstract void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to);
internal abstract bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from);
internal abstract void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to);
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace Lucene.Net.Codecs.Lucene42
{
using Lucene.Net.Util.Fst;
using ArrayUtil = Lucene.Net.Util.ArrayUtil;
using BlockPackedWriter = Lucene.Net.Util.Packed.BlockPackedWriter;
using ByteArrayDataOutput = Lucene.Net.Store.ByteArrayDataOutput;
using BytesRef = Lucene.Net.Util.BytesRef;
/*
* 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 FieldInfo = Lucene.Net.Index.FieldInfo;
using FormatAndBits = Lucene.Net.Util.Packed.PackedInts.FormatAndBits;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using INPUT_TYPE = Lucene.Net.Util.Fst.FST.INPUT_TYPE;
using IntsRef = Lucene.Net.Util.IntsRef;
using IOUtils = Lucene.Net.Util.IOUtils;
using MathUtil = Lucene.Net.Util.MathUtil;
using MonotonicBlockPackedWriter = Lucene.Net.Util.Packed.MonotonicBlockPackedWriter;
using PackedInts = Lucene.Net.Util.Packed.PackedInts;
using PositiveIntOutputs = Lucene.Net.Util.Fst.PositiveIntOutputs;
using SegmentWriteState = Lucene.Net.Index.SegmentWriteState;
using Util = Lucene.Net.Util.Fst.Util;
// Constants use Lucene42DocValuesProducer.
/// <summary>
/// Writer for <seealso cref="Lucene42DocValuesFormat"/>
/// </summary>
internal class Lucene42DocValuesConsumer : DocValuesConsumer
{
internal readonly IndexOutput Data, Meta;
internal readonly int MaxDoc;
internal readonly float AcceptableOverheadRatio;
internal Lucene42DocValuesConsumer(SegmentWriteState state, string dataCodec, string dataExtension, string metaCodec, string metaExtension, float acceptableOverheadRatio)
{
this.AcceptableOverheadRatio = acceptableOverheadRatio;
MaxDoc = state.SegmentInfo.DocCount;
bool success = false;
try
{
string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, dataExtension);
Data = state.Directory.CreateOutput(dataName, state.Context);
// this writer writes the format 4.2 did!
CodecUtil.WriteHeader(Data, dataCodec, Lucene42DocValuesProducer.VERSION_GCD_COMPRESSION);
string metaName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, metaExtension);
Meta = state.Directory.CreateOutput(metaName, state.Context);
CodecUtil.WriteHeader(Meta, metaCodec, Lucene42DocValuesProducer.VERSION_GCD_COMPRESSION);
success = true;
}
finally
{
if (!success)
{
IOUtils.CloseWhileHandlingException(this);
}
}
}
public override void AddNumericField(FieldInfo field, IEnumerable<long?> values)
{
AddNumericField(field, values, true);
}
internal virtual void AddNumericField(FieldInfo field, IEnumerable<long?> values, bool optimizeStorage)
{
Meta.WriteVInt(field.Number);
Meta.WriteByte((byte)Lucene42DocValuesProducer.NUMBER);
Meta.WriteLong(Data.FilePointer);
long minValue = long.MaxValue;
long maxValue = long.MinValue;
long gcd = 0;
// TODO: more efficient?
HashSet<long> uniqueValues = null;
if (optimizeStorage)
{
uniqueValues = new HashSet<long>();
long count = 0;
foreach (long? nv in values)
{
// TODO: support this as MemoryDVFormat (and be smart about missing maybe)
long v = nv == null ? 0 : (long)nv;
if (gcd != 1)
{
if (v < long.MinValue / 2 || v > long.MaxValue / 2)
{
// in that case v - minValue might overflow and make the GCD computation return
// wrong results. Since these extreme values are unlikely, we just discard
// GCD computation for them
gcd = 1;
} // minValue needs to be set first
else if (count != 0)
{
gcd = MathUtil.Gcd(gcd, v - minValue);
}
}
minValue = Math.Min(minValue, v);
maxValue = Math.Max(maxValue, v);
if (uniqueValues != null)
{
if (uniqueValues.Add(v))
{
if (uniqueValues.Count > 256)
{
uniqueValues = null;
}
}
}
++count;
}
Debug.Assert(count == MaxDoc);
}
if (uniqueValues != null)
{
// small number of unique values
int bitsPerValue = PackedInts.BitsRequired(uniqueValues.Count - 1);
FormatAndBits formatAndBits = PackedInts.FastestFormatAndBits(MaxDoc, bitsPerValue, AcceptableOverheadRatio);
if (formatAndBits.bitsPerValue == 8 && minValue >= sbyte.MinValue && maxValue <= sbyte.MaxValue)
{
Meta.WriteByte((byte)Lucene42DocValuesProducer.UNCOMPRESSED); // uncompressed
foreach (long? nv in values)
{
Data.WriteByte(nv == null ? (byte)0 : (byte)nv);
}
}
else
{
Meta.WriteByte((byte)Lucene42DocValuesProducer.TABLE_COMPRESSED); // table-compressed
long[] decode = uniqueValues.ToArray(/*new long?[uniqueValues.Count]*/);
var encode = new Dictionary<long, int>();
Data.WriteVInt(decode.Length);
for (int i = 0; i < decode.Length; i++)
{
Data.WriteLong(decode[i]);
encode[decode[i]] = i;
}
Meta.WriteVInt(PackedInts.VERSION_CURRENT);
Data.WriteVInt(formatAndBits.format.id);
Data.WriteVInt(formatAndBits.bitsPerValue);
PackedInts.Writer writer = PackedInts.GetWriterNoHeader(Data, formatAndBits.format, MaxDoc, formatAndBits.bitsPerValue, PackedInts.DEFAULT_BUFFER_SIZE);
foreach (long? nv in values)
{
writer.Add(encode[nv == null ? 0 : (long)nv]);
}
writer.Finish();
}
}
else if (gcd != 0 && gcd != 1)
{
Meta.WriteByte((byte)Lucene42DocValuesProducer.GCD_COMPRESSED);
Meta.WriteVInt(PackedInts.VERSION_CURRENT);
Data.WriteLong(minValue);
Data.WriteLong(gcd);
Data.WriteVInt(Lucene42DocValuesProducer.BLOCK_SIZE);
BlockPackedWriter writer = new BlockPackedWriter(Data, Lucene42DocValuesProducer.BLOCK_SIZE);
foreach (long? nv in values)
{
long value = nv == null ? 0 : (long)nv;
writer.Add((value - minValue) / gcd);
}
writer.Finish();
}
else
{
Meta.WriteByte((byte)Lucene42DocValuesProducer.DELTA_COMPRESSED); // delta-compressed
Meta.WriteVInt(PackedInts.VERSION_CURRENT);
Data.WriteVInt(Lucene42DocValuesProducer.BLOCK_SIZE);
BlockPackedWriter writer = new BlockPackedWriter(Data, Lucene42DocValuesProducer.BLOCK_SIZE);
foreach (long? nv in values)
{
writer.Add(nv == null ? 0 : (long)nv);
}
writer.Finish();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
bool success = false;
try
{
if (Meta != null)
{
Meta.WriteVInt(-1); // write EOF marker
}
success = true;
}
finally
{
if (success)
{
IOUtils.Close(Data, Meta);
}
else
{
IOUtils.CloseWhileHandlingException(Data, Meta);
}
}
}
}
public override void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values)
{
// write the byte[] data
Meta.WriteVInt(field.Number);
Meta.WriteByte((byte)Lucene42DocValuesProducer.BYTES);
int minLength = int.MaxValue;
int maxLength = int.MinValue;
long startFP = Data.FilePointer;
foreach (BytesRef v in values)
{
int length = v == null ? 0 : v.Length;
if (length > Lucene42DocValuesFormat.MAX_BINARY_FIELD_LENGTH)
{
throw new System.ArgumentException("DocValuesField \"" + field.Name + "\" is too large, must be <= " + Lucene42DocValuesFormat.MAX_BINARY_FIELD_LENGTH);
}
minLength = Math.Min(minLength, length);
maxLength = Math.Max(maxLength, length);
if (v != null)
{
Data.WriteBytes(v.Bytes, v.Offset, v.Length);
}
}
Meta.WriteLong(startFP);
Meta.WriteLong(Data.FilePointer - startFP);
Meta.WriteVInt(minLength);
Meta.WriteVInt(maxLength);
// if minLength == maxLength, its a fixed-length byte[], we are done (the addresses are implicit)
// otherwise, we need to record the length fields...
if (minLength != maxLength)
{
Meta.WriteVInt(PackedInts.VERSION_CURRENT);
Meta.WriteVInt(Lucene42DocValuesProducer.BLOCK_SIZE);
MonotonicBlockPackedWriter writer = new MonotonicBlockPackedWriter(Data, Lucene42DocValuesProducer.BLOCK_SIZE);
long addr = 0;
foreach (BytesRef v in values)
{
if (v != null)
{
addr += v.Length;
}
writer.Add(addr);
}
writer.Finish();
}
}
private void WriteFST(FieldInfo field, IEnumerable<BytesRef> values)
{
Meta.WriteVInt(field.Number);
Meta.WriteByte((byte)Lucene42DocValuesProducer.FST);
Meta.WriteLong(Data.FilePointer);
PositiveIntOutputs outputs = PositiveIntOutputs.Singleton;
Builder<long?> builder = new Builder<long?>(INPUT_TYPE.BYTE1, outputs);
IntsRef scratch = new IntsRef();
long ord = 0;
foreach (BytesRef v in values)
{
builder.Add(Util.ToIntsRef(v, scratch), ord);
ord++;
}
var fst = builder.Finish();
if (fst != null)
{
fst.Save(Data);
}
Meta.WriteVLong(ord);
}
public override void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd)
{
// three cases for simulating the old writer:
// 1. no missing
// 2. missing (and empty string in use): remap ord=-1 -> ord=0
// 3. missing (and empty string not in use): remap all ords +1, insert empty string into values
bool anyMissing = false;
foreach (long? n in docToOrd)
{
if (n.Value == -1)
{
anyMissing = true;
break;
}
}
bool hasEmptyString = false;
foreach (BytesRef b in values)
{
hasEmptyString = b.Length == 0;
break;
}
if (!anyMissing)
{
// nothing to do
}
else if (hasEmptyString)
{
docToOrd = MissingOrdRemapper.MapMissingToOrd0(docToOrd);
}
else
{
docToOrd = MissingOrdRemapper.MapAllOrds(docToOrd);
values = MissingOrdRemapper.InsertEmptyValue(values);
}
// write the ordinals as numerics
AddNumericField(field, docToOrd, false);
// write the values as FST
WriteFST(field, values);
}
// note: this might not be the most efficient... but its fairly simple
public override void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords)
{
// write the ordinals as a binary field
AddBinaryField(field, new IterableAnonymousInnerClassHelper(this, docToOrdCount, ords));
// write the values as FST
WriteFST(field, values);
}
private class IterableAnonymousInnerClassHelper : IEnumerable<BytesRef>
{
private readonly Lucene42DocValuesConsumer OuterInstance;
private IEnumerable<long?> DocToOrdCount;
private IEnumerable<long?> Ords;
public IterableAnonymousInnerClassHelper(Lucene42DocValuesConsumer outerInstance, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords)
{
this.OuterInstance = outerInstance;
this.DocToOrdCount = docToOrdCount;
this.Ords = ords;
}
public IEnumerator<BytesRef> GetEnumerator()
{
return new SortedSetIterator(DocToOrdCount.GetEnumerator(), Ords.GetEnumerator());
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
// per-document vint-encoded byte[]
internal class SortedSetIterator : IEnumerator<BytesRef>
{
internal byte[] Buffer = new byte[10];
internal ByteArrayDataOutput @out = new ByteArrayDataOutput();
internal BytesRef @ref = new BytesRef();
internal readonly IEnumerator<long?> Counts;
internal readonly IEnumerator<long?> Ords;
internal SortedSetIterator(IEnumerator<long?> counts, IEnumerator<long?> ords)
{
this.Counts = counts;
this.Ords = ords;
}
public bool MoveNext()
{
if (!Counts.MoveNext())
{
return false;
}
int count = (int)Counts.Current;
int maxSize = count * 9; //worst case
if (maxSize > Buffer.Length)
{
Buffer = ArrayUtil.Grow(Buffer, maxSize);
}
try
{
EncodeValues(count);
}
catch (IOException bogus)
{
throw new Exception(bogus.Message, bogus);
}
@ref.Bytes = Buffer;
@ref.Offset = 0;
@ref.Length = @out.Position;
return true;
}
public BytesRef Current
{
get { return @ref; }
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
// encodes count values to buffer
internal virtual void EncodeValues(int count)
{
@out.Reset(Buffer);
long lastOrd = 0;
for (int i = 0; i < count; i++)
{
Ords.MoveNext();
long ord = Ords.Current.Value;
@out.WriteVLong(ord - lastOrd);
lastOrd = ord;
}
}
public void Reset()
{
throw new NotImplementedException();
}
public void Dispose()
{
}
}
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using FileStaging;
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// An Azure Batch task. A task is a piece of work that is associated with a job and runs on a compute node.
/// </summary>
public partial class CloudTask : ITransportObjectProvider<Models.TaskAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<AffinityInformation> AffinityInformationProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<AuthenticationTokenSettings> AuthenticationTokenSettingsProperty;
public readonly PropertyAccessor<string> CommandLineProperty;
public readonly PropertyAccessor<ComputeNodeInformation> ComputeNodeInformationProperty;
public readonly PropertyAccessor<TaskConstraints> ConstraintsProperty;
public readonly PropertyAccessor<DateTime?> CreationTimeProperty;
public readonly PropertyAccessor<TaskDependencies> DependsOnProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty;
public readonly PropertyAccessor<string> ETagProperty;
public readonly PropertyAccessor<TaskExecutionInformation> ExecutionInformationProperty;
public readonly PropertyAccessor<ExitConditions> ExitConditionsProperty;
public readonly PropertyAccessor<IList<IFileStagingProvider>> FilesToStageProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<DateTime?> LastModifiedProperty;
public readonly PropertyAccessor<MultiInstanceSettings> MultiInstanceSettingsProperty;
public readonly PropertyAccessor<Common.TaskState?> PreviousStateProperty;
public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty;
public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty;
public readonly PropertyAccessor<Common.TaskState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<TaskStatistics> StatisticsProperty;
public readonly PropertyAccessor<string> UrlProperty;
public readonly PropertyAccessor<UserIdentity> UserIdentityProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AffinityInformationProperty = this.CreatePropertyAccessor<AffinityInformation>("AffinityInformation", BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>("ApplicationPackageReferences", BindingAccess.Read | BindingAccess.Write);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor<AuthenticationTokenSettings>("AuthenticationTokenSettings", BindingAccess.Read | BindingAccess.Write);
this.CommandLineProperty = this.CreatePropertyAccessor<string>("CommandLine", BindingAccess.Read | BindingAccess.Write);
this.ComputeNodeInformationProperty = this.CreatePropertyAccessor<ComputeNodeInformation>("ComputeNodeInformation", BindingAccess.None);
this.ConstraintsProperty = this.CreatePropertyAccessor<TaskConstraints>("Constraints", BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>("CreationTime", BindingAccess.None);
this.DependsOnProperty = this.CreatePropertyAccessor<TaskDependencies>("DependsOn", BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>("DisplayName", BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>("EnvironmentSettings", BindingAccess.Read | BindingAccess.Write);
this.ETagProperty = this.CreatePropertyAccessor<string>("ETag", BindingAccess.None);
this.ExecutionInformationProperty = this.CreatePropertyAccessor<TaskExecutionInformation>("ExecutionInformation", BindingAccess.None);
this.ExitConditionsProperty = this.CreatePropertyAccessor<ExitConditions>("ExitConditions", BindingAccess.Read | BindingAccess.Write);
this.FilesToStageProperty = this.CreatePropertyAccessor<IList<IFileStagingProvider>>("FilesToStage", BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor<string>("Id", BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>("LastModified", BindingAccess.None);
this.MultiInstanceSettingsProperty = this.CreatePropertyAccessor<MultiInstanceSettings>("MultiInstanceSettings", BindingAccess.Read | BindingAccess.Write);
this.PreviousStateProperty = this.CreatePropertyAccessor<Common.TaskState?>("PreviousState", BindingAccess.None);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("PreviousStateTransitionTime", BindingAccess.None);
this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>("ResourceFiles", BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor<Common.TaskState?>("State", BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("StateTransitionTime", BindingAccess.None);
this.StatisticsProperty = this.CreatePropertyAccessor<TaskStatistics>("Statistics", BindingAccess.None);
this.UrlProperty = this.CreatePropertyAccessor<string>("Url", BindingAccess.None);
this.UserIdentityProperty = this.CreatePropertyAccessor<UserIdentity>("UserIdentity", BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.CloudTask protocolObject) : base(BindingState.Bound)
{
this.AffinityInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AffinityInfo, o => new AffinityInformation(o).Freeze()),
"AffinityInformation",
BindingAccess.Read);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollectionAndFreeze(protocolObject.ApplicationPackageReferences),
"ApplicationPackageReferences",
BindingAccess.Read);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AuthenticationTokenSettings, o => new AuthenticationTokenSettings(o).Freeze()),
"AuthenticationTokenSettings",
BindingAccess.Read);
this.CommandLineProperty = this.CreatePropertyAccessor(
protocolObject.CommandLine,
"CommandLine",
BindingAccess.Read);
this.ComputeNodeInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NodeInfo, o => new ComputeNodeInformation(o).Freeze()),
"ComputeNodeInformation",
BindingAccess.Read);
this.ConstraintsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new TaskConstraints(o)),
"Constraints",
BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor(
protocolObject.CreationTime,
"CreationTime",
BindingAccess.Read);
this.DependsOnProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.DependsOn, o => new TaskDependencies(o).Freeze()),
"DependsOn",
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
"DisplayName",
BindingAccess.Read);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollectionAndFreeze(protocolObject.EnvironmentSettings),
"EnvironmentSettings",
BindingAccess.Read);
this.ETagProperty = this.CreatePropertyAccessor(
protocolObject.ETag,
"ETag",
BindingAccess.Read);
this.ExecutionInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new TaskExecutionInformation(o).Freeze()),
"ExecutionInformation",
BindingAccess.Read);
this.ExitConditionsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExitConditions, o => new ExitConditions(o).Freeze()),
"ExitConditions",
BindingAccess.Read);
this.FilesToStageProperty = this.CreatePropertyAccessor<IList<IFileStagingProvider>>(
"FilesToStage",
BindingAccess.None);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
"Id",
BindingAccess.Read);
this.LastModifiedProperty = this.CreatePropertyAccessor(
protocolObject.LastModified,
"LastModified",
BindingAccess.Read);
this.MultiInstanceSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.MultiInstanceSettings, o => new MultiInstanceSettings(o).Freeze()),
"MultiInstanceSettings",
BindingAccess.Read);
this.PreviousStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.TaskState, Common.TaskState>(protocolObject.PreviousState),
"PreviousState",
BindingAccess.Read);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.PreviousStateTransitionTime,
"PreviousStateTransitionTime",
BindingAccess.Read);
this.ResourceFilesProperty = this.CreatePropertyAccessor(
ResourceFile.ConvertFromProtocolCollectionAndFreeze(protocolObject.ResourceFiles),
"ResourceFiles",
BindingAccess.Read);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.TaskState, Common.TaskState>(protocolObject.State),
"State",
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
"StateTransitionTime",
BindingAccess.Read);
this.StatisticsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new TaskStatistics(o).Freeze()),
"Statistics",
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
"Url",
BindingAccess.Read);
this.UserIdentityProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.UserIdentity, o => new UserIdentity(o).Freeze()),
"UserIdentity",
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
private readonly string parentJobId;
internal string ParentJobId
{
get
{
return this.parentJobId;
}
}
#region Constructors
internal CloudTask(
BatchClient parentBatchClient,
string parentJobId,
Models.CloudTask protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentJobId = parentJobId;
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="CloudTask"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region CloudTask
/// <summary>
/// Gets or sets a locality hint that can be used by the Batch service to select a node on which to start the task.
/// </summary>
public AffinityInformation AffinityInformation
{
get { return this.propertyContainer.AffinityInformationProperty.Value; }
set { this.propertyContainer.AffinityInformationProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of application packages that the Batch service will deploy to the compute node before running
/// the command line.
/// </summary>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the settings for an authentication token that the task can use to perform Batch service operations.
/// </summary>
/// <remarks>
/// If this property is set, the Batch service provides the task with an authentication token which can be used to
/// authenticate Batch service operations without requiring an account access key. The token is provided via the
/// AZ_BATCH_AUTHENTICATION_TOKEN environment variable. The operations that the task can carry out using the token
/// depend on the settings. For example, a task can request job permissions in order to add other tasks to the job,
/// or check the status of the job or of other tasks.
/// </remarks>
public AuthenticationTokenSettings AuthenticationTokenSettings
{
get { return this.propertyContainer.AuthenticationTokenSettingsProperty.Value; }
set { this.propertyContainer.AuthenticationTokenSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment
/// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command
/// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// </remarks>
public string CommandLine
{
get { return this.propertyContainer.CommandLineProperty.Value; }
set { this.propertyContainer.CommandLineProperty.Value = value; }
}
/// <summary>
/// Gets information about the compute node on which the task ran.
/// </summary>
public ComputeNodeInformation ComputeNodeInformation
{
get { return this.propertyContainer.ComputeNodeInformationProperty.Value; }
}
/// <summary>
/// Gets or sets the execution constraints that apply to this task.
/// </summary>
public TaskConstraints Constraints
{
get { return this.propertyContainer.ConstraintsProperty.Value; }
set { this.propertyContainer.ConstraintsProperty.Value = value; }
}
/// <summary>
/// Gets the creation time of the task.
/// </summary>
public DateTime? CreationTime
{
get { return this.propertyContainer.CreationTimeProperty.Value; }
}
/// <summary>
/// Gets or sets any other tasks that this <see cref="CloudTask"/> depends on. The task will not be scheduled until
/// all depended-on tasks have completed successfully.
/// </summary>
/// <remarks>
/// The job must set <see cref="CloudJob.UsesTaskDependencies"/> to true in order to use task dependencies. If UsesTaskDependencies
/// is false (the default), adding a task with dependencies will fail with an error.
/// </remarks>
public TaskDependencies DependsOn
{
get { return this.propertyContainer.DependsOnProperty.Value; }
set { this.propertyContainer.DependsOnProperty.Value = value; }
}
/// <summary>
/// Gets or sets the display name of the task.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of environment variable settings for the task.
/// </summary>
public IList<EnvironmentSetting> EnvironmentSettings
{
get { return this.propertyContainer.EnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the ETag for the task.
/// </summary>
public string ETag
{
get { return this.propertyContainer.ETagProperty.Value; }
}
/// <summary>
/// Gets the execution information for the task.
/// </summary>
public TaskExecutionInformation ExecutionInformation
{
get { return this.propertyContainer.ExecutionInformationProperty.Value; }
}
/// <summary>
/// Gets or sets how the Batch service should respond when the task completes.
/// </summary>
public ExitConditions ExitConditions
{
get { return this.propertyContainer.ExitConditionsProperty.Value; }
set { this.propertyContainer.ExitConditionsProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files to be staged for the task.
/// </summary>
public IList<IFileStagingProvider> FilesToStage
{
get { return this.propertyContainer.FilesToStageProperty.Value; }
set
{
this.propertyContainer.FilesToStageProperty.Value = ConcurrentChangeTrackedList<IFileStagingProvider>.TransformEnumerableToConcurrentList(value);
}
}
/// <summary>
/// Gets or sets the id of the task.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets the last modified time of the task.
/// </summary>
public DateTime? LastModified
{
get { return this.propertyContainer.LastModifiedProperty.Value; }
}
/// <summary>
/// Gets or sets information about how to run the multi-instance task.
/// </summary>
public MultiInstanceSettings MultiInstanceSettings
{
get { return this.propertyContainer.MultiInstanceSettingsProperty.Value; }
set { this.propertyContainer.MultiInstanceSettingsProperty.Value = value; }
}
/// <summary>
/// Gets the previous state of the task.
/// </summary>
/// <remarks>
/// If the task is in its initial <see cref="Common.TaskState.Active"/> state, the PreviousState property is not
/// defined.
/// </remarks>
public Common.TaskState? PreviousState
{
get { return this.propertyContainer.PreviousStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the task entered its previous state.
/// </summary>
/// <remarks>
/// If the task is in its initial <see cref="Common.TaskState.Active"/> state, the PreviousStateTransitionTime property
/// is not defined.
/// </remarks>
public DateTime? PreviousStateTransitionTime
{
get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will download to the compute node before running the command
/// line.
/// </summary>
public IList<ResourceFile> ResourceFiles
{
get { return this.propertyContainer.ResourceFilesProperty.Value; }
set
{
this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the current state of the task.
/// </summary>
public Common.TaskState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the task entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets resource usage statistics for the task.
/// </summary>
/// <remarks>
/// This property is populated only if the <see cref="CloudTask"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/>
/// including the 'stats' attribute; otherwise it is null.
/// </remarks>
public TaskStatistics Statistics
{
get { return this.propertyContainer.StatisticsProperty.Value; }
}
/// <summary>
/// Gets the URL of the task.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
/// <summary>
/// Gets or sets the user identity under which the task runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to the task.
/// </remarks>
public UserIdentity UserIdentity
{
get { return this.propertyContainer.UserIdentityProperty.Value; }
set { this.propertyContainer.UserIdentityProperty.Value = value; }
}
#endregion // CloudTask
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.TaskAddParameter ITransportObjectProvider<Models.TaskAddParameter>.GetTransportObject()
{
Models.TaskAddParameter result = new Models.TaskAddParameter()
{
AffinityInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.AffinityInformation, (o) => o.GetTransportObject()),
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
AuthenticationTokenSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.AuthenticationTokenSettings, (o) => o.GetTransportObject()),
CommandLine = this.CommandLine,
Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()),
DependsOn = UtilitiesInternal.CreateObjectWithNullCheck(this.DependsOn, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings),
ExitConditions = UtilitiesInternal.CreateObjectWithNullCheck(this.ExitConditions, (o) => o.GetTransportObject()),
Id = this.Id,
MultiInstanceSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.MultiInstanceSettings, (o) => o.GetTransportObject()),
ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles),
UserIdentity = UtilitiesInternal.CreateObjectWithNullCheck(this.UserIdentity, (o) => o.GetTransportObject()),
};
return result;
}
#endregion // Internal/private methods
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Pipeline;
#pragma warning disable SA1402 // File may only contain a single type
// branching logic on wrapping seekable vs unseekable streams has been handled via inheritance
namespace Azure.Storage.Shared
{
/// <summary>
/// Exposes a predetermined slice of a larger stream using the same Stream interface.
/// There should not be access to the base stream while this facade is in use.
/// </summary>
internal abstract class WindowStream : SlicedStream
{
private Stream InnerStream { get; }
public override long AbsolutePosition { get; }
public override bool CanRead => true;
public override bool CanWrite => false;
/// <summary>
/// Constructs a window of an underlying stream.
/// </summary>
/// <param name="stream">
/// Potentialy unseekable stream to expose a window of.
/// </param>
/// <param name="absolutePosition">
/// The offset of this stream from the start of the wrapped stream.
/// </param>
private WindowStream(Stream stream, long absolutePosition)
{
InnerStream = stream;
AbsolutePosition = absolutePosition;
}
public static WindowStream GetWindow(Stream stream, long maxWindowLength, long absolutePosition = default)
{
if (stream.CanSeek)
{
return new SeekableWindowStream(stream, maxWindowLength);
}
else
{
return new UnseekableWindowStream(stream, maxWindowLength, absolutePosition);
}
}
public override void Flush()
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void WriteByte(byte value) => throw new NotSupportedException();
/// <inheritdoc/>
/// <remarks>
/// Implementing this method takes advantage of any optimizations in the wrapped stream's implementation.
/// </remarks>
public override int ReadByte()
{
if (AdjustCount(1) <= 0)
{
return -1;
}
int val = InnerStream.ReadByte();
if (val != -1)
{
ReportInnerStreamRead(1);
}
return val;
}
public override int Read(byte[] buffer, int offset, int count)
=> ReadInternal(buffer, offset, count, async: false, cancellationToken: default).EnsureCompleted();
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
=> await ReadInternal(buffer, offset, count, async: true, cancellationToken).ConfigureAwait(false);
private async Task<int> ReadInternal(byte[] buffer, int offset, int count, bool async, CancellationToken cancellationToken)
{
count = AdjustCount(count);
if (count <= 0)
{
return 0;
}
int result = async
? await InnerStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false)
: InnerStream.Read(buffer, offset, count);
ReportInnerStreamRead(result);
return result;
}
protected abstract int AdjustCount(int count);
protected abstract void ReportInnerStreamRead(int resultRead);
/// <summary>
/// Exposes a predetermined slice of a larger, unseekable stream using the same Stream
/// interface. There should not be access to the base stream while this facade is in use.
/// This stream wrapper is unseekable. To wrap a partition of an unseekable stream where
/// the partition is seekable, see <see cref="PooledMemoryStream"/>.
/// </summary>
private class UnseekableWindowStream : WindowStream
{
private long _position = 0;
private long MaxLength { get; }
public UnseekableWindowStream(Stream stream, long maxWindowLength, long absolutePosition) : base(stream, absolutePosition)
{
MaxLength = maxWindowLength;
}
public override bool CanSeek => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
protected override int AdjustCount(int count)
=> (int)Math.Min(count, MaxLength - _position);
protected override void ReportInnerStreamRead(int resultRead)
=> _position += resultRead;
}
/// <summary>
/// Exposes a predetermined slice of a larger, seekable stream using the same Stream
/// interface. There should not be access to the base stream while this facade is in use.
/// This stream wrapper is sseekable. To wrap a partition of an unseekable stream where
/// the partition is seekable, see <see cref="PooledMemoryStream"/>.
/// </summary>
private class SeekableWindowStream : WindowStream
{
public SeekableWindowStream(Stream stream, long maxWindowLength) : base(stream, stream.Position)
{
// accessing the stream's Position in the constructor acts as our validator that we're wrapping a seekable stream
Length = Math.Min(
stream.Length - stream.Position,
maxWindowLength);
}
public override bool CanSeek => true;
public override long Length { get; }
public override long Position
{
get => InnerStream.Position - AbsolutePosition;
set => InnerStream.Position = AbsolutePosition + value;
}
public override long Seek(long offset, SeekOrigin origin)
{
switch (origin)
{
case SeekOrigin.Begin:
InnerStream.Seek(AbsolutePosition + offset, SeekOrigin.Begin);
break;
case SeekOrigin.Current:
InnerStream.Seek(InnerStream.Position + offset, SeekOrigin.Current);
break;
case SeekOrigin.End:
InnerStream.Seek((AbsolutePosition + this.Length) - InnerStream.Length + offset, SeekOrigin.End);
break;
}
return Position;
}
public override void SetLength(long value) => throw new NotSupportedException();
protected override int AdjustCount(int count)
=> (int)Math.Min(count, Length - Position);
protected override void ReportInnerStreamRead(int resultRead)
{
// no-op, inner stream took care of position adjustment
}
}
}
internal static partial class StreamExtensions
{
/// <summary>
/// Some streams will throw if you try to access their length so we wrap
/// the check in a TryGet helper.
/// </summary>
public static long? GetPositionOrDefault(this Stream content)
{
if (content == null)
{
/* Returning 0 instead of default puts us on the quick and clean one-shot upload,
* which produces more consistent fail state with how a 1-1 method on the convenience
* layer would fail.
*/
return 0;
}
try
{
if (content.CanSeek)
{
return content.Position;
}
}
catch (NotSupportedException)
{
}
return default;
}
}
}
| |
// 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.Diagnostics {
using System.Text;
using System;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
// There is no good reason for the methods of this class to be virtual.
// In order to ensure trusted code can trust the data it gets from a
// StackTrace, we use an InheritanceDemand to prevent partially-trusted
// subclasses.
#if !FEATURE_CORECLR
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
#endif
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StackFrame
{
private MethodBase method;
private int offset;
private int ILOffset;
private String strFileName;
private int iLineNumber;
private int iColumnNumber;
#if FEATURE_EXCEPTIONDISPATCHINFO
[System.Runtime.Serialization.OptionalField]
private bool fIsLastFrameFromForeignExceptionStackTrace;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
internal void InitMembers()
{
method = null;
offset = OFFSET_UNKNOWN;
ILOffset = OFFSET_UNKNOWN;
strFileName = null;
iLineNumber = 0;
iColumnNumber = 0;
#if FEATURE_EXCEPTIONDISPATCHINFO
fIsLastFrameFromForeignExceptionStackTrace = false;
#endif // FEATURE_EXCEPTIONDISPATCHINFO
}
// Constructs a StackFrame corresponding to the active stack frame.
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
public StackFrame()
{
InitMembers();
BuildStackFrame (0 + StackTrace.METHODS_TO_SKIP, false);// iSkipFrames=0
}
// Constructs a StackFrame corresponding to the active stack frame.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackFrame(bool fNeedFileInfo)
{
InitMembers();
BuildStackFrame (0 + StackTrace.METHODS_TO_SKIP, fNeedFileInfo);// iSkipFrames=0
}
// Constructs a StackFrame corresponding to a calling stack frame.
//
public StackFrame(int skipFrames)
{
InitMembers();
BuildStackFrame (skipFrames + StackTrace.METHODS_TO_SKIP, false);
}
// Constructs a StackFrame corresponding to a calling stack frame.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public StackFrame(int skipFrames, bool fNeedFileInfo)
{
InitMembers();
BuildStackFrame (skipFrames + StackTrace.METHODS_TO_SKIP, fNeedFileInfo);
}
// Called from the class "StackTrace"
//
internal StackFrame(bool DummyFlag1, bool DummyFlag2)
{
InitMembers();
}
// Constructs a "fake" stack frame, just containing the given file
// name and line number. Use when you don't want to use the
// debugger's line mapping logic.
//
public StackFrame(String fileName, int lineNumber)
{
InitMembers();
BuildStackFrame (StackTrace.METHODS_TO_SKIP, false);
strFileName = fileName;
iLineNumber = lineNumber;
iColumnNumber = 0;
}
// Constructs a "fake" stack frame, just containing the given file
// name, line number and column number. Use when you don't want to
// use the debugger's line mapping logic.
//
public StackFrame(String fileName, int lineNumber, int colNumber)
{
InitMembers();
BuildStackFrame (StackTrace.METHODS_TO_SKIP, false);
strFileName = fileName;
iLineNumber = lineNumber;
iColumnNumber = colNumber;
}
// Constant returned when the native or IL offset is unknown
public const int OFFSET_UNKNOWN = -1;
internal virtual void SetMethodBase (MethodBase mb)
{
method = mb;
}
internal virtual void SetOffset (int iOffset)
{
offset = iOffset;
}
internal virtual void SetILOffset (int iOffset)
{
ILOffset = iOffset;
}
internal virtual void SetFileName (String strFName)
{
strFileName = strFName;
}
internal virtual void SetLineNumber (int iLine)
{
iLineNumber = iLine;
}
internal virtual void SetColumnNumber (int iCol)
{
iColumnNumber = iCol;
}
#if FEATURE_EXCEPTIONDISPATCHINFO
internal virtual void SetIsLastFrameFromForeignExceptionStackTrace (bool fIsLastFrame)
{
fIsLastFrameFromForeignExceptionStackTrace = fIsLastFrame;
}
internal virtual bool GetIsLastFrameFromForeignExceptionStackTrace()
{
return fIsLastFrameFromForeignExceptionStackTrace;
}
#endif // FEATURE_EXCEPTIONDISPATCHINFO
// Returns the method the frame is executing
//
public virtual MethodBase GetMethod ()
{
Contract.Ensures(Contract.Result<MethodBase>() != null);
return method;
}
// Returns the offset from the start of the native (jitted) code for the
// method being executed
//
public virtual int GetNativeOffset ()
{
return offset;
}
// Returns the offset from the start of the IL code for the
// method being executed. This offset may be approximate depending
// on whether the jitter is generating debuggable code or not.
//
public virtual int GetILOffset()
{
return ILOffset;
}
// Returns the file name containing the code being executed. This
// information is normally extracted from the debugging symbols
// for the executable.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
public virtual String GetFileName()
{
if (strFileName != null)
{
// This isn't really correct, but we don't have
// a permission that protects discovery of potentially
// local urls so we'll use this.
FileIOPermission perm = new FileIOPermission( PermissionState.None );
perm.AllFiles = FileIOPermissionAccess.PathDiscovery;
perm.Demand();
}
return strFileName;
}
// Returns the line number in the file containing the code being executed.
// This information is normally extracted from the debugging symbols
// for the executable.
//
public virtual int GetFileLineNumber()
{
return iLineNumber;
}
// Returns the column number in the line containing the code being executed.
// This information is normally extracted from the debugging symbols
// for the executable.
//
public virtual int GetFileColumnNumber()
{
return iColumnNumber;
}
// Builds a readable representation of the stack frame
//
[System.Security.SecuritySafeCritical] // auto-generated
public override String ToString()
{
StringBuilder sb = new StringBuilder(255);
if (method != null)
{
sb.Append(method.Name);
// deal with the generic portion of the method
if (method is MethodInfo && ((MethodInfo)method).IsGenericMethod)
{
Type[] typars = ((MethodInfo)method).GetGenericArguments();
sb.Append('<');
int k = 0;
bool fFirstTyParam = true;
while (k < typars.Length)
{
if (fFirstTyParam == false)
sb.Append(',');
else
fFirstTyParam = false;
sb.Append(typars[k].Name);
k++;
}
sb.Append('>');
}
sb.Append(" at offset ");
if (offset == OFFSET_UNKNOWN)
sb.Append("<offset unknown>");
else
sb.Append(offset);
sb.Append(" in file:line:column ");
bool useFileName = (strFileName != null);
if (useFileName)
{
try
{
// This isn't really correct, but we don't have
// a permission that protects discovery of potentially
// local urls so we'll use this.
FileIOPermission perm = new FileIOPermission(PermissionState.None);
perm.AllFiles = FileIOPermissionAccess.PathDiscovery;
perm.Demand();
}
catch (System.Security.SecurityException)
{
useFileName = false;
}
}
if (!useFileName)
sb.Append("<filename unknown>");
else
sb.Append(strFileName);
sb.Append(':');
sb.Append(iLineNumber);
sb.Append(':');
sb.Append(iColumnNumber);
}
else
{
sb.Append("<null>");
}
sb.Append(Environment.NewLine);
return sb.ToString();
}
private void BuildStackFrame(int skipFrames, bool fNeedFileInfo)
{
using (StackFrameHelper StackF = new StackFrameHelper(null))
{
StackF.InitializeSourceInfo(0, fNeedFileInfo, null);
int iNumOfFrames = StackF.GetNumberOfFrames();
skipFrames += StackTrace.CalculateFramesToSkip(StackF, iNumOfFrames);
if ((iNumOfFrames - skipFrames) > 0)
{
method = StackF.GetMethodBase(skipFrames);
offset = StackF.GetOffset(skipFrames);
ILOffset = StackF.GetILOffset(skipFrames);
if (fNeedFileInfo)
{
strFileName = StackF.GetFilename(skipFrames);
iLineNumber = StackF.GetLineNumber(skipFrames);
iColumnNumber = StackF.GetColumnNumber(skipFrames);
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Signum.Engine.Maps;
using Signum.Entities;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.DataStructures;
using Signum.Utilities.ExpressionTrees;
using Signum.Utilities.Reflection;
namespace Signum.Engine.Cache
{
class ToStringExpressionVisitor : ExpressionVisitor
{
Dictionary<ParameterExpression, Expression> replacements = new Dictionary<ParameterExpression, Expression>();
CachedEntityExpression root;
public ToStringExpressionVisitor(ParameterExpression param, CachedEntityExpression root)
{
this.root = root;
this.replacements = new Dictionary<ParameterExpression, Expression> { { param, root } };
}
public static Expression<Func<PrimaryKey, string>> GetToString<T>(CachedTableConstructor constructor, Expression<Func<T, string>> lambda)
{
Table table = (Table)constructor.table;
var param = lambda.Parameters.SingleEx();
if (param.Type != table.Type)
throw new InvalidOperationException("incorrect lambda paramer type");
var pk = Expression.Parameter(typeof(PrimaryKey), "pk");
var root = new CachedEntityExpression(pk, typeof(T), constructor, null, null);
var visitor = new ToStringExpressionVisitor(param, root);
var result = visitor.Visit(lambda.Body);
return Expression.Lambda<Func<PrimaryKey, string>>(result, pk);
}
protected override Expression VisitMember(MemberExpression node)
{
var exp = this.Visit(node.Expression);
if (exp is CachedEntityExpression cee)
{
Field field =
cee.FieldEmbedded != null ? cee.FieldEmbedded.GetField(node.Member) :
cee.FieldMixin != null ? cee.FieldMixin.GetField(node.Member) :
((Table)cee.Constructor.table).GetField(node.Member);
return BindMember(cee, field, cee.PrimaryKey);
}
return node.Update(exp);
}
private Expression BindMember(CachedEntityExpression n, Field field, Expression? prevPrimaryKey)
{
Expression body = GetField(field, n.Constructor, prevPrimaryKey);
ConstantExpression tab = Expression.Constant(n.Constructor.cachedTable, typeof(CachedTable<>).MakeGenericType(((Table)n.Constructor.table).Type));
Expression origin = Expression.Convert(Expression.Property(Expression.Call(tab, "GetRows", null), "Item", n.PrimaryKey.UnNullify()), n.Constructor.tupleType);
var result = ExpressionReplacer.Replace(body, new Dictionary<ParameterExpression, Expression> { { n.Constructor.origin, origin } });
if (!n.PrimaryKey.Type.IsNullable())
return result;
return Expression.Condition(
Expression.Equal(n.PrimaryKey, Expression.Constant(null, n.PrimaryKey.Type)),
Expression.Constant(null, result.Type.Nullify()),
result.Nullify());
}
private Expression GetField(Field field, CachedTableConstructor constructor, Expression? previousPrimaryKey)
{
if (field is FieldValue)
{
var value = constructor.GetTupleProperty((IColumn)field);
return value.Type == field.FieldType ? value : Expression.Convert(value, field.FieldType);
}
if (field is FieldEnum)
return Expression.Convert(constructor.GetTupleProperty((IColumn)field), field.FieldType);
if (field is FieldPrimaryKey)
return constructor.GetTupleProperty((IColumn)field);
if (field is IFieldReference)
{
bool isLite = ((IFieldReference)field).IsLite;
if (field is FieldReference)
{
IColumn column = (IColumn)field;
return GetEntity(isLite, column, field.FieldType.CleanType(), constructor);
}
if (field is FieldImplementedBy ib)
{
var nullRef = Expression.Constant(null, field.FieldType);
var call = ib.ImplementationColumns.Aggregate((Expression)nullRef, (acum, kvp) =>
{
IColumn column = (IColumn)kvp.Value;
var entity = GetEntity(isLite, column, kvp.Key, constructor);
return Expression.Condition(Expression.NotEqual(constructor.GetTupleProperty(column), Expression.Constant(column.Type)),
Expression.Convert(entity, field.FieldType),
acum);
});
return call;
}
if (field is FieldImplementedByAll)
{
throw new NotImplementedException("FieldImplementedByAll not supported in cached ToString");
}
}
if (field is FieldEmbedded fe)
{
return new CachedEntityExpression(previousPrimaryKey!, fe.FieldType, constructor, fe, null);
}
if (field is FieldMixin fm)
{
return new CachedEntityExpression(previousPrimaryKey!, fm.FieldType, constructor, null, fm);
}
if (field is FieldMList)
{
throw new NotImplementedException("FieldMList not supported in cached ToString");
}
throw new InvalidOperationException("Unexpected {0}".FormatWith(field.GetType().Name));
}
private Expression GetEntity(bool isLite, IColumn column, Type entityType, CachedTableConstructor constructor)
{
Expression id = constructor.GetTupleProperty(column);
var pk = CachedTableConstructor.WrapPrimaryKey(id);
CachedTableConstructor typeConstructor = CacheLogic.GetCacheType(entityType) == CacheType.Cached ?
CacheLogic.GetCachedTable(entityType).Constructor :
constructor.cachedTable.SubTables!.SingleEx(a => a.ParentColumn == column).Constructor;
return new CachedEntityExpression(pk, entityType, typeConstructor, null, null);
}
protected override Expression VisitUnary(UnaryExpression node)
{
var operand = Visit(node.Operand);
if (operand != node.Operand && node.NodeType == ExpressionType.Convert)
{
return Expression.Convert(operand, node.Type);
}
return node.Update(operand);
}
static readonly MethodInfo miToString = ReflectionTools.GetMethodInfo((object o) => o.ToString());
protected override Expression VisitMethodCall(MethodCallExpression node)
{
if (node.Method.DeclaringType == typeof(string) && node.Method.Name == nameof(string.Format) ||
node.Method.DeclaringType == typeof(StringExtensions) && node.Method.Name == nameof(StringExtensions.FormatWith))
{
if (node.Arguments[0].Type == typeof(IFormatProvider))
throw new NotSupportedException("string.Format with IFormatProvider");
var formatStr = Visit(node.Arguments[0]);
if (node.Arguments.Count == 2 && node.Arguments[1] is NewArrayExpression nae)
{
var expressions = nae.Expressions.Select(a => Visit(ToString(a))).ToList();
return node.Update(null!, new[] { formatStr, Expression.NewArrayInit(nae.Type.ElementType()!, expressions) });
}
else
{
var remainging = node.Arguments.Skip(1).Select(a => Visit(ToString(a))).ToList();
return node.Update(null!, new Sequence<Expression> { formatStr, remainging });
}
}
var obj = base.Visit(node.Object);
var args = base.Visit(node.Arguments);
if (node.Method.Name == "ToString" && node.Arguments.IsEmpty() && obj is CachedEntityExpression ce && ce.Type.IsEntity())
{
var table = (Table)ce.Constructor.table;
if (table.ToStrColumn != null)
{
return BindMember(ce, (FieldValue)table.ToStrColumn, null);
}
else if(this.root != ce)
{
var cachedTableType = typeof(CachedTable<>).MakeGenericType(table.Type);
ConstantExpression tab = Expression.Constant(ce.Constructor.cachedTable, cachedTableType);
var mi = cachedTableType.GetMethod(nameof(CachedTable<Entity>.GetToString))!;
return Expression.Call(tab, mi, ce.PrimaryKey.UnNullify());
}
}
LambdaExpression? lambda = ExpressionCleaner.GetFieldExpansion(obj?.Type, node.Method);
if (lambda != null)
{
var replace = ExpressionReplacer.Replace(Expression.Invoke(lambda, obj == null ? args : args.PreAnd(obj)));
return this.Visit(replace);
}
if (node.Method.Name == nameof(Entity.Mixin) && obj is CachedEntityExpression cee)
{
var mixin = ((Table)cee.Constructor.table).GetField(node.Method);
return GetField(mixin, cee.Constructor, cee.PrimaryKey);
}
return node.Update(obj!, args);
}
protected override Expression VisitParameter(ParameterExpression node)
{
return this.replacements.TryGetC(node) ?? node;
}
protected override Expression VisitBinary(BinaryExpression node)
{
var result = (BinaryExpression)base.VisitBinary(node);
if (result.NodeType == ExpressionType.Equal || result.NodeType == ExpressionType.NotEqual)
{
if (result.Left is CachedEntityExpression ceLeft && ceLeft.FieldEmbedded?.HasValue == null ||
result.Right is CachedEntityExpression ceRight && ceRight.FieldEmbedded?.HasValue == null)
{
var left = GetPrimaryKey(result.Left);
var right = GetPrimaryKey(result.Right);
if (left.Type.IsNullable() || right.Type.IsNullable())
return Expression.MakeBinary(node.NodeType, left.Nullify(), right.Nullify());
else
return Expression.MakeBinary(node.NodeType, left, right);
}
if (result.Left is CachedEntityExpression ceLeft2 && ceLeft2.FieldEmbedded?.HasValue != null ||
result.Right is CachedEntityExpression ceRight2 && ceRight2.FieldEmbedded?.HasValue != null)
{
var left = GetHasValue(result.Left);
var right = GetHasValue(result.Right);
return Expression.MakeBinary(node.NodeType, left, right);
}
}
if(result.NodeType == ExpressionType.Add && (result.Left.Type == typeof(string) || result.Right.Type == typeof(string)))
{
var lefto = this.Visit(ToString(result.Left));
var righto = this.Visit(ToString(result.Right));
return Expression.Add(lefto, righto, result.Method);
}
return result;
}
private Expression ToString(Expression node)
{
if (node.Type == typeof(string))
return node;
return Expression.Condition(
Expression.Equal(node.Nullify(), Expression.Constant(null, node.Type.Nullify())),
Expression.Constant(null, typeof(string)),
Expression.Call(node, miToString));
}
private Expression GetPrimaryKey(Expression exp)
{
if (exp is ConstantExpression && ((ConstantExpression)exp).Value == null)
return Expression.Constant(null, typeof(PrimaryKey?));
if (exp is CachedEntityExpression cee && cee.FieldEmbedded?.HasValue == null)
return cee.PrimaryKey;
throw new InvalidOperationException("");
}
private Expression GetHasValue(Expression exp)
{
if (exp is ConstantExpression && ((ConstantExpression)exp).Value == null)
return Expression.Constant(false, typeof(bool));
if (exp is CachedEntityExpression n && n.FieldEmbedded?.HasValue != null)
{
var body = n.Constructor.GetTupleProperty(n.FieldEmbedded.HasValue);
ConstantExpression tab = Expression.Constant(n.Constructor.cachedTable, typeof(CachedTable<>).MakeGenericType(((Table)n.Constructor.table).Type));
Expression origin = Expression.Convert(Expression.Property(Expression.Call(tab, "GetRows", null), "Item", n.PrimaryKey.UnNullify()), n.Constructor.tupleType);
var result = ExpressionReplacer.Replace(body, new Dictionary<ParameterExpression, Expression> { { n.Constructor.origin, origin } });
return result;
}
throw new InvalidOperationException("");
}
}
internal class CachedEntityExpression : Expression
{
public override ExpressionType NodeType
{
get { return ExpressionType.Extension; }
}
public readonly CachedTableConstructor Constructor;
public readonly Expression PrimaryKey;
public readonly FieldEmbedded? FieldEmbedded;
public readonly FieldMixin? FieldMixin;
public readonly Type type;
public override Type Type { get { return type; } }
public CachedEntityExpression(Expression primaryKey, Type type, CachedTableConstructor constructor, FieldEmbedded? embedded, FieldMixin? mixin)
{
if (primaryKey == null)
throw new ArgumentNullException(nameof(primaryKey));
if (primaryKey.Type.UnNullify() != typeof(PrimaryKey))
throw new InvalidOperationException("primaryKey should be a PrimaryKey");
if (type.IsEmbeddedEntity())
{
this.FieldEmbedded = embedded ?? throw new ArgumentNullException(nameof(embedded));
}
else if (type.IsMixinEntity())
{
this.FieldMixin = mixin ?? throw new ArgumentNullException(nameof(mixin));
}
else
{
if (((Table)constructor.table).Type != type.CleanType())
throw new InvalidOperationException("Wrong type");
}
this.PrimaryKey = primaryKey;
this.type = type;
this.Constructor = constructor;
}
protected override Expression VisitChildren(ExpressionVisitor visitor)
{
if (this.PrimaryKey == null)
return this;
var pk = visitor.Visit(this.PrimaryKey);
if (pk == this.PrimaryKey)
return this;
return new CachedEntityExpression(pk, type, Constructor, FieldEmbedded, FieldMixin);
}
public override string ToString()
{
return $"CachedEntityExpression({Type.TypeName()}, {PrimaryKey})";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Wooga.Lambda.Control.Concurrent;
using Wooga.Lambda.Data;
using FileContent = System.Collections.Generic.IEnumerable<byte>;
namespace Wooga.Lambda.Storage
{
public class VirtualFileSystem : FileSystem
{
private readonly VirtualDir Root;
private VirtualFileSystem()
{
Root = new VirtualDir();
}
public static FileSystem Create()
{
return new VirtualFileSystem();
}
public Async<FileContent> ReadFileAsync(string p)
{
return () => Root.GetNameInDirectory(p).GetFile();
}
public Async<Unit> WriteFileAsync(string p, FileContent c)
{
return () =>
{
var d = Root.GetNameInExistingDirectory(p);
d.Item1.SetFile(d.Item2, c.ToList());
return Unit.Default;
};
}
public Async<Unit> AppendFileAsync(string p, FileContent c)
{
return () =>
{
var d = Root.GetNameInDirectory(p);
if (d.FileExists())
{
var contents = d.GetFile();
contents.AddRange(c);
}
else
{
WriteFileAsync(p, c).RunSynchronously();
}
return Unit.Default;
};
}
public Async<Dir> GetDirAsync(string p)
{
return () => Root.GetDirectory(p.Split(Path.DirectorySeparatorChar)).ToDir();
}
public Async<bool> HasFileAsync(string p)
{
return () => Root.GetNameInDirectory(p).FileExists();
}
public Async<bool> HasDirAsync(string p)
{
return () => Root.GetDirectory(p) != null;
}
public Async<Unit> NewDirAsync(string p)
{
return () => Root.CreateDirectory(p);
}
public Async<Unit> RmDirAsync(string p)
{
return () => Root.GetDirectory(p).Remove();
}
public Async<Unit> RmFileAsync(string p)
{
return () => Root.GetNameInDirectory(p).DeleteFile();
}
public Async<Unit> MvDirAsync(string ps, string pt)
{
return () => Root.GetDirectory(ps).MoveTo(Root.GetNameInDirectory(pt));
}
public Async<Unit> MvFileAsync(string ps, string pt)
{
return () => Root.GetNameInDirectory(ps).MoveTo(Root.GetNameInDirectory(pt));
}
public Async<Unit> CpDirAsync(string ps, string pt)
{
return () => Root.GetDirectory(ps).CopyTo(Root.GetNameInDirectory(pt));
}
public Async<Unit> CpFileAsync(string ps, string pt)
{
return () => Root.GetNameInDirectory(ps).CopyTo(Root.GetNameInDirectory(pt));
}
}
internal class VirtualDir
{
internal Dictionary<string, List<byte>> Files = new Dictionary<string, List<byte>>();
internal Dictionary<string, VirtualDir> Directories = new Dictionary<string, VirtualDir>();
internal VirtualDir Parent;
public string Name;
public bool DirectoryExists(string element)
{
return Directories.ContainsKey(element);
}
public Unit CreateDirectory(string path)
{
CreateDirectory(path.Split(Path.DirectorySeparatorChar));
return Unit.Default;
}
public VirtualDir CreateDirectory(IEnumerable<string> path)
{
if (!path.Any())
{
return this;
}
if (Files.ContainsKey(path.First()))
{
throw new Exception("file exists when creating directory");
}
if (!Directories.ContainsKey(path.First()))
{
Directories[path.First()] = new VirtualDir() { Parent = this, Name = path.First() };
}
return Directories[path.First()].CreateDirectory(path.Skip(1));
}
public bool FileExists(string name)
{
return Files.ContainsKey(name);
}
public VirtualDir GetDirectory(string name)
{
return GetDirectory(name.Split(Path.DirectorySeparatorChar));
}
public List<byte> GetFile(string name)
{
if (!FileExists(name))
{
throw new IOException(name + " does not exist");
}
return Files[name];
}
public void SetFile(string name, List<byte> content)
{
Files[name] = content;
}
public VirtualDir GetDirectory(IEnumerable<string> path)
{
if (!path.Any())
{
return this;
}
if (Directories.ContainsKey(path.First()))
{
return Directories[path.First()].GetDirectory(path.Skip(1));
}
return null;
}
internal string GetPath()
{
if (Parent != null)
{
if (Parent.Parent == null)
{
return Name + Path.DirectorySeparatorChar;
}
return Path.Combine(Parent.GetPath(), Name);
}
return "";
}
internal void RemoveDir(VirtualDir virtualDir)
{
Directories.Remove(virtualDir.Name);
}
public void DeleteFile(string name)
{
Files.Remove(name);
}
public VirtualDir Clone()
{
var dir = new VirtualDir();
foreach (var sd in Directories)
{
dir.Directories[sd.Key] = sd.Value.Clone();
}
foreach (var sf in Files)
{
dir.Files[sf.Key] = sf.Value.ConvertAll(_ => _);
}
return dir;
}
}
internal static class VirtualDirExtension
{
public static bool FileExists(this Tuple<VirtualDir, string> d)
{
return d != null && d.Item1.FileExists(d.Item2);
}
public static bool DirectoryExists(this Tuple<VirtualDir, string> d)
{
return d != null && d.Item1.DirectoryExists(d.Item2);
}
public static List<byte> GetFile(this Tuple<VirtualDir, string> d)
{
if (d == null || !d.FileExists())
{
throw new IOException("file does not exist");
}
return d.Item1.Files[d.Item2];
}
public static Unit DeleteFile(this Tuple<VirtualDir, string> d)
{
if (d != null)
{
d.Item1.DeleteFile(d.Item2);
}
return Unit.Default;
}
public static Unit MoveTo(this Tuple<VirtualDir, string> src, Tuple<VirtualDir, string> dest)
{
if (src == null)
{
throw new DirectoryNotFoundException("source directory does not exist");
}
if (!src.FileExists())
{
throw new IOException("source file does not exist");
}
if (dest == null)
{
throw new DirectoryNotFoundException("target directory does not exist");
}
if (dest.DirectoryExists() || dest.FileExists())
{
throw new IOException("destination already exists");
}
dest.Item1.Files[dest.Item2] = src.Item1.GetFile(src.Item2);
src.Item1.Files.Remove(src.Item2);
return Unit.Default;
}
public static Unit CopyTo(this Tuple<VirtualDir, string> src, Tuple<VirtualDir, string> dest)
{
if (src == null)
{
throw new IOException("source directory does not exist");
}
if (!src.FileExists())
{
throw new IOException("source file does not exist");
}
if (dest == null)
{
throw new DirectoryNotFoundException("target directory does not exist");
}
if (dest.DirectoryExists() || dest.FileExists())
{
throw new IOException("destination already exists");
}
dest.Item1.Files[dest.Item2] = src.Item1.GetFile(src.Item2);
return Unit.Default;
}
public static Unit MoveTo(this VirtualDir dir, Tuple<VirtualDir, string> d)
{
if (dir == null)
{
throw new DirectoryNotFoundException("source directory does not exist");
}
if (d == null)
{
throw new DirectoryNotFoundException("target directory does not exist");
}
if (d.Item1.DirectoryExists(d.Item2) || d.Item1.FileExists(d.Item2))
{
throw new IOException("name in target exists");
}
dir.Parent.Directories.Remove(dir.Name);
dir.Name = d.Item2;
dir.Parent = d.Item1;
d.Item1.Directories[dir.Name] = dir;
return Unit.Default;
}
public static Unit CopyTo(this VirtualDir dir, Tuple<VirtualDir, string> d)
{
if (dir == null)
{
throw new IOException("source directory does not exist");
}
if (d == null)
{
throw new DirectoryNotFoundException();
}
if (d.Item1.DirectoryExists(d.Item2) || d.Item1.FileExists(d.Item2))
{
throw new IOException("name in target exists");
}
var newDir = dir.Clone();
newDir.Name = d.Item2;
newDir.Parent = d.Item1;
d.Item1.Directories[newDir.Name] = newDir;
return Unit.Default;
}
public static Dir ToDir(this VirtualDir dir)
{
if (dir == null)
{
throw new IOException("does not exist");
}
var path = dir.GetPath();
var fs = dir.Files.Select(x => Path.Combine(path, x.Key));
var ds = dir.Directories.Select(x => Path.Combine(path, x.Key));
return Dir.Create(path, ds, fs);
}
public static Unit Remove(this VirtualDir dir)
{
if (dir == null)
{
throw new DirectoryNotFoundException();
}
if (dir.Parent != null)
{
dir.Parent.RemoveDir(dir);
dir.Parent = null;
}
return Unit.Default;
}
public static Tuple<VirtualDir, string> GetNameInDirectory(this VirtualDir dir, string path)
{
return dir.GetNameInDirectory(path.Split(Path.DirectorySeparatorChar));
}
public static Tuple<VirtualDir, string> GetNameInDirectory(this VirtualDir dir, IEnumerable<string> path)
{
if (dir == null)
{
return null;
}
if (!path.Any())
{
throw new Exception("GetNameInDirectory called with an empty string");
}
if (path.Count() == 1)
{
return new Tuple<VirtualDir, string>(dir, path.Last());
}
VirtualDir directory;
dir.Directories.TryGetValue(path.First(), out directory);
return directory.GetNameInDirectory(path.Skip(1));
}
public static Tuple<VirtualDir, string> GetNameInExistingDirectory(this VirtualDir dir, string path)
{
return dir.GetNameInExistingDirectory(path.Split(Path.DirectorySeparatorChar));
}
public static Tuple<VirtualDir, string> GetNameInExistingDirectory(this VirtualDir dir, IEnumerable<string> path)
{
if (dir == null)
{
throw new DirectoryNotFoundException("directory does not exist");
}
if (!path.Any())
{
throw new Exception("GetNameInDirectory called with an empty string");
}
if (path.Count() == 1)
{
return new Tuple<VirtualDir, string>(dir, path.Last());
}
VirtualDir directory;
dir.Directories.TryGetValue(path.First(), out directory);
return directory.GetNameInExistingDirectory(path.Skip(1));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.AspNetCore.Routing;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
public class AnchorTagHelperTest
{
[Fact]
public async Task ProcessAsync_GeneratesExpectedOutput()
{
// Arrange
var expectedTagName = "not-a";
var metadataProvider = new TestModelMetadataProvider();
var tagHelperContext = new TagHelperContext(
tagName: "not-a",
allAttributes: new TagHelperAttributeList
{
{ "id", "myanchor" },
{ "asp-route-name", "value" },
{ "asp-action", "index" },
{ "asp-controller", "home" },
{ "asp-fragment", "hello=world" },
{ "asp-host", "contoso.com" },
{ "asp-protocol", "http" }
},
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
expectedTagName,
attributes: new TagHelperAttributeList
{
{ "id", "myanchor" },
},
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something Else");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.Content.SetContent("Something");
var urlHelper = new Mock<IUrlHelper>();
urlHelper
.Setup(mock => mock.Action(It.IsAny<UrlActionContext>())).Returns("home/index");
var htmlGenerator = new TestableHtmlGenerator(metadataProvider, urlHelper.Object);
var viewContext = TestableHtmlGenerator.GetViewContext(
model: null,
htmlGenerator: htmlGenerator,
metadataProvider: metadataProvider);
var anchorTagHelper = new AnchorTagHelper(htmlGenerator)
{
Action = "index",
Controller = "home",
Fragment = "hello=world",
Host = "contoso.com",
Protocol = "http",
RouteValues =
{
{ "name", "value" },
},
ViewContext = viewContext,
};
// Act
await anchorTagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.Equal(2, output.Attributes.Count);
var attribute = Assert.Single(output.Attributes, attr => attr.Name.Equals("id"));
Assert.Equal("myanchor", attribute.Value);
attribute = Assert.Single(output.Attributes, attr => attr.Name.Equals("href"));
Assert.Equal("home/index", attribute.Value);
Assert.Equal("Something", output.Content.GetContent());
Assert.Equal(expectedTagName, output.TagName);
}
[Fact]
public async Task ProcessAsync_CallsIntoRouteLinkWithExpectedParameters()
{
// Arrange
var context = new TagHelperContext(
tagName: "a",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"a",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.Content.SetContent(string.Empty);
var generator = new Mock<IHtmlGenerator>(MockBehavior.Strict);
generator
.Setup(mock => mock.GenerateRouteLink(
It.IsAny<ViewContext>(),
string.Empty,
"Default",
"http",
"contoso.com",
"hello=world",
It.IsAny<IDictionary<string, object>>(),
null))
.Returns(new TagBuilder("a"))
.Verifiable();
var anchorTagHelper = new AnchorTagHelper(generator.Object)
{
Fragment = "hello=world",
Host = "contoso.com",
Protocol = "http",
Route = "Default",
};
// Act & Assert
await anchorTagHelper.ProcessAsync(context, output);
generator.Verify();
Assert.Equal("a", output.TagName);
Assert.Empty(output.Attributes);
Assert.Empty(output.Content.GetContent());
}
[Fact]
public async Task ProcessAsync_CallsIntoActionLinkWithExpectedParameters()
{
// Arrange
var context = new TagHelperContext(
tagName: "a",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"a",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.Content.SetContent(string.Empty);
var generator = new Mock<IHtmlGenerator>();
generator
.Setup(mock => mock.GenerateActionLink(
It.IsAny<ViewContext>(),
string.Empty,
"Index",
"Home",
"http",
"contoso.com",
"hello=world",
It.IsAny<IDictionary<string, object>>(),
null))
.Returns(new TagBuilder("a"))
.Verifiable();
var anchorTagHelper = new AnchorTagHelper(generator.Object)
{
Action = "Index",
Controller = "Home",
Fragment = "hello=world",
Host = "contoso.com",
Protocol = "http",
};
// Act & Assert
await anchorTagHelper.ProcessAsync(context, output);
generator.Verify();
Assert.Equal("a", output.TagName);
Assert.Empty(output.Attributes);
Assert.Empty(output.Content.GetContent());
}
[Fact]
public async Task ProcessAsync_AddsAreaToRouteValuesAndCallsIntoActionLinkWithExpectedParameters()
{
// Arrange
var context = new TagHelperContext(
tagName: "a",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"a",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.Content.SetContent(string.Empty);
var generator = new Mock<IHtmlGenerator>();
var expectedRouteValues = new Dictionary<string, object> { { "area", "Admin" } };
generator
.Setup(mock => mock.GenerateActionLink(
It.IsAny<ViewContext>(),
string.Empty,
"Index",
"Home",
"http",
"contoso.com",
"hello=world",
expectedRouteValues,
null))
.Returns(new TagBuilder("a"))
.Verifiable();
var anchorTagHelper = new AnchorTagHelper(generator.Object)
{
Action = "Index",
Controller = "Home",
Area = "Admin",
Fragment = "hello=world",
Host = "contoso.com",
Protocol = "http",
};
// Act
await anchorTagHelper.ProcessAsync(context, output);
// Assert
generator.Verify();
Assert.Equal("a", output.TagName);
Assert.Empty(output.Attributes);
Assert.Empty(output.Content.GetContent());
}
[Fact]
public async Task ProcessAsync_AspAreaOverridesAspRouteArea()
{
// Arrange
var context = new TagHelperContext(
tagName: "a",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"a",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.Content.SetContent(string.Empty);
var generator = new Mock<IHtmlGenerator>();
var expectedRouteValues = new Dictionary<string, object> { { "area", "Admin" } };
generator
.Setup(mock => mock.GenerateActionLink(
It.IsAny<ViewContext>(),
string.Empty,
"Index",
"Home",
"http",
"contoso.com",
"hello=world",
expectedRouteValues,
null))
.Returns(new TagBuilder("a"))
.Verifiable();
var anchorTagHelper = new AnchorTagHelper(generator.Object)
{
Action = "Index",
Controller = "Home",
Area = "Admin",
Fragment = "hello=world",
Host = "contoso.com",
Protocol = "http",
RouteValues = new Dictionary<string, string> { { "area", "Home" } }
};
// Act
await anchorTagHelper.ProcessAsync(context, output);
// Assert
generator.Verify();
Assert.Equal("a", output.TagName);
Assert.Empty(output.Attributes);
Assert.Empty(output.Content.GetContent());
}
[Fact]
public async Task ProcessAsync_EmptyStringOnAspAreaIsPassedThroughToRouteValues()
{
// Arrange
var context = new TagHelperContext(
tagName: "a",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"a",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.Content.SetContent(string.Empty);
var generator = new Mock<IHtmlGenerator>();
var expectedRouteValues = new Dictionary<string, object> { { "area", string.Empty } };
generator
.Setup(mock => mock.GenerateActionLink(
It.IsAny<ViewContext>(),
string.Empty,
"Index",
"Home",
"http",
"contoso.com",
"hello=world",
expectedRouteValues,
null))
.Returns(new TagBuilder("a"))
.Verifiable();
var anchorTagHelper = new AnchorTagHelper(generator.Object)
{
Action = "Index",
Controller = "Home",
Area = string.Empty,
Fragment = "hello=world",
Host = "contoso.com",
Protocol = "http"
};
// Act
await anchorTagHelper.ProcessAsync(context, output);
// Assert
generator.Verify();
Assert.Equal("a", output.TagName);
Assert.Empty(output.Attributes);
Assert.Empty(output.Content.GetContent());
}
[Fact]
public async Task ProcessAsync_AddsPageToRouteValuesAndCallsPageLinkWithExpectedParameters()
{
// Arrange
var context = new TagHelperContext(
tagName: "a",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"a",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.Content.SetContent(string.Empty);
var generator = new Mock<IHtmlGenerator>();
generator
.Setup(mock => mock.GeneratePageLink(
It.IsAny<ViewContext>(),
string.Empty,
"/User/Home/Index",
"page-handler",
"http",
"contoso.com",
"hello=world",
It.IsAny<object>(),
null))
.Returns(new TagBuilder("a"))
.Verifiable();
var anchorTagHelper = new AnchorTagHelper(generator.Object)
{
Page = "/User/Home/Index",
PageHandler = "page-handler",
Fragment = "hello=world",
Host = "contoso.com",
Protocol = "http",
};
// Act
await anchorTagHelper.ProcessAsync(context, output);
// Assert
generator.Verify();
}
[Fact]
public async Task ProcessAsync_AddsAreaToRouteValuesAndCallsPageLinkWithExpectedParameters()
{
// Arrange
var context = new TagHelperContext(
tagName: "a",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
"a",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.Content.SetContent(string.Empty);
var generator = new Mock<IHtmlGenerator>();
generator
.Setup(mock => mock.GeneratePageLink(
It.IsAny<ViewContext>(),
string.Empty,
"/User/Home/Index",
"page-handler",
"http",
"contoso.com",
"hello=world",
It.IsAny<object>(),
null))
.Callback((ViewContext v, string linkText, string pageName, string pageHandler, string protocol, string hostname, string fragment, object routeValues, object htmlAttributes) =>
{
var rvd = Assert.IsType<RouteValueDictionary>(routeValues);
Assert.Collection(rvd.OrderBy(item => item.Key),
item =>
{
Assert.Equal("area", item.Key);
Assert.Equal("test-area", item.Value);
});
})
.Returns(new TagBuilder("a"))
.Verifiable();
var anchorTagHelper = new AnchorTagHelper(generator.Object)
{
Page = "/User/Home/Index",
Area = "test-area",
PageHandler = "page-handler",
Fragment = "hello=world",
Host = "contoso.com",
Protocol = "http",
};
// Act
await anchorTagHelper.ProcessAsync(context, output);
// Assert
generator.Verify();
}
[Theory]
[InlineData("Action")]
[InlineData("Controller")]
[InlineData("Route")]
[InlineData("Protocol")]
[InlineData("Host")]
[InlineData("Fragment")]
[InlineData("asp-route-")]
[InlineData("Page")]
[InlineData("PageHandler")]
public async Task ProcessAsync_ThrowsIfHrefConflictsWithBoundAttributes(string propertyName)
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var anchorTagHelper = new AnchorTagHelper(htmlGenerator);
var output = new TagHelperOutput(
"a",
attributes: new TagHelperAttributeList
{
{ "href", "http://www.contoso.com" }
},
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null));
if (propertyName == "asp-route-")
{
anchorTagHelper.RouteValues.Add("name", "value");
}
else
{
typeof(AnchorTagHelper).GetProperty(propertyName).SetValue(anchorTagHelper, "Home");
}
var expectedErrorMessage = "Cannot override the 'href' attribute for <a>. An <a> with a specified " +
"'href' must not have attributes starting with 'asp-route-' or an " +
"'asp-action', 'asp-controller', 'asp-area', 'asp-route', 'asp-protocol', 'asp-host', " +
"'asp-fragment', 'asp-page' or 'asp-page-handler' attribute.";
var context = new TagHelperContext(
tagName: "test",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(
() => anchorTagHelper.ProcessAsync(context, output));
Assert.Equal(expectedErrorMessage, ex.Message);
}
[Theory]
[InlineData("Action")]
[InlineData("Controller")]
public async Task ProcessAsync_ThrowsIfRouteAndActionOrControllerProvided(string propertyName)
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var anchorTagHelper = new AnchorTagHelper(htmlGenerator)
{
Route = "Default",
};
typeof(AnchorTagHelper).GetProperty(propertyName).SetValue(anchorTagHelper, "Home");
var output = new TagHelperOutput(
"a",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null));
var expectedErrorMessage = string.Join(
Environment.NewLine,
"Cannot determine the 'href' attribute for <a>. The following attributes are mutually exclusive:",
"asp-route",
"asp-controller, asp-action",
"asp-page, asp-page-handler");
var context = new TagHelperContext(
tagName: "test",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(
() => anchorTagHelper.ProcessAsync(context, output));
Assert.Equal(expectedErrorMessage, ex.Message);
}
[Fact]
public async Task ProcessAsync_ThrowsIfRouteAndPageProvided()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var anchorTagHelper = new AnchorTagHelper(htmlGenerator)
{
Route = "Default",
Page = "Page",
};
var output = new TagHelperOutput(
"a",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null));
var expectedErrorMessage = string.Join(
Environment.NewLine,
"Cannot determine the 'href' attribute for <a>. The following attributes are mutually exclusive:",
"asp-route",
"asp-controller, asp-action",
"asp-page, asp-page-handler");
var context = new TagHelperContext(
tagName: "test",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(
() => anchorTagHelper.ProcessAsync(context, output));
Assert.Equal(expectedErrorMessage, ex.Message);
}
[Fact]
public async Task ProcessAsync_ThrowsIfActionAndPageProvided()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var anchorTagHelper = new AnchorTagHelper(htmlGenerator)
{
Action = "Action",
Page = "Page",
};
var output = new TagHelperOutput(
"a",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null));
var expectedErrorMessage = string.Join(
Environment.NewLine,
"Cannot determine the 'href' attribute for <a>. The following attributes are mutually exclusive:",
"asp-route",
"asp-controller, asp-action",
"asp-page, asp-page-handler");
var context = new TagHelperContext(
tagName: "test",
allAttributes: new TagHelperAttributeList(
Enumerable.Empty<TagHelperAttribute>()),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act & Assert
var ex = await Assert.ThrowsAsync<InvalidOperationException>(
() => anchorTagHelper.ProcessAsync(context, output));
Assert.Equal(expectedErrorMessage, ex.Message);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*=============================================================================
**
**
**
** Purpose: Component that implements the ITypeLibConverter interface and
** does the actual work of converting a typelib to metadata and
** vice versa.
**
**
=============================================================================*/
#if !FEATURE_CORECLR // current implementation requires reflection only load
namespace System.Runtime.InteropServices {
using System;
using System.Diagnostics.Contracts;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.InteropServices.TCEAdapterGen;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Configuration.Assemblies;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Versioning;
using WORD = System.UInt16;
using DWORD = System.UInt32;
using _TYPELIBATTR = System.Runtime.InteropServices.ComTypes.TYPELIBATTR;
[Guid("F1C3BF79-C3E4-11d3-88E7-00902754C43A")]
[ClassInterface(ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class TypeLibConverter : ITypeLibConverter
{
private const String s_strTypeLibAssemblyTitlePrefix = "TypeLib ";
private const String s_strTypeLibAssemblyDescPrefix = "Assembly generated from typelib ";
private const int MAX_NAMESPACE_LENGTH = 1024;
//
// ITypeLibConverter interface.
//
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib,
String asmFileName,
int flags,
ITypeLibImporterNotifySink notifySink,
byte[] publicKey,
StrongNameKeyPair keyPair,
bool unsafeInterfaces)
{
return ConvertTypeLibToAssembly(typeLib,
asmFileName,
(unsafeInterfaces
? TypeLibImporterFlags.UnsafeInterfaces
: 0),
notifySink,
publicKey,
keyPair,
null,
null);
}
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] Object typeLib,
String asmFileName,
TypeLibImporterFlags flags,
ITypeLibImporterNotifySink notifySink,
byte[] publicKey,
StrongNameKeyPair keyPair,
String asmNamespace,
Version asmVersion)
{
// Validate the arguments.
if (typeLib == null)
throw new ArgumentNullException("typeLib");
if (asmFileName == null)
throw new ArgumentNullException("asmFileName");
if (notifySink == null)
throw new ArgumentNullException("notifySink");
if (String.Empty.Equals(asmFileName))
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), "asmFileName");
if (asmFileName.Length > Path.MAX_PATH)
throw new ArgumentException(Environment.GetResourceString("IO.PathTooLong"), asmFileName);
if ((flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0 && publicKey == null && keyPair == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed"));
Contract.EndContractBlock();
ArrayList eventItfInfoList = null;
// Determine the AssemblyNameFlags
AssemblyNameFlags asmNameFlags = AssemblyNameFlags.None;
// Retrieve the assembly name from the typelib.
AssemblyName asmName = GetAssemblyNameFromTypelib(typeLib, asmFileName, publicKey, keyPair, asmVersion, asmNameFlags);
// Create the dynamic assembly that will contain the converted typelib types.
AssemblyBuilder asmBldr = CreateAssemblyForTypeLib(typeLib, asmFileName, asmName,
(flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0,
(flags & TypeLibImporterFlags.ReflectionOnlyLoading) != 0,
(flags & TypeLibImporterFlags.NoDefineVersionResource) != 0);
// Define a dynamic module that will contain the contain the imported types.
String strNonQualifiedAsmFileName = Path.GetFileName(asmFileName);
ModuleBuilder modBldr = asmBldr.DefineDynamicModule(strNonQualifiedAsmFileName, strNonQualifiedAsmFileName);
// If the namespace hasn't been specified, then use the assembly name.
if (asmNamespace == null)
asmNamespace = asmName.Name;
// Create a type resolve handler that will also intercept resolve ref messages
// on the sink interface to build up a list of referenced assemblies.
TypeResolveHandler typeResolveHandler = new TypeResolveHandler(modBldr, notifySink);
// Add a listener for the type resolve events.
AppDomain currentDomain = Thread.GetDomain();
ResolveEventHandler resolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveEvent);
ResolveEventHandler asmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveAsmEvent);
ResolveEventHandler ROAsmResolveHandler = new ResolveEventHandler(typeResolveHandler.ResolveROAsmEvent);
currentDomain.TypeResolve += resolveHandler;
currentDomain.AssemblyResolve += asmResolveHandler;
currentDomain.ReflectionOnlyAssemblyResolve += ROAsmResolveHandler;
// Convert the types contained in the typelib into metadata and add them to the assembly.
nConvertTypeLibToMetadata(typeLib, asmBldr.InternalAssembly, modBldr.InternalModule, asmNamespace, flags, typeResolveHandler, out eventItfInfoList);
// Update the COM types in the assembly.
UpdateComTypesInAssembly(asmBldr, modBldr);
// If there are any event sources then generate the TCE adapters.
if (eventItfInfoList.Count > 0)
new TCEAdapterGenerator().Process(modBldr, eventItfInfoList);
// Remove the listener for the type resolve events.
currentDomain.TypeResolve -= resolveHandler;
currentDomain.AssemblyResolve -= asmResolveHandler;
currentDomain.ReflectionOnlyAssemblyResolve -= ROAsmResolveHandler;
// We have finished converting the typelib and now have a fully formed assembly.
return asmBldr;
}
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)]
[return : MarshalAs(UnmanagedType.Interface)]
public Object ConvertAssemblyToTypeLib(Assembly assembly, String strTypeLibName, TypeLibExporterFlags flags, ITypeLibExporterNotifySink notifySink)
{
RuntimeAssembly rtAssembly;
AssemblyBuilder ab = assembly as AssemblyBuilder;
if (ab != null)
rtAssembly = ab.InternalAssembly;
else
rtAssembly = assembly as RuntimeAssembly;
return nConvertAssemblyToTypeLib(rtAssembly, strTypeLibName, flags, notifySink);
}
public bool GetPrimaryInteropAssembly(Guid g, Int32 major, Int32 minor, Int32 lcid, out String asmName, out String asmCodeBase)
{
String strTlbId = "{" + g.ToString().ToUpper(CultureInfo.InvariantCulture) + "}";
String strVersion = major.ToString("x", CultureInfo.InvariantCulture) + "." + minor.ToString("x", CultureInfo.InvariantCulture);
// Set the two out values to null before we start.
asmName = null;
asmCodeBase = null;
// Try to open the HKEY_CLASS_ROOT\TypeLib key.
using (RegistryKey TypeLibKey = Registry.ClassesRoot.OpenSubKey("TypeLib", false))
{
if (TypeLibKey != null)
{
// Try to open the HKEY_CLASS_ROOT\TypeLib\<TLBID> key.
using (RegistryKey TypeLibSubKey = TypeLibKey.OpenSubKey(strTlbId))
{
if (TypeLibSubKey != null)
{
// Try to open the HKEY_CLASS_ROOT\TypeLib\<TLBID>\<Major.Minor> key.
using (RegistryKey VersionKey = TypeLibSubKey.OpenSubKey(strVersion, false))
{
if (VersionKey != null)
{
// Attempt to retrieve the assembly name and codebase under the version key.
asmName = (String)VersionKey.GetValue("PrimaryInteropAssemblyName");
asmCodeBase = (String)VersionKey.GetValue("PrimaryInteropAssemblyCodeBase");
}
}
}
}
}
}
// If the assembly name isn't null, then we found an PIA.
return asmName != null;
}
//
// Non native helper methods.
//
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
private static AssemblyBuilder CreateAssemblyForTypeLib(Object typeLib, String asmFileName, AssemblyName asmName, bool bPrimaryInteropAssembly, bool bReflectionOnly, bool bNoDefineVersionResource)
{
// Retrieve the current app domain.
AppDomain currentDomain = Thread.GetDomain();
// Retrieve the directory from the assembly file name.
String dir = null;
if (asmFileName != null)
{
dir = Path.GetDirectoryName(asmFileName);
if (String.IsNullOrEmpty(dir))
dir = null;
}
AssemblyBuilderAccess aba;
if (bReflectionOnly)
{
aba = AssemblyBuilderAccess.ReflectionOnly;
}
else
{
aba = AssemblyBuilderAccess.RunAndSave;
}
// Create the dynamic assembly itself.
AssemblyBuilder asmBldr;
List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>();
#if !FEATURE_CORECLR
// mscorlib.dll must specify the security rules that assemblies it emits are to use, since by
// default all assemblies will follow security rule set level 2, and we want to make that an
// explicit decision.
ConstructorInfo securityRulesCtor = typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) });
CustomAttributeBuilder securityRulesAttribute =
new CustomAttributeBuilder(securityRulesCtor, new object[] { SecurityRuleSet.Level2 });
assemblyAttributes.Add(securityRulesAttribute);
#endif // !FEATURE_CORECLR
asmBldr = currentDomain.DefineDynamicAssembly(asmName, aba, dir, false, assemblyAttributes);
// Set the Guid custom attribute on the assembly.
SetGuidAttributeOnAssembly(asmBldr, typeLib);
// Set the imported from COM attribute on the assembly and return it.
SetImportedFromTypeLibAttrOnAssembly(asmBldr, typeLib);
// Set the version information on the typelib.
if (bNoDefineVersionResource)
{
SetTypeLibVersionAttribute(asmBldr, typeLib);
}
else
{
SetVersionInformation(asmBldr, typeLib, asmName);
}
// If we are generating a PIA, then set the PIA custom attribute.
if (bPrimaryInteropAssembly)
SetPIAAttributeOnAssembly(asmBldr, typeLib);
return asmBldr;
}
[System.Security.SecurityCritical] // auto-generated
internal static AssemblyName GetAssemblyNameFromTypelib(Object typeLib, String asmFileName, byte[] publicKey, StrongNameKeyPair keyPair, Version asmVersion, AssemblyNameFlags asmNameFlags)
{
// Extract the name of the typelib.
String strTypeLibName = null;
String strDocString = null;
int dwHelpContext = 0;
String strHelpFile = null;
ITypeLib pTLB = (ITypeLib)typeLib;
pTLB.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
// Retrieve the name to use for the assembly.
if (asmFileName == null)
{
asmFileName = strTypeLibName;
}
else
{
Contract.Assert((asmFileName != null) && (asmFileName.Length > 0), "The assembly file name cannot be an empty string!");
String strFileNameNoPath = Path.GetFileName(asmFileName);
String strExtension = Path.GetExtension(asmFileName);
// Validate that the extension is valid.
bool bExtensionValid = ".dll".Equals(strExtension, StringComparison.OrdinalIgnoreCase);
// If the extension is not valid then tell the user and quit.
if (!bExtensionValid)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileExtension"));
// The assembly cannot contain the path nor the extension.
asmFileName = strFileNameNoPath.Substring(0, strFileNameNoPath.Length - ".dll".Length);
}
// If the version information was not specified, then retrieve it from the typelib.
if (asmVersion == null)
{
int major;
int minor;
Marshal.GetTypeLibVersion(pTLB, out major, out minor);
asmVersion = new Version(major, minor, 0, 0);
}
// Create the assembly name for the imported typelib's assembly.
AssemblyName AsmName = new AssemblyName();
AsmName.Init(
asmFileName,
publicKey,
null,
asmVersion,
null,
AssemblyHashAlgorithm.None,
AssemblyVersionCompatibility.SameMachine,
null,
asmNameFlags,
keyPair);
return AsmName;
}
private static void UpdateComTypesInAssembly(AssemblyBuilder asmBldr, ModuleBuilder modBldr)
{
// Retrieve the AssemblyBuilderData associated with the assembly builder.
AssemblyBuilderData AsmBldrData = asmBldr.m_assemblyData;
// Go through the types in the module and add them as public COM types.
Type[] aTypes = modBldr.GetTypes();
int NumTypes = aTypes.Length;
for (int cTypes = 0; cTypes < NumTypes; cTypes++)
AsmBldrData.AddPublicComType(aTypes[cTypes]);
}
[System.Security.SecurityCritical] // auto-generated
private static void SetGuidAttributeOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
{
// Retrieve the GuidAttribute constructor.
Type []aConsParams = new Type[1] {typeof(String)};
ConstructorInfo GuidAttrCons = typeof(GuidAttribute).GetConstructor(aConsParams);
// Create an instance of the custom attribute builder.
Object[] aArgs = new Object[1] {Marshal.GetTypeLibGuid((ITypeLib)typeLib).ToString()};
CustomAttributeBuilder GuidCABuilder = new CustomAttributeBuilder(GuidAttrCons, aArgs);
// Set the GuidAttribute on the assembly builder.
asmBldr.SetCustomAttribute(GuidCABuilder);
}
[System.Security.SecurityCritical] // auto-generated
private static void SetImportedFromTypeLibAttrOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
{
// Retrieve the ImportedFromTypeLibAttribute constructor.
Type []aConsParams = new Type[1] {typeof(String)};
ConstructorInfo ImpFromComAttrCons = typeof(ImportedFromTypeLibAttribute).GetConstructor(aConsParams);
// Retrieve the name of the typelib.
String strTypeLibName = Marshal.GetTypeLibName((ITypeLib)typeLib);
// Create an instance of the custom attribute builder.
Object[] aArgs = new Object[1] {strTypeLibName};
CustomAttributeBuilder ImpFromComCABuilder = new CustomAttributeBuilder(ImpFromComAttrCons, aArgs);
// Set the ImportedFromTypeLibAttribute on the assembly builder.
asmBldr.SetCustomAttribute(ImpFromComCABuilder);
}
[System.Security.SecurityCritical] // auto-generated
private static void SetTypeLibVersionAttribute(AssemblyBuilder asmBldr, Object typeLib)
{
Type []aConsParams = new Type[2] {typeof(int), typeof(int)};
ConstructorInfo TypeLibVerCons = typeof(TypeLibVersionAttribute).GetConstructor(aConsParams);
// Get the typelib version
int major;
int minor;
Marshal.GetTypeLibVersion((ITypeLib)typeLib, out major, out minor);
// Create an instance of the custom attribute builder.
Object[] aArgs = new Object[2] {major, minor};
CustomAttributeBuilder TypeLibVerBuilder = new CustomAttributeBuilder(TypeLibVerCons, aArgs);
// Set the attribute on the assembly builder.
asmBldr.SetCustomAttribute(TypeLibVerBuilder);
}
[System.Security.SecurityCritical] // auto-generated
private static void SetVersionInformation(AssemblyBuilder asmBldr, Object typeLib, AssemblyName asmName)
{
// Extract the name of the typelib.
String strTypeLibName = null;
String strDocString = null;
int dwHelpContext = 0;
String strHelpFile = null;
ITypeLib pTLB = (ITypeLib)typeLib;
pTLB.GetDocumentation(-1, out strTypeLibName, out strDocString, out dwHelpContext, out strHelpFile);
// Generate the product name string from the named of the typelib.
String strProductName = String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("TypeLibConverter_ImportedTypeLibProductName"), strTypeLibName);
// Set the OS version information.
asmBldr.DefineVersionInfoResource(strProductName, asmName.Version.ToString(), null, null, null);
// Set the TypeLibVersion attribute
SetTypeLibVersionAttribute(asmBldr, typeLib);
}
[System.Security.SecurityCritical] // auto-generated
private static void SetPIAAttributeOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
{
IntPtr pAttr = IntPtr.Zero;
_TYPELIBATTR Attr;
ITypeLib pTLB = (ITypeLib)typeLib;
int Major = 0;
int Minor = 0;
// Retrieve the PrimaryInteropAssemblyAttribute constructor.
Type []aConsParams = new Type[2] {typeof(int), typeof(int)};
ConstructorInfo PIAAttrCons = typeof(PrimaryInteropAssemblyAttribute).GetConstructor(aConsParams);
// Retrieve the major and minor version from the typelib.
try
{
pTLB.GetLibAttr(out pAttr);
Attr = (_TYPELIBATTR)Marshal.PtrToStructure(pAttr, typeof(_TYPELIBATTR));
Major = Attr.wMajorVerNum;
Minor = Attr.wMinorVerNum;
}
finally
{
// Release the typelib attributes.
if (pAttr != IntPtr.Zero)
pTLB.ReleaseTLibAttr(pAttr);
}
// Create an instance of the custom attribute builder.
Object[] aArgs = new Object[2] {Major, Minor};
CustomAttributeBuilder PIACABuilder = new CustomAttributeBuilder(PIAAttrCons, aArgs);
// Set the PrimaryInteropAssemblyAttribute on the assembly builder.
asmBldr.SetCustomAttribute(PIACABuilder);
}
//
// Native helper methods.
//
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void nConvertTypeLibToMetadata(Object typeLib, RuntimeAssembly asmBldr, RuntimeModule modBldr, String nameSpace, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, out ArrayList eventItfInfoList);
// Must use assembly versioning or GuidAttribute to avoid collisions in typelib export or registration.
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object nConvertAssemblyToTypeLib(RuntimeAssembly assembly, String strTypeLibName, TypeLibExporterFlags flags, ITypeLibExporterNotifySink notifySink);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal extern static void LoadInMemoryTypeByName(RuntimeModule module, String className);
//
// Helper class called when a resolve type event is fired.
//
private class TypeResolveHandler : ITypeLibImporterNotifySink
{
public TypeResolveHandler(ModuleBuilder mod, ITypeLibImporterNotifySink userSink)
{
m_Module = mod;
m_UserSink = userSink;
}
public void ReportEvent(ImporterEventKind eventKind, int eventCode, String eventMsg)
{
m_UserSink.ReportEvent(eventKind, eventCode, eventMsg);
}
public Assembly ResolveRef(Object typeLib)
{
Contract.Ensures(Contract.Result<Assembly>() != null && Contract.Result<Assembly>() is RuntimeAssembly);
Contract.EndContractBlock();
// Call the user sink to resolve the reference.
Assembly asm = m_UserSink.ResolveRef(typeLib);
if (asm == null)
throw new ArgumentNullException();
// Return the resolved assembly. We extract the internal assembly because we are called
// by the VM which accesses fields of the object directly and does not go via those
// delegating properties (the fields are empty if asm is an (external) AssemblyBuilder).
RuntimeAssembly rtAssembly = asm as RuntimeAssembly;
if (rtAssembly == null)
{
AssemblyBuilder ab = asm as AssemblyBuilder;
if (ab != null)
rtAssembly = ab.InternalAssembly;
}
if (rtAssembly == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"));
// Add the assembly to the list of assemblies.
m_AsmList.Add(rtAssembly);
return rtAssembly;
}
[System.Security.SecurityCritical] // auto-generated
public Assembly ResolveEvent(Object sender, ResolveEventArgs args)
{
// We need to load the type in the resolve event so that we will deal with
// cases where we are trying to load the CoClass before the interface has
// been loaded.
try
{
LoadInMemoryTypeByName(m_Module.GetNativeHandle(), args.Name);
return m_Module.Assembly;
}
catch (TypeLoadException e)
{
if (e.ResourceId != System.__HResults.COR_E_TYPELOAD) // type not found
throw;
}
foreach (RuntimeAssembly asm in m_AsmList)
{
try
{
asm.GetType(args.Name, true, false);
return asm;
}
catch (TypeLoadException e)
{
if (e._HResult != System.__HResults.COR_E_TYPELOAD) // type not found
throw;
}
}
return null;
}
public Assembly ResolveAsmEvent(Object sender, ResolveEventArgs args)
{
foreach (RuntimeAssembly asm in m_AsmList)
{
if (String.Compare(asm.FullName, args.Name, StringComparison.OrdinalIgnoreCase) == 0)
return asm;
}
return null;
}
public Assembly ResolveROAsmEvent(Object sender, ResolveEventArgs args)
{
foreach (RuntimeAssembly asm in m_AsmList)
{
if (String.Compare(asm.FullName, args.Name, StringComparison.OrdinalIgnoreCase) == 0)
return asm;
}
// We failed to find the referenced assembly in our pre-loaded assemblies, so try to load it based on policy.
string asmName = AppDomain.CurrentDomain.ApplyPolicy(args.Name);
return Assembly.ReflectionOnlyLoad(asmName);
}
private ModuleBuilder m_Module;
private ITypeLibImporterNotifySink m_UserSink;
private List<RuntimeAssembly> m_AsmList = new List<RuntimeAssembly>();
}
}
}
#endif // !FEATURE_CORECLR // current implementation requires reflection only load
| |
using System.Net;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Updating.Resources;
public sealed class AtomicUpdateToOneRelationshipTests : IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext;
private readonly OperationsFakers _fakers = new();
public AtomicUpdateToOneRelationshipTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<OperationsController>();
}
[Fact]
public async Task Can_clear_OneToOne_relationship_from_principal_side()
{
// Arrange
Lyric existingLyric = _fakers.Lyric.Generate();
existingLyric.Track = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<MusicTrack>();
dbContext.Lyrics.Add(existingLyric);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "lyrics",
id = existingLyric.StringId,
relationships = new
{
track = new
{
data = (object?)null
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Lyric lyricInDatabase = await dbContext.Lyrics.Include(lyric => lyric.Track).FirstWithIdAsync(existingLyric.Id);
lyricInDatabase.Track.Should().BeNull();
List<MusicTrack> tracksInDatabase = await dbContext.MusicTracks.ToListAsync();
tracksInDatabase.ShouldHaveCount(1);
});
}
[Fact]
public async Task Can_clear_OneToOne_relationship_from_dependent_side()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.Lyric = _fakers.Lyric.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Lyric>();
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = (object?)null
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Lyric).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.Lyric.Should().BeNull();
List<Lyric> lyricsInDatabase = await dbContext.Lyrics.ToListAsync();
lyricsInDatabase.ShouldHaveCount(1);
});
}
[Fact]
public async Task Can_clear_ManyToOne_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.OwnedBy = _fakers.RecordCompany.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<RecordCompany>();
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
ownedBy = new
{
data = (object?)null
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.OwnedBy).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.OwnedBy.Should().BeNull();
List<RecordCompany> companiesInDatabase = await dbContext.RecordCompanies.ToListAsync();
companiesInDatabase.ShouldHaveCount(1);
});
}
[Fact]
public async Task Can_create_OneToOne_relationship_from_principal_side()
{
// Arrange
Lyric existingLyric = _fakers.Lyric.Generate();
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.AddInRange(existingLyric, existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "lyrics",
id = existingLyric.StringId,
relationships = new
{
track = new
{
data = new
{
type = "musicTracks",
id = existingTrack.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Lyric lyricInDatabase = await dbContext.Lyrics.Include(lyric => lyric.Track).FirstWithIdAsync(existingLyric.Id);
lyricInDatabase.Track.ShouldNotBeNull();
lyricInDatabase.Track.Id.Should().Be(existingTrack.Id);
});
}
[Fact]
public async Task Can_create_OneToOne_relationship_from_dependent_side()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
Lyric existingLyric = _fakers.Lyric.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.AddInRange(existingTrack, existingLyric);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = new
{
type = "lyrics",
id = existingLyric.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Lyric).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.Lyric.ShouldNotBeNull();
trackInDatabase.Lyric.Id.Should().Be(existingLyric.Id);
});
}
[Fact]
public async Task Can_create_ManyToOne_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
RecordCompany existingCompany = _fakers.RecordCompany.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.AddInRange(existingTrack, existingCompany);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
ownedBy = new
{
data = new
{
type = "recordCompanies",
id = existingCompany.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.OwnedBy).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.OwnedBy.ShouldNotBeNull();
trackInDatabase.OwnedBy.Id.Should().Be(existingCompany.Id);
});
}
[Fact]
public async Task Can_replace_OneToOne_relationship_from_principal_side()
{
// Arrange
Lyric existingLyric = _fakers.Lyric.Generate();
existingLyric.Track = _fakers.MusicTrack.Generate();
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<MusicTrack>();
dbContext.AddInRange(existingLyric, existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "lyrics",
id = existingLyric.StringId,
relationships = new
{
track = new
{
data = new
{
type = "musicTracks",
id = existingTrack.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Lyric lyricInDatabase = await dbContext.Lyrics.Include(lyric => lyric.Track).FirstWithIdAsync(existingLyric.Id);
lyricInDatabase.Track.ShouldNotBeNull();
lyricInDatabase.Track.Id.Should().Be(existingTrack.Id);
List<MusicTrack> tracksInDatabase = await dbContext.MusicTracks.ToListAsync();
tracksInDatabase.ShouldHaveCount(2);
});
}
[Fact]
public async Task Can_replace_OneToOne_relationship_from_dependent_side()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.Lyric = _fakers.Lyric.Generate();
Lyric existingLyric = _fakers.Lyric.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Lyric>();
dbContext.AddInRange(existingTrack, existingLyric);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = new
{
type = "lyrics",
id = existingLyric.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.Lyric).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.Lyric.ShouldNotBeNull();
trackInDatabase.Lyric.Id.Should().Be(existingLyric.Id);
List<Lyric> lyricsInDatabase = await dbContext.Lyrics.ToListAsync();
lyricsInDatabase.ShouldHaveCount(2);
});
}
[Fact]
public async Task Can_replace_ManyToOne_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
existingTrack.OwnedBy = _fakers.RecordCompany.Generate();
RecordCompany existingCompany = _fakers.RecordCompany.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<RecordCompany>();
dbContext.AddInRange(existingTrack, existingCompany);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
ownedBy = new
{
data = new
{
type = "recordCompanies",
id = existingCompany.StringId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);
responseDocument.Should().BeEmpty();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
MusicTrack trackInDatabase = await dbContext.MusicTracks.Include(musicTrack => musicTrack.OwnedBy).FirstWithIdAsync(existingTrack.Id);
trackInDatabase.OwnedBy.ShouldNotBeNull();
trackInDatabase.OwnedBy.Id.Should().Be(existingCompany.Id);
List<RecordCompany> companiesInDatabase = await dbContext.RecordCompanies.ToListAsync();
companiesInDatabase.ShouldHaveCount(2);
});
}
[Fact]
public async Task Cannot_create_for_null_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = (object?)null
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected an object, instead of 'null'.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/lyric");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_missing_data_in_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'data' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/lyric");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_array_data_in_relationship()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = new[]
{
new
{
type = "lyrics",
id = Unknown.StringId.For<Lyric, long>()
}
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Expected an object or 'null', instead of an array.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/lyric/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_missing_type_in_relationship_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "lyrics",
id = Unknown.StringId.For<Lyric, long>(),
relationships = new
{
track = new
{
data = new
{
id = Unknown.StringId.For<MusicTrack, Guid>()
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'type' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/track/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_unknown_type_in_relationship_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationships = new
{
lyric = new
{
data = new
{
type = Unknown.ResourceType,
id = Unknown.StringId.For<Lyric, long>()
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: Unknown resource type found.");
error.Detail.Should().Be($"Resource type '{Unknown.ResourceType}' does not exist.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/lyric/data/type");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_missing_ID_in_relationship_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationships = new
{
lyric = new
{
data = new
{
type = "lyrics"
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'id' or 'lid' element is required.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/lyric/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_ID_and_local_ID_in_relationship_data()
{
// Arrange
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = Unknown.StringId.For<MusicTrack, Guid>(),
relationships = new
{
lyric = new
{
data = new
{
type = "lyrics",
id = Unknown.StringId.For<Lyric, long>(),
lid = "local-1"
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity);
error.Title.Should().Be("Failed to deserialize request body: The 'id' and 'lid' element are mutually exclusive.");
error.Detail.Should().BeNull();
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/lyric/data");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
[Fact]
public async Task Cannot_create_for_unknown_ID_in_relationship_data()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
string lyricId = Unknown.StringId.For<Lyric, long>();
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = new
{
type = "lyrics",
id = lyricId
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.NotFound);
error.Title.Should().Be("A related resource does not exist.");
error.Detail.Should().Be($"Related resource of type 'lyrics' with ID '{lyricId}' in relationship 'lyric' does not exist.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]");
error.Meta.Should().NotContainKey("requestBody");
}
[Fact]
public async Task Cannot_create_for_relationship_mismatch()
{
// Arrange
MusicTrack existingTrack = _fakers.MusicTrack.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.MusicTracks.Add(existingTrack);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
atomic__operations = new[]
{
new
{
op = "update",
data = new
{
type = "musicTracks",
id = existingTrack.StringId,
relationships = new
{
lyric = new
{
data = new
{
type = "playlists",
id = Unknown.StringId.For<Playlist, long>()
}
}
}
}
}
}
};
const string route = "/operations";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Conflict);
error.Title.Should().Be("Failed to deserialize request body: Incompatible resource type found.");
error.Detail.Should().Be("Type 'playlists' is incompatible with type 'lyrics' of relationship 'lyric'.");
error.Source.ShouldNotBeNull();
error.Source.Pointer.Should().Be("/atomic:operations[0]/data/relationships/lyric/data/type");
error.Meta.ShouldContainKey("requestBody").With(value => value.ShouldNotBeNull().ToString().ShouldNotBeEmpty());
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ScoreUI : MonoBehaviour {
private int scoreRed;
private int scoreBlue;
public GUIStyle style;
public int winningScore;
private bool fim = false;
private bool gameOverCalled = false;
public GameManager gameManager;
Dictionary<int, Transform> segments, segments2;
void OnGUI()
{
GUIStyle mystyle = new GUIStyle();
Font myFont = (Font)Resources.Load("Fonts/LCD", typeof(Font));
mystyle.font = myFont;
mystyle.fontSize = 60;
mystyle.fontStyle= FontStyle.Bold;
mystyle.onNormal.textColor = Color.yellow;
mystyle.onActive.textColor = Color.blue;
mystyle.onFocused.textColor = Color.red;
if (!fim) {
GameObject go = GameObject.Find ("Ball(Clone)");
if(go != null)
{
Ball other = (Ball)go.GetComponent (typeof(Ball));
scoreRed = other.GetScoreRed ();
scoreBlue = other.GetScoreBlue ();
}
else
{
scoreRed = scoreBlue = 0;
}
}
float x = Screen.width/2f;
float y = 30f;
float width = 400f;
float height = 50f;
SetNumber(scoreRed, scoreBlue);
if (scoreRed >= winningScore || scoreBlue >= winningScore)
{
GameObject ball = GameObject.Find("Ball(Clone)");
if (ball != null)
{
ball.SetActive(false);
fim=true;
}
string winMessage = "Player Left won";
if (scoreBlue >= winningScore)
{
winMessage = "Player Right won";
}
//GUI.Box(new Rect(85,100,450,100),"");
GUI.Button(new Rect(95,100,200,40),winMessage, mystyle);
}
if(fim && !gameOverCalled)
{
gameManager.gameOver();
gameOverCalled = true;
}
}
public void restartGame(){
scoreBlue = scoreRed = 0;
fim = gameOverCalled = false;
}
void Awake()
{
segments = new Dictionary<int, Transform>();
segments[1] = GameObject.Find ("seg1").GetComponent<Transform> ();
segments[2] = GameObject.Find ("seg2").GetComponent<Transform> ();
segments[3] = GameObject.Find ("seg3").GetComponent<Transform> ();
segments[4] = GameObject.Find ("seg4").GetComponent<Transform> ();
segments[5] = GameObject.Find ("seg5").GetComponent<Transform> ();
segments[6] = GameObject.Find ("seg6").GetComponent<Transform> ();
segments[7] = GameObject.Find ("seg7").GetComponent<Transform> ();
segments2 = new Dictionary<int, Transform>();
segments2[1] = GameObject.Find ("_seg1").GetComponent<Transform> ();
segments2[2] = GameObject.Find ("_seg2").GetComponent<Transform> ();
segments2[3] = GameObject.Find ("_seg3").GetComponent<Transform> ();
segments2[4] = GameObject.Find ("_seg4").GetComponent<Transform> ();
segments2[5] = GameObject.Find ("_seg5").GetComponent<Transform> ();
segments2[6] = GameObject.Find ("_seg6").GetComponent<Transform> ();
segments2[7] = GameObject.Find ("_seg7").GetComponent<Transform> ();
}
public void SetNumber(int n, int m)
{
switch (n){
case 0:
segments[1].gameObject.SetActive(true);
segments[2].gameObject.SetActive(true);
segments[3].gameObject.SetActive(true);
segments[4].gameObject.SetActive(true);
segments[5].gameObject.SetActive(true);
segments[6].gameObject.SetActive(true);
segments[7].gameObject.SetActive(false);
break;
case 1:
segments[1].gameObject.SetActive(false);
segments[2].gameObject.SetActive(false);
segments[3].gameObject.SetActive(true);
segments[4].gameObject.SetActive(true);
segments[5].gameObject.SetActive(false);
segments[6].gameObject.SetActive(false);
segments[7].gameObject.SetActive(false);
break;
case 2:
segments[1].gameObject.SetActive(true);
segments[2].gameObject.SetActive(true);
segments[3].gameObject.SetActive(false);
segments[4].gameObject.SetActive(true);
segments[5].gameObject.SetActive(true);
segments[6].gameObject.SetActive(false);
segments[7].gameObject.SetActive(true);
break;
case 3:
segments[1].gameObject.SetActive(true);
segments[2].gameObject.SetActive(true);
segments[3].gameObject.SetActive(false);
segments[4].gameObject.SetActive(false);
segments[5].gameObject.SetActive(true);
segments[6].gameObject.SetActive(true);
segments[7].gameObject.SetActive(true);
break;
case 4:
segments[1].gameObject.SetActive(true);
segments[2].gameObject.SetActive(false);
segments[3].gameObject.SetActive(true);
segments[4].gameObject.SetActive(false);
segments[5].gameObject.SetActive(false);
segments[6].gameObject.SetActive(true);
segments[7].gameObject.SetActive(true);
break;
case 5:
segments[1].gameObject.SetActive(false);
segments[2].gameObject.SetActive(true);
segments[3].gameObject.SetActive(true);
segments[4].gameObject.SetActive(false);
segments[5].gameObject.SetActive(true);
segments[6].gameObject.SetActive(true);
segments[7].gameObject.SetActive(true);
break;
case 6:
segments[1].gameObject.SetActive(false);
segments[2].gameObject.SetActive(true);
segments[3].gameObject.SetActive(true);
segments[4].gameObject.SetActive(true);
segments[5].gameObject.SetActive(true);
segments[6].gameObject.SetActive(true);
segments[7].gameObject.SetActive(true);
break;
case 7:
segments[1].gameObject.SetActive(true);
segments[2].gameObject.SetActive(true);
segments[3].gameObject.SetActive(false);
segments[4].gameObject.SetActive(false);
segments[5].gameObject.SetActive(false);
segments[6].gameObject.SetActive(true);
segments[7].gameObject.SetActive(false);
break;
case 8:
segments[1].gameObject.SetActive(true);
segments[2].gameObject.SetActive(true);
segments[3].gameObject.SetActive(true);
segments[4].gameObject.SetActive(true);
segments[5].gameObject.SetActive(true);
segments[6].gameObject.SetActive(true);
segments[7].gameObject.SetActive(true);
break;
case 9:
segments[1].gameObject.SetActive(true);
segments[2].gameObject.SetActive(true);
segments[3].gameObject.SetActive(true);
segments[4].gameObject.SetActive(false);
segments[5].gameObject.SetActive(true);
segments[6].gameObject.SetActive(true);
segments[7].gameObject.SetActive(true);
break;
}
switch (m){
case 0:
segments2[1].gameObject.SetActive(true);
segments2[2].gameObject.SetActive(true);
segments2[3].gameObject.SetActive(true);
segments2[4].gameObject.SetActive(true);
segments2[5].gameObject.SetActive(true);
segments2[6].gameObject.SetActive(true);
segments2[7].gameObject.SetActive(false);
break;
case 1:
segments2[1].gameObject.SetActive(false);
segments2[2].gameObject.SetActive(false);
segments2[3].gameObject.SetActive(true);
segments2[4].gameObject.SetActive(true);
segments2[5].gameObject.SetActive(false);
segments2[6].gameObject.SetActive(false);
segments2[7].gameObject.SetActive(false);
break;
case 2:
segments2[1].gameObject.SetActive(true);
segments2[2].gameObject.SetActive(true);
segments2[3].gameObject.SetActive(false);
segments2[4].gameObject.SetActive(true);
segments2[5].gameObject.SetActive(true);
segments2[6].gameObject.SetActive(false);
segments2[7].gameObject.SetActive(true);
break;
case 3:
segments2[1].gameObject.SetActive(true);
segments2[2].gameObject.SetActive(true);
segments2[3].gameObject.SetActive(false);
segments2[4].gameObject.SetActive(false);
segments2[5].gameObject.SetActive(true);
segments2[6].gameObject.SetActive(true);
segments2[7].gameObject.SetActive(true);
break;
case 4:
segments2[1].gameObject.SetActive(true);
segments2[2].gameObject.SetActive(false);
segments2[3].gameObject.SetActive(true);
segments2[4].gameObject.SetActive(false);
segments2[5].gameObject.SetActive(false);
segments2[6].gameObject.SetActive(true);
segments2[7].gameObject.SetActive(true);
break;
case 5:
segments2[1].gameObject.SetActive(false);
segments2[2].gameObject.SetActive(true);
segments2[3].gameObject.SetActive(true);
segments2[4].gameObject.SetActive(false);
segments2[5].gameObject.SetActive(true);
segments2[6].gameObject.SetActive(true);
segments2[7].gameObject.SetActive(true);
break;
case 6:
segments2[1].gameObject.SetActive(false);
segments2[2].gameObject.SetActive(true);
segments2[3].gameObject.SetActive(true);
segments2[4].gameObject.SetActive(true);
segments2[5].gameObject.SetActive(true);
segments2[6].gameObject.SetActive(true);
segments2[7].gameObject.SetActive(true);
break;
case 7:
segments2[1].gameObject.SetActive(true);
segments2[2].gameObject.SetActive(true);
segments2[3].gameObject.SetActive(false);
segments2[4].gameObject.SetActive(false);
segments2[5].gameObject.SetActive(false);
segments2[6].gameObject.SetActive(true);
segments2[7].gameObject.SetActive(false);
break;
case 8:
segments2[1].gameObject.SetActive(true);
segments2[2].gameObject.SetActive(true);
segments2[3].gameObject.SetActive(true);
segments2[4].gameObject.SetActive(true);
segments2[5].gameObject.SetActive(true);
segments2[6].gameObject.SetActive(true);
segments2[7].gameObject.SetActive(true);
break;
case 9:
segments2[1].gameObject.SetActive(true);
segments2[2].gameObject.SetActive(true);
segments2[3].gameObject.SetActive(true);
segments2[4].gameObject.SetActive(false);
segments2[5].gameObject.SetActive(true);
segments2[6].gameObject.SetActive(true);
segments2[7].gameObject.SetActive(true);
break;
}
}
}
| |
/* **************************************************************
* Name: BotSuite.NET
* Purpose: Framework for creating bots
* Homepage: http://www.wieschoo.com
* Copyright: (c) 2013 wieschoo & enWare
* License: http://www.wieschoo.com/botsuite/license/
* *************************************************************/
using System;
using System.Drawing;
using System.Windows.Forms;
namespace BotSuite
{
/// <summary>
/// Class for simulating mouse actions
/// </summary>
public class Mouse
{
/// <summary>
/// performs a left click at current cursor position
/// </summary>
/// <remarks>
/// you have to move the cursor at the correct position before fire a left click
/// </remarks>
/// <example>
/// <code>
/// <![CDATA[
/// Mouse.LeftClick();
/// ]]>
/// </code>
/// </example>
/// <returns></returns>
public static void LeftClick()
{
LeftDown();
Utility.Delay(10, 30);
LeftUp();
}
/// <summary>
/// simulates a left click at a specific coordinate
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ApplicationTunnel Trainer = new ApplicationTunnel("notepade.exe");
/// Point p = new Point(400,600);
/// Mouse.LeftClick(Trainer.GetHandle(),p);
/// ]]>
/// </code>
/// </example>
/// <param name="handle">The handle of the window to click</param>
/// <param name="point">The point to click</param>
public static void LeftClick(IntPtr handle, Point point)
{
LeftDown(handle, point);
Utility.Delay(10, 30);
LeftUp(handle, point);
}
/// <summary>
/// performs a left button down at the current cursor position
/// </summary>
/// <remarks>
/// make sure to release the mouse button using "LeftUp()". Otherwise there can happen unintended consequences
/// </remarks>
/// <example>
/// <code>
/// Mouse.LeftDown();
/// </code>
/// </example>
/// <returns></returns>
public static void LeftDown()
{
NativeMethods.mouse_event((Int32) (NativeMethods.MouseEventFlags.LEFTDOWN), 0, 0, 0, new IntPtr(0));
}
private static IntPtr GetLParam(Point point)
{
return (IntPtr) ((point.Y << 16) | point.X);
}
/// <summary>
/// Simulates a left button down at the current cursor position
/// </summary>
/// <remarks>
/// make sure to release the mouse button using "LeftUp()". Otherwise there can happen unintended consequences
/// </remarks>
/// <example>
/// <code>
/// <![CDATA[
/// ApplicationTunnel Trainer = new ApplicationTunnel("notepade.exe");
/// Point p = new Point(400,600);
/// Mouse.LeftDown(Trainer.GetHandle(),p);
/// ]]>
/// </code>
/// </example>
/// <param name="handle">The handle of the window to click</param>
/// <param name="point">The point to click</param>
public static void LeftDown(IntPtr handle, Point point)
{
IntPtr wParam = IntPtr.Zero;
NativeMethods.SendMessage(handle, (uint) MouseEvents.WM_LBUTTONDOWN, wParam, GetLParam(point));
}
/// <summary>
/// Performs a left button up
/// </summary>
/// <example>
/// <code>
/// Mouse.LeftUp();
/// </code>
/// </example>
/// <returns></returns>
public static void LeftUp()
{
NativeMethods.mouse_event((Int32) (NativeMethods.MouseEventFlags.LEFTUP), 0, 0, 0, new IntPtr(0));
}
/// <summary>
/// Simulates a left button at a predefined cursor position
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ApplicationTunnel Trainer = new ApplicationTunnel("notepade.exe");
/// Point p = new Point(400,600);
/// Mouse.LeftUp(Trainer.GetHandle(),p);
/// ]]>
/// </code>
/// </example>
/// <param name="handle">The handle of the window to click</param>
/// <param name="point">The point to click</param>
public static void LeftUp(IntPtr handle, Point point)
{
IntPtr wParam = IntPtr.Zero;
NativeMethods.SendMessage(handle, (uint) MouseEvents.WM_LBUTTONUP, wParam, GetLParam(point));
}
/// <summary>
/// Performs a right click
/// </summary>
/// <example>
/// <code>
/// Mouse.RightClick();
/// </code>
/// </example>
/// <returns></returns>
public static void RightClick()
{
RightDown();
Utility.Delay(10, 30);
RightUp();
}
/// <summary>
/// simulates a right click at a specific point
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ApplicationTunnel Trainer = new ApplicationTunnel("notepade.exe");
/// Point p = new Point(400,600);
/// Mouse.RightClick(Trainer.GetHandle(),p);
/// ]]>
/// </code>
/// </example>
/// <param name="handle">The handle of the window to click</param>
/// <param name="point">The point to click</param>
public static void RightClick(IntPtr handle, Point point)
{
RightUp(handle, point);
Utility.Delay(10, 30);
RightDown(handle, point);
}
/// <summary>
/// performs a right button down
/// </summary>
/// <example>
/// <code>
/// Mouse.RightDown();
/// </code>
/// </example>
/// <returns></returns>
public static void RightDown()
{
NativeMethods.mouse_event((Int32) (NativeMethods.MouseEventFlags.RIGHTDOWN), 0, 0, 0, new IntPtr(0));
}
/// <summary>
/// simulates a right button down
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ApplicationTunnel Trainer = new ApplicationTunnel("notepade.exe");
/// Point p = new Point(400,600);
/// Mouse.RightDown(Trainer.GetHandle(),p);
/// ]]>
/// </code>
/// </example>
/// <param name="handle">The handle of the window to click</param>
/// <param name="point">The point to click</param>
public static void RightDown(IntPtr handle, Point point)
{
IntPtr wParam = IntPtr.Zero;
NativeMethods.SendMessage(handle, (uint) MouseEvents.WM_RBUTTONDOWN, wParam, GetLParam(point));
}
/// <summary>
/// Performs a right button up
/// </summary>
/// <example>
/// <code>
/// Mouse.RightUp();
/// </code>
/// </example>
/// <returns></returns>
public static void RightUp()
{
NativeMethods.mouse_event((Int32) (NativeMethods.MouseEventFlags.RIGHTUP), 0, 0, 0, new IntPtr(0));
}
/// <summary>
/// Simulates a right button up through the native methods
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ApplicationTunnel Trainer = new ApplicationTunnel("notepade.exe");
/// Point p = new Point(400,600);
/// Mouse.RightUp(Trainer.GetHandle(),p);
/// ]]>
/// </code>
/// </example>
/// <param name="handle">The handle of the window to click</param>
/// <param name="point">The point to click</param>
public static void RightUp(IntPtr handle, Point point)
{
IntPtr wParam = IntPtr.Zero;
NativeMethods.SendMessage(handle, (uint) MouseEvents.WM_RBUTTONUP, wParam, GetLParam(point));
}
/// <summary>
/// performs a double-click (left button) at the current cursor position
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// Mouse.DoubleClick();
/// ]]>
/// </code>
/// </example>
public static void DoubleClick()
{
LeftClick();
Utility.Delay(150);
LeftClick();
}
/// <summary>
/// Simulates a double-click (left button) at a given coordinate on screen relative to the window
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// ApplicationTunnel Trainer = new ApplicationTunnel("notepade.exe");
/// Point p = new Point(400,600);
/// Mouse.DoubleClick(Trainer.GetHandle(),p);
/// ]]>
/// </code>
/// </example>
/// <param name="handle">The handle of the window to click</param>
/// <param name="point">The point to click</param>
public static void DoubleClick(IntPtr handle, Point point)
{
LeftClick(handle, point);
Utility.Delay(150);
LeftClick(handle, point);
}
/// <summary>
/// moves the mouse to a specific point "target" through "steps" number of points
/// </summary>
/// <remarks>
/// The more points you`ll use the more smoother the curve will be
/// If the option "human" is false the cursor will jump to the target point and ignores "steps"
/// </remarks>
/// <example>
/// <code>
/// Point target = new Point(10,10);
/// Mouse.Move(target,true,10);
/// </code>
/// </example>
/// <param name="targetPosition">The target position</param>
/// <param name="human">Simulate human-like jumps</param>
/// <param name="steps">The points of pathpolygons</param>
/// <returns></returns>
public static Boolean Move(Point targetPosition, Boolean human = true, Int32 steps = 100)
{
if (!human)
{
Cursor.Position = targetPosition;
return true;
}
Point start = GetPosition();
PointF iterPoint = start;
var slope = new PointF(targetPosition.X - start.X, targetPosition.Y - start.Y);
slope.X = slope.X/steps;
slope.Y = slope.Y/steps;
for (int i = 0; i < steps; i++)
{
iterPoint = new PointF(iterPoint.X + slope.X, iterPoint.Y + slope.Y);
Cursor.Position = Point.Round(iterPoint);
Utility.Delay(5, 10);
}
// test if it works
if ((Cursor.Position.X == targetPosition.X) && (Cursor.Position.Y == targetPosition.Y))
return true;
return false;
}
/// <summary>
/// Moves the mouse to the middle of a rectangle
/// </summary>
/// <example>
/// <code>
/// Rectangle r = new Rectangle(50, 50, 100, 100);
/// Mouse.Move(r,true,10);
/// </code>
/// </example>
/// <param name="R">The rectangle to move to</param>
/// <param name="human">Simulate human-like jumps</param>
/// <param name="steps">The points of pathpolygons</param>
/// <returns></returns>
public static Boolean Move(Rectangle R, Boolean human = true, Int32 steps = 100)
{
return Move(new Point(Convert.ToInt32(R.Left + (R.Width/2)), Convert.ToInt32(R.Top + (R.Height/2))), human,
steps);
}
/// <summary>
/// Performs a drag-and-drop action
/// </summary>
/// <remarks>
/// If the option "human" is true, then the mouse can jiggle and the movement have some delays to emulate human mouse movement behavior,
/// since no human performs a complete linear straight cursor movement line
/// </remarks>
/// <param name="source">The drag point (drag from here)</param>
/// <param name="target">The drop point (drop here)</param>
/// <param name="human">Simulate human-like jumps </param>
/// <param name="steps">The points of pathpolygons</param>
/// <returns></returns>
public static void DragAndDrop(Point source, Point target, Boolean human = true, Int32 steps = 100)
{
Move(source, human, steps);
LeftClick();
if (human)
Jiggle();
Utility.Delay(10, 30);
Move(target, human, steps);
LeftClick();
}
/// <summary>
/// Returns the current position of the mouse
/// </summary>
/// <example>
/// <code>
/// Point CurPos = Point.Empty;
/// CurPos = Mouse.GetPosition();
/// </code>
/// </example>
/// <returns>The mouse position</returns>
public static Point GetPosition()
{
return Cursor.Position;
}
/// <summary>
/// Simulates a mouse jiggle
/// </summary>
/// <example>
/// <code>
/// Mouse.Jiggle();
/// </code>
/// </example>
/// <returns></returns>
public static void Jiggle()
{
Int32 xChange = Utility.Random(-10, 10);
Int32 yChange = Utility.Random(-10, 10);
Move(new Point(Cursor.Position.X + xChange, Cursor.Position.Y + yChange), true, 5);
Utility.Delay(20, 60);
Move(new Point(Cursor.Position.X - xChange, Cursor.Position.Y - yChange), true, 5);
}
/// <summary>
/// Moves the mouse relatively to a window
/// </summary>
/// <example>
/// <code>
/// IntPtr hwnd = ... ;
/// bool res = MoveRelativeToWindow(hwnd, 20, 35, true, 10);
/// </code>
/// </example>
/// <param name="windowHandle">The handle of the window</param>
/// <param name="point">The target point</param>
/// <param name="human">Simulate human-like jumps</param>
/// <param name="steps">The points of pathpolygons</param>
/// <returns>true/false</returns>
public static Boolean MoveRelativeToWindow(IntPtr windowHandle, Point point, Boolean human = true,
Int32 steps = 100)
{
var WINDOW = new NativeMethods.RECT();
if (!NativeMethods.GetWindowRect(windowHandle, out WINDOW))
return false;
if (!Move(new Point(WINDOW.Left + point.X, WINDOW.Top + point.Y), human, steps))
return false;
return true;
}
/// <summary>
/// Returns the current position of the mouse, relative to a window
/// </summary>
/// <example>
/// <code>
/// Point CurPos = Point.Empty;
/// IntPtr hwnd = ... ;
/// CurPos = Mouse.GetPositionRelativeToControl(hwnd);
/// </code>
/// </example>
/// <param name="controlHandle">The handle of the window</param>
/// <returns>Point position</returns>
public static Point GetPositionRelativeToControl(IntPtr controlHandle)
{
Point position = Cursor.Position;
var WINDOW = new NativeMethods.RECT();
NativeMethods.GetWindowRect(controlHandle, out WINDOW);
return new Point(position.X - WINDOW.Left, position.Y - WINDOW.Top);
}
/// <summary>
/// Tests if the mouse is hovering a window
/// </summary>
/// <example>
/// <code>
/// bool OverTextbox = Mouse.HoverControl(Textbox1.Handle);
/// </code>
/// </example>
/// <param name="controlHandle">The handle of the window</param>
/// <returns>true/false</returns>
public static bool HoverControl(IntPtr controlHandle)
{
Point mousePosition = GetPositionRelativeToControl(controlHandle);
var WINDOW = new NativeMethods.RECT();
NativeMethods.GetWindowRect(controlHandle, out WINDOW);
return InRectangle(mousePosition, WINDOW.Top, WINDOW.Left, WINDOW.Bottom, WINDOW.Right);
}
/// <summary>
/// Returns whether the mouse is inside a rectangle or not
/// </summary>
/// <example>
/// <code>
/// Point Pos = GetPosition(); // get position of the mouse
/// bool InRectangle = Mouse.InRectangle(Pos,50, 10, 20, 70);
/// </code>
/// </example>
/// <param name="point">The point to test</param>
/// <param name="top">The top of the rectangle</param>
/// <param name="left">The left of the rectangle</param>
/// <param name="bottom">The bottom of the rectangle</param>
/// <param name="right">The right of the rectangle</param>
/// <returns>inside=true / outside=false</returns>
public static bool InRectangle(Point point, int top, int left, int bottom, int right)
{
return (
(left < point.X) && (point.X < right) && (top < point.Y) && (point.Y < bottom)
);
}
/// <summary>
/// Returns whether the mouse is inside a rectangle or not
/// </summary>
/// <example>
/// <code>
/// bool InRectangle = Mouse.InRectangle(50, 10, 20, 70);
/// </code>
/// </example>
/// <param name="top">The top of the rectangle</param>
/// <param name="left">The left of the rectangle</param>
/// <param name="bottom">The bottom of the rectangle</param>
/// <param name="right">The right of the rectangle</param>
/// <returns>inside=true / outside=false</returns>
public static bool InRectangle(int top, int left, int bottom, int right)
{
return InRectangle(GetPosition(), top, left, bottom, right);
}
/// <summary>
/// Performs a mouse scroll
/// </summary>
/// <example>
/// <code>
/// Mouse.Scroll(-50);
/// </code>
/// </example>
/// <param name="wheeldelta">Positive scrolls down, negative scrolls up</param>
public static void Scroll(int wheeldelta)
{
NativeMethods.mouse_event((uint) NativeMethods.MouseEventFlags.WHEEL, 0, 0, -wheeldelta, IntPtr.Zero);
}
private enum MouseEvents : uint
{
WM_MOUSEFIRST = 0x200,
WM_MOUSEMOVE = 0x200,
WM_LBUTTONDOWN = 0x201,
WM_LBUTTONUP = 0x202,
WM_LBUTTONDBLCLK = 0x203,
WM_RBUTTONDOWN = 0x204,
WM_RBUTTONUP = 0x205,
WM_RBUTTONDBLCLK = 0x206,
WM_MBUTTONDOWN = 0x207,
WM_MBUTTONUP = 0x208,
WM_MBUTTONDBLCLK = 0x209,
WM_MOUSEWHEEL = 0x20A,
WM_MOUSEHWHEEL = 0x20E
}
}
}
| |
/*
* CrystalUnityBasic.cs
*
* Created by Gareth Reese
* Copyright 2009 Chillingo Ltd. All rights reserved.
*
*/
using System;
using UnityEngine;
/**
* @brief The interface to all of the Crystal SDK functionality.
*/
public class CrystalUnityBasic : MonoBehaviour
{
public string lastIncomingChallenge;
public string startedFromChallenge;
public bool popoversActivated;
private bool isOkToRun()
{
if ( (Application.platform == RuntimePlatform.IPhonePlayer) && !Application.isEditor )
return true;
else
return false;
}
/**
* @brief The section (tab) of the Crystal UI to display to the user by default
*/
public enum ActivateUiType
{
StandardUi, ///< Opens up the Crystal UI at the default tab on iPhone and without and popovers open on iPad
ProfileUi, ///< Opens up the Profile tab
ChallengesUi, ///< Opens up the Challenges tab
LeaderboardsUi, ///< Opens up the Leaderboards tab
AchievementsUi ///< Opens up the Achievements tab
}
/**
* @brief Crystal settings that enable workaround functionality within the system.
* You should only enable these settings if you're seeing a specific problem that you think may be resolved by one of these options.
* In general you will be instructed to use one of these settings by an FAQ article or directly by the Crystal SDK support team.
*/
public enum CrystalSetting
{
/** @brief Activate the CrystalSettingCocosAchievementWorkaround setting if you're seeing a vertical bar instead of the achievement popup.
* value:"YES" activates the setting
*/
CrystalSettingCocosAchievementWorkaround = 1,
/** @brief Activate the CrystalSettingAvoidBackgroundActivity setting if you're seeing occasional slowdowns during high-CPU activity.
* This setting is intended to be used sparingly during 3D cut scenes and similar and will affect achievement posting etc.
* The setting should be returned to the NO state as soon as possible and the NO state should be the game's default.
* No user data should be lost while the setting is set to NO however.
* value:"YES" - Crystal will avoid any background processing or network activity.
* value:"NO" - Return Crystal to its default state.
*/
CrystalSettingAvoidBackgroundActivity = 2,
/** @brief Activate this setting for framework crashes in [UIWindow _shouldAutorotateToInterfaceOrientation:].
* You'll most commonly see this problem while rotating the device in projects with no UIViewController instance
* such as purely OpenGL-based games.
* value:"YES" activates this setting
*/
CrystalSettingShouldAutorotateWorkaround = 3,
/**
* @brief Activate this setting to restrict Crystal on iPad to one popover, rather than the hierarchical popover method.
* The hierarchical popoevers are more visually appealing but ma contradict some recent Apple Human Interface Guideline changes.
* value:"YES" activates this setting
*/
CrystalSettingSingleiPadPopover = 4,
/**
* @brief Activate this setting to enable the Game Center support within Crystal.
* This setting can be called as a result of an enable/disable Game Center switch in the game UI if desired.
* value:"YES" activates this setting
*/
CrystalSettingEnableGameCenterSupport = 5,
}
public void Update()
{
// Called every frame so we need to make sure that we only check what we need to to ensure good performance
// If you're not using challenges then you can comment out the CCChallengeNotification & CCStartedFromChallenge code below
// If you're not using the popoversActivated property you can comment out the CCStartedFromChallenge code
if (Time.frameCount % 30 == 0)
{
string incomingChallenge = PlayerPrefs.GetString("CCChallengeNotification");
if (incomingChallenge != "")
{
lastIncomingChallenge = incomingChallenge;
PlayerPrefs.SetString("CCChallengeNotification", "");
//////////////////////////////////////////////////////////////////////////////
// The user has started a challenge from the Crystal UI
//
// Call your incoming challenge handler script here or check
// the incomingChallenge attribute for an ID every so often
//////////////////////////////////////////////////////////////////////////////
}
}
else if (Time.frameCount % 30 == 10)
{
if (startedFromChallenge == "")
startedFromChallenge = PlayerPrefs.GetString("CCStartedFromChallenge");
if (startedFromChallenge != "")
{
//////////////////////////////////////////////////////////////////////////////
// The game was started from a push notification, with the intention
// of playing a challenge
//
// Call your challenge handler script here or check
// the incomingChallenge attribute for an ID every so often
//////////////////////////////////////////////////////////////////////////////
}
}
else if (Time.frameCount % 30 == 20)
{
string popoversActivatedString = PlayerPrefs.GetString("CCPopoversActivated");
bool popoversActivatedBool = (popoversActivatedString == "YES") ? true : false;
if (popoversActivatedBool != popoversActivated)
{
Debug.Log("> CrystalUnity_Basic popovers activated " + popoversActivatedBool);
popoversActivated = popoversActivatedBool;
//////////////////////////////////////////////////////////////////////////////
// The Crystal popovers have either been activated or deactivated
// If you'd prefer to grey-out your main menu buttons when the popovers are
// activated you can do it from here or check the popoversActivated property
//////////////////////////////////////////////////////////////////////////////
}
}
}
/**
* @brief Ask the session whether the application was started from an incoming challenge (push) notification
* @return true if the application was started from an incoming challenge
*/
public bool AppWasStartedFromPendingChallenge()
{
if (startedFromChallenge != "")
return true;
else
return false;
}
/**
* @brief Ask the session whether there is an incoming challenge from the Crystal UI.
* This will occur when the user initiates a challenge from the Crystal UI and reactivates the game.
* @return true if the user initiated a challenge in the Crystal UI
*/
public bool HaveIncomingChallengeFromCrystal()
{
if (lastIncomingChallenge != "")
return false;
else
return true;
}
/**
* Activates the Crystal UI
*/
public void ActivateUi()
{
Debug.Log("> CrystalUnityBasic ActivateUi");
ActivateUi(CrystalUnityBasic.ActivateUiType.StandardUi);
}
/**
* Activates the Crystal UI at the specified UI area where possible
* @param type The ActivateUiType as specified above
*/
public void ActivateUi(CrystalUnityBasic.ActivateUiType type)
{
if (isOkToRun())
{
AddCommand("ActivateUi|" + (int)type);
}
else
Debug.Log("> CrystalUnityBasic ActivateUi" + type);
}
/**
* Deactivates the Crystal UI at the specified UI area where possible
* @param type The ActivateUiType as specified above
*/
public void DeactivateUi()
{
if (isOkToRun())
{
AddCommand("DeactivateUi");
}
else
Debug.Log("> CrystalUnityBasic DeactivateUi");
}
/**
* @brief Post the result of the last challenge that the game was notified for
* The game will be notified of the challenge via the challengeStartedWithGameConfig: method of CrystalSessionDelegate.
* @param result The result of the challenge, either as a numerical value or as a number of seconds for time-based scores
* @param doDialog If true Crystal will display a dialog over the game user interface
*/
public void PostChallengeResultForLastChallenge(double result)
{
if (isOkToRun())
{
AddCommand("PostChallengeResultForLastChallenge|" + result);
}
else
{
Debug.Log("> CrystalUnityBasic PostChallengeResultForLastChallenge" + result);
}
}
/**
* @brief Notify the Crystal servers and the user (via a popup notification) that an achievement has been completed.
* The game designer should not attempt to cache, buffer or otherwise restrict the number of times this method is called.
* All logic with regards to reducing server load, handling multiple users and avoiding excessive popups is handled within the Crystal SDK.
* Please call this method whenever an achievement is achieved. Failure to do so will almost certainly cause problems for multiple Crystal users on the same device.
* @param achievementId The ID of the achievement as shown in the Crystal control panel
* @param wasObtained true if the achievement has been obtained or NO to 'unobtain' it.
* @param description A description of the achievement to be displayed to the user. Supplying the description here allows the developer to localize the description. Crystal may not necessarily have a network connection so the only way to get the achievement description is here. If no desctiption is supplied then no notification will be displayed to the user.
* @param alwaysPopup if true the achievement popup will always be displayed to the user. If false (the most common choice) the popup will only be displayed the first time that the achievement is achieved.
*/
public void PostAchievement(string achievementId, bool wasObtained, string description, bool alwaysPopup)
{
if (isOkToRun())
{
AddCommand("PostAchievement|" + achievementId + "|" + wasObtained + "|" + description + "|" + alwaysPopup);
}
else
{
Debug.Log("> CrystalUnityBasic PostAchievement" + achievementId + ", " + wasObtained + ", " + description + ", " + alwaysPopup);
}
}
/**
* @brief Notify the Crystal servers of a leaderboard result for the specified leaderboard ID.
* The game designer should not attempt to cache, buffer or otherwise restrict the number of times this method is called.
* All logic with regards to reducing server load, handling multiple users and avoiding unneeded posts is handled within the Crystal SDK.
* Please call this method whenever a score is scored. Failure to do so will almost certainly cause problems for multiple Crystal users on the same device.
* @param result The score to publish, either as a numerical value or as a number of seconds for time-based scores
* @param leaderboardId The ID of the leaderboard to post to, which should be taken from the Developer Dashboard
* @param lowestValFirst Set this if you have YES set for lowest value first in the developer dashboard. This parameter MUST match the flag in the developer dashboard!
*/
public void PostLeaderboardResult(string leaderboardId, float result, bool lowestValFirst)
{
if (isOkToRun())
{
AddCommand("PostLeaderboardResult|" + leaderboardId + "|" + result + "|" + lowestValFirst);
}
else
{
Debug.Log("> CrystalUnityBasic PostLeaderboardResult" + leaderboardId + ", " + result + ", " + lowestValFirst);
}
}
/**
* @brief Lock the crystal interface to the specified interface orientation
* This method will override any call to lockToOrientation: in AppController+Crystal.mm
* Supported orientations are Portrait, LandscapeLeft and LandscapeRight
* @param orientation The orientation to lock the interface to
*/
public void LockToOrientation(iPhoneScreenOrientation orientation)
{
string orientationString = null;
switch (orientation)
{
case iPhoneScreenOrientation.Portrait:
orientationString = "portrait";
break;
case iPhoneScreenOrientation.LandscapeLeft:
orientationString = "landscapeLeft";
break;
case iPhoneScreenOrientation.LandscapeRight:
orientationString = "landscapeRight";
break;
}
if (isOkToRun() && orientationString != null)
{
AddCommand("LockToOrientation|" + orientationString);
}
else
{
Debug.Log("> CrystalUnityBasic LockToOrientation" + orientationString);
}
}
/**
* @brief Displays the Crystal splash screen
* This method displays the Crystal splash screen to the user above the current game UI.
* It is the responsibility of the developer to ensure that this dialog is displayed at an appropriate time, generally just after the game is started.
* When the splash screen has been dismissed splashScreenFinishedWithActivateCrystal: will be called in the delegate.
* Normally the game would only display this splash screen once to the user.
*/
public void DisplaySplashScreen()
{
if (isOkToRun())
{
AddCommand("DisplaySplashScreen");
}
else
{
Debug.Log("> CrystalUnityBasic DisplaySplashScreen");
}
}
/**
* @brief Sets values for various internal Crystal settings.
* This method is provided for developers to activate workarounds for bugs on the iPhone and the graphics libraries used by developers
* @param setting the CrystalSetting to set
* @param settingValue the value to set for this setting, which will generally be @"YES" to activate a setting
*/
public void ActivateCrystalSetting(CrystalSetting setting, string settingValue)
{
if (isOkToRun() && settingValue != null)
{
AddCommand("ActivateCrystalSetting|" + (int)setting + "|" + settingValue);
}
else
{
Debug.Log("> CrystalUnityBasic ActivateCrystalSetting, " + (int)setting + ", " + settingValue);
}
}
/**
* @brief Call this after your game has loaded to initiate login to Game Center
* Calling this method can initiate the Game Center login dialog, so ensure that you call this at a suitable moment.
* After the user has signed up to Game Center this method will display a 'welcome back' overlay.
* At the time of writing (iOS 4.1 beta 3) the iOS APIs used by this method must be called before scores and achievements can be posted.
* As a result of this you must be careful of the timing of this call.
*/
public void AuthenticateLocalPlayer()
{
if (isOkToRun())
{
AddCommand("AuthenticateLocalPlayer");
}
else
{
Debug.Log("> CrystalUnityBasic AuthenticateLocalPlayer");
}
}
private void AddCommand(string newCommand)
{
string currentCommand = PlayerPrefs.GetString("CCCommands");
if (currentCommand != "")
{
// We already have a command so we need to append this one to the end
PlayerPrefs.SetString("CCCommands", currentCommand + "!<->!" + newCommand);
}
else
{
// This is the first
PlayerPrefs.SetString("CCCommands", newCommand);
}
}
private static CrystalUnityBasic _singleton = null;
public CrystalUnityBasic()
{
if (_singleton != null) {
return;
}
_singleton = this;
}
/**
* @brief Get hold of the singleton instance
*/
public static CrystalUnityBasic singleton
{
get {
if (_singleton == null) {
new CrystalUnityBasic();
}
return _singleton;
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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
namespace System.Patterns.UI.Forms
{
/// <summary>
/// Provides an object-oriented encapsulation of the primary attributes of a command to be executed against
/// a database.
/// </summary>
public class FormCommand
{
/// <summary>
///
/// </summary>
public const string InitCommandId = "Init";
/// <summary>
///
/// </summary>
public const string ResetCommandId = "Reset";
private string _commandId = "Init";
private string _commandText = string.Empty;
private object _commandArgument;
private string _commandTargetId = string.Empty;
/// <summary>
/// Initializes a new instance of the <see cref="FormCommand"/> class.
/// </summary>
public FormCommand() { }
/// <summary>
/// Initializes a new instance of the <see cref="FormCommand"/> class.
/// </summary>
/// <param name="commandId">The command id.</param>
public FormCommand(string commandId)
{
if (string.IsNullOrEmpty(commandId))
throw new ArgumentNullException("commandId");
_commandId = commandId;
}
/// <summary>
/// Initializes a new instance of the <see cref="FormCommand"/> class.
/// </summary>
/// <param name="commandId">The command id.</param>
/// <param name="commandText">The command text.</param>
public FormCommand(string commandId, string commandText)
{
if (string.IsNullOrEmpty(commandId))
throw new ArgumentNullException("commandId");
_commandId = commandId;
_commandText = (commandText ?? string.Empty);
}
/// <summary>
/// Resets this instance to a non-initalized state.
/// </summary>
public void Clear()
{
_commandId = InitCommandId;
_commandTargetId = string.Empty;
_commandArgument = null;
_commandText = string.Empty;
}
/// <summary>
/// Sets the CommandId property based on the name and argument values provided.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="argument">The argument.</param>
public void SetCommand(string name, object argument)
{
_commandId = name.ParseBoundedPrefix("[]", out _commandTargetId);
if (string.IsNullOrEmpty(_commandId))
throw new ArgumentNullException("name", "Core_.Local.UndefinedCommandId");
CommandArgument = argument;
}
/// <summary>
/// Gets or sets the command argument.
/// </summary>
/// <value>The command argument.</value>
public object CommandArgument
{
get { return _commandArgument; }
set
{
string valueText = (value as string);
if (valueText != null)
{
_commandArgument = valueText.Split(';');
_commandText = valueText;
}
else
{
_commandArgument = value;
_commandText = (value != null ? value.ToString() : string.Empty);
}
}
}
/// <summary>
/// Gets or sets the command id.
/// </summary>
/// <value>The command id.</value>
public string CommandId
{
get { return _commandId; }
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException("value");
_commandId = value;
}
}
/// <summary>
/// Gets or sets the command target id.
/// </summary>
/// <value>The command target id.</value>
public string CommandTargetId
{
get { return _commandTargetId; }
set { _commandTargetId = (value ?? string.Empty); }
}
/// <summary>
/// Gets or sets the command text.
/// </summary>
/// <value>The command text.</value>
public string CommandText
{
get { return _commandText; }
set
{
_commandArgument = null;
_commandText = (value ?? string.Empty);
}
}
/// <summary>
/// Gets a value indicating whether the CommandId for this class begins with "@".
/// </summary>
/// <value>
/// <c>true</c> if this instance is check data; otherwise, <c>false</c>.
/// </value>
public bool IsCheckData
{
get { return ((!string.IsNullOrEmpty(_commandId)) && (_commandId.Substring(0, 1) == "@")); }
}
/// <summary>
/// Gets a value indicating whether the CommandId for this instance is either 'Init' or 'Reset'.
/// </summary>
/// <value>
/// <c>true</c> if the CommandId is either 'Init' or 'Reset'; otherwise, <c>false</c>.
/// </value>
public bool IsNew
{
get { return ((!string.IsNullOrEmpty(_commandId)) && ((_commandId == InitCommandId) || (_commandId == ResetCommandId) || (_commandId[0] == 'i'))); }
}
/// <summary>
/// Gets a value indicating whether the CommandId is equal 'Init'.
/// </summary>
/// <value>
/// <c>true</c> if this instance is equal to 'Init'; otherwise, <c>false</c>.
/// </value>
public bool IsNewByInit
{
get { return (_commandId == InitCommandId); }
}
/// <summary>
/// Gets a value indicating whether the CommandId is equal 'Reset'.
/// </summary>
/// <value>
/// <c>true</c> if this instance is equal to 'Reset'; otherwise, <c>false</c>.
/// </value>
public bool IsNewByReset
{
get { return (_commandId == ResetCommandId); }
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Compute
{
using System.Collections.Generic;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Task test result.
/// </summary>
public class BinarizableTaskTest : AbstractTaskTest
{
/// <summary>
/// Constructor.
/// </summary>
public BinarizableTaskTest() : base(false) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="fork">Fork flag.</param>
protected BinarizableTaskTest(bool fork) : base(fork) { }
/// <summary>
/// Test for task result.
/// </summary>
[Test]
public void TestBinarizableObjectInTask()
{
var taskArg = new BinarizableWrapper {Item = ToBinary(Grid1, new BinarizableTaskArgument(100))};
TestTask task = new TestTask(Grid1, taskArg);
var res = Grid1.GetCompute().Execute(task, taskArg).Item;
Assert.NotNull(res);
Assert.AreEqual(400, res.GetField<int>("val"));
BinarizableTaskResult resObj = res.Deserialize<BinarizableTaskResult>();
Assert.AreEqual(400, resObj.Val);
}
private static IBinaryObject ToBinary(IIgnite grid, object obj)
{
var cache = grid.GetCache<object, object>(Cache1Name).WithKeepBinary<object, object>();
cache.Put(1, obj);
return (IBinaryObject) cache.Get(1);
}
/** <inheritDoc /> */
override protected void GetBinaryTypeConfigurations(ICollection<BinaryTypeConfiguration> portTypeCfgs)
{
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableJobArgument)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableJobResult)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableTaskArgument)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableTaskResult)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableJob)));
portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableWrapper)));
}
/// <summary>
/// Test task.
/// </summary>
class TestTask : ComputeTaskAdapter<BinarizableWrapper, BinarizableWrapper, BinarizableWrapper>
{
/** */
private readonly IIgnite _grid;
private readonly BinarizableWrapper _taskArgField;
public TestTask(IIgnite grid, BinarizableWrapper taskArgField)
{
_grid = grid;
_taskArgField = taskArgField;
}
/** <inheritDoc /> */
override public IDictionary<IComputeJob<BinarizableWrapper>, IClusterNode> Map(IList<IClusterNode> subgrid, BinarizableWrapper arg)
{
Assert.AreEqual(2, subgrid.Count);
Assert.NotNull(_grid);
var taskArg = arg;
CheckTaskArgument(taskArg);
CheckTaskArgument(_taskArgField);
var jobs = new Dictionary<IComputeJob<BinarizableWrapper>, IClusterNode>();
foreach (IClusterNode node in subgrid)
{
var job = new BinarizableJob
{
Arg = new BinarizableWrapper {Item = ToBinary(_grid, new BinarizableJobArgument(200))}
};
jobs.Add(job, node);
}
Assert.AreEqual(2, jobs.Count);
return jobs;
}
private void CheckTaskArgument(BinarizableWrapper arg)
{
Assert.IsNotNull(arg);
var taskArg = arg.Item;
Assert.IsNotNull(taskArg);
Assert.AreEqual(100, taskArg.GetField<int>("val"));
BinarizableTaskArgument taskArgObj = taskArg.Deserialize<BinarizableTaskArgument>();
Assert.AreEqual(100, taskArgObj.Val);
}
/** <inheritDoc /> */
override public BinarizableWrapper Reduce(IList<IComputeJobResult<BinarizableWrapper>> results)
{
Assert.NotNull(_grid);
Assert.AreEqual(2, results.Count);
foreach (var res in results)
{
var jobRes = res.Data.Item;
Assert.NotNull(jobRes);
Assert.AreEqual(300, jobRes.GetField<int>("val"));
BinarizableJobResult jobResObj = jobRes.Deserialize<BinarizableJobResult>();
Assert.AreEqual(300, jobResObj.Val);
}
return new BinarizableWrapper {Item = ToBinary(_grid, new BinarizableTaskResult(400))};
}
}
/// <summary>
///
/// </summary>
class BinarizableJobArgument
{
/** */
public readonly int Val;
public BinarizableJobArgument(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
class BinarizableJobResult
{
/** */
public readonly int Val;
public BinarizableJobResult(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
class BinarizableTaskArgument
{
/** */
public readonly int Val;
public BinarizableTaskArgument(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
class BinarizableTaskResult
{
/** */
public readonly int Val;
public BinarizableTaskResult(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
class BinarizableJob : IComputeJob<BinarizableWrapper>
{
[InstanceResource]
private readonly IIgnite _grid = null;
/** */
public BinarizableWrapper Arg;
/** <inheritDoc /> */
public BinarizableWrapper Execute()
{
Assert.IsNotNull(Arg);
var arg = Arg.Item;
Assert.IsNotNull(arg);
Assert.AreEqual(200, arg.GetField<int>("val"));
var argObj = arg.Deserialize<BinarizableJobArgument>();
Assert.AreEqual(200, argObj.Val);
return new BinarizableWrapper {Item = ToBinary(_grid, new BinarizableJobResult(300))};
}
public void Cancel()
{
// No-op.
}
}
class BinarizableWrapper
{
public IBinaryObject Item { get; set; }
}
}
}
| |
// This file was generated by CSLA Object Generator - CslaGenFork v4.5
//
// Filename: Role
// ObjectType: Role
// CSLAType: EditableRoot
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using DocStore.Business.Util;
using Csla.Rules;
using Csla.Rules.CommonRules;
using DocStore.Business.Security;
namespace DocStore.Business.Admin
{
/// <summary>
/// Role (editable root object).<br/>
/// This is a generated <see cref="Role"/> business object.
/// </summary>
[Serializable]
public partial class Role : BusinessBase<Role>
{
#region Static Fields
private static int _lastId;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="RoleID"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<int> RoleIDProperty = RegisterProperty<int>(p => p.RoleID, "Role ID");
/// <summary>
/// Gets the Role ID.
/// </summary>
/// <value>The Role ID.</value>
public int RoleID
{
get { return GetProperty(RoleIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RoleName"/> property.
/// </summary>
public static readonly PropertyInfo<string> RoleNameProperty = RegisterProperty<string>(p => p.RoleName, "Role Name");
/// <summary>
/// Gets or sets the Role Name.
/// </summary>
/// <value>The Role Name.</value>
public string RoleName
{
get { return GetProperty(RoleNameProperty); }
set { SetProperty(RoleNameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="IsActive"/> property.
/// </summary>
public static readonly PropertyInfo<bool> IsActiveProperty = RegisterProperty<bool>(p => p.IsActive, "IsActive");
/// <summary>
/// Gets or sets the active or deleted state.
/// </summary>
/// <value><c>true</c> if IsActive; otherwise, <c>false</c>.</value>
public bool IsActive
{
get { return GetProperty(IsActiveProperty); }
set { SetProperty(IsActiveProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
/// <summary>
/// Gets the Create Date.
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> CreateUserIDProperty = RegisterProperty<int>(p => p.CreateUserID, "Create User ID");
/// <summary>
/// Gets the Create User ID.
/// </summary>
/// <value>The Create User ID.</value>
public int CreateUserID
{
get { return GetProperty(CreateUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Gets the Change Date.
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUserID"/> property.
/// </summary>
public static readonly PropertyInfo<int> ChangeUserIDProperty = RegisterProperty<int>(p => p.ChangeUserID, "Change User ID");
/// <summary>
/// Gets the Change User ID.
/// </summary>
/// <value>The Change User ID.</value>
public int ChangeUserID
{
get { return GetProperty(ChangeUserIDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="RowVersion"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version");
/// <summary>
/// Gets the Row Version.
/// </summary>
/// <value>The Row Version.</value>
public byte[] RowVersion
{
get { return GetProperty(RowVersionProperty); }
}
/// <summary>
/// Gets the Create User Name.
/// </summary>
/// <value>The Create User Name.</value>
public string CreateUserName
{
get
{
var result = string.Empty;
if (UserNVL.GetUserNVL().ContainsKey(CreateUserID))
result = UserNVL.GetUserNVL().GetItemByKey(CreateUserID).Value;
return result;
}
}
/// <summary>
/// Gets the Change User Name.
/// </summary>
/// <value>The Change User Name.</value>
public string ChangeUserName
{
get
{
var result = string.Empty;
if (UserNVL.GetUserNVL().ContainsKey(ChangeUserID))
result = UserNVL.GetUserNVL().GetItemByKey(ChangeUserID).Value;
return result;
}
}
#endregion
#region BusinessBase<T> overrides
/// <summary>
/// Returns a string that represents the current <see cref="Role"/>
/// </summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
// Return the Primary Key as a string
return RoleName.ToString();
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="Role"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="Role"/> object.</returns>
public static Role NewRole()
{
return DataPortal.Create<Role>();
}
/// <summary>
/// Factory method. Loads a <see cref="Role"/> object, based on given parameters.
/// </summary>
/// <param name="roleID">The RoleID parameter of the Role to fetch.</param>
/// <returns>A reference to the fetched <see cref="Role"/> object.</returns>
public static Role GetRole(int roleID)
{
return DataPortal.Fetch<Role>(roleID);
}
/// <summary>
/// Factory method. Deletes a <see cref="Role"/> object, based on given parameters.
/// </summary>
/// <param name="roleID">The RoleID of the Role to delete.</param>
public static void DeleteRole(int roleID)
{
DataPortal.Delete<Role>(roleID);
}
/// <summary>
/// Factory method. Undeletes a <see cref="Role"/> object, based on given parameters.
/// </summary>
/// <param name="roleID">The RoleID of the Role to undelete.</param>
/// <returns>A reference to the undeleted <see cref="Role"/> object.</returns>
public static Role UndeleteRole(int roleID)
{
var obj = DataPortal.Fetch<Role>(roleID);
obj.IsActive = true;
return obj.Save();
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="Role"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewRole(EventHandler<DataPortalResult<Role>> callback)
{
DataPortal.BeginCreate<Role>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="Role"/> object, based on given parameters.
/// </summary>
/// <param name="roleID">The RoleID parameter of the Role to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetRole(int roleID, EventHandler<DataPortalResult<Role>> callback)
{
DataPortal.BeginFetch<Role>(roleID, callback);
}
/// <summary>
/// Factory method. Asynchronously deletes a <see cref="Role"/> object, based on given parameters.
/// </summary>
/// <param name="roleID">The RoleID of the Role to delete.</param>
/// <param name="callback">The completion callback method.</param>
public static void DeleteRole(int roleID, EventHandler<DataPortalResult<Role>> callback)
{
DataPortal.BeginDelete<Role>(roleID, callback);
}
/// <summary>
/// Factory method. Asynchronously undeletes a <see cref="Role"/> object, based on given parameters.
/// </summary>
/// <param name="roleID">The RoleID of the Role to undelete.</param>
/// <param name="callback">The completion callback method.</param>
public static void UndeleteRole(int roleID, EventHandler<DataPortalResult<Role>> callback)
{
var obj = new Role();
DataPortal.BeginFetch<Role>(roleID, (o, e) =>
{
if (e.Error != null)
throw e.Error;
else
obj = e.Object;
});
obj.IsActive = true;
obj.BeginSave(callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="Role"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public Role()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Object Authorization
/// <summary>
/// Adds the object authorization rules.
/// </summary>
protected static void AddObjectAuthorizationRules()
{
BusinessRules.AddRule(typeof (Role), new IsInRole(AuthorizationActions.CreateObject, "Manager"));
BusinessRules.AddRule(typeof (Role), new IsInRole(AuthorizationActions.GetObject, "User"));
BusinessRules.AddRule(typeof (Role), new IsInRole(AuthorizationActions.EditObject, "Manager"));
BusinessRules.AddRule(typeof (Role), new IsInRole(AuthorizationActions.DeleteObject, "Admin"));
AddObjectAuthorizationRulesExtend();
}
/// <summary>
/// Allows the set up of custom object authorization rules.
/// </summary>
static partial void AddObjectAuthorizationRulesExtend();
/// <summary>
/// Checks if the current user can create a new Role object.
/// </summary>
/// <returns><c>true</c> if the user can create a new object; otherwise, <c>false</c>.</returns>
public static bool CanAddObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(Role));
}
/// <summary>
/// Checks if the current user can retrieve Role's properties.
/// </summary>
/// <returns><c>true</c> if the user can read the object; otherwise, <c>false</c>.</returns>
public static bool CanGetObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(Role));
}
/// <summary>
/// Checks if the current user can change Role's properties.
/// </summary>
/// <returns><c>true</c> if the user can update the object; otherwise, <c>false</c>.</returns>
public static bool CanEditObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(Role));
}
/// <summary>
/// Checks if the current user can delete a Role object.
/// </summary>
/// <returns><c>true</c> if the user can delete the object; otherwise, <c>false</c>.</returns>
public static bool CanDeleteObject()
{
return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(Role));
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="Role"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(RoleIDProperty, System.Threading.Interlocked.Decrement(ref _lastId));
LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
LoadProperty(CreateUserIDProperty, UserInformation.UserId);
LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty));
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="Role"/> object from the database, based on given criteria.
/// </summary>
/// <param name="roleID">The Role ID.</param>
protected void DataPortal_Fetch(int roleID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("GetRole", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@RoleID", roleID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, roleID);
OnFetchPre(args);
Fetch(cmd);
OnFetchPost(args);
}
}
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="Role"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(RoleIDProperty, dr.GetInt32("RoleID"));
LoadProperty(RoleNameProperty, dr.GetString("RoleName"));
LoadProperty(IsActiveProperty, dr.GetBoolean("IsActive"));
LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true));
LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID"));
LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true));
LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID"));
LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]);
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="Role"/> object in the database.
/// </summary>
protected override void DataPortal_Insert()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("AddRole", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@RoleID", ReadProperty(RoleIDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@RoleName", ReadProperty(RoleNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@IsActive", ReadProperty(IsActiveProperty)).DbType = DbType.Boolean;
cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(RoleIDProperty, (int) cmd.Parameters["@RoleID"].Value);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="Role"/> object.
/// </summary>
protected override void DataPortal_Update()
{
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("UpdateRole", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@RoleID", ReadProperty(RoleIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RoleName", ReadProperty(RoleNameProperty)).DbType = DbType.String;
cmd.Parameters.AddWithValue("@IsActive", ReadProperty(IsActiveProperty)).DbType = DbType.Boolean;
cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary;
cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value);
}
ctx.Commit();
}
}
private void SimpleAuditTrail()
{
LoadProperty(ChangeDateProperty, DateTime.Now);
LoadProperty(ChangeUserIDProperty, UserInformation.UserId);
OnPropertyChanged("ChangeUserName");
if (IsNew)
{
LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty));
OnPropertyChanged("CreateUserName");
}
}
/// <summary>
/// Self deletes the <see cref="Role"/> object.
/// </summary>
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(RoleID);
}
/// <summary>
/// Deletes the <see cref="Role"/> object from database.
/// </summary>
/// <param name="roleID">The delete criteria.</param>
protected void DataPortal_Delete(int roleID)
{
// audit the object, just in case soft delete is used on this object
SimpleAuditTrail();
using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false))
{
using (var cmd = new SqlCommand("DeleteRole", ctx.Connection))
{
cmd.Transaction = ctx.Transaction;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@RoleID", roleID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, roleID);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
ctx.Commit();
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using UnityEngine;
namespace Chronos
{
/// <summary>
/// Determines how a clock combines its time scale with that of others.
/// </summary>
public enum ClockBlend
{
/// <summary>
/// The clock's time scale is multiplied with that of others.
/// </summary>
Multiplicative = 0,
/// <summary>
/// The clock's time scale is added to that of others.
/// </summary>
Additive = 1
}
/// <summary>
/// An abstract base component that provides common timing functionality to all types of clocks.
/// </summary>
[HelpURL("http://ludiq.io/chronos/documentation#Clock")]
public abstract class Clock : MonoBehaviour
{
protected virtual void Awake() { }
protected virtual void Start()
{
if (string.IsNullOrEmpty(_parentKey))
{
parent = null;
}
else if (Timekeeper.instance.HasClock(_parentKey))
{
parent = Timekeeper.instance.Clock(_parentKey);
}
else
{
throw new ChronosException(string.Format("Missing parent clock: '{0}'.", _parentKey));
}
startTime = Time.unscaledTime;
if (parent != null)
{
parent.Register(this);
}
ComputeTimeScale();
}
protected virtual void Update()
{
if (isLerping)
{
_localTimeScale = Mathf.Lerp(lerpFrom, lerpTo, (unscaledTime - lerpStart) / (lerpEnd - lerpStart));
if (unscaledTime >= lerpEnd)
{
isLerping = false;
}
}
ComputeTimeScale();
float unscaledDeltaTime = Timekeeper.unscaledDeltaTime;
deltaTime = unscaledDeltaTime * timeScale;
fixedDeltaTime = Time.fixedDeltaTime * timeScale;
time += deltaTime;
unscaledTime += unscaledDeltaTime;
}
#region Fields
protected bool isLerping;
protected float lerpStart;
protected float lerpEnd;
protected float lerpFrom;
protected float lerpTo;
#endregion
#region Properties
[SerializeField]
private float _localTimeScale = 1;
/// <summary>
/// The scale at which the time is passing for the clock. This can be used for slow motion, acceleration, pause or even rewind effects.
/// </summary>
public float localTimeScale
{
get { return _localTimeScale; }
set { _localTimeScale = value; }
}
/// <summary>
/// The computed time scale of the clock. This value takes into consideration all of the clock's parameters (parent, paused, etc.) and multiplies their effect accordingly.
/// </summary>
public float timeScale { get; protected set; }
/// <summary>
/// The time in seconds since the creation of the clock, affected by the time scale. Returns the same value if called multiple times in a single frame.
/// Unlike Time.time, this value will not return Time.fixedTime when called inside MonoBehaviour's FixedUpdate.
/// </summary>
public float time { get; protected set; }
/// <summary>
/// The time in seconds since the creation of the clock, regardless of the time scale. Returns the same value if called multiple times in a single frame.
/// </summary>
public float unscaledTime { get; protected set; }
/// <summary>
/// The time in seconds it took to complete the last frame, multiplied by the time scale. Returns the same value if called multiple times in a single frame.
/// Unlike Time.deltaTime, this value will not return Time.fixedDeltaTime when called inside MonoBehaviour's FixedUpdate.
/// </summary>
public float deltaTime { get; protected set; }
/// <summary>
/// The interval in seconds at which physics and other fixed frame rate updates, multiplied by the time scale.
/// </summary>
public float fixedDeltaTime { get; protected set; }
/// <summary>
/// The unscaled time in seconds between the start of the game and the creation of the clock.
/// </summary>
public float startTime { get; protected set; }
[SerializeField]
private bool _paused;
/// <summary>
/// Determines whether the clock is paused. This toggle is especially useful if you want to pause a clock without having to worry about storing its previous time scale to restore it afterwards.
/// </summary>
public bool paused
{
get { return _paused; }
set { _paused = value; }
}
[SerializeField, GlobalClock]
private string _parentKey;
private GlobalClock _parent;
/// <summary>
/// The parent global clock. The parent clock will multiply its time scale with all of its children, allowing for cascading time effects.
/// </summary>
public GlobalClock parent
{
get { return _parent; }
set
{
if (_parent != null)
{
_parent.Unregister(this);
}
if (value != null)
{
if (value == this)
{
throw new ChronosException("Global clock parent cannot be itself.");
}
_parentKey = value.key;
_parent = value;
_parent.Register(this);
}
else
{
_parentKey = null;
_parent = null;
}
}
}
[SerializeField]
private ClockBlend _parentBlend = ClockBlend.Multiplicative;
/// <summary>
/// Determines how the clock combines its time scale with that of its parent.
/// </summary>
public ClockBlend parentBlend
{
get { return _parentBlend; }
set { _parentBlend = value; }
}
/// <summary>
/// Indicates the state of the clock.
/// </summary>
public TimeState state
{
get { return Timekeeper.GetTimeState(timeScale); }
}
#endregion
/// <summary>
/// The time scale is only computed once per update to improve performance. If you need to ensure it is correct in the same frame, call this method to compute it manually.
/// </summary>
public virtual void ComputeTimeScale()
{
if (paused)
{
timeScale = 0;
}
else if (parent == null)
{
timeScale = localTimeScale;
}
else
{
if (parentBlend == ClockBlend.Multiplicative)
{
timeScale = parent.timeScale * localTimeScale;
}
else // if (combinationMode == ClockCombinationMode.Additive)
{
timeScale = parent.timeScale + localTimeScale;
}
}
}
/// <summary>
/// Changes the local time scale smoothly over the given duration in seconds.
/// </summary>
public void LerpTimeScale(float timeScale, float duration, bool steady = false)
{
if (duration < 0) throw new ArgumentException("Duration must be positive.", "duration");
if (duration == 0)
{
localTimeScale = timeScale;
isLerping = false;
return;
}
float modifier = 1;
if (steady)
{
modifier = Mathf.Abs(localTimeScale - timeScale);
}
if (modifier != 0)
{
lerpFrom = localTimeScale;
lerpStart = unscaledTime;
lerpTo = timeScale;
lerpEnd = lerpStart + (duration * modifier);
isLerping = true;
}
}
}
}
| |
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.Modules.Core;
using ReactNative.UIManager;
using System.Collections.Generic;
using Windows.ApplicationModel.Core;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
namespace ReactNative.Modules.DeviceInfo
{
/// <summary>
/// Native module that manages window dimension updates to JavaScript.
/// </summary>
class DeviceInfoModule : ReactContextNativeModuleBase, ILifecycleEventListener, IBackgroundEventListener
{
private readonly IReadOnlyDictionary<string, object> _constants;
private bool _isSubscribed;
/// <summary>
/// Instantiates the <see cref="DeviceInfoModule"/>.
/// </summary>
/// <param name="reactContext">The React context.</param>
public DeviceInfoModule(ReactContext reactContext)
: base(reactContext)
{
var displayMetrics = HasCoreWindow
? DisplayMetrics.GetForCurrentView()
: DisplayMetrics.Empty;
_constants = new Dictionary<string, object>
{
{ "Dimensions", GetDimensions(displayMetrics) },
};
}
/// <summary>
/// The name of the native module.
/// </summary>
public override string Name
{
get { return "DeviceInfo"; }
}
/// <summary>
/// Native module constants.
/// </summary>
public override IReadOnlyDictionary<string, object> Constants
{
get
{
return _constants;
}
}
private static bool HasCoreWindow
{
get
{
return CoreApplication.MainView.CoreWindow != null;
}
}
/// <summary>
/// Called after the creation of a <see cref="IReactInstance"/>,
/// </summary>
public override void Initialize()
{
Context.AddLifecycleEventListener(this);
Context.AddBackgroundEventListener(this);
}
/// <summary>
/// Called when the application is suspended.
/// </summary>
public void OnSuspend()
{
Unsubscribe();
}
/// <summary>
/// Called when the application is resumed.
/// </summary>
public void OnResume()
{
Subscribe();
}
/// <summary>
/// Called when the host entered background mode.
/// </summary>
public void OnEnteredBackground()
{
Unsubscribe();
}
/// <summary>
/// Called when the host is leaving background mode.
/// </summary>
public void OnLeavingBackground()
{
Subscribe();
}
private void Subscribe()
{
if (!_isSubscribed && HasCoreWindow)
{
_isSubscribed = true;
ApplicationView.GetForCurrentView().VisibleBoundsChanged += OnVisibleBoundsChanged;
DisplayInformation.GetForCurrentView().OrientationChanged += OnOrientationChanged;
SendUpdateDimensionsEvent();
}
}
private void Unsubscribe()
{
if (_isSubscribed && HasCoreWindow)
{
_isSubscribed = false;
ApplicationView.GetForCurrentView().VisibleBoundsChanged -= OnVisibleBoundsChanged;
DisplayInformation.GetForCurrentView().OrientationChanged -= OnOrientationChanged;
}
}
/// <summary>
/// Called when the application is terminated.
/// </summary>
public void OnDestroy()
{
}
private void OnVisibleBoundsChanged(ApplicationView sender, object args)
{
SendUpdateDimensionsEvent();
}
private void OnOrientationChanged(DisplayInformation displayInformation, object args)
{
var name = default(string);
var degrees = default(double);
var isLandscape = false;
switch (displayInformation.CurrentOrientation)
{
case DisplayOrientations.Landscape:
name = "landscape-primary";
degrees = -90.0;
isLandscape = true;
break;
case DisplayOrientations.Portrait:
name = "portrait-primary";
degrees = 0.0;
break;
case DisplayOrientations.LandscapeFlipped:
name = "landscape-secondary";
degrees = 90.0;
isLandscape = true;
break;
case DisplayOrientations.PortraitFlipped:
name = "portraitSecondary";
degrees = 180.0;
break;
}
if (name != null)
{
Context.GetJavaScriptModule<RCTDeviceEventEmitter>()
.emit("namedOrientationDidChange", new JObject
{
{ "name", name },
{ "rotationDegrees", degrees },
{ "isLandscape", isLandscape },
});
}
}
private void SendUpdateDimensionsEvent()
{
Context.GetJavaScriptModule<RCTDeviceEventEmitter>()
.emit("didUpdateDimensions", GetDimensions());
}
private static IDictionary<string, object> GetDimensions()
{
return GetDimensions(DisplayMetrics.GetForCurrentView());
}
private static IDictionary<string, object> GetDimensions(DisplayMetrics displayMetrics)
{
return new Dictionary<string, object>
{
{
"window",
new Dictionary<string, object>
{
{ "width", displayMetrics.Width },
{ "height", displayMetrics.Height },
{ "scale", displayMetrics.Scale },
/* TODO: density and DPI needed? */
}
},
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace SineSignal.Ottoman.Serialization
{
// This is loosely based off of LitJson's JsonReader. I modified the naming convention and also updated
// it a little also to take advantage of newer language features. It will do for now, until I have more
// time to revisit and finish the task below.
// TODO: Refactor when we refactor JsonParser
public sealed class JsonReader
{
private static IDictionary<int, IDictionary<int, int[]>> parseTable;
private Stack<int> AutomationStack { get; set; }
private int CurrentInput { get; set; }
private int CurrentSymbol { get; set; }
private JsonParser Parser { get; set; }
private bool ParserInString { get; set; }
private bool ParserReturn { get; set; }
private bool ReadStarted { get; set; }
private TextReader Reader { get; set; }
private bool ReaderIsOwned { get; set; }
public bool EndOfInput { get; private set; }
public bool EndOfJson { get; private set; }
public JsonToken CurrentToken { get; private set; }
public object CurrentTokenValue { get; private set; }
public bool AllowComments
{
get { return Parser.AllowComments; }
set { Parser.AllowComments = value; }
}
public bool AllowSingleQuotedStrings
{
get { return Parser.AllowSingleQuotedStrings; }
set { Parser.AllowSingleQuotedStrings = value; }
}
static JsonReader()
{
PopulateParseTable();
}
public JsonReader(string json) : this(new StringReader(json), true)
{
}
public JsonReader(TextReader reader) : this(reader, false)
{
}
public JsonReader(TextReader reader, bool owned)
{
if (reader == null)
throw new ArgumentNullException("reader");
ParserInString = false;
ParserReturn = false;
ReadStarted = false;
AutomationStack = new Stack<int>();
AutomationStack.Push((int)JsonParserToken.End);
AutomationStack.Push((int)JsonParserToken.Text);
Parser = new JsonParser(reader);
EndOfInput = false;
EndOfJson = false;
this.Reader = reader;
ReaderIsOwned = owned;
}
public bool Read()
{
if (EndOfInput)
return false;
if (EndOfJson)
{
EndOfJson = false;
AutomationStack.Clear();
AutomationStack.Push((int)JsonParserToken.End);
AutomationStack.Push((int)JsonParserToken.Text);
}
ParserInString = false;
ParserReturn = false;
CurrentToken = JsonToken.None;
CurrentTokenValue = null;
if (!ReadStarted)
{
ReadStarted = true;
if (!ReadToken())
return false;
}
int[] entry_symbols;
while (true)
{
if (ParserReturn)
{
if (AutomationStack.Peek() == (int)JsonParserToken.End)
EndOfJson = true;
return true;
}
CurrentSymbol = AutomationStack.Pop();
ProcessSymbol();
if (CurrentSymbol == CurrentInput)
{
if (!ReadToken())
{
if (AutomationStack.Peek() != (int)JsonParserToken.End)
throw new JsonException("Input doesn't evaluate to proper JSON text");
if (ParserReturn)
return true;
return false;
}
continue;
}
try
{
entry_symbols = parseTable[CurrentSymbol][CurrentInput];
}
catch(KeyNotFoundException e)
{
throw new JsonException((JsonParserToken)CurrentInput, e);
}
if (entry_symbols[0] == (int)JsonParserToken.Epsilon)
continue;
for (int index = entry_symbols.Length - 1; index >= 0; index--)
{
AutomationStack.Push(entry_symbols[index]);
}
}
}
public void Close()
{
if (EndOfInput)
return;
EndOfInput = true;
EndOfJson = true;
if (ReaderIsOwned)
Reader.Close();
Reader = null;
}
private bool ReadToken()
{
if (EndOfInput)
return false;
Parser.NextToken();
if (Parser.EndOfInput)
{
Close();
return false;
}
CurrentInput = Parser.Token;
return true;
}
private void ProcessSymbol()
{
if (CurrentSymbol == '[')
{
CurrentToken = JsonToken.ArrayStart;
ParserReturn = true;
}
else if (CurrentSymbol == ']')
{
CurrentToken = JsonToken.ArrayEnd;
ParserReturn = true;
}
else if (CurrentSymbol == '{')
{
CurrentToken = JsonToken.ObjectStart;
ParserReturn = true;
}
else if (CurrentSymbol == '}')
{
CurrentToken = JsonToken.ObjectEnd;
ParserReturn = true;
}
else if (CurrentSymbol == '"')
{
if (ParserInString)
{
ParserInString = false;
ParserReturn = true;
}
else
{
if (CurrentToken == JsonToken.None)
CurrentToken = JsonToken.String;
ParserInString = true;
}
}
else if (CurrentSymbol == (int)JsonParserToken.CharSeq)
{
CurrentTokenValue = Parser.StringValue;
}
else if (CurrentSymbol == (int)JsonParserToken.False)
{
CurrentToken = JsonToken.Boolean;
CurrentTokenValue = false;
ParserReturn = true;
}
else if (CurrentSymbol == (int)JsonParserToken.Null)
{
CurrentToken = JsonToken.Null;
ParserReturn = true;
}
else if (CurrentSymbol == (int)JsonParserToken.Number)
{
ProcessNumber(Parser.StringValue);
ParserReturn = true;
}
else if (CurrentSymbol == (int)JsonParserToken.Pair)
{
CurrentToken = JsonToken.MemberName;
}
else if (CurrentSymbol == (int)JsonParserToken.True)
{
CurrentToken = JsonToken.Boolean;
CurrentTokenValue = true;
ParserReturn = true;
}
}
private void ProcessNumber(string number)
{
if (number.IndexOf('.') != -1 ||
number.IndexOf('e') != -1 ||
number.IndexOf('E') != -1)
{
double n_double;
if (Double.TryParse(number, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out n_double))
{
CurrentToken = JsonToken.Double;
CurrentTokenValue = n_double;
return;
}
}
int n_int32;
if (Int32.TryParse(number, out n_int32))
{
CurrentToken = JsonToken.Int;
CurrentTokenValue = n_int32;
return;
}
long n_int64;
if (Int64.TryParse(number, out n_int64))
{
CurrentToken = JsonToken.Long;
CurrentTokenValue = n_int64;
return;
}
// Shouldn't happen, but just in case, return something
CurrentToken = JsonToken.Int;
CurrentTokenValue = 0;
}
private static void PopulateParseTable()
{
parseTable = new Dictionary<int, IDictionary<int, int[]>>();
TableAddRow(JsonParserToken.Array);
TableAddColumn(JsonParserToken.Array,
'[', '[', (int)JsonParserToken.ArrayPrime);
TableAddRow(JsonParserToken.ArrayPrime);
TableAddColumn(JsonParserToken.ArrayPrime,
'"', (int)JsonParserToken.Value, (int)JsonParserToken.ValueRest, ']');
TableAddColumn(JsonParserToken.ArrayPrime,
'[', (int)JsonParserToken.Value, (int)JsonParserToken.ValueRest, ']');
TableAddColumn(JsonParserToken.ArrayPrime,
']', ']');
TableAddColumn(JsonParserToken.ArrayPrime,
'{', (int)JsonParserToken.Value, (int)JsonParserToken.ValueRest, ']');
TableAddColumn(JsonParserToken.ArrayPrime,
(int)JsonParserToken.Number, (int)JsonParserToken.Value, (int)JsonParserToken.ValueRest, ']');
TableAddColumn(JsonParserToken.ArrayPrime,
(int)JsonParserToken.True, (int)JsonParserToken.Value, (int)JsonParserToken.ValueRest, ']');
TableAddColumn(JsonParserToken.ArrayPrime,
(int)JsonParserToken.False, (int)JsonParserToken.Value, (int)JsonParserToken.ValueRest, ']');
TableAddColumn(JsonParserToken.ArrayPrime,
(int)JsonParserToken.Null, (int)JsonParserToken.Value, (int)JsonParserToken.ValueRest, ']');
TableAddRow(JsonParserToken.Object);
TableAddColumn(JsonParserToken.Object,
'{', '{', (int)JsonParserToken.ObjectPrime);
TableAddRow(JsonParserToken.ObjectPrime);
TableAddColumn(JsonParserToken.ObjectPrime,
'"', (int)JsonParserToken.Pair, (int)JsonParserToken.PairRest, '}');
TableAddColumn(JsonParserToken.ObjectPrime,
'}', '}');
TableAddRow(JsonParserToken.Pair);
TableAddColumn(JsonParserToken.Pair,
'"', (int)JsonParserToken.String, ':', (int)JsonParserToken.Value);
TableAddRow(JsonParserToken.PairRest);
TableAddColumn(JsonParserToken.PairRest,
',', ',', (int)JsonParserToken.Pair, (int)JsonParserToken.PairRest);
TableAddColumn(JsonParserToken.PairRest,
'}', (int)JsonParserToken.Epsilon);
TableAddRow(JsonParserToken.String);
TableAddColumn(JsonParserToken.String,
'"', '"', (int)JsonParserToken.CharSeq, '"');
TableAddRow(JsonParserToken.Text);
TableAddColumn(JsonParserToken.Text,
'[', (int)JsonParserToken.Array);
TableAddColumn(JsonParserToken.Text,
'{', (int)JsonParserToken.Object);
TableAddRow(JsonParserToken.Value);
TableAddColumn(JsonParserToken.Value,
'"', (int)JsonParserToken.String);
TableAddColumn(JsonParserToken.Value,
'[', (int)JsonParserToken.Array);
TableAddColumn(JsonParserToken.Value,
'{', (int)JsonParserToken.Object);
TableAddColumn(JsonParserToken.Value,
(int)JsonParserToken.Number, (int)JsonParserToken.Number);
TableAddColumn(JsonParserToken.Value,
(int)JsonParserToken.True, (int)JsonParserToken.True);
TableAddColumn(JsonParserToken.Value,
(int)JsonParserToken.False, (int)JsonParserToken.False);
TableAddColumn(JsonParserToken.Value,
(int)JsonParserToken.Null, (int)JsonParserToken.Null);
TableAddRow(JsonParserToken.ValueRest);
TableAddColumn(JsonParserToken.ValueRest,
',', ',', (int)JsonParserToken.Value, (int)JsonParserToken.ValueRest);
TableAddColumn(JsonParserToken.ValueRest, ']', (int)JsonParserToken.Epsilon);
}
private static void TableAddColumn(JsonParserToken row, int column, params int[] symbols)
{
parseTable[(int)row].Add(column, symbols);
}
private static void TableAddRow(JsonParserToken rule)
{
parseTable.Add((int)rule, new Dictionary<int, int[]>());
}
}
public enum JsonToken
{
None,
ObjectStart,
MemberName,
ObjectEnd,
ArrayStart,
ArrayEnd,
Int,
Long,
Double,
String,
Boolean,
Null
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace WebApiProxy.TestServer.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
#region Copyright
//
// This framework is based on log4j see http://jakarta.apache.org/log4j
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.Text;
using log4net.Layout;
using log4net.spi;
using log4net.DateFormatter;
namespace log4net.helpers
{
/// <summary>
/// Most of the work of the <see cref="PatternLayout"/> class
/// is delegated to the PatternParser class.
/// </summary>
public class PatternParser
{
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="PatternParser" /> class
/// with the specified pattern string.
/// </summary>
/// <param name="pattern">The pattern to parse.</param>
public PatternParser(string pattern)
{
m_pattern = pattern;
m_patternLength = pattern.Length;
m_state = LITERAL_STATE;
}
#endregion Public Instance Constructors
#region Public Instance Methods
/// <summary>
/// Parses the pattern into a chain of pattern converters.
/// </summary>
/// <returns>The head of a chain of pattern converters.</returns>
public PatternConverter Parse()
{
char c;
m_index = 0;
while(m_index < m_patternLength)
{
c = m_pattern[m_index++];
switch(m_state)
{
case LITERAL_STATE:
// In literal state, the last char is always a literal.
if (m_index == m_patternLength)
{
m_currentLiteral.Append(c);
continue;
}
if (c == ESCAPE_CHAR)
{
// peek at the next char.
switch(m_pattern[m_index])
{
case ESCAPE_CHAR:
m_currentLiteral.Append(c);
m_index++; // move pointer
break;
case 'n':
m_currentLiteral.Append(SystemInfo.NewLine);
m_index++; // move pointer
break;
default:
if (m_currentLiteral.Length != 0)
{
AddToList(new LiteralPatternConverter(m_currentLiteral.ToString()));
}
m_currentLiteral.Length = 0;
m_currentLiteral.Append(c); // append %
m_state = CONVERTER_STATE;
m_formattingInfo.Reset();
break;
}
}
else
{
m_currentLiteral.Append(c);
}
break;
case CONVERTER_STATE:
m_currentLiteral.Append(c);
switch(c)
{
case '-':
m_formattingInfo.LeftAlign = true;
break;
case '.':
m_state = DOT_STATE;
break;
default:
if (c >= '0' && c <= '9')
{
m_formattingInfo.Min = c - '0';
m_state = MIN_STATE;
}
else
{
FinalizeConverter(c);
}
break;
} // switch
break;
case MIN_STATE:
m_currentLiteral.Append(c);
if (c >= '0' && c <= '9')
{
m_formattingInfo.Min = (m_formattingInfo.Min * 10) + (c - '0');
}
else if (c == '.')
{
m_state = DOT_STATE;
}
else
{
FinalizeConverter(c);
}
break;
case DOT_STATE:
m_currentLiteral.Append(c);
if (c >= '0' && c <= '9')
{
m_formattingInfo.Max = c - '0';
m_state = MAX_STATE;
}
else
{
LogLog.Error("PatternParser: Error occurred in position ["+m_index+"].\n Was expecting digit, instead got char ["+c+"].");
m_state = LITERAL_STATE;
}
break;
case MAX_STATE:
m_currentLiteral.Append(c);
if (c >= '0' && c <= '9')
{
m_formattingInfo.Max = (m_formattingInfo.Max * 10) + (c - '0');
}
else
{
FinalizeConverter(c);
m_state = LITERAL_STATE;
}
break;
} // switch
} // while
if (m_currentLiteral.Length != 0)
{
AddToList(new LiteralPatternConverter(m_currentLiteral.ToString()));
}
return m_head;
}
#endregion Public Instance Methods
#region Protected Instance Methods
/// <summary>
/// Extracts the option from the pattern at the current index.
/// </summary>
/// <remarks>
/// The option is the section of the pattern between '{' and '}'.
/// </remarks>
/// <returns>
/// The option if the current index of the parse is at the start
/// of the option, otherwise <c>null</c>.
/// </returns>
protected string ExtractOption()
{
if ((m_index < m_patternLength) && (m_pattern[m_index] == '{'))
{
int end = m_pattern.IndexOf('}', m_index);
if (end > m_index)
{
string r = m_pattern.Substring(m_index + 1, end - m_index - 1);
m_index = end + 1;
return r;
}
}
return null;
}
/// <summary>
/// The option is expected to be in decimal and positive. In case of error, zero is returned.
/// </summary>
/// <returns>The option as a number.</returns>
protected int ExtractPrecisionOption()
{
string opt = ExtractOption();
int r = 0;
if (opt != null)
{
try
{
r = int.Parse(opt, System.Globalization.NumberFormatInfo.InvariantInfo);
if (r <= 0)
{
LogLog.Error("PatternParser: Precision option ["+opt+"] isn't a positive integer.");
r = 0;
}
}
catch (Exception e)
{
LogLog.Error("PatternParser: Logger option ["+opt+"] not a decimal integer.", e);
}
}
return r;
}
/// <summary>
/// Internal method that works on a single option in the
/// pattern
/// </summary>
/// <param name="c">The option specifier.</param>
protected void FinalizeConverter(char c)
{
PatternConverter pc = null;
switch(c)
{
case 'a':
pc = new BasicPatternConverter(m_formattingInfo, APPDOMAIN_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 'c':
pc = new LoggerPatternConverter(m_formattingInfo, ExtractPrecisionOption());
m_currentLiteral.Length = 0;
break;
case 'C':
pc = new ClassNamePatternConverter(m_formattingInfo, ExtractPrecisionOption());
m_currentLiteral.Length = 0;
break;
case 'd':
string dateFormatStr = AbsoluteTimeDateFormatter.ISO8601_DATE_FORMAT;
IDateFormatter df;
string dOpt = ExtractOption();
if (dOpt != null)
{
dateFormatStr = dOpt;
}
if (string.Compare(dateFormatStr, AbsoluteTimeDateFormatter.ISO8601_DATE_FORMAT, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
{
df = new ISO8601DateFormatter();
}
else if (string.Compare(dateFormatStr, AbsoluteTimeDateFormatter.ABS_TIME_DATE_FORMAT, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
{
df = new AbsoluteTimeDateFormatter();
}
else if (string.Compare(dateFormatStr, AbsoluteTimeDateFormatter.DATE_AND_TIME_DATE_FORMAT, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
{
df = new DateTimeDateFormatter();
}
else
{
try
{
df = new SimpleDateFormatter(dateFormatStr);
}
catch (Exception e)
{
LogLog.Error("PatternParser: Could not instantiate SimpleDateFormatter with ["+dateFormatStr+"]", e);
df = new ISO8601DateFormatter();
}
}
pc = new DatePatternConverter(m_formattingInfo, df);
m_currentLiteral.Length = 0;
break;
case 'F':
pc = new LocationPatternConverter(m_formattingInfo, FILE_LOCATION_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 'l':
pc = new LocationPatternConverter(m_formattingInfo, FULL_LOCATION_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 'L':
pc = new LocationPatternConverter(m_formattingInfo, LINE_LOCATION_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 'm':
pc = new BasicPatternConverter(m_formattingInfo, MESSAGE_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 'M':
pc = new LocationPatternConverter(m_formattingInfo, METHOD_LOCATION_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 'p':
pc = new BasicPatternConverter(m_formattingInfo, LEVEL_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 'P':
pc = new PropertyPatternConverter(m_formattingInfo, this.ExtractOption());
m_currentLiteral.Length = 0;
break;
case 'r':
pc = new BasicPatternConverter(m_formattingInfo, RELATIVE_TIME_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 't':
pc = new BasicPatternConverter(m_formattingInfo, THREAD_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 'u':
pc = new BasicPatternConverter(m_formattingInfo, IDENTITY_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 'W':
pc = new BasicPatternConverter(m_formattingInfo, USERNAME_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 'x':
pc = new BasicPatternConverter(m_formattingInfo, NDC_CONVERTER);
m_currentLiteral.Length = 0;
break;
case 'X':
pc = new MDCPatternConverter(m_formattingInfo, this.ExtractOption());
m_currentLiteral.Length = 0;
break;
default:
LogLog.Error("PatternParser: Unexpected char ["+c+"] at position ["+m_index+"] in conversion pattern.");
pc = new LiteralPatternConverter(m_currentLiteral.ToString());
m_currentLiteral.Length = 0;
break;
}
AddConverter(pc);
}
/// <summary>
/// Resets the internal state of the parser and adds the specified pattern converter
/// to the chain.
/// </summary>
/// <param name="pc">The pattern converter to add.</param>
protected void AddConverter(PatternConverter pc)
{
m_currentLiteral.Length = 0;
// Add the pattern converter to the list.
AddToList(pc);
// Next pattern is assumed to be a literal.
m_state = LITERAL_STATE;
// Reset formatting info
m_formattingInfo.Reset();
}
#endregion Protected Instance Methods
#region Private Instance Methods
/// <summary>
/// Adds a pattern converter to the chain.
/// </summary>
/// <param name="pc">The converter to add.</param>
private void AddToList(PatternConverter pc)
{
if (m_head == null)
{
m_head = m_tail = pc;
}
else
{
m_tail.Next = pc;
m_tail = pc;
}
}
#endregion Private Instance Methods
#region Private Static Fields
private const char ESCAPE_CHAR = '%';
private const int LITERAL_STATE = 0;
private const int CONVERTER_STATE = 1;
private const int MINUS_STATE = 2;
private const int DOT_STATE = 3;
private const int MIN_STATE = 4;
private const int MAX_STATE = 5;
private const int FULL_LOCATION_CONVERTER = 1000;
private const int METHOD_LOCATION_CONVERTER = 1001;
private const int CLASS_LOCATION_CONVERTER = 1002;
private const int LINE_LOCATION_CONVERTER = 1003;
private const int FILE_LOCATION_CONVERTER = 1004;
private const int RELATIVE_TIME_CONVERTER = 2000;
private const int THREAD_CONVERTER = 2001;
private const int LEVEL_CONVERTER = 2002;
private const int NDC_CONVERTER = 2003;
private const int MESSAGE_CONVERTER = 2004;
private const int USERNAME_CONVERTER = 3000;
private const int IDENTITY_CONVERTER = 3001;
private const int APPDOMAIN_CONVERTER = 3002;
#endregion Private Static Fields
#region Private Instance Fields
private int m_state;
/// <summary>
/// the literal being parsed
/// </summary>
private StringBuilder m_currentLiteral = new StringBuilder(32);
/// <summary>
/// the total length of the pattern
/// </summary>
private int m_patternLength;
/// <summary>
/// the current index into the pattern
/// </summary>
private int m_index;
/// <summary>
/// The first pattern converter in the chain
/// </summary>
private PatternConverter m_head;
/// <summary>
/// the last pattern converter in the chain
/// </summary>
private PatternConverter m_tail;
/// <summary>
/// the formatting info object
/// </summary>
private FormattingInfo m_formattingInfo = new FormattingInfo();
/// <summary>
/// The pattern
/// </summary>
private string m_pattern;
#endregion Private Instance Fields
// ---------------------------------------------------------------------
// PatternConverters
// ---------------------------------------------------------------------
/// <summary>
/// Basic pattern converter
/// </summary>
internal class BasicPatternConverter : PatternConverter
{
private int m_type;
/// <summary>
/// Construct the pattern converter with formatting info and type
/// </summary>
/// <param name="formattingInfo">the formatting info</param>
/// <param name="type">the type of pattern</param>
internal BasicPatternConverter(FormattingInfo formattingInfo, int type) : base(formattingInfo)
{
m_type = type;
}
/// <summary>
/// To the conversion
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <returns>the result of converting the pattern</returns>
override protected string Convert(LoggingEvent loggingEvent)
{
switch(m_type)
{
case RELATIVE_TIME_CONVERTER:
return TimeDifferenceInMillis(LoggingEvent.StartTime, loggingEvent.TimeStamp).ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
case THREAD_CONVERTER:
return loggingEvent.ThreadName;
case LEVEL_CONVERTER:
return loggingEvent.Level.ToString();
case NDC_CONVERTER:
return loggingEvent.NestedContext;
case MESSAGE_CONVERTER:
return loggingEvent.RenderedMessage;
case USERNAME_CONVERTER:
return loggingEvent.UserName;
case IDENTITY_CONVERTER:
return loggingEvent.Identity;
case APPDOMAIN_CONVERTER:
return loggingEvent.Domain;
default:
return null;
}
}
/// <summary>
/// Internal method to get the time difference between two DateTime objects
/// </summary>
/// <param name="start">start time</param>
/// <param name="end">end time</param>
/// <returns>the time difference in milliseconds</returns>
private static long TimeDifferenceInMillis(DateTime start, DateTime end)
{
return ((end.Ticks - start.Ticks) / TimeSpan.TicksPerMillisecond);
}
}
/// <summary>
/// Pattern converter for literal instances in the pattern
/// </summary>
internal class LiteralPatternConverter : PatternConverter
{
private string m_literal;
/// <summary>
/// Constructor, takes the literal string
/// </summary>
/// <param name="strValue"></param>
internal LiteralPatternConverter(string strValue)
{
m_literal = strValue;
}
/// <summary>
/// Override the formatting behaviour to ignore the FormattingInfo
/// because we have a literal instead.
/// </summary>
/// <param name="buffer">the builder to write to</param>
/// <param name="loggingEvent">the event being logged</param>
override public void Format(StringBuilder buffer, LoggingEvent loggingEvent)
{
buffer.Append(m_literal);
}
/// <summary>
/// Convert this pattern into the rendered message
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <returns>the literal</returns>
override protected string Convert(LoggingEvent loggingEvent)
{
return m_literal;
}
}
/// <summary>
/// Mapped Diagnostic pattern converter
/// </summary>
internal class MDCPatternConverter : PatternConverter
{
private string m_key;
/// <summary>
/// Construct the pattern converter with formatting info and MDC key
/// </summary>
/// <param name="formattingInfo">the formatting info</param>
/// <param name="key">the MDC key to emit</param>
internal MDCPatternConverter(FormattingInfo formattingInfo, string key) : base(formattingInfo)
{
m_key = key;
}
/// <summary>
/// To the conversion
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <returns>the result of converting the pattern</returns>
override protected string Convert(LoggingEvent loggingEvent)
{
return loggingEvent.LookupMappedContext(m_key);
}
}
/// <summary>
/// Property pattern converter
/// </summary>
internal class PropertyPatternConverter : PatternConverter
{
private string m_key;
/// <summary>
/// Construct the pattern converter with formatting info and event property key
/// </summary>
/// <param name="formattingInfo">the formatting info</param>
/// <param name="key">the property key to emit</param>
internal PropertyPatternConverter(FormattingInfo formattingInfo, string key) : base(formattingInfo)
{
m_key = key;
}
/// <summary>
/// To the conversion
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <returns>the result of converting the pattern</returns>
override protected string Convert(LoggingEvent loggingEvent)
{
object prop = loggingEvent.Properties[m_key];
if (prop != null)
{
return prop.ToString();
}
return null;
}
}
/// <summary>
/// Date pattern converter, uses a <see cref="IDateFormatter"/> to format the date
/// </summary>
internal class DatePatternConverter : PatternConverter
{
private IDateFormatter m_df;
private DateTime m_date;
/// <summary>
/// Construct the converter with formatting info and a
/// <see cref="IDateFormatter"/> to format the date
/// </summary>
/// <param name="formattingInfo">the formatting info</param>
/// <param name="df">the date formatter</param>
internal DatePatternConverter(FormattingInfo formattingInfo, IDateFormatter df) : base(formattingInfo)
{
m_df = df;
}
/// <summary>
/// Convert the pattern into the rendered message
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <returns></returns>
override protected string Convert(LoggingEvent loggingEvent)
{
m_date = loggingEvent.TimeStamp;
string converted = null;
try
{
converted = m_df.FormatDate(m_date, new StringBuilder()).ToString();
}
catch (Exception ex)
{
LogLog.Error("PatternParser: Error occurred while converting date.", ex);
}
return converted;
}
}
/// <summary>
/// Converter to include event location information
/// </summary>
internal class LocationPatternConverter : PatternConverter
{
private int m_type;
/// <summary>
/// Construct the converter with formatting information and
/// the type of location information required.
/// </summary>
/// <param name="formattingInfo"></param>
/// <param name="type"></param>
internal LocationPatternConverter(FormattingInfo formattingInfo, int type) : base(formattingInfo)
{
m_type = type;
}
/// <summary>
/// Convert the pattern to the rendered message
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <returns>the relevant location information</returns>
override protected string Convert(LoggingEvent loggingEvent)
{
LocationInfo locationInfo = loggingEvent.LocationInformation;
switch(m_type)
{
case FULL_LOCATION_CONVERTER:
return locationInfo.FullInfo;
case METHOD_LOCATION_CONVERTER:
return locationInfo.MethodName;
case LINE_LOCATION_CONVERTER:
return locationInfo.LineNumber;
case FILE_LOCATION_CONVERTER:
return locationInfo.FileName;
default:
return null;
}
}
}
/// <summary>
/// Converter to deal with '.' separated strings
/// </summary>
internal abstract class NamedPatternConverter : PatternConverter
{
protected int m_precision;
/// <summary>
/// Construct a converter with formatting info and a precision
/// argument. The precision is the number of '.' separated sections
/// to return, starting from the end of the string and working
/// towards to the start.
/// </summary>
/// <param name="formattingInfo">the formatting info</param>
/// <param name="precision">the precision</param>
internal NamedPatternConverter(FormattingInfo formattingInfo, int precision) : base(formattingInfo)
{
m_precision = precision;
}
/// <summary>
/// Overridden by subclasses to get the fully qualified name before the
/// precision is applied to it.
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <returns>the fully qualified name</returns>
abstract protected string GetFullyQualifiedName(LoggingEvent loggingEvent);
/// <summary>
/// Convert the pattern to the rendered message
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <returns>the precision of the fully qualified name specified</returns>
override protected string Convert(LoggingEvent loggingEvent)
{
string n = GetFullyQualifiedName(loggingEvent);
if (m_precision <= 0)
{
return n;
}
else
{
int len = n.Length;
// We subtract 1 from 'len' when assigning to 'end' to avoid out of
// bounds exception in return r.substring(end+1, len). This can happen if
// precision is 1 and the logger name ends with a dot.
int end = len -1 ;
for(int i = m_precision; i > 0; i--)
{
end = n.LastIndexOf('.', end-1);
if (end == -1)
{
return n;
}
}
return n.Substring(end+1, len-end-1);
}
}
}
/// <summary>
/// Pattern converter for the class name
/// </summary>
internal class ClassNamePatternConverter : NamedPatternConverter
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="formattingInfo">formatting info</param>
/// <param name="precision">namespace depth precision</param>
internal ClassNamePatternConverter(FormattingInfo formattingInfo, int precision) : base(formattingInfo, precision)
{
}
/// <summary>
/// Gets the fully qualified name of the class
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <returns>the class name</returns>
override protected string GetFullyQualifiedName(LoggingEvent loggingEvent)
{
return loggingEvent.LocationInformation.ClassName;
}
}
/// <summary>
/// Converter for logger name
/// </summary>
internal class LoggerPatternConverter : NamedPatternConverter
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="formattingInfo">formatting info</param>
/// <param name="precision">logger hierarchy depth precision</param>
internal LoggerPatternConverter(FormattingInfo formattingInfo, int precision) : base(formattingInfo, precision)
{
}
/// <summary>
/// Gets the fully qualified name of the logger
/// </summary>
/// <param name="loggingEvent">the event being logged</param>
/// <returns>the logger name</returns>
override protected string GetFullyQualifiedName(LoggingEvent loggingEvent)
{
return loggingEvent.LoggerName;
}
}
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Metadata;
using Mono.Cecil.PE;
using NUnit.Framework;
namespace Mono.Cecil.Tests {
[TestFixture]
public class CustomAttributesTests : BaseTestFixture {
[Test]
public void StringArgumentOnType ()
{
TestCSharp ("CustomAttributes.cs", module => {
var hamster = module.GetType ("Hamster");
Assert.IsTrue (hamster.HasCustomAttributes);
Assert.AreEqual (1, hamster.CustomAttributes.Count);
var attribute = hamster.CustomAttributes [0];
Assert.AreEqual ("System.Void FooAttribute::.ctor(System.String)",
attribute.Constructor.FullName);
Assert.IsTrue (attribute.HasConstructorArguments);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
AssertArgument ("bar", attribute.ConstructorArguments [0]);
});
}
[Test]
public void NullString ()
{
TestCSharp ("CustomAttributes.cs", module => {
var dentist = module.GetType ("Dentist");
var attribute = GetAttribute (dentist, "Foo");
Assert.IsNotNull (attribute);
AssertArgument<string> (null, attribute.ConstructorArguments [0]);
});
}
[Test]
public void Primitives1 ()
{
TestCSharp ("CustomAttributes.cs", module => {
var steven = module.GetType ("Steven");
var attribute = GetAttribute (steven, "Foo");
Assert.IsNotNull (attribute);
AssertArgument<sbyte> (-12, attribute.ConstructorArguments [0]);
AssertArgument<byte> (242, attribute.ConstructorArguments [1]);
AssertArgument<bool> (true, attribute.ConstructorArguments [2]);
AssertArgument<bool> (false, attribute.ConstructorArguments [3]);
AssertArgument<ushort> (4242, attribute.ConstructorArguments [4]);
AssertArgument<short> (-1983, attribute.ConstructorArguments [5]);
AssertArgument<char> ('c', attribute.ConstructorArguments [6]);
});
}
[Test]
public void Primitives2 ()
{
TestCSharp ("CustomAttributes.cs", module => {
var seagull = module.GetType ("Seagull");
var attribute = GetAttribute (seagull, "Foo");
Assert.IsNotNull (attribute);
AssertArgument<int> (-100000, attribute.ConstructorArguments [0]);
AssertArgument<uint> (200000, attribute.ConstructorArguments [1]);
AssertArgument<float> (12.12f, attribute.ConstructorArguments [2]);
AssertArgument<long> (long.MaxValue, attribute.ConstructorArguments [3]);
AssertArgument<ulong> (ulong.MaxValue, attribute.ConstructorArguments [4]);
AssertArgument<double> (64.646464, attribute.ConstructorArguments [5]);
});
}
[Test]
public void StringArgumentOnAssembly ()
{
TestCSharp ("CustomAttributes.cs", module => {
var assembly = module.Assembly;
var attribute = GetAttribute (assembly, "Foo");
Assert.IsNotNull (attribute);
AssertArgument ("bingo", attribute.ConstructorArguments [0]);
});
}
[Test]
public void CharArray ()
{
TestCSharp ("CustomAttributes.cs", module => {
var rifle = module.GetType ("Rifle");
var attribute = GetAttribute (rifle, "Foo");
Assert.IsNotNull (attribute);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Char[]", argument.Type.FullName);
var array = argument.Value as CustomAttributeArgument [];
Assert.IsNotNull (array);
var str = "cecil";
Assert.AreEqual (array.Length, str.Length);
for (int i = 0; i < str.Length; i++)
AssertArgument (str [i], array [i]);
});
}
[Test]
public void BoxedArguments ()
{
TestCSharp ("CustomAttributes.cs", module => {
var worm = module.GetType ("Worm");
var attribute = GetAttribute (worm, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (".ctor ((Object:(String:\"2\")), (Object:(I4:2)))", PrettyPrint (attribute));
});
}
[Test]
public void BoxedArraysArguments ()
{
TestCSharp ("CustomAttributes.cs", module => {
var sheep = module.GetType ("Sheep");
var attribute = GetAttribute (sheep, "Foo");
Assert.IsNotNull (attribute);
// [Foo (new object [] { "2", 2, 'c' }, new object [] { new object [] { 1, 2, 3}, null })]
AssertCustomAttribute (".ctor ((Object:(Object[]:{(Object:(String:\"2\")), (Object:(I4:2)), (Object:(Char:'c'))})), (Object:(Object[]:{(Object:(Object[]:{(Object:(I4:1)), (Object:(I4:2)), (Object:(I4:3))})), (Object:(String:null))})))", attribute);
});
}
[Test]
public void FieldsAndProperties ()
{
TestCSharp ("CustomAttributes.cs", module => {
var angola = module.GetType ("Angola");
var attribute = GetAttribute (angola, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (2, attribute.Fields.Count);
var argument = attribute.Fields.Where (a => a.Name == "Pan").First ();
AssertCustomAttributeArgument ("(Object:(Object[]:{(Object:(I4:1)), (Object:(String:\"2\")), (Object:(Char:'3'))}))", argument);
argument = attribute.Fields.Where (a => a.Name == "PanPan").First ();
AssertCustomAttributeArgument ("(String[]:{(String:\"yo\"), (String:\"yo\")})", argument);
Assert.AreEqual (2, attribute.Properties.Count);
argument = attribute.Properties.Where (a => a.Name == "Bang").First ();
AssertArgument (42, argument);
argument = attribute.Properties.Where (a => a.Name == "Fiou").First ();
AssertArgument<string> (null, argument);
});
}
[Test]
public void BoxedStringField ()
{
TestCSharp ("CustomAttributes.cs", module => {
var type = module.GetType ("BoxedStringField");
var attribute = GetAttribute (type, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.Fields.Count);
var argument = attribute.Fields.Where (a => a.Name == "Pan").First ();
AssertCustomAttributeArgument ("(Object:(String:\"fiouuu\"))", argument);
});
}
[Test]
public void TypeDefinitionEnum ()
{
TestCSharp ("CustomAttributes.cs", module => {
var zero = module.GetType ("Zero");
var attribute = GetAttribute (zero, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
Assert.AreEqual ((short) 2, attribute.ConstructorArguments [0].Value);
Assert.AreEqual ("Bingo", attribute.ConstructorArguments [0].Type.FullName);
});
}
[Test]
public void TypeReferenceEnum ()
{
TestCSharp ("CustomAttributes.cs", module => {
var ace = module.GetType ("Ace");
var attribute = GetAttribute (ace, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
Assert.AreEqual ((byte) 0x04, attribute.ConstructorArguments [0].Value);
Assert.AreEqual ("System.Security.AccessControl.AceFlags", attribute.ConstructorArguments [0].Type.FullName);
Assert.AreEqual (module, attribute.ConstructorArguments [0].Type.Module);
});
}
[Test]
public void BoxedEnumReference ()
{
TestCSharp ("CustomAttributes.cs", module => {
var bzzz = module.GetType ("Bzzz");
var attribute = GetAttribute (bzzz, "Foo");
Assert.IsNotNull (attribute);
// [Foo (new object [] { Bingo.Fuel, Bingo.Binga }, null, Pan = System.Security.AccessControl.AceFlags.NoPropagateInherit)]
Assert.AreEqual (2, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
AssertCustomAttributeArgument ("(Object:(Object[]:{(Object:(Bingo:2)), (Object:(Bingo:4))}))", argument);
argument = attribute.ConstructorArguments [1];
AssertCustomAttributeArgument ("(Object:(String:null))", argument);
argument = attribute.Fields.Where (a => a.Name == "Pan").First ().Argument;
AssertCustomAttributeArgument ("(Object:(System.Security.AccessControl.AceFlags:4))", argument);
});
}
[Test]
public void TypeOfTypeDefinition ()
{
TestCSharp ("CustomAttributes.cs", module => {
var typed = module.GetType ("Typed");
var attribute = GetAttribute (typed, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeDefinition;
Assert.IsNotNull (type);
Assert.AreEqual ("Bingo", type.FullName);
});
}
[Test]
public void TypeOfNestedTypeDefinition ()
{
TestCSharp ("CustomAttributes.cs", module => {
var typed = module.GetType ("NestedTyped");
var attribute = GetAttribute (typed, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeDefinition;
Assert.IsNotNull (type);
Assert.AreEqual ("FooAttribute/Token", type.FullName);
});
}
[Test]
public void FieldTypeOf ()
{
TestCSharp ("CustomAttributes.cs", module => {
var truc = module.GetType ("Truc");
var attribute = GetAttribute (truc, "Foo");
Assert.IsNotNull (attribute);
var argument = attribute.Fields.Where (a => a.Name == "Chose").First ().Argument;
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeDefinition;
Assert.IsNotNull (type);
Assert.AreEqual ("Typed", type.FullName);
});
}
[Test]
public void EscapedTypeName ()
{
TestModule ("bug-185.dll", module => {
var foo = module.GetType ("Foo");
var foo_do = foo.Methods.Where (m => !m.IsConstructor).First ();
var attribute = foo_do.CustomAttributes.Where (ca => ca.AttributeType.Name == "AsyncStateMachineAttribute").First ();
Assert.AreEqual (foo.NestedTypes [0], attribute.ConstructorArguments [0].Value);
var function = module.GetType ("Function`1");
var apply = function.Methods.Where(m => !m.IsConstructor).First ();
attribute = apply.CustomAttributes.Where (ca => ca.AttributeType.Name == "AsyncStateMachineAttribute").First ();
Assert.AreEqual (function.NestedTypes [0], attribute.ConstructorArguments [0].Value);
});
}
[Test]
public void FieldNullTypeOf ()
{
TestCSharp ("CustomAttributes.cs", module => {
var truc = module.GetType ("Machin");
var attribute = GetAttribute (truc, "Foo");
Assert.IsNotNull (attribute);
var argument = attribute.Fields.Where (a => a.Name == "Chose").First ().Argument;
Assert.AreEqual ("System.Type", argument.Type.FullName);
Assert.IsNull (argument.Value);
});
}
[Test]
public void OpenGenericTypeOf ()
{
TestCSharp ("CustomAttributes.cs", module => {
var open_generic = module.GetType ("OpenGeneric`2");
Assert.IsNotNull (open_generic);
var attribute = GetAttribute (open_generic, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeReference;
Assert.IsNotNull (type);
Assert.AreEqual ("System.Collections.Generic.Dictionary`2", type.FullName);
});
}
[Test]
public void ClosedGenericTypeOf ()
{
TestCSharp ("CustomAttributes.cs", module => {
var closed_generic = module.GetType ("ClosedGeneric");
Assert.IsNotNull (closed_generic);
var attribute = GetAttribute (closed_generic, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeReference;
Assert.IsNotNull (type);
Assert.AreEqual ("System.Collections.Generic.Dictionary`2<System.String,OpenGeneric`2<Machin,System.Int32>[,]>", type.FullName);
});
}
[Test]
public void TypeOfArrayOfNestedClass ()
{
TestCSharp ("CustomAttributes.cs", module => {
var parent = module.GetType ("Parent");
Assert.IsNotNull (parent);
var attribute = GetAttribute (parent, "Foo");
Assert.IsNotNull (attribute);
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
var argument = attribute.ConstructorArguments [0];
Assert.AreEqual ("System.Type", argument.Type.FullName);
var type = argument.Value as TypeReference;
Assert.IsNotNull (type);
Assert.AreEqual ("Parent/Child[]", type.FullName);
});
}
[Test]
public void EmptyBlob ()
{
TestIL ("ca-empty-blob.il", module => {
var attribute = module.GetType ("CustomAttribute");
Assert.AreEqual (1, attribute.CustomAttributes.Count);
Assert.AreEqual (0, attribute.CustomAttributes [0].ConstructorArguments.Count);
}, verify: !Platform.OnMono);
}
[Test]
public void InterfaceImplementation ()
{
OnlyOnWindows (); // Mono's ilasm doesn't support .interfaceimpl
TestIL ("ca-iface-impl.il", module => {
var type = module.GetType ("FooType");
var iface = type.Interfaces.Single (i => i.InterfaceType.FullName == "IFoo");
Assert.IsTrue (iface.HasCustomAttributes);
var attributes = iface.CustomAttributes;
Assert.AreEqual (1, attributes.Count);
Assert.AreEqual ("FooAttribute", attributes [0].AttributeType.FullName);
});
}
[Test]
public void GenericParameterConstraint ()
{
TestModule ("GenericParameterConstraintAttributes.dll", module => {
var type = module.GetType ("Foo.Library`1");
var gp = type.GenericParameters.Single ();
var constraint = gp.Constraints.Single ();
Assert.IsTrue (constraint.HasCustomAttributes);
var attributes = constraint.CustomAttributes;
Assert.AreEqual (1, attributes.Count);
Assert.AreEqual ("System.Runtime.CompilerServices.NullableAttribute", attributes [0].AttributeType.FullName);
}, verify: !Platform.OnMono);
}
[Test]
public void NullCharInString ()
{
TestCSharp ("CustomAttributes.cs", module => {
var type = module.GetType ("NullCharInString");
var attributes = type.CustomAttributes;
Assert.AreEqual (1, attributes.Count);
var attribute = attributes [0];
Assert.AreEqual (1, attribute.ConstructorArguments.Count);
var value = (string) attribute.ConstructorArguments [0].Value;
Assert.AreEqual (8, value.Length);
Assert.AreEqual ('\0', value [7]);
});
}
[Test]
public void OrderedAttributes ()
{
TestModule ("ordered-attrs.exe", module => {
var type = module.GetType ("Program");
var method = type.GetMethod ("Main");
var attributes = method.CustomAttributes;
Assert.AreEqual (6, attributes.Count);
Assert.AreEqual ("AAttribute", attributes [0].AttributeType.Name);
Assert.AreEqual ("Main.A1", attributes [0].Fields [0].Argument.Value as string);
Assert.AreEqual ("AAttribute", attributes [1].AttributeType.Name);
Assert.AreEqual ("Main.A2", attributes [1].Fields [0].Argument.Value as string);
Assert.AreEqual ("BAttribute", attributes [2].AttributeType.Name);
Assert.AreEqual ("Main.B1", attributes [2].Fields [0].Argument.Value as string);
Assert.AreEqual ("AAttribute", attributes [3].AttributeType.Name);
Assert.AreEqual ("Main.A3", attributes [3].Fields [0].Argument.Value as string);
Assert.AreEqual ("BAttribute", attributes [4].AttributeType.Name);
Assert.AreEqual ("Main.B2", attributes [4].Fields [0].Argument.Value as string);
Assert.AreEqual ("BAttribute", attributes [5].AttributeType.Name);
Assert.AreEqual ("Main.B3", attributes [5].Fields [0].Argument.Value as string);
});
}
[Test]
public void DefineCustomAttributeFromBlob ()
{
var file = Path.Combine (Path.GetTempPath (), "CaBlob.dll");
var module = ModuleDefinition.CreateModule ("CaBlob.dll", new ModuleParameters { Kind = ModuleKind.Dll, Runtime = TargetRuntime.Net_2_0 });
var assembly_title_ctor = module.ImportReference (typeof (System.Reflection.AssemblyTitleAttribute).GetConstructor (new [] {typeof (string)}));
Assert.IsNotNull (assembly_title_ctor);
var buffer = new ByteBuffer ();
buffer.WriteUInt16 (1); // ca signature
var title = Encoding.UTF8.GetBytes ("CaBlob");
buffer.WriteCompressedUInt32 ((uint) title.Length);
buffer.WriteBytes (title);
buffer.WriteUInt16 (0); // named arguments
var blob = new byte [buffer.length];
Buffer.BlockCopy (buffer.buffer, 0, blob, 0, buffer.length);
var attribute = new CustomAttribute (assembly_title_ctor, blob);
module.Assembly.CustomAttributes.Add (attribute);
module.Write (file);
module = ModuleDefinition.ReadModule (file);
attribute = GetAttribute (module.Assembly, "AssemblyTitle");
Assert.IsNotNull (attribute);
Assert.AreEqual ("CaBlob", (string) attribute.ConstructorArguments [0].Value);
module.Dispose ();
}
static void AssertCustomAttribute (string expected, CustomAttribute attribute)
{
Assert.AreEqual (expected, PrettyPrint (attribute));
}
static void AssertCustomAttributeArgument (string expected, CustomAttributeNamedArgument named_argument)
{
AssertCustomAttributeArgument (expected, named_argument.Argument);
}
static void AssertCustomAttributeArgument (string expected, CustomAttributeArgument argument)
{
var result = new StringBuilder ();
PrettyPrint (argument, result);
Assert.AreEqual (expected, result.ToString ());
}
static string PrettyPrint (CustomAttribute attribute)
{
var signature = new StringBuilder ();
signature.Append (".ctor (");
for (int i = 0; i < attribute.ConstructorArguments.Count; i++) {
if (i > 0)
signature.Append (", ");
PrettyPrint (attribute.ConstructorArguments [i], signature);
}
signature.Append (")");
return signature.ToString ();
}
static void PrettyPrint (CustomAttributeArgument argument, StringBuilder signature)
{
var value = argument.Value;
signature.Append ("(");
PrettyPrint (argument.Type, signature);
signature.Append (":");
PrettyPrintValue (argument.Value, signature);
signature.Append (")");
}
static void PrettyPrintValue (object value, StringBuilder signature)
{
if (value == null) {
signature.Append ("null");
return;
}
var arguments = value as CustomAttributeArgument [];
if (arguments != null) {
signature.Append ("{");
for (int i = 0; i < arguments.Length; i++) {
if (i > 0)
signature.Append (", ");
PrettyPrint (arguments [i], signature);
}
signature.Append ("}");
return;
}
switch (Type.GetTypeCode (value.GetType ())) {
case System.TypeCode.String:
signature.AppendFormat ("\"{0}\"", value);
break;
case System.TypeCode.Char:
signature.AppendFormat ("'{0}'", (char) value);
break;
default:
var formattable = value as IFormattable;
if (formattable != null) {
signature.Append (formattable.ToString (null, CultureInfo.InvariantCulture));
return;
}
if (value is CustomAttributeArgument) {
PrettyPrint ((CustomAttributeArgument) value, signature);
return;
}
break;
}
}
static void PrettyPrint (TypeReference type, StringBuilder signature)
{
if (type.IsArray) {
ArrayType array = (ArrayType) type;
signature.AppendFormat ("{0}[]", array.ElementType.etype.ToString ());
} else if (type.etype == ElementType.None) {
signature.Append (type.FullName);
} else
signature.Append (type.etype.ToString ());
}
static void AssertArgument<T> (T value, CustomAttributeNamedArgument named_argument)
{
AssertArgument (value, named_argument.Argument);
}
static void AssertArgument<T> (T value, CustomAttributeArgument argument)
{
AssertArgument (typeof (T).FullName, (object) value, argument);
}
static void AssertArgument (string type, object value, CustomAttributeArgument argument)
{
Assert.AreEqual (type, argument.Type.FullName);
Assert.AreEqual (value, argument.Value);
}
static CustomAttribute GetAttribute (ICustomAttributeProvider owner, string type)
{
Assert.IsTrue (owner.HasCustomAttributes);
foreach (var attribute in owner.CustomAttributes)
if (attribute.Constructor.DeclaringType.Name.StartsWith (type))
return attribute;
return null;
}
}
}
| |
/* This class has been written by
* Corinna John (Hannover, Germany)
* cj@binary-universe.net
*
* You may do with this code whatever you like,
* except selling it or claiming any rights/ownership.
*
* Please send me a little feedback about what you're
* using this code for and what changes you'd like to
* see in later versions. (And please excuse my bad english.)
*
* WARNING: This is experimental code.
* Please do not expect "Release Quality".
* */
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
namespace CameraLib.AVI
{
public class VideoStream : AviStream
{
/// <summary>handle for AVIStreamGetFrame</summary>
private int getFrameObject;
/// <summary>size of an imge in bytes, stride*height</summary>
private int frameSize;
public int FrameSize {
get { return frameSize; }
}
protected double frameRate;
public double FrameRate {
get{ return frameRate; }
}
private int width;
public int Width{
get{ return width; }
}
private int height;
public int Height{
get{ return height; }
}
private Int16 countBitsPerPixel;
public Int16 CountBitsPerPixel {
get{ return countBitsPerPixel; }
}
/// <summary>count of frames in the stream</summary>
protected int countFrames = 0;
public int CountFrames{
get{ return countFrames; }
}
/// <summary>Palette for indexed frames</summary>
protected Avi.RGBQUAD[] palette;
public Avi.RGBQUAD[] Palette{
get { return palette; }
}
/// <summary>initial frame index</summary>
/// <remarks>Added by M. Covington</remarks>
protected int firstFrame = 0;
public int FirstFrame
{
get { return firstFrame; }
}
private Avi.AVICOMPRESSOPTIONS compressOptions;
public Avi.AVICOMPRESSOPTIONS CompressOptions {
get { return compressOptions; }
}
public Avi.AVISTREAMINFO StreamInfo {
get { return GetStreamInfo(aviStream); }
}
/// <summary>Initialize an empty VideoStream</summary>
/// <param name="aviFile">The file that contains the stream</param>
/// <param name="writeCompressed">true: Create a compressed stream before adding frames</param>
/// <param name="frameRate">Frames per second</param>
/// <param name="frameSize">Size of one frame in bytes</param>
/// <param name="width">Width of each image</param>
/// <param name="height">Height of each image</param>
/// <param name="format">PixelFormat of the images</param>
public VideoStream(int aviFile, bool writeCompressed, double frameRate, int frameSize, int width, int height, PixelFormat format) {
this.aviFile = aviFile;
this.writeCompressed = writeCompressed;
this.frameRate = frameRate;
this.frameSize = frameSize;
this.width = width;
this.height = height;
this.countBitsPerPixel = ConvertPixelFormatToBitCount(format);
this.firstFrame = 0;
CreateStream();
}
/// <summary>Initialize a new VideoStream and add the first frame</summary>
/// <param name="aviFile">The file that contains the stream</param>
/// <param name="writeCompressed">true: create a compressed stream before adding frames</param>
/// <param name="frameRate">Frames per second</param>
/// <param name="firstFrame">Image to write into the stream as the first frame</param>
public VideoStream(int aviFile, bool writeCompressed, double frameRate, Bitmap firstFrame) {
Initialize(aviFile, writeCompressed, frameRate, firstFrame);
CreateStream();
AddFrame(firstFrame);
}
/// <summary>Initialize a new VideoStream and add the first frame</summary>
/// <param name="aviFile">The file that contains the stream</param>
/// <param name="writeCompressed">true: create a compressed stream before adding frames</param>
/// <param name="frameRate">Frames per second</param>
/// <param name="firstFrame">Image to write into the stream as the first frame</param>
public VideoStream(int aviFile, Avi.AVICOMPRESSOPTIONS compressOptions, double frameRate, Bitmap firstFrame) {
Initialize(aviFile, true, frameRate, firstFrame);
CreateStream(compressOptions);
AddFrame(firstFrame);
}
/// <summary>Initialize a VideoStream for an existing stream</summary>
/// <param name="aviFile">The file that contains the stream</param>
/// <param name="aviStream">An IAVISTREAM from [aviFile]</param>
public VideoStream(int aviFile, IntPtr aviStream){
this.aviFile = aviFile;
this.aviStream = aviStream;
Avi.AVISTREAMINFO streamInfo = GetStreamInfo(aviStream);
//Avi.BITMAPINFOHEADER bih = new Avi.BITMAPINFOHEADER();
//int size = Marshal.SizeOf(bih);
Avi.BITMAPINFO bih = new Avi.BITMAPINFO();
int size = Marshal.SizeOf(bih.bmiHeader);
Avi.AVIStreamReadFormat(aviStream, 0, ref bih, ref size);
if (bih.bmiHeader.biBitCount < 24)
{
size = Marshal.SizeOf(bih.bmiHeader) + Avi.PALETTE_SIZE;
Avi.AVIStreamReadFormat(aviStream, 0, ref bih, ref size);
CopyPalette(bih.bmiColors);
}
this.frameRate = (float)streamInfo.dwRate / (float)streamInfo.dwScale;
this.width = (int)streamInfo.rcFrame.right;
this.height = (int)streamInfo.rcFrame.bottom;
this.frameSize = bih.bmiHeader.biSizeImage;
this.countBitsPerPixel = bih.bmiHeader.biBitCount;
this.firstFrame = Avi.AVIStreamStart(aviStream.ToInt32());
this.countFrames = Avi.AVIStreamLength(aviStream.ToInt32());
}
/// <summary>Copy all properties from one VideoStream to another one</summary>
/// <remarks>Used by EditableVideoStream</remarks>
/// <param name="frameSize"></param><param name="frameRate"></param>
/// <param name="width"></param><param name="height"></param>
/// <param name="countBitsPerPixel"></param>
/// <param name="countFrames"></param><param name="compressOptions"></param>
internal VideoStream(int frameSize, double frameRate, int width, int height, Int16 countBitsPerPixel, int countFrames, Avi.AVICOMPRESSOPTIONS compressOptions, bool writeCompressed) {
this.frameSize = frameSize;
this.frameRate = frameRate;
this.width = width;
this.height = height;
this.countBitsPerPixel = countBitsPerPixel;
this.countFrames = countFrames;
this.compressOptions = compressOptions;
this.writeCompressed = writeCompressed;
this.firstFrame = 0;
}
/// <summary>Copy a palette</summary>
/// <param name="template">Original palette</param>
private void CopyPalette(ColorPalette template)
{
this.palette = new Avi.RGBQUAD[template.Entries.Length];
for (int n = 0; n < this.palette.Length; n++)
{
if (n < template.Entries.Length)
{
this.palette[n].rgbRed = template.Entries[n].R;
this.palette[n].rgbGreen = template.Entries[n].G;
this.palette[n].rgbBlue = template.Entries[n].B;
}
else
{
this.palette[n].rgbRed = 0;
this.palette[n].rgbGreen = 0;
this.palette[n].rgbBlue = 0;
}
}
}
/// <summary>Copy a palette</summary>
/// <param name="template">Original palette</param>
private void CopyPalette(Avi.RGBQUAD[] template)
{
this.palette = new Avi.RGBQUAD[template.Length];
for (int n = 0; n < this.palette.Length; n++)
{
if (n < template.Length)
{
this.palette[n].rgbRed = template[n].rgbRed;
this.palette[n].rgbGreen = template[n].rgbGreen;
this.palette[n].rgbBlue = template[n].rgbBlue;
}
else
{
this.palette[n].rgbRed = 0;
this.palette[n].rgbGreen = 0;
this.palette[n].rgbBlue = 0;
}
}
}
/// <summary>Initialize a new VideoStream</summary>
/// <remarks>Used only by constructors</remarks>
/// <param name="aviFile">The file that contains the stream</param>
/// <param name="writeCompressed">true: create a compressed stream before adding frames</param>
/// <param name="frameRate">Frames per second</param>
/// <param name="firstFrame">Image to write into the stream as the first frame</param>
private void Initialize(int aviFile, bool writeCompressed, double frameRate, Bitmap firstFrameBitmap) {
this.aviFile = aviFile;
this.writeCompressed = writeCompressed;
this.frameRate = frameRate;
this.firstFrame = 0;
CopyPalette(firstFrameBitmap.Palette);
BitmapData bmpData = firstFrameBitmap.LockBits(new Rectangle(
0, 0, firstFrameBitmap.Width, firstFrameBitmap.Height),
ImageLockMode.ReadOnly, firstFrameBitmap.PixelFormat);
this.frameSize = bmpData.Stride * bmpData.Height;
this.width = firstFrameBitmap.Width;
this.height = firstFrameBitmap.Height;
this.countBitsPerPixel = ConvertPixelFormatToBitCount(firstFrameBitmap.PixelFormat);
firstFrameBitmap.UnlockBits(bmpData);
}
/// <summary>Get the count of bits per pixel from a PixelFormat value</summary>
/// <param name="format">One of the PixelFormat members beginning with "Format..." - all others are not supported</param>
/// <returns>bit count</returns>
private Int16 ConvertPixelFormatToBitCount(PixelFormat format){
String formatName = format.ToString();
if(formatName.Substring(0, 6) != "Format"){
throw new Exception("Unknown pixel format: "+formatName);
}
formatName = formatName.Substring(6, 2);
Int16 bitCount = 0;
if( Char.IsNumber(formatName[1]) ){ //16, 32, 48
bitCount = Int16.Parse(formatName);
}else{ //4, 8
bitCount = Int16.Parse(formatName[0].ToString());
}
return bitCount;
}
/// <summary>Returns a PixelFormat value for a specific bit count</summary>
/// <param name="bitCount">count of bits per pixel</param>
/// <returns>A PixelFormat value for [bitCount]</returns>
private PixelFormat ConvertBitCountToPixelFormat(int bitCount){
String formatName;
if(bitCount > 16){
formatName = String.Format("Format{0}bppRgb", bitCount);
}else if(bitCount == 16){
formatName = "Format16bppRgb555";
}else{ // < 16
formatName = String.Format("Format{0}bppIndexed", bitCount);
}
return (PixelFormat)Enum.Parse(typeof(PixelFormat), formatName);
}
private Avi.AVISTREAMINFO GetStreamInfo(IntPtr aviStream){
Avi.AVISTREAMINFO streamInfo = new Avi.AVISTREAMINFO();
int result = Avi.AVIStreamInfo(StreamPointer, ref streamInfo, Marshal.SizeOf(streamInfo));
if(result != 0) {
throw new Exception("Exception in VideoStreamInfo: "+result.ToString());
}
return streamInfo;
}
private void GetRateAndScale(ref double frameRate, ref int scale) {
scale = 1;
while (frameRate != (long)frameRate) {
frameRate = frameRate * 10;
scale *= 10;
}
}
/// <summary>Create a new stream</summary>
private void CreateStreamWithoutFormat() {
int scale = 1;
double rate = frameRate;
GetRateAndScale(ref rate, ref scale);
Avi.AVISTREAMINFO strhdr = new Avi.AVISTREAMINFO();
strhdr.fccType = Avi.mmioStringToFOURCC("vids", 0);
strhdr.fccHandler = Avi.mmioStringToFOURCC("CVID", 0);
strhdr.dwFlags = 0;
strhdr.dwCaps = 0;
strhdr.wPriority = 0;
strhdr.wLanguage = 0;
strhdr.dwScale = (int)scale;
strhdr.dwRate = (int)rate; // Frames per Second
strhdr.dwStart = 0;
strhdr.dwLength = 0;
strhdr.dwInitialFrames = 0;
strhdr.dwSuggestedBufferSize = frameSize; //height_ * stride_;
strhdr.dwQuality = -1; //default
strhdr.dwSampleSize = 0;
strhdr.rcFrame.top = 0;
strhdr.rcFrame.left = 0;
strhdr.rcFrame.bottom = (uint)height;
strhdr.rcFrame.right = (uint)width;
strhdr.dwEditCount = 0;
strhdr.dwFormatChangeCount = 0;
strhdr.szName = new UInt16[64];
int result = Avi.AVIFileCreateStream(aviFile, out aviStream, ref strhdr);
if (result != 0) {
throw new Exception("Exception in AVIFileCreateStream: " + result.ToString());
}
}
/// <summary>Create a new stream</summary>
private void CreateStream() {
CreateStreamWithoutFormat();
if (writeCompressed) {
CreateCompressedStream();
} else {
//SetFormat(aviStream, 0);
}
}
/// <summary>Create a new stream</summary>
private void CreateStream(Avi.AVICOMPRESSOPTIONS options){
CreateStreamWithoutFormat();
CreateCompressedStream(options);
}
/// <summary>Create a compressed stream from an uncompressed stream</summary>
private void CreateCompressedStream(){
//display the compression options dialog...
Avi.AVICOMPRESSOPTIONS_CLASS options = new Avi.AVICOMPRESSOPTIONS_CLASS();
//options.fccType = (uint)Avi.streamtypeVIDEO;
//options.lpParms = IntPtr.Zero;
//options.lpFormat = IntPtr.Zero;
//Avi.AVISaveOptions(IntPtr.Zero, Avi.ICMF_CHOOSE_KEYFRAME | Avi.ICMF_CHOOSE_DATARATE, 1, ref aviStream, ref options);
//..or set static options
Avi.AVICOMPRESSOPTIONS opts = new Avi.AVICOMPRESSOPTIONS();
opts.fccType = (UInt32)Avi.mmioStringToFOURCC("vids", 0);
opts.fccHandler = (UInt32)Avi.mmioStringToFOURCC("XVID", 0);
//opts.fccType = 0;
//opts.fccHandler = 1684633208;
opts.dwKeyFrameEvery = 0;
opts.dwQuality = 0; // 0 .. 10000
opts.dwFlags = 8; // AVICOMRPESSF_KEYFRAMES = 4
opts.dwBytesPerSecond = 0;
opts.lpFormat = new IntPtr(0);
opts.cbFormat = 0;
opts.lpParms = Marshal.AllocHGlobal(sizeof(int));
opts.cbParms = 0;
opts.dwInterleaveEvery = 0;
//get the compressed stream
//this.compressOptions = options.ToStruct();
this.compressOptions = opts;
int result = Avi.AVIMakeCompressedStream(out compressedStream, aviStream, ref compressOptions, 0);
if(result != 0) {
throw new Exception("Exception in AVIMakeCompressedStream: "+result.ToString());
}
//Avi.AVISaveOptionsFree(1, ref options);
SetFormat(compressedStream, 0);
}
/// <summary>Create a compressed stream from an uncompressed stream</summary>
private void CreateCompressedStream(Avi.AVICOMPRESSOPTIONS options) {
int result = Avi.AVIMakeCompressedStream(out compressedStream, aviStream, ref options, 0);
if (result != 0) {
throw new Exception("Exception in AVIMakeCompressedStream: " + result.ToString());
}
this.compressOptions = options;
SetFormat(compressedStream, 0);
}
/// <summary>Add one frame to a new stream</summary>
/// <param name="bmp"></param>
/// <remarks>
/// This works only with uncompressed streams,
/// and compressed streams that have not been saved yet.
/// Use DecompressToNewFile to edit saved compressed streams.
/// </remarks>
public void AddFrame(Bitmap bmp){
bmp.RotateFlip(RotateFlipType.RotateNoneFlipY);
// NEW 2012-11-10
if (countFrames == 0)
{
CopyPalette(bmp.Palette);
SetFormat(writeCompressed ? compressedStream : StreamPointer, countFrames);
}
BitmapData bmpDat = bmp.LockBits(
new Rectangle(
0,0, bmp.Width, bmp.Height),
ImageLockMode.ReadOnly, bmp.PixelFormat);
int result = Avi.AVIStreamWrite(writeCompressed ? compressedStream : StreamPointer,
countFrames, 1,
bmpDat.Scan0,
(Int32)(bmpDat.Stride * bmpDat.Height),
0, 0, 0);
if (result!= 0) {
throw new Exception("Exception in VideoStreamWrite: "+result.ToString());
}
bmp.UnlockBits(bmpDat);
countFrames++;
}
/// <summary>Apply a format to a new stream</summary>
/// <param name="aviStream">The IAVISTREAM</param>
/// <remarks>
/// The format must be set before the first frame can be written,
/// and it cannot be changed later.
/// </remarks>
private void SetFormat(IntPtr aviStream, int writePosition){
Avi.BITMAPINFO bi = new Avi.BITMAPINFO();
bi.bmiHeader.biWidth = width;
bi.bmiHeader.biHeight = height;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = countBitsPerPixel;
bi.bmiHeader.biSizeImage = frameSize;
bi.bmiHeader.biSize = Marshal.SizeOf(bi.bmiHeader);
if (countBitsPerPixel < 24)
{
bi.bmiHeader.biClrUsed = this.palette.Length;
bi.bmiHeader.biClrImportant = this.palette.Length;
bi.bmiColors = new Avi.RGBQUAD[this.palette.Length];
this.palette.CopyTo(bi.bmiColors, 0);
bi.bmiHeader.biSize += bi.bmiColors.Length * Avi.RGBQUAD_SIZE;
}
int result = Avi.AVIStreamSetFormat(aviStream, writePosition, ref bi, bi.bmiHeader.biSize);
if(result != 0){ throw new Exception("Error in VideoStreamSetFormat: "+ result.ToString("X")); }
}
/// <summary>Prepare for decompressing frames</summary>
/// <remarks>
/// This method has to be called before GetBitmap and ExportBitmap.
/// Release ressources with GetFrameClose.
/// </remarks>
public void GetFrameOpen(){
Avi.AVISTREAMINFO streamInfo = GetStreamInfo(StreamPointer);
//Open frames
Avi.BITMAPINFOHEADER bih = new Avi.BITMAPINFOHEADER();
bih.biBitCount = countBitsPerPixel;
bih.biClrImportant = 0;
bih.biClrUsed = 0;
bih.biCompression = 0;
bih.biPlanes = 1;
bih.biSize = Marshal.SizeOf(bih);
bih.biXPelsPerMeter = 0;
bih.biYPelsPerMeter = 0;
// Corrections by M. Covington:
// If these are pre-set, interlaced video is not handled correctly.
// Better to give zeroes and let Windows fill them in.
bih.biHeight = 0; // was (Int32)streamInfo.rcFrame.bottom;
bih.biWidth = 0; // was (Int32)streamInfo.rcFrame.right;
// Corrections by M. Covington:
// Validate the bit count, because some AVI files give a bit count
// that is not one of the allowed values in a BitmapInfoHeader.
// Here 0 means for Windows to figure it out from other information.
if (bih.biBitCount > 24)
{
bih.biBitCount = 32;
}
else if (bih.biBitCount > 16)
{
bih.biBitCount = 24;
}
else if (bih.biBitCount > 8)
{
bih.biBitCount = 16;
}
else if (bih.biBitCount > 4)
{
bih.biBitCount = 8;
}
else if (bih.biBitCount > 0)
{
bih.biBitCount = 4;
}
getFrameObject = Avi.AVIStreamGetFrameOpen(StreamPointer, ref bih);
if(getFrameObject == 0){ throw new Exception("Exception in VideoStreamGetFrameOpen!"); }
}
/// <summary>Export a frame into a bitmap file</summary>
/// <param name="position">Position of the frame</param>
/// <param name="dstFileName">Name of the file to store the bitmap</param>
public void ExportBitmap(int position, String dstFileName){
Bitmap bmp = GetBitmap(position);
bmp.Save(dstFileName, ImageFormat.Bmp);
bmp.Dispose();
}
/// <summary>Export a frame into a bitmap</summary>
/// <param name="position">Position of the frame</param>
public Bitmap GetBitmap(int position){
if(position > countFrames){
throw new Exception("Invalid frame position: "+position);
}
Avi.AVISTREAMINFO streamInfo = GetStreamInfo(StreamPointer);
Avi.BITMAPINFO bih = new Avi.BITMAPINFO();
int headerSize = Marshal.SizeOf(bih.bmiHeader);
//Decompress the frame and return a pointer to the DIB
int dib = Avi.AVIStreamGetFrame(getFrameObject, firstFrame + position);
//Copy the bitmap header into a managed struct
bih.bmiColors = this.palette;
bih.bmiHeader = (Avi.BITMAPINFOHEADER)Marshal.PtrToStructure(new IntPtr(dib), bih.bmiHeader.GetType());
if (bih.bmiHeader.biSizeImage < 1)
{
throw new Exception("Exception in VideoStreamGetFrame");
}
//copy the image
int framePaletteSize = bih.bmiHeader.biClrUsed * Avi.RGBQUAD_SIZE;
byte[] bitmapData = new byte[bih.bmiHeader.biSizeImage];
IntPtr dibPointer = new IntPtr(dib + Marshal.SizeOf(bih.bmiHeader) + framePaletteSize);
Marshal.Copy(dibPointer, bitmapData, 0, bih.bmiHeader.biSizeImage);
//copy bitmap info
byte[] bitmapInfo = new byte[Marshal.SizeOf(bih)];
IntPtr ptr = Marshal.AllocHGlobal(bitmapInfo.Length);
Marshal.StructureToPtr(bih, ptr, false);
Marshal.Copy(ptr, bitmapInfo, 0, bitmapInfo.Length);
Marshal.FreeHGlobal(ptr);
//create file header
Avi.BITMAPFILEHEADER bfh = new Avi.BITMAPFILEHEADER();
bfh.bfType = Avi.BMP_MAGIC_COOKIE;
bfh.bfSize = (Int32)(55 + bih.bmiHeader.biSizeImage); //size of file as written to disk
bfh.bfReserved1 = 0;
bfh.bfReserved2 = 0;
bfh.bfOffBits = Marshal.SizeOf(bih) + Marshal.SizeOf(bfh);
if(bih.bmiHeader.biBitCount < 8){
//There is a palette between header and pixel data
bfh.bfOffBits += bih.bmiHeader.biClrUsed * Avi.RGBQUAD_SIZE; //Avi.PALETTE_SIZE;
}
//write a bitmap stream
BinaryWriter bw = new BinaryWriter( new MemoryStream() );
//write header
bw.Write(bfh.bfType);
bw.Write(bfh.bfSize);
bw.Write(bfh.bfReserved1);
bw.Write(bfh.bfReserved2);
bw.Write(bfh.bfOffBits);
//write bitmap info
bw.Write(bitmapInfo);
//write bitmap data
bw.Write(bitmapData);
Bitmap bmp = (Bitmap)Image.FromStream(bw.BaseStream);
Bitmap saveableBitmap = new Bitmap(bmp.Width, bmp.Height);
Graphics g = Graphics.FromImage(saveableBitmap);
g.DrawImage(bmp, 0,0);
g.Dispose();
bmp.Dispose();
bw.Close();
return saveableBitmap;
}
/// <summary>Free ressources that have been used by GetFrameOpen</summary>
public void GetFrameClose(){
if(getFrameObject != 0){
Avi.AVIStreamGetFrameClose(getFrameObject);
getFrameObject = 0;
}
}
/// <summary>Copy all frames into a new file</summary>
/// <param name="fileName">Name of the new file</param>
/// <param name="recompress">true: Compress the new stream</param>
/// <returns>AviManager for the new file</returns>
/// <remarks>Use this method if you want to append frames to an existing, compressed stream</remarks>
public AviManager DecompressToNewFile(String fileName, bool recompress, out VideoStream newStream2){
AviManager newFile = new AviManager(fileName, false);
this.GetFrameOpen();
Bitmap frame = GetBitmap(0);
VideoStream newStream = newFile.AddVideoStream(recompress, frameRate, frame);
frame.Dispose();
for(int n=1; n<countFrames; n++){
frame = GetBitmap(n);
newStream.AddFrame(frame);
frame.Dispose();
}
this.GetFrameClose();
newStream2 = newStream;
return newFile;
}
/// <summary>Copy the stream into a new file</summary>
/// <param name="fileName">Name of the new file</param>
public override void ExportStream(String fileName){
Avi.AVICOMPRESSOPTIONS_CLASS opts = new Avi.AVICOMPRESSOPTIONS_CLASS();
opts.fccType = (uint)Avi.streamtypeVIDEO;
opts.lpParms = IntPtr.Zero;
opts.lpFormat = IntPtr.Zero;
IntPtr streamPointer = StreamPointer;
Avi.AVISaveOptions(IntPtr.Zero, Avi.ICMF_CHOOSE_KEYFRAME | Avi.ICMF_CHOOSE_DATARATE, 1, ref streamPointer, ref opts);
Avi.AVISaveOptionsFree(1, ref opts);
Avi.AVISaveV(fileName, 0, 0, 1, ref aviStream, ref opts);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using Xunit;
using Xunit.Abstractions;
using static System.Runtime.InteropServices.MemoryMarshal;
namespace System.Slices.Tests
{
public class UsageScenarioTests
{
private readonly ITestOutputHelper output;
public UsageScenarioTests(ITestOutputHelper output)
{
this.output = output;
}
private struct MyByte
{
public MyByte(byte value)
{
Value = value;
}
public byte Value { get; private set; }
}
[Theory]
[InlineData(new byte[] { })]
[InlineData(new byte[] { 0 })]
[InlineData(new byte[] { 0, 1 })]
[InlineData(new byte[] { 0, 1, 2 })]
[InlineData(new byte[] { 0, 1, 2, 3 })]
[InlineData(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 })]
public void CtorSpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array)
{
Span<byte> span = new Span<byte>(array);
Assert.Equal(array.Length, span.Length);
for (int i = 0; i < span.Length; i++)
{
Assert.Equal(array[i], Read<byte>(span.Slice(i)));
Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value);
array[i] = unchecked((byte)(array[i] + 1));
Assert.Equal(array[i], Read<byte>(span.Slice(i)));
Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value);
var byteValue = unchecked((byte)(array[i] + 1));
Write(span.Slice(i), ref byteValue);
Assert.Equal(array[i], Read<byte>(span.Slice(i)));
Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value);
var myByteValue = unchecked(new MyByte((byte)(array[i] + 1)));
Write(span.Slice(i), ref myByteValue);
Assert.Equal(array[i], Read<byte>(span.Slice(i)));
Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value);
}
}
[Theory]
[InlineData(new byte[] { })]
[InlineData(new byte[] { 0 })]
[InlineData(new byte[] { 0, 1 })]
[InlineData(new byte[] { 0, 1, 2 })]
[InlineData(new byte[] { 0, 1, 2, 3 })]
[InlineData(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 })]
public void CtorReadOnlySpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array)
{
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(array);
Assert.Equal(array.Length, span.Length);
for (int i = 0; i < span.Length; i++)
{
Assert.Equal(array[i], Read<byte>(span.Slice(i)));
Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value);
array[i] = unchecked((byte)(array[i] + 1));
Assert.Equal(array[i], Read<byte>(span.Slice(i)));
Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value);
}
}
[Theory]
// copy whole buffer
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 6)]
// copy first half to first half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 3)]
// copy second half to second half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3,
new byte[] { 1, 2, 3, 7, 7, 7 }, 3, 3)]
// copy first half to first half
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 0
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 3
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting at the end
[InlineData(
new byte[] { 7, 7, 7, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy first byte of 1 element array to last position
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 6 }, 0, 1,
new byte[] { 1, 2, 3, 4, 5, 7 }, 5, 1)]
// copy first two bytes of 2 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6, 7 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy last two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 5, 6 }, 1, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 2 element array to the middle of other array
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 3, 4 }, 0, 2,
new byte[] { 1, 2, 7, 7, 5, 6 }, 2, 3)]
// copy one byte from the beginning at the end of other array
[InlineData(
null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
// copy one byte from the beginning at the end of other array
[InlineData(
null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 4, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
public void SpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount)
{
if (expected != null)
{
Span<byte> spanA = new Span<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
spanA.CopyTo(spanB);
Assert.Equal(expected, b);
Span<byte> spanExpected = new Span<byte>(expected);
Span<byte> spanBAll = new Span<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else
{
Span<byte> spanA = new Span<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
try
{
spanA.CopyTo(spanB);
Assert.True(false);
}
catch (Exception)
{
Assert.True(true);
}
}
}
[Theory]
// copy whole buffer
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 6)]
// copy first half to first half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 3)]
// copy second half to second half (length match)
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3,
new byte[] { 1, 2, 3, 7, 7, 7 }, 3, 3)]
// copy first half to first half
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 0
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting from index 3
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0,
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)]
// copy no bytes starting at the end
[InlineData(
new byte[] { 7, 7, 7, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0,
new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)]
// copy first byte of 1 element array to last position
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 6 }, 0, 1,
new byte[] { 1, 2, 3, 4, 5, 7 }, 5, 1)]
// copy first two bytes of 2 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 5, 6, 7 }, 0, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy last two bytes of 3 element array to last two positions
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 5, 6 }, 1, 2,
new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)]
// copy first two bytes of 2 element array to the middle of other array
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 3, 4 }, 0, 2,
new byte[] { 1, 2, 7, 7, 5, 6 }, 2, 3)]
// copy one byte from the beginning at the end of other array
[InlineData(
null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
// copy one byte from the beginning at the end of other array
[InlineData(
null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1,
new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)]
// copy two bytes from the beginning at 5th element
[InlineData(
null,
new byte[] { 7, 7, 7, 7, 7, 7 }, 4, 2,
new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)]
public void ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount)
{
if (expected != null)
{
ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
spanA.CopyTo(spanB);
Assert.Equal(expected, b);
ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected);
ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else
{
ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount);
Span<byte> spanB = new Span<byte>(b, bidx, bcount);
try
{
spanA.CopyTo(spanB);
Assert.True(false);
}
catch (Exception)
{
Assert.True(true);
}
}
ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCasesNative(expected, a, aidx, acount, b, bidx, bcount);
}
public unsafe void ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCasesNative(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount)
{
IntPtr pa = Marshal.AllocHGlobal(a.Length);
Span<byte> na = new Span<byte>(pa.ToPointer(), a.Length);
a.CopyTo(na);
IntPtr pb = Marshal.AllocHGlobal(b.Length);
Span<byte> nb = new Span<byte>(pb.ToPointer(), b.Length);
b.CopyTo(nb);
ReadOnlySpan<byte> spanA = na.Slice(aidx, acount);
Span<byte> spanB = nb.Slice(bidx, bcount);
if (expected != null) {
spanA.CopyTo(spanB);
Assert.Equal(expected, b);
ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected);
ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else {
try
{
spanA.CopyTo(spanB);
Assert.True(false);
}
catch (Exception)
{
Assert.True(true);
}
}
Marshal.FreeHGlobal(pa);
Marshal.FreeHGlobal(pb);
}
[Theory]
// copy whole buffer
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6,
new byte[] { 7, 7, 7, 7, 7, 7 })]
// copy first half
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 })]
// copy second half
[InlineData(
new byte[] { 4, 5, 6, 7, 7, 7 },
new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3,
new byte[] { 7, 7, 7, 7, 7, 7 })]
// copy no bytes starting from index 0
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0,
new byte[] { 1, 2, 3, 4, 5, 6 })]
// copy no bytes starting from index 3
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0,
new byte[] { 1, 2, 3, 4, 5, 6 })]
// copy no bytes starting at the end
[InlineData(
new byte[] { 7, 7, 7, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0,
new byte[] { 7, 7, 7, 4, 5, 6 })]
// copy first byte of 1 element array
[InlineData(
new byte[] { 6, 2, 3, 4, 5, 6 },
new byte[] { 6 }, 0, 1,
new byte[] { 1, 2, 3, 4, 5, 6 })]
public void SpanCopyToArrayTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b)
{
if (expected != null)
{
Span<byte> spanA = new Span<byte>(a, aidx, acount);
spanA.CopyTo(b);
Assert.Equal(expected, b);
Span<byte> spanExpected = new Span<byte>(expected);
Span<byte> spanBAll = new Span<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else
{
Span<byte> spanA = new Span<byte>(a, aidx, acount);
try
{
spanA.CopyTo(b);
Assert.True(false);
}
catch (Exception)
{
Assert.True(true);
}
}
}
[Theory]
// copy whole buffer
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6,
new byte[] { 7, 7, 7, 7, 7, 7 })]
// copy first half
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3,
new byte[] { 7, 7, 7, 4, 5, 6 })]
// copy second half
[InlineData(
new byte[] { 4, 5, 6, 7, 7, 7 },
new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3,
new byte[] { 7, 7, 7, 7, 7, 7 })]
// copy no bytes starting from index 0
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0,
new byte[] { 1, 2, 3, 4, 5, 6 })]
// copy no bytes starting from index 3
[InlineData(
new byte[] { 1, 2, 3, 4, 5, 6 },
new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0,
new byte[] { 1, 2, 3, 4, 5, 6 })]
// copy no bytes starting at the end
[InlineData(
new byte[] { 7, 7, 7, 4, 5, 6 },
new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0,
new byte[] { 7, 7, 7, 4, 5, 6 })]
// copy first byte of 1 element array
[InlineData(
new byte[] { 6, 2, 3, 4, 5, 6 },
new byte[] { 6 }, 0, 1,
new byte[] { 1, 2, 3, 4, 5, 6 })]
public void ROSpanCopyToArrayTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b)
{
if (expected != null)
{
ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount);
spanA.CopyTo(b);
Assert.Equal(expected, b);
ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected);
ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b);
Assert.True(spanExpected.SequenceEqual(spanBAll));
}
else
{
ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount);
try
{
spanA.CopyTo(b);
Assert.True(false);
}
catch (Exception)
{
Assert.True(true);
}
}
}
}
}
| |
namespace Gu.Wpf.UiAutomation.UiTests.Input
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using NUnit.Framework;
public class MouseTests
{
private const string ExeFileName = "WpfApplication.exe";
private const string WindowName = "MouseWindow";
[SetUp]
public void SetUp()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
app.MainWindow.FindButton("Clear").Click();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
Application.KillLaunched(ExeFileName);
}
[Test]
public void Position()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.TopLeft;
Wait.UntilInputIsProcessed();
var expected = new List<string>
{
"MouseEnter Position: 0,0",
"PreviewMouseMove Position: 0,0",
"MouseMove Position: 0,0",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
Mouse.Position = mouseArea.Bounds.Center();
Wait.UntilInputIsProcessed();
expected.AddRange(new[]
{
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
});
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void MoveBy()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
Mouse.MoveBy(-20, 0);
Mouse.MoveBy(0, -20);
Mouse.MoveBy(20, 20);
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseMove Position: 230,300",
"MouseMove Position: 230,300",
"PreviewMouseMove Position: 230,280",
"MouseMove Position: 230,280",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void MoveTo()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
Mouse.MoveTo(mouseArea.Bounds.Center() + new Vector(-20, 0));
Mouse.MoveTo(mouseArea.Bounds.Center() + new Vector(-20, -20));
Mouse.MoveTo(mouseArea.Bounds.Center());
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseMove Position: 230,300",
"MouseMove Position: 230,300",
"PreviewMouseMove Position: 230,280",
"MouseMove Position: 230,280",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[TestCase(0)]
[TestCase(200)]
public void MoveToWithDuration(int milliseconds)
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
Mouse.MoveTo(mouseArea.Bounds.Center() + new Vector(-20, 0), TimeSpan.FromMilliseconds(milliseconds));
Mouse.MoveTo(mouseArea.Bounds.Center() + new Vector(-20, -20), TimeSpan.FromMilliseconds(milliseconds));
Mouse.MoveTo(mouseArea.Bounds.Center(), TimeSpan.FromMilliseconds(milliseconds));
Wait.UntilInputIsProcessed();
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseMove Position: 230,300",
"MouseMove Position: 230,300",
"PreviewMouseMove Position: 230,280",
"MouseMove Position: 230,280",
};
if (milliseconds == 0)
{
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
else
{
CollectionAssert.IsSubsetOf(expected, events.Items.Select(x => x.Text).ToArray());
}
}
[TestCase(2000)]
[TestCase(double.PositiveInfinity)]
public void MoveToWithSpeed(double speed)
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
Mouse.MoveTo(mouseArea.Bounds.Center() + new Vector(-20, 0), speed);
Mouse.MoveTo(mouseArea.Bounds.Center() + new Vector(-20, -20), speed);
Mouse.MoveTo(mouseArea.Bounds.Center(), speed);
Wait.UntilInputIsProcessed();
if (double.IsInfinity(speed))
{
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseMove Position: 230,300",
"MouseMove Position: 230,300",
"PreviewMouseMove Position: 230,280",
"MouseMove Position: 230,280",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
else
{
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseMove Position: 230,300",
"MouseMove Position: 230,300",
"PreviewMouseMove Position: 230,280",
"MouseMove Position: 230,280",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
}
[TestCase(0)]
[TestCase(200)]
public void MoveByWithDuration(int milliseconds)
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
Mouse.MoveBy(new Vector(-20, 0), TimeSpan.FromMilliseconds(milliseconds));
Mouse.MoveBy(new Vector(0, -20), TimeSpan.FromMilliseconds(milliseconds));
Mouse.MoveBy(new Vector(20, 20), TimeSpan.FromMilliseconds(milliseconds));
Wait.UntilInputIsProcessed();
if (milliseconds == 0)
{
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseMove Position: 230,300",
"MouseMove Position: 230,300",
"PreviewMouseMove Position: 230,280",
"MouseMove Position: 230,280",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
else
{
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseMove Position: 230,300",
"MouseMove Position: 230,300",
"PreviewMouseMove Position: 230,280",
"MouseMove Position: 230,280",
};
CollectionAssert.IsSubsetOf(expected, events.Items.Select(x => x.Text).ToArray());
}
}
[TestCase(200)]
[TestCase(2000)]
[TestCase(double.PositiveInfinity)]
public void MoveByWithSpeed(double speed)
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
Mouse.MoveBy(new Vector(-20, 0), speed);
Mouse.MoveBy(new Vector(0, -20), speed);
Mouse.MoveBy(new Vector(20, 20), speed);
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseMove Position: 230,300",
"MouseMove Position: 230,300",
"PreviewMouseMove Position: 230,280",
"MouseMove Position: 230,280",
};
CollectionAssert.IsSubsetOf(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void ClickMouseButtonLeft()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Click(MouseButton.Left, mouseArea.Bounds.Center());
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"PreviewMouseDown Position: 250,300 Button: Left Pressed",
"MouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"MouseDown Position: 250,300",
"PreviewMouseLeftButtonUp Position: 250,300 Button: Left Released",
"PreviewMouseUp Position: 250,300 Button: Left Released",
"MouseLeftButtonUp Position: 250,300 Button: Left Released",
"MouseUp Position: 250,300",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void ClickMouseButtonRight()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Click(MouseButton.Right, mouseArea.Bounds.Center());
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseRightButtonDown Position: 250,300 Button: Right Pressed",
"PreviewMouseDown Position: 250,300 Button: Right Pressed",
"MouseRightButtonDown Position: 250,300 Button: Right Pressed",
"MouseDown Position: 250,300",
"PreviewMouseRightButtonUp Position: 250,300 Button: Right Released",
"PreviewMouseUp Position: 250,300 Button: Right Released",
"MouseRightButtonUp Position: 250,300 Button: Right Released",
"MouseUp Position: 250,300",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void LeftClick()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.LeftClick(mouseArea.Bounds.Center());
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"PreviewMouseDown Position: 250,300 Button: Left Pressed",
"MouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"MouseDown Position: 250,300",
"PreviewMouseLeftButtonUp Position: 250,300 Button: Left Released",
"PreviewMouseUp Position: 250,300 Button: Left Released",
"MouseLeftButtonUp Position: 250,300 Button: Left Released",
"MouseUp Position: 250,300",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void RightClick()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.RightClick(mouseArea.Bounds.Center());
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseRightButtonDown Position: 250,300 Button: Right Pressed",
"PreviewMouseDown Position: 250,300 Button: Right Pressed",
"MouseRightButtonDown Position: 250,300 Button: Right Pressed",
"MouseDown Position: 250,300",
"PreviewMouseRightButtonUp Position: 250,300 Button: Right Released",
"PreviewMouseUp Position: 250,300 Button: Right Released",
"MouseRightButtonUp Position: 250,300 Button: Right Released",
"MouseUp Position: 250,300",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void LeftDoubleClick()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.DoubleClick(MouseButton.Left, mouseArea.Bounds.Center());
var expected = new[]
{
"MouseEnter Position: 250,300",
"PreviewMouseMove Position: 250,300",
"MouseMove Position: 250,300",
"PreviewMouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"PreviewMouseDown Position: 250,300 Button: Left Pressed",
"MouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"MouseDown Position: 250,300",
"PreviewMouseLeftButtonUp Position: 250,300 Button: Left Released",
"PreviewMouseUp Position: 250,300 Button: Left Released",
"MouseLeftButtonUp Position: 250,300 Button: Left Released",
"MouseUp Position: 250,300",
"PreviewMouseDoubleClick Position: 250,300 Button: Left Pressed",
"MouseDoubleClick Position: 250,300",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void LeftDownThenUp()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
app.MainWindow.FindButton("Clear").Invoke();
Mouse.Down(MouseButton.Left);
var expected = new List<string>
{
"PreviewMouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"PreviewMouseDown Position: 250,300 Button: Left Pressed",
"MouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"MouseDown Position: 250,300",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
Mouse.Up(MouseButton.Left);
expected.AddRange(new[]
{
"PreviewMouseLeftButtonUp Position: 250,300 Button: Left Released",
"PreviewMouseUp Position: 250,300 Button: Left Released",
"MouseLeftButtonUp Position: 250,300 Button: Left Released",
"MouseUp Position: 250,300",
});
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void RightDownThenUp()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
app.MainWindow.FindButton("Clear").Invoke();
Mouse.Down(MouseButton.Right);
var expected = new List<string>
{
"PreviewMouseRightButtonDown Position: 250,300 Button: Right Pressed",
"PreviewMouseDown Position: 250,300 Button: Right Pressed",
"MouseRightButtonDown Position: 250,300 Button: Right Pressed",
"MouseDown Position: 250,300",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
Mouse.Up(MouseButton.Right);
expected.AddRange(new[]
{
"PreviewMouseRightButtonUp Position: 250,300 Button: Right Released",
"PreviewMouseUp Position: 250,300 Button: Right Released",
"MouseRightButtonUp Position: 250,300 Button: Right Released",
"MouseUp Position: 250,300",
});
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void HoldLeft()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
app.MainWindow.FindButton("Clear").Invoke();
List<string> expected;
using (Mouse.Hold(MouseButton.Left))
{
expected = new List<string>
{
"PreviewMouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"PreviewMouseDown Position: 250,300 Button: Left Pressed",
"MouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"MouseDown Position: 250,300",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
expected.AddRange(new[]
{
"PreviewMouseLeftButtonUp Position: 250,300 Button: Left Released",
"PreviewMouseUp Position: 250,300 Button: Left Released",
"MouseLeftButtonUp Position: 250,300 Button: Left Released",
"MouseUp Position: 250,300",
});
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void HoldRight()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
app.MainWindow.FindButton("Clear").Invoke();
List<string> expected;
using (Mouse.Hold(MouseButton.Right))
{
expected = new List<string>
{
"PreviewMouseRightButtonDown Position: 250,300 Button: Right Pressed",
"PreviewMouseDown Position: 250,300 Button: Right Pressed",
"MouseRightButtonDown Position: 250,300 Button: Right Pressed",
"MouseDown Position: 250,300",
};
}
expected.AddRange(new[]
{
"PreviewMouseRightButtonUp Position: 250,300 Button: Right Released",
"PreviewMouseUp Position: 250,300 Button: Right Released",
"MouseRightButtonUp Position: 250,300 Button: Right Released",
"MouseUp Position: 250,300",
});
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void Drag()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
app.MainWindow.FindButton("Clear").Invoke();
Mouse.Drag(MouseButton.Left, mouseArea.Bounds.Center(), mouseArea.Bounds.Center() + new Vector(10, 20));
var expected = new[]
{
"PreviewMouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"PreviewMouseDown Position: 250,300 Button: Left Pressed",
"MouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"MouseDown Position: 250,300",
"PreviewMouseMove Position: 260,320",
"MouseMove Position: 260,320",
"PreviewMouseLeftButtonUp Position: 260,320 Button: Left Released",
"PreviewMouseUp Position: 260,320 Button: Left Released",
"MouseLeftButtonUp Position: 260,320 Button: Left Released",
"MouseUp Position: 260,320",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[TestCase(0)]
[TestCase(200)]
public void DragWithDuration(int milliseconds)
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
app.MainWindow.FindButton("Clear").Invoke();
Mouse.Drag(MouseButton.Left, mouseArea.Bounds.Center(), mouseArea.Bounds.Center() + new Vector(10, 20), TimeSpan.FromMilliseconds(milliseconds));
Wait.UntilInputIsProcessed();
var expected = new[]
{
"PreviewMouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"PreviewMouseDown Position: 250,300 Button: Left Pressed",
"MouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"MouseDown Position: 250,300",
"PreviewMouseMove Position: 260,320",
"MouseMove Position: 260,320",
"PreviewMouseLeftButtonUp Position: 260,320 Button: Left Released",
"PreviewMouseUp Position: 260,320 Button: Left Released",
"MouseLeftButtonUp Position: 260,320 Button: Left Released",
"MouseUp Position: 260,320",
};
if (milliseconds == 0)
{
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
else
{
CollectionAssert.IsSubsetOf(expected, events.Items.Select(x => x.Text).ToArray());
}
}
[Test]
public void DragDragHorizontally()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
app.MainWindow.FindButton("Clear").Invoke();
Mouse.DragHorizontally(MouseButton.Left, mouseArea.Bounds.Center(), 10);
var expected = new[]
{
"PreviewMouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"PreviewMouseDown Position: 250,300 Button: Left Pressed",
"MouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"MouseDown Position: 250,300",
"PreviewMouseMove Position: 260,300",
"MouseMove Position: 260,300",
"PreviewMouseLeftButtonUp Position: 260,300 Button: Left Released",
"PreviewMouseUp Position: 260,300 Button: Left Released",
"MouseLeftButtonUp Position: 260,300 Button: Left Released",
"MouseUp Position: 260,300",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[Test]
public void DragVertically()
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
app.MainWindow.FindButton("Clear").Invoke();
Mouse.DragVertically(MouseButton.Left, mouseArea.Bounds.Center(), 10);
var expected = new[]
{
"PreviewMouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"PreviewMouseDown Position: 250,300 Button: Left Pressed",
"MouseLeftButtonDown Position: 250,300 Button: Left Pressed",
"MouseDown Position: 250,300",
"PreviewMouseMove Position: 250,310",
"MouseMove Position: 250,310",
"PreviewMouseLeftButtonUp Position: 250,310 Button: Left Released",
"PreviewMouseUp Position: 250,310 Button: Left Released",
"MouseLeftButtonUp Position: 250,310 Button: Left Released",
"MouseUp Position: 250,310",
};
CollectionAssert.AreEqual(expected, events.Items.Select(x => x.Text).ToArray());
}
[TestCase(-2, "-240")]
[TestCase(-1, "-120")]
[TestCase(1, "120")]
[TestCase(2, "240")]
public void Scroll(int scroll, string expected)
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
app.MainWindow.FindButton("Clear").Invoke();
Mouse.Scroll(scroll);
var expecteds = new[]
{
$"PreviewMouseWheel Position: 250,300 {expected}",
$"MouseWheel Position: 250,300 {expected}",
};
CollectionAssert.AreEqual(expecteds, events.Items.Select(x => x.Text).ToArray());
}
[TestCase(-2, "-240")]
[TestCase(-1, "-120")]
[TestCase(1, "120")]
[TestCase(2, "240")]
public void HorizontalScroll(int scroll, string expected)
{
using var app = Application.AttachOrLaunch(ExeFileName, WindowName);
var window = app.MainWindow;
var mouseArea = window.FindGroupBox("Mouse area");
var events = window.FindListBox("Events");
Mouse.Position = mouseArea.Bounds.Center();
app.MainWindow.FindButton("Clear").Invoke();
Mouse.HorizontalScroll(scroll);
Assert.Inconclusive($"Not sure if we can detect any events here. Expected {expected}");
var expecteds = new[]
{
$"PreviewMouseWheel Position: 250,300 {expected}",
$"MouseWheel Position: 250,300 {expected}",
};
CollectionAssert.AreEqual(expecteds, events.Items.Select(x => x.Text).ToArray());
}
// ReSharper disable once UnusedMember.Local
private static void Dump(ListBox events)
{
foreach (var item in events.Items)
{
Console.WriteLine($"\"{item.Text}\",");
}
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmKeyboard
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmKeyboard() : base()
{
Load += frmKeyboard_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.Button withEventsField_cmdClose;
public System.Windows.Forms.Button cmdClose {
get { return withEventsField_cmdClose; }
set {
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click -= cmdClose_Click;
}
withEventsField_cmdClose = value;
if (withEventsField_cmdClose != null) {
withEventsField_cmdClose.Click += cmdClose_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdPrint;
public System.Windows.Forms.Button cmdPrint {
get { return withEventsField_cmdPrint; }
set {
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click -= cmdPrint_Click;
}
withEventsField_cmdPrint = value;
if (withEventsField_cmdPrint != null) {
withEventsField_cmdPrint.Click += cmdPrint_Click;
}
}
}
public System.Windows.Forms.Panel picButtons;
private myDataGridView withEventsField_gridEdit;
public myDataGridView gridEdit {
get { return withEventsField_gridEdit; }
set {
if (withEventsField_gridEdit != null) {
withEventsField_gridEdit.Click -= gridEdit_ClickEvent;
}
withEventsField_gridEdit = value;
if (withEventsField_gridEdit != null) {
withEventsField_gridEdit.Click += gridEdit_ClickEvent;
}
}
}
public System.Windows.Forms.Label Label1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmKeyboard));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.txtName = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdClose = new System.Windows.Forms.Button();
this.cmdPrint = new System.Windows.Forms.Button();
this.gridEdit = new myDataGridView();
this.Label1 = new System.Windows.Forms.Label();
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.gridEdit).BeginInit();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Keyboard Layout Editor";
this.ClientSize = new System.Drawing.Size(434, 611);
this.Location = new System.Drawing.Point(3, 29);
this.ControlBox = false;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.KeyPreview = false;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmKeyboard";
this.txtName.AutoSize = false;
this.txtName.Size = new System.Drawing.Size(301, 24);
this.txtName.Location = new System.Drawing.Point(125, 48);
this.txtName.TabIndex = 4;
this.txtName.Text = "Text1";
this.txtName.AcceptsReturn = true;
this.txtName.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtName.BackColor = System.Drawing.SystemColors.Window;
this.txtName.CausesValidation = true;
this.txtName.Enabled = true;
this.txtName.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtName.HideSelection = true;
this.txtName.ReadOnly = false;
this.txtName.MaxLength = 0;
this.txtName.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtName.Multiline = false;
this.txtName.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtName.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtName.TabStop = true;
this.txtName.Visible = true;
this.txtName.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtName.Name = "txtName";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.ForeColor = System.Drawing.SystemColors.WindowText;
this.picButtons.Size = new System.Drawing.Size(434, 44);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 1;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.picButtons.Name = "picButtons";
this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdClose.Text = "E&xit";
this.cmdClose.Size = new System.Drawing.Size(73, 29);
this.cmdClose.Location = new System.Drawing.Point(352, 6);
this.cmdClose.TabIndex = 3;
this.cmdClose.BackColor = System.Drawing.SystemColors.Control;
this.cmdClose.CausesValidation = true;
this.cmdClose.Enabled = true;
this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdClose.TabStop = true;
this.cmdClose.Name = "cmdClose";
this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPrint.Text = "&Print";
this.cmdPrint.Size = new System.Drawing.Size(73, 29);
this.cmdPrint.Location = new System.Drawing.Point(270, 6);
this.cmdPrint.TabIndex = 2;
this.cmdPrint.TabStop = false;
this.cmdPrint.BackColor = System.Drawing.SystemColors.Control;
this.cmdPrint.CausesValidation = true;
this.cmdPrint.Enabled = true;
this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPrint.Name = "cmdPrint";
//gridEdit.OcxState = CType(resources.GetObject("gridEdit.OcxState"), System.Windows.Forms.AxHost.State)
this.gridEdit.Size = new System.Drawing.Size(419, 526);
this.gridEdit.Location = new System.Drawing.Point(9, 75);
this.gridEdit.TabIndex = 0;
this.gridEdit.Name = "gridEdit";
this.Label1.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.Label1.Text = "Keyboard Name:";
this.Label1.ForeColor = System.Drawing.Color.Black;
this.Label1.Size = new System.Drawing.Size(117, 16);
this.Label1.Location = new System.Drawing.Point(6, 51);
this.Label1.TabIndex = 5;
this.Label1.BackColor = System.Drawing.Color.Transparent;
this.Label1.Enabled = true;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.UseMnemonic = true;
this.Label1.Visible = true;
this.Label1.AutoSize = true;
this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label1.Name = "Label1";
this.Controls.Add(txtName);
this.Controls.Add(picButtons);
this.Controls.Add(gridEdit);
this.Controls.Add(Label1);
this.picButtons.Controls.Add(cmdClose);
this.picButtons.Controls.Add(cmdPrint);
((System.ComponentModel.ISupportInitialize)this.gridEdit).EndInit();
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
namespace Nancy.Bootstrapper
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Nancy.Diagnostics;
using Nancy.ErrorHandling;
using Nancy.ModelBinding;
using Nancy.Routing;
using Nancy.Routing.Constraints;
using Nancy.Routing.Trie;
using Nancy.ViewEngines;
using Responses;
using Responses.Negotiation;
using Security;
using Nancy.Validation;
using Nancy.Culture;
using Nancy.Localization;
/// <summary>
/// Configuration class for Nancy's internals.
/// Contains implementation types/configuration for Nancy that usually
/// remain do not require overriding in "general use".
/// </summary>
public sealed class NancyInternalConfiguration
{
/// <summary>
/// Gets the Nancy default configuration
/// </summary>
public static NancyInternalConfiguration Default
{
get
{
return new NancyInternalConfiguration
{
RouteResolver = typeof(DefaultRouteResolver),
RoutePatternMatcher = typeof(DefaultRoutePatternMatcher),
ContextFactory = typeof(DefaultNancyContextFactory),
NancyEngine = typeof(NancyEngine),
RouteCache = typeof(RouteCache),
RouteCacheProvider = typeof(DefaultRouteCacheProvider),
ViewLocator = typeof(DefaultViewLocator),
ViewFactory = typeof(DefaultViewFactory),
NancyModuleBuilder = typeof(DefaultNancyModuleBuilder),
ResponseFormatterFactory = typeof(DefaultResponseFormatterFactory),
ModelBinderLocator = typeof(DefaultModelBinderLocator),
Binder = typeof(DefaultBinder),
BindingDefaults = typeof(BindingDefaults),
FieldNameConverter = typeof(DefaultFieldNameConverter),
ViewResolver = typeof(DefaultViewResolver),
ViewCache = typeof(DefaultViewCache),
RenderContextFactory = typeof(DefaultRenderContextFactory),
ModelValidatorLocator = typeof(DefaultValidatorLocator),
ViewLocationProvider = typeof(FileSystemViewLocationProvider),
StatusCodeHandlers = new List<Type>(AppDomainAssemblyTypeScanner.TypesOf<IStatusCodeHandler>(ScanMode.ExcludeNancy).Concat(new[] { typeof(DefaultStatusCodeHandler) })),
CsrfTokenValidator = typeof(DefaultCsrfTokenValidator),
ObjectSerializer = typeof(DefaultObjectSerializer),
Serializers = AppDomainAssemblyTypeScanner.TypesOf<ISerializer>(ScanMode.ExcludeNancy).Union(new List<Type>(new[] { typeof(DefaultJsonSerializer), typeof(DefaultXmlSerializer) })).ToList(),
InteractiveDiagnosticProviders = new List<Type>(AppDomainAssemblyTypeScanner.TypesOf<IDiagnosticsProvider>()),
RequestTracing = typeof(DefaultRequestTracing),
RouteInvoker = typeof(DefaultRouteInvoker),
ResponseProcessors = AppDomainAssemblyTypeScanner.TypesOf<IResponseProcessor>().ToList(),
RequestDispatcher = typeof(DefaultRequestDispatcher),
Diagnostics = typeof(DefaultDiagnostics),
RouteSegmentExtractor = typeof(DefaultRouteSegmentExtractor),
RouteDescriptionProvider = typeof(DefaultRouteDescriptionProvider),
CultureService = typeof(DefaultCultureService),
TextResource = typeof(ResourceBasedTextResource),
ResourceAssemblyProvider = typeof(ResourceAssemblyProvider),
ResourceReader = typeof(DefaultResourceReader),
StaticContentProvider = typeof(DefaultStaticContentProvider),
RouteResolverTrie = typeof(RouteResolverTrie),
TrieNodeFactory = typeof(TrieNodeFactory),
RouteSegmentConstraints = AppDomainAssemblyTypeScanner.TypesOf<IRouteSegmentConstraint>().ToList()
};
}
}
public Type RouteResolver { get; set; }
public Type RoutePatternMatcher { get; set; }
public Type ContextFactory { get; set; }
public Type NancyEngine { get; set; }
public Type RouteCache { get; set; }
public Type RouteCacheProvider { get; set; }
public Type ViewLocator { get; set; }
public Type ViewFactory { get; set; }
public Type NancyModuleBuilder { get; set; }
public Type ResponseFormatterFactory { get; set; }
public Type ModelBinderLocator { get; set; }
public Type Binder { get; set; }
public Type BindingDefaults { get; set; }
public Type FieldNameConverter { get; set; }
public Type ModelValidatorLocator { get; set; }
public Type ViewResolver { get; set; }
public Type ViewCache { get; set; }
public Type RenderContextFactory { get; set; }
public Type ViewLocationProvider { get; set; }
public IList<Type> StatusCodeHandlers { get; set; }
public Type CsrfTokenValidator { get; set; }
public Type ObjectSerializer { get; set; }
public IList<Type> Serializers { get; set; }
public IList<Type> InteractiveDiagnosticProviders { get; set; }
public Type RequestTracing { get; set; }
public Type RouteInvoker { get; set; }
public IList<Type> ResponseProcessors { get; set; }
public Type RequestDispatcher { get; set; }
public Type Diagnostics { get; set; }
public Type RouteSegmentExtractor { get; set; }
public Type RouteDescriptionProvider { get; set; }
public Type CultureService { get; set; }
public Type TextResource { get; set; }
public Type ResourceAssemblyProvider { get; set; }
public Type ResourceReader { get; set; }
public Type StaticContentProvider { get; set; }
public Type RouteResolverTrie { get; set; }
public Type TrieNodeFactory { get; set; }
public IList<Type> RouteSegmentConstraints { get; set; }
/// <summary>
/// Gets a value indicating whether the configuration is valid.
/// </summary>
public bool IsValid
{
get
{
try
{
return this.GetTypeRegistations().All(tr => tr.RegistrationType != null);
}
catch (ArgumentNullException)
{
return false;
}
}
}
/// <summary>
/// Default Nancy configuration with specific overloads
/// </summary>
/// <param name="configurationBuilder">Configuration builder for overriding the default configuration properties.</param>
/// <returns>Nancy configuration instance</returns>
public static NancyInternalConfiguration WithOverrides(Action<NancyInternalConfiguration> configurationBuilder)
{
var configuration = Default;
configurationBuilder.Invoke(configuration);
return configuration;
}
/// <summary>
/// Returns the configuration types as a TypeRegistration collection
/// </summary>
/// <returns>TypeRegistration collection representing the configurationt types</returns>
public IEnumerable<TypeRegistration> GetTypeRegistations()
{
return new[]
{
new TypeRegistration(typeof(IRouteResolver), this.RouteResolver),
new TypeRegistration(typeof(INancyEngine), this.NancyEngine),
new TypeRegistration(typeof(IRouteCache), this.RouteCache),
new TypeRegistration(typeof(IRouteCacheProvider), this.RouteCacheProvider),
new TypeRegistration(typeof(IRoutePatternMatcher), this.RoutePatternMatcher),
new TypeRegistration(typeof(IViewLocator), this.ViewLocator),
new TypeRegistration(typeof(IViewFactory), this.ViewFactory),
new TypeRegistration(typeof(INancyContextFactory), this.ContextFactory),
new TypeRegistration(typeof(INancyModuleBuilder), this.NancyModuleBuilder),
new TypeRegistration(typeof(IResponseFormatterFactory), this.ResponseFormatterFactory),
new TypeRegistration(typeof(IModelBinderLocator), this.ModelBinderLocator),
new TypeRegistration(typeof(IBinder), this.Binder),
new TypeRegistration(typeof(BindingDefaults), this.BindingDefaults),
new TypeRegistration(typeof(IFieldNameConverter), this.FieldNameConverter),
new TypeRegistration(typeof(IViewResolver), this.ViewResolver),
new TypeRegistration(typeof(IViewCache), this.ViewCache),
new TypeRegistration(typeof(IRenderContextFactory), this.RenderContextFactory),
new TypeRegistration(typeof(IViewLocationProvider), this.ViewLocationProvider),
new TypeRegistration(typeof(ICsrfTokenValidator), this.CsrfTokenValidator),
new TypeRegistration(typeof(IObjectSerializer), this.ObjectSerializer),
new TypeRegistration(typeof(IModelValidatorLocator), this.ModelValidatorLocator),
new TypeRegistration(typeof(IRequestTracing), this.RequestTracing),
new TypeRegistration(typeof(IRouteInvoker), this.RouteInvoker),
new TypeRegistration(typeof(IRequestDispatcher), this.RequestDispatcher),
new TypeRegistration(typeof(IDiagnostics), this.Diagnostics),
new TypeRegistration(typeof(IRouteSegmentExtractor), this.RouteSegmentExtractor),
new TypeRegistration(typeof(IRouteDescriptionProvider), this.RouteDescriptionProvider),
new TypeRegistration(typeof(ICultureService), this.CultureService),
new TypeRegistration(typeof(ITextResource), this.TextResource),
new TypeRegistration(typeof(IResourceAssemblyProvider), this.ResourceAssemblyProvider),
new TypeRegistration(typeof(IResourceReader), this.ResourceReader),
new TypeRegistration(typeof(IStaticContentProvider), this.StaticContentProvider),
new TypeRegistration(typeof(IRouteResolverTrie), this.RouteResolverTrie),
new TypeRegistration(typeof(ITrieNodeFactory), this.TrieNodeFactory),
};
}
/// <summary>
/// Returns the collection configuration types as a CollectionTypeRegistration collection
/// </summary>
/// <returns>CollectionTypeRegistration collection representing the configuration types</returns>
public IEnumerable<CollectionTypeRegistration> GetCollectionTypeRegistrations()
{
return new[]
{
new CollectionTypeRegistration(typeof(IResponseProcessor), this.ResponseProcessors),
new CollectionTypeRegistration(typeof(ISerializer), this.Serializers),
new CollectionTypeRegistration(typeof(IStatusCodeHandler), this.StatusCodeHandlers),
new CollectionTypeRegistration(typeof(IDiagnosticsProvider), this.InteractiveDiagnosticProviders),
new CollectionTypeRegistration(typeof(IRouteSegmentConstraint), this.RouteSegmentConstraints),
};
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Commands;
using Microsoft.PythonTools.Debugger;
using Microsoft.PythonTools.Debugger.DebugEngine;
using Microsoft.PythonTools.Debugger.Remote;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Intellisense;
using Microsoft.PythonTools.InteractiveWindow.Shell;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.InterpreterList;
using Microsoft.PythonTools.Navigation;
using Microsoft.PythonTools.Options;
using Microsoft.PythonTools.Project;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Navigation;
using Microsoft.VisualStudioTools.Project;
using NativeMethods = Microsoft.VisualStudioTools.Project.NativeMethods;
namespace Microsoft.PythonTools {
/// <summary>
/// This is the class that implements the package exposed by this assembly.
///
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell.
/// </summary>
[PackageRegistration(UseManagedResourcesOnly = true)] // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is a package.
// This attribute is used to register the informations needed to show the this package in the Help/About dialog of Visual Studio.
[InstalledProductRegistration("#110", "#112", AssemblyVersionInfo.Version, IconResourceID = 400)]
// This attribute is needed to let the shell know that this package exposes some menus.
[ProvideMenuResource(1000, 1)]
[ProvideKeyBindingTable(PythonConstants.EditorFactoryGuid, 3004, AllowNavKeyBinding = true)]
[Description("Python Tools Package")]
[ProvideAutomationObject("VsPython")]
[ProvideLanguageEditorOptionPage(typeof(PythonAdvancedEditorOptionsPage), PythonConstants.LanguageName, "", "Advanced", "113")]
[ProvideLanguageEditorOptionPage(typeof(PythonFormattingGeneralOptionsPage), PythonConstants.LanguageName, "Formatting", "General", "120")]
//[ProvideLanguageEditorOptionPage(typeof(PythonFormattingNewLinesOptionsPage), PythonConstants.LanguageName, "Formatting", "New Lines", "121")]
[ProvideLanguageEditorOptionPage(typeof(PythonFormattingSpacingOptionsPage), PythonConstants.LanguageName, "Formatting", "Spacing", "122")]
[ProvideLanguageEditorOptionPage(typeof(PythonFormattingStatementsOptionsPage), PythonConstants.LanguageName, "Formatting", "Statements", "123")]
[ProvideLanguageEditorOptionPage(typeof(PythonFormattingWrappingOptionsPage), PythonConstants.LanguageName, "Formatting", "Wrapping", "124")]
[ProvideOptionPage(typeof(PythonInteractiveOptionsPage), "Python Tools", "Interactive Windows", 115, 117, true)]
[ProvideOptionPage(typeof(PythonGeneralOptionsPage), "Python Tools", "General", 115, 120, true)]
[ProvideOptionPage(typeof(PythonDebuggingOptionsPage), "Python Tools", "Debugging", 115, 125, true)]
[Guid(GuidList.guidPythonToolsPkgString)] // our packages GUID
[ProvideLanguageService(typeof(PythonLanguageInfo), PythonConstants.LanguageName, 106, RequestStockColors = true, ShowSmartIndent = true, ShowCompletion = true, DefaultToInsertSpaces = true, HideAdvancedMembersByDefault = true, EnableAdvancedMembersOption = true, ShowDropDownOptions = true)]
[ProvideLanguageExtension(typeof(PythonLanguageInfo), PythonConstants.FileExtension)]
[ProvideLanguageExtension(typeof(PythonLanguageInfo), PythonConstants.WindowsFileExtension)]
[ProvideDebugEngine(AD7Engine.DebugEngineName, typeof(AD7ProgramProvider), typeof(AD7Engine), AD7Engine.DebugEngineId, hitCountBp: true)]
[ProvideDebugLanguage("Python", "{DA3C7D59-F9E4-4697-BEE7-3A0703AF6BFF}", PythonExpressionEvaluatorGuid, AD7Engine.DebugEngineId)]
[ProvideDebugPortSupplier("Python remote (ptvsd)", typeof(PythonRemoteDebugPortSupplier), PythonRemoteDebugPortSupplier.PortSupplierId, typeof(PythonRemoteDebugPortPicker))]
[ProvideDebugPortPicker(typeof(PythonRemoteDebugPortPicker))]
#region Exception List
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ArithmeticError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "AssertionError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "AttributeError", BreakByDefault = false)]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "BaseException")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "BufferError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "BytesWarning")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "DeprecationWarning")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "EOFError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "EnvironmentError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "Exception")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "FloatingPointError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "FutureWarning")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "GeneratorExit", BreakByDefault = false)]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "IOError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ImportError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ImportWarning")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "IndentationError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "IndexError", BreakByDefault = false)]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "KeyError", BreakByDefault = false)]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "KeyboardInterrupt")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "LookupError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "MemoryError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "NameError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "NotImplementedError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "BlockingIOError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ChildProcessError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "BrokenPipeError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "ConnectionAbortedError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "ConnectionRefusedError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ConnectionError", "ConnectionResetError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "FileExistsError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "FileNotFoundError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "InterruptedError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "IsADirectoryError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "NotADirectoryError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "PermissionError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "ProcessLookupError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OSError", "TimeoutError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "OverflowError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "PendingDeprecationWarning")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ReferenceError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "RuntimeError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "RuntimeWarning")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "StandardError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "StopIteration", BreakByDefault = false)]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SyntaxError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SyntaxWarning")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SystemError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "SystemExit")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "TabError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "TypeError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnboundLocalError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeDecodeError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeEncodeError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeTranslateError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UnicodeWarning")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "UserWarning")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ValueError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "Warning")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "WindowsError")]
[ProvideDebugException(AD7Engine.DebugEngineId, "Python Exceptions", "ZeroDivisionError")]
#endregion
[ProvideComponentPickerPropertyPage(typeof(PythonToolsPackage), typeof(WebPiComponentPickerControl), "WebPi", DefaultPageNameValue = "#4000")]
[ProvideToolWindow(typeof(InterpreterListToolWindow), Style = VsDockStyle.Linked, Window = ToolWindowGuids80.SolutionExplorer)]
[ProvideDiffSupportedContentType(".py;.pyw", "")]
[ProvideCodeExpansions(GuidList.guidPythonLanguageService, false, 106, "Python", @"Snippets\%LCID%\SnippetsIndex.xml", @"Snippets\%LCID%\Python\")]
[ProvideCodeExpansionPath("Python", "Test", @"Snippets\%LCID%\Test\")]
[ProvideInteractiveWindow(GuidList.guidPythonInteractiveWindow, Style = VsDockStyle.Linked, Orientation = ToolWindowOrientation.none, Window = ToolWindowGuids80.Outputwindow)]
[ProvideBraceCompletion(PythonCoreConstants.ContentType)]
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "Object is owned by VS and cannot be disposed")]
internal sealed class PythonToolsPackage : CommonPackage, IVsComponentSelectorProvider, IPythonToolsToolWindowService {
private PythonAutomation _autoObject;
private PackageContainer _packageContainer;
internal const string PythonExpressionEvaluatorGuid = "{D67D5DB8-3D44-4105-B4B8-47AB1BA66180}";
/// <summary>
/// Default constructor of the package.
/// Inside this method you can place any initialization code that does not require
/// any Visual Studio service because at this point the package object is created but
/// not sited yet inside Visual Studio environment. The place to do all the other
/// initialization is the Initialize method.
/// </summary>
public PythonToolsPackage() {
Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
#if DEBUG
System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (sender, e) => {
if (!e.Observed) {
var str = e.Exception.ToString();
if (str.Contains("Python")) {
try {
ActivityLog.LogError(
"UnobservedTaskException",
string.Format("An exception in a task was not observed: {0}", e.Exception.ToString())
);
} catch (InvalidOperationException) {
}
Debug.Fail("An exception in a task was not observed. See ActivityLog.xml for more details.", e.Exception.ToString());
}
e.SetObserved();
}
};
#endif
}
protected override int CreateToolWindow(ref Guid toolWindowType, int id) {
if (toolWindowType == GuidList.guidPythonInteractiveWindowGuid) {
var pyService = this.GetPythonToolsService();
var category = SelectableReplEvaluator.GetSettingsCategory(id.ToString());
string replId;
try {
replId = pyService.LoadString("Id", category);
} catch (Exception ex) when (!ex.IsCriticalException()) {
Debug.Fail("Could not load settings for interactive window.", ex.ToString());
pyService.DeleteCategory(category);
return VSConstants.S_OK;
}
pyService.ComponentModel.GetService<InteractiveWindowProvider>().Create(replId, id);
return VSConstants.S_OK;
}
return base.CreateToolWindow(ref toolWindowType, id);
}
internal static void NavigateTo(System.IServiceProvider serviceProvider, string filename, Guid docViewGuidType, int line, int col) {
VsUtilities.NavigateTo(serviceProvider, filename, docViewGuidType, line, col);
}
internal static void NavigateTo(System.IServiceProvider serviceProvider, string filename, Guid docViewGuidType, int pos) {
IVsTextView viewAdapter;
IVsWindowFrame pWindowFrame;
VsUtilities.OpenDocument(serviceProvider, filename, out viewAdapter, out pWindowFrame);
ErrorHandler.ThrowOnFailure(pWindowFrame.Show());
// Set the cursor at the beginning of the declaration.
int line, col;
ErrorHandler.ThrowOnFailure(viewAdapter.GetLineAndColumn(pos, out line, out col));
ErrorHandler.ThrowOnFailure(viewAdapter.SetCaretPos(line, col));
// Make sure that the text is visible.
viewAdapter.CenterLines(line, 1);
}
internal static ITextBuffer GetBufferForDocument(System.IServiceProvider serviceProvider, string filename) {
IVsTextView viewAdapter;
IVsWindowFrame frame;
VsUtilities.OpenDocument(serviceProvider, filename, out viewAdapter, out frame);
IVsTextLines lines;
ErrorHandler.ThrowOnFailure(viewAdapter.GetBuffer(out lines));
var adapter = serviceProvider.GetComponentModel().GetService<IVsEditorAdaptersFactoryService>();
return adapter.GetDocumentBuffer(lines);
}
internal static IProjectLauncher GetLauncher(IServiceProvider serviceProvider, IPythonProject project) {
var launchProvider = serviceProvider.GetUIThread().Invoke<string>(() => project.GetProperty(PythonConstants.LaunchProvider));
IPythonLauncherProvider defaultLaunchProvider = null;
foreach (var launcher in serviceProvider.GetComponentModel().GetExtensions<IPythonLauncherProvider>()) {
if (launcher.Name == launchProvider) {
return serviceProvider.GetUIThread().Invoke<IProjectLauncher>(() => launcher.CreateLauncher(project));
}
if (launcher.Name == DefaultLauncherProvider.DefaultLauncherName) {
defaultLaunchProvider = launcher;
}
}
// no launcher configured, use the default one.
Debug.Assert(defaultLaunchProvider != null);
return (defaultLaunchProvider != null) ?
serviceProvider.GetUIThread().Invoke<IProjectLauncher>(() => defaultLaunchProvider.CreateLauncher(project)) :
null;
}
ToolWindowPane IPythonToolsToolWindowService.GetWindowPane(Type windowType, bool create) {
return FindWindowPane(windowType, 0, create) as ToolWindowPane;
}
void IPythonToolsToolWindowService.ShowWindowPane(Type windowType, bool focus) {
var window = FindWindowPane(windowType, 0, true) as ToolWindowPane;
if (window != null) {
var frame = window.Frame as IVsWindowFrame;
if (frame != null) {
ErrorHandler.ThrowOnFailure(frame.Show());
}
if (focus) {
var content = window.Content as System.Windows.UIElement;
if (content != null) {
content.Focus();
}
}
}
}
internal static void OpenNoInterpretersHelpPage(System.IServiceProvider serviceProvider, string page = null) {
OpenVsWebBrowser(serviceProvider, page ?? PythonToolsInstallPath.GetFile("NoInterpreters.html"));
}
public static string InterpreterHelpUrl {
get {
return string.Format("http://go.microsoft.com/fwlink/?LinkId=299429&clcid=0x{0:X}",
CultureInfo.CurrentCulture.LCID);
}
}
protected override object GetAutomationObject(string name) {
if (name == "VsPython") {
if (_autoObject == null) {
_autoObject = new PythonAutomation(this);
}
return _autoObject;
}
return base.GetAutomationObject(name);
}
public override bool IsRecognizedFile(string filename) {
return ModulePath.IsPythonSourceFile(filename);
}
public override Type GetLibraryManagerType() {
return typeof(IPythonLibraryManager);
}
private new IComponentModel ComponentModel {
get {
return (IComponentModel)GetService(typeof(SComponentModel));
}
}
internal override LibraryManager CreateLibraryManager(CommonPackage package) {
return new PythonLibraryManager((PythonToolsPackage)package);
}
/////////////////////////////////////////////////////////////////////////////
// Overriden Package Implementation
/// <summary>
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initilaization code that rely on services provided by VisualStudio.
/// </summary>
protected override void Initialize() {
Trace.WriteLine("Entering Initialize() of: {0}".FormatUI(this));
base.Initialize();
var services = (IServiceContainer)this;
services.AddService(typeof(IPythonToolsOptionsService), PythonToolsOptionsService.CreateService, promote: true);
services.AddService(typeof(IClipboardService), new ClipboardService(), promote: true);
services.AddService(typeof(IPythonToolsToolWindowService), this, promote: true);
services.AddService(typeof(PythonLanguageInfo), (container, serviceType) => new PythonLanguageInfo(container), true);
services.AddService(typeof(PythonToolsService), PythonToolsService.CreateService, promote: true);
services.AddService(typeof(ErrorTaskProvider), ErrorTaskProvider.CreateService, promote: true);
services.AddService(typeof(CommentTaskProvider), CommentTaskProvider.CreateService, promote: true);
var solutionEventListener = new SolutionEventsListener(this);
solutionEventListener.StartListeningForChanges();
services.AddService(typeof(SolutionEventsListener), solutionEventListener, promote: true);
// Register custom debug event service
var customDebuggerEventHandler = new CustomDebuggerEventHandler(this);
services.AddService(customDebuggerEventHandler.GetType(), customDebuggerEventHandler, promote: true);
// Enable the mixed-mode debugger UI context
UIContext.FromUIContextGuid(DkmEngineId.NativeEng).IsActive = true;
// Add our command handlers for menu (commands must exist in the .vsct file)
RegisterCommands(new Command[] {
new OpenReplCommand(this, (int)PkgCmdIDList.cmdidReplWindow),
new OpenReplCommand(this, (int)PythonConstants.OpenInteractiveForEnvironment),
new OpenDebugReplCommand(this),
new ExecuteInReplCommand(this),
new SendToReplCommand(this),
new StartWithoutDebuggingCommand(this),
new StartDebuggingCommand(this),
new FillParagraphCommand(this),
new DiagnosticsCommand(this),
new RemoveImportsCommand(this, true),
new RemoveImportsCommand(this, false),
new OpenInterpreterListCommand(this),
new ImportWizardCommand(this),
new SurveyNewsCommand(this),
new ImportCoverageCommand(this),
new ShowPythonViewCommand(this),
new ShowCppViewCommand(this),
new ShowNativePythonFrames(this),
new UsePythonStepping(this),
new AzureExplorerAttachDebuggerCommand(this),
new OpenWebUrlCommand(this, "https://go.microsoft.com/fwlink/?linkid=832525", PkgCmdIDList.cmdidWebPythonAtMicrosoft),
new OpenWebUrlCommand(this, Strings.IssueTrackerUrl, PkgCmdIDList.cmdidWebPTVSSupport, false),
new OpenWebUrlCommand(this, "https://go.microsoft.com/fwlink/?linkid=832517", PkgCmdIDList.cmdidWebDGProducts),
}, GuidList.guidPythonToolsCmdSet);
// Enable the Python debugger UI context
UIContext.FromUIContextGuid(AD7Engine.DebugEngineGuid).IsActive = true;
// The variable is inherited by child processes backing Test Explorer, and is used in PTVS
// test discoverer and test executor to connect back to VS.
Environment.SetEnvironmentVariable("_PTVS_PID", Process.GetCurrentProcess().Id.ToString());
Trace.WriteLine("Leaving Initialize() of: {0}".FormatUI(this));
}
internal static bool TryGetStartupFileAndDirectory(System.IServiceProvider serviceProvider, out string filename, out string dir, out VsProjectAnalyzer analyzer) {
var startupProject = GetStartupProject(serviceProvider);
if (startupProject != null) {
filename = startupProject.GetStartupFile();
dir = startupProject.GetWorkingDirectory();
analyzer = ((PythonProjectNode)startupProject).GetAnalyzer();
} else {
var textView = CommonPackage.GetActiveTextView(serviceProvider);
if (textView == null) {
filename = null;
dir = null;
analyzer = null;
return false;
}
filename = textView.GetFilePath();
analyzer = textView.GetAnalyzerAtCaret(serviceProvider);
dir = Path.GetDirectoryName(filename);
}
return true;
}
public EnvDTE.DTE DTE {
get {
return (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
}
}
#region IVsComponentSelectorProvider Members
public int GetComponentSelectorPage(ref Guid rguidPage, VSPROPSHEETPAGE[] ppage) {
if (rguidPage == typeof(WebPiComponentPickerControl).GUID) {
var page = new VSPROPSHEETPAGE();
page.dwSize = (uint)Marshal.SizeOf(typeof(VSPROPSHEETPAGE));
var pickerPage = new WebPiComponentPickerControl();
if (_packageContainer == null) {
_packageContainer = new PackageContainer(this);
}
_packageContainer.Add(pickerPage);
//IWin32Window window = pickerPage;
page.hwndDlg = pickerPage.Handle;
ppage[0] = page;
return VSConstants.S_OK;
}
return VSConstants.E_FAIL;
}
/// <devdoc>
/// This class derives from container to provide a service provider
/// connection to the package.
/// </devdoc>
private sealed class PackageContainer : Container {
private IUIService _uis;
private AmbientProperties _ambientProperties;
private System.IServiceProvider _provider;
/// <devdoc>
/// Creates a new container using the given service provider.
/// </devdoc>
internal PackageContainer(System.IServiceProvider provider) {
_provider = provider;
}
/// <devdoc>
/// Override to GetService so we can route requests
/// to the package's service provider.
/// </devdoc>
protected override object GetService(Type serviceType) {
if (serviceType == null) {
throw new ArgumentNullException("serviceType");
}
if (_provider != null) {
if (serviceType.IsEquivalentTo(typeof(AmbientProperties))) {
if (_uis == null) {
_uis = (IUIService)_provider.GetService(typeof(IUIService));
}
if (_ambientProperties == null) {
_ambientProperties = new AmbientProperties();
}
if (_uis != null) {
// update the _ambientProperties in case the styles have changed
// since last time.
_ambientProperties.Font = (Font)_uis.Styles["DialogFont"];
}
return _ambientProperties;
}
object service = _provider.GetService(serviceType);
if (service != null) {
return service;
}
}
return base.GetService(serviceType);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// GroupByQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading;
using IEnumerator = System.Collections.IEnumerator;
namespace System.Linq.Parallel
{
/// <summary>
/// The operator type for GroupBy statements. This operator groups the input based on
/// a key-selection routine, yielding one-to-many values of key-to-elements. The
/// implementation is very much like the hash join operator, in which we first build
/// a big hashtable of the input; then we just iterate over each unique key in the
/// hashtable, yielding it plus all of the elements with the same key.
/// </summary>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TGroupKey"></typeparam>
/// <typeparam name="TElement"></typeparam>
internal sealed class GroupByQueryOperator<TSource, TGroupKey, TElement> :
UnaryQueryOperator<TSource, IGrouping<TGroupKey, TElement>>
{
private readonly Func<TSource, TGroupKey> _keySelector; // Key selection function.
private readonly Func<TSource, TElement> _elementSelector; // Optional element selection function.
private readonly IEqualityComparer<TGroupKey> _keyComparer; // An optional key comparison object.
//---------------------------------------------------------------------------------------
// Initializes a new group by operator.
//
// Arguments:
// child - the child operator or data source from which to pull data
// keySelector - a delegate representing the key selector function
// elementSelector - a delegate representing the element selector function
// keyComparer - an optional key comparison routine
//
// Assumptions:
// keySelector must be non null.
// elementSelector must be non null.
//
internal GroupByQueryOperator(IEnumerable<TSource> child,
Func<TSource, TGroupKey> keySelector,
Func<TSource, TElement> elementSelector,
IEqualityComparer<TGroupKey> keyComparer)
: base(child)
{
Contract.Assert(child != null, "child data source cannot be null");
Contract.Assert(keySelector != null, "need a selector function");
Contract.Assert(elementSelector != null ||
typeof(TSource) == typeof(TElement), "need an element function if TSource!=TElement");
_keySelector = keySelector;
_elementSelector = elementSelector;
_keyComparer = keyComparer;
SetOrdinalIndexState(OrdinalIndexState.Shuffled);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
bool preferStriping, QuerySettings settings)
{
// Hash-repartion the source stream
if (Child.OutputOrdered)
{
WrapPartitionedStreamHelperOrdered<TKey>(
ExchangeUtilities.HashRepartitionOrdered<TSource, TGroupKey, TKey>(
inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
recipient,
settings.CancellationState.MergedCancellationToken
);
}
else
{
WrapPartitionedStreamHelper<TKey, int>(
ExchangeUtilities.HashRepartition<TSource, TGroupKey, TKey>(
inputStream, _keySelector, _keyComparer, null, settings.CancellationState.MergedCancellationToken),
recipient,
settings.CancellationState.MergedCancellationToken
);
}
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelper<TIgnoreKey, TKey>(
PartitionedStream<Pair, TKey> hashStream,
IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream =
new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
// If there is no element selector, we return a special identity enumerator. Otherwise,
// we return one that will apply the element selection function during enumeration.
for (int i = 0; i < partitionCount; i++)
{
if (_elementSelector == null)
{
Contract.Assert(typeof(TSource) == typeof(TElement));
var enumerator = new GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>(
hashStream[i], _keyComparer, cancellationToken);
outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator;
}
else
{
outputStream[i] = new GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>(
hashStream[i], _keyComparer, _elementSelector, cancellationToken);
}
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelperOrdered<TKey>(
PartitionedStream<Pair, TKey> hashStream,
IPartitionedStreamRecipient<IGrouping<TGroupKey, TElement>> recipient,
CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<IGrouping<TGroupKey, TElement>, TKey> outputStream =
new PartitionedStream<IGrouping<TGroupKey, TElement>, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
// If there is no element selector, we return a special identity enumerator. Otherwise,
// we return one that will apply the element selection function during enumeration.
IComparer<TKey> orderComparer = hashStream.KeyComparer;
for (int i = 0; i < partitionCount; i++)
{
if (_elementSelector == null)
{
Contract.Assert(typeof(TSource) == typeof(TElement));
var enumerator = new OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TKey>(
hashStream[i], _keySelector, _keyComparer, orderComparer, cancellationToken);
outputStream[i] = (QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TKey>)(object)enumerator;
}
else
{
outputStream[i] = new OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TKey>(
hashStream[i], _keySelector, _elementSelector, _keyComparer, orderComparer,
cancellationToken);
}
}
recipient.Receive(outputStream);
}
//-----------------------------------------------------------------------------------
// Override of the query operator base class's Open method.
//
internal override QueryResults<IGrouping<TGroupKey, TElement>> Open(QuerySettings settings, bool preferStriping)
{
// We just open our child operator. Do not propagate the preferStriping value, but instead explicitly
// set it to false. Regardless of whether the parent prefers striping or range partitioning, the output
// will be hash-partititioned.
QueryResults<TSource> childResults = Child.Open(settings, false);
return new UnaryQueryOperatorResults(childResults, this, settings, false);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<IGrouping<TGroupKey, TElement>> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TSource> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token);
if (_elementSelector == null)
{
Contract.Assert(typeof(TElement) == typeof(TSource));
return (IEnumerable<IGrouping<TGroupKey, TElement>>)(object)(wrappedChild.GroupBy(_keySelector, _keyComparer));
}
else
{
return wrappedChild.GroupBy(_keySelector, _elementSelector, _keyComparer);
}
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
}
//---------------------------------------------------------------------------------------
// The enumerator type responsible for grouping elements and yielding the key-value sets.
//
// Assumptions:
// Just like the Join operator, this won't work properly at all if the analysis engine
// didn't choose to hash partition. We will simply not yield correct groupings.
//
internal abstract class GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey>
{
protected readonly QueryOperatorEnumerator<Pair, TOrderKey> _source; // The data source to enumerate.
protected readonly IEqualityComparer<TGroupKey> _keyComparer; // A key comparer.
protected readonly CancellationToken _cancellationToken;
private Mutables _mutables; // All of the mutable state.
class Mutables
{
internal HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> _hashLookup; // The lookup with key-value mappings.
internal int _hashLookupIndex; // The current index within the lookup.
}
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
protected GroupByQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair, TOrderKey> source,
IEqualityComparer<TGroupKey> keyComparer, CancellationToken cancellationToken)
{
Contract.Assert(source != null);
_source = source;
_keyComparer = keyComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext will invoke the entire query sub-tree, accumulating results into a hash-
// table, upon the first call. Then for the first call and all subsequent calls, we will
// just enumerate the key-set from the hash-table, retrieving groupings of key-elements.
//
internal override bool MoveNext(ref IGrouping<TGroupKey, TElement> currentElement, ref TOrderKey currentKey)
{
Contract.Assert(_source != null);
// Lazy-init the mutable state. This also means we haven't yet built our lookup of
// groupings, so we can go ahead and do that too.
Mutables mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
// Build the hash lookup and start enumerating the lookup at the beginning.
mutables._hashLookup = BuildHashLookup();
Contract.Assert(mutables._hashLookup != null);
mutables._hashLookupIndex = -1;
}
// Now, with a hash lookup in hand, we just enumerate the keys. So long
// as the key-value lookup has elements, we have elements.
if (++mutables._hashLookupIndex < mutables._hashLookup.Count)
{
currentElement = new GroupByGrouping<TGroupKey, TElement>(
mutables._hashLookup[mutables._hashLookupIndex]);
return true;
}
return false;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected abstract HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup();
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
}
//---------------------------------------------------------------------------------------
// A specialization of the group by enumerator for yielding elements with the identity
// function.
//
internal sealed class GroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> :
GroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey>
{
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal GroupByIdentityQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair, TOrderKey> source,
IEqualityComparer<TGroupKey> keyComparer, CancellationToken cancellationToken)
: base(source, keyComparer, cancellationToken)
{
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>> hashlookup =
new HashLookup<Wrapper<TGroupKey>, ListChunk<TSource>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair sourceElement = new Pair(default(TSource), default(TGroupKey));
TOrderKey sourceKeyUnused = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>((TGroupKey)sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
ListChunk<TSource> currentValue = null;
if (!hashlookup.TryGetValue(key, ref currentValue))
{
const int INITIAL_CHUNK_SIZE = 2;
currentValue = new ListChunk<TSource>(INITIAL_CHUNK_SIZE);
hashlookup.Add(key, currentValue);
}
Contract.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue.Add((TSource)sourceElement.First);
}
return hashlookup;
}
}
//---------------------------------------------------------------------------------------
// A specialization of the group by enumerator for yielding elements with any arbitrary
// element selection function.
//
internal sealed class GroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
GroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey>
{
private readonly Func<TSource, TElement> _elementSelector; // Function to select elements.
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal GroupByElementSelectorQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair, TOrderKey> source,
IEqualityComparer<TGroupKey> keyComparer, Func<TSource, TElement> elementSelector, CancellationToken cancellationToken) :
base(source, keyComparer, cancellationToken)
{
Contract.Assert(elementSelector != null);
_elementSelector = elementSelector;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>> hashlookup =
new HashLookup<Wrapper<TGroupKey>, ListChunk<TElement>>(new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair sourceElement = new Pair(default(TSource), default(TGroupKey));
TOrderKey sourceKeyUnused = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>((TGroupKey)sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
ListChunk<TElement> currentValue = null;
if (!hashlookup.TryGetValue(key, ref currentValue))
{
const int INITIAL_CHUNK_SIZE = 2;
currentValue = new ListChunk<TElement>(INITIAL_CHUNK_SIZE);
hashlookup.Add(key, currentValue);
}
Contract.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue.Add(_elementSelector((TSource)sourceElement.First));
}
return hashlookup;
}
}
//---------------------------------------------------------------------------------------
// Ordered version of the GroupBy operator.
//
internal abstract class OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
QueryOperatorEnumerator<IGrouping<TGroupKey, TElement>, TOrderKey>
{
protected readonly QueryOperatorEnumerator<Pair, TOrderKey> _source; // The data source to enumerate.
private readonly Func<TSource, TGroupKey> _keySelector; // The key selection routine.
protected readonly IEqualityComparer<TGroupKey> _keyComparer; // The key comparison routine.
protected readonly IComparer<TOrderKey> _orderComparer; // The comparison routine for order keys.
protected readonly CancellationToken _cancellationToken;
private Mutables _mutables; // All the mutable state.
class Mutables
{
internal HashLookup<Wrapper<TGroupKey>, GroupKeyData> _hashLookup; // The lookup with key-value mappings.
internal int _hashLookupIndex; // The current index within the lookup.
}
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
protected OrderedGroupByQueryOperatorEnumerator(QueryOperatorEnumerator<Pair, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken)
{
Contract.Assert(source != null);
Contract.Assert(keySelector != null);
_source = source;
_keySelector = keySelector;
_keyComparer = keyComparer;
_orderComparer = orderComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext will invoke the entire query sub-tree, accumulating results into a hash-
// table, upon the first call. Then for the first call and all subsequent calls, we will
// just enumerate the key-set from the hash-table, retrieving groupings of key-elements.
//
internal override bool MoveNext(ref IGrouping<TGroupKey, TElement> currentElement, ref TOrderKey currentKey)
{
Contract.Assert(_source != null);
Contract.Assert(_keySelector != null);
// Lazy-init the mutable state. This also means we haven't yet built our lookup of
// groupings, so we can go ahead and do that too.
Mutables mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
// Build the hash lookup and start enumerating the lookup at the beginning.
mutables._hashLookup = BuildHashLookup();
Contract.Assert(mutables._hashLookup != null);
mutables._hashLookupIndex = -1;
}
// Now, with a hash lookup in hand, we just enumerate the keys. So long
// as the key-value lookup has elements, we have elements.
if (++mutables._hashLookupIndex < mutables._hashLookup.Count)
{
GroupKeyData value = mutables._hashLookup[mutables._hashLookupIndex].Value;
currentElement = value._grouping;
currentKey = value._orderKey;
return true;
}
return false;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected abstract HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup();
protected override void Dispose(bool disposing)
{
_source.Dispose();
}
//-----------------------------------------------------------------------------------
// A data structure that holds information about elements with a particular key.
//
// This information includes two parts:
// - An order key for the grouping.
// - The grouping itself. The grouping consists of elements and the grouping key.
//
protected class GroupKeyData
{
internal TOrderKey _orderKey;
internal OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> _grouping;
internal GroupKeyData(TOrderKey orderKey, TGroupKey hashKey, IComparer<TOrderKey> orderComparer)
{
_orderKey = orderKey;
_grouping = new OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement>(hashKey, orderComparer);
}
}
}
//---------------------------------------------------------------------------------------
// A specialization of the ordered GroupBy enumerator for yielding elements with the identity
// function.
//
internal sealed class OrderedGroupByIdentityQueryOperatorEnumerator<TSource, TGroupKey, TOrderKey> :
OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TSource, TOrderKey>
{
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal OrderedGroupByIdentityQueryOperatorEnumerator(QueryOperatorEnumerator<Pair, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken)
: base(source, keySelector, keyComparer, orderComparer, cancellationToken)
{
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>(
new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair sourceElement = new Pair(default(TSource), default(TGroupKey));
TOrderKey sourceOrderKey = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceOrderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>((TGroupKey)sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
GroupKeyData currentValue = null;
if (hashLookup.TryGetValue(key, ref currentValue))
{
if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0)
{
currentValue._orderKey = sourceOrderKey;
}
}
else
{
currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer);
hashLookup.Add(key, currentValue);
}
Contract.Assert(currentValue != null);
currentValue._grouping.Add((TSource)sourceElement.First, sourceOrderKey);
}
// Sort the elements within each group
for (int j = 0; j < hashLookup.Count; j++)
{
hashLookup[j].Value._grouping.DoneAdding();
}
return hashLookup;
}
}
//---------------------------------------------------------------------------------------
// A specialization of the ordered GroupBy enumerator for yielding elements with any arbitrary
// element selection function.
//
internal sealed class OrderedGroupByElementSelectorQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey> :
OrderedGroupByQueryOperatorEnumerator<TSource, TGroupKey, TElement, TOrderKey>
{
private readonly Func<TSource, TElement> _elementSelector; // Function to select elements.
//---------------------------------------------------------------------------------------
// Instantiates a new group by enumerator.
//
internal OrderedGroupByElementSelectorQueryOperatorEnumerator(QueryOperatorEnumerator<Pair, TOrderKey> source,
Func<TSource, TGroupKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TGroupKey> keyComparer, IComparer<TOrderKey> orderComparer,
CancellationToken cancellationToken) :
base(source, keySelector, keyComparer, orderComparer, cancellationToken)
{
Contract.Assert(elementSelector != null);
_elementSelector = elementSelector;
}
//-----------------------------------------------------------------------------------
// Builds the hash lookup, transforming from TSource to TElement through whatever means is appropriate.
//
protected override HashLookup<Wrapper<TGroupKey>, GroupKeyData> BuildHashLookup()
{
HashLookup<Wrapper<TGroupKey>, GroupKeyData> hashLookup = new HashLookup<Wrapper<TGroupKey>, GroupKeyData>(
new WrapperEqualityComparer<TGroupKey>(_keyComparer));
Pair sourceElement = new Pair(default(TSource), default(TGroupKey));
TOrderKey sourceOrderKey = default(TOrderKey);
int i = 0;
while (_source.MoveNext(ref sourceElement, ref sourceOrderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Generate a key and place it into the hashtable.
Wrapper<TGroupKey> key = new Wrapper<TGroupKey>((TGroupKey)sourceElement.Second);
// If the key already exists, we just append it to the existing list --
// otherwise we will create a new one and add it to that instead.
GroupKeyData currentValue = null;
if (hashLookup.TryGetValue(key, ref currentValue))
{
if (_orderComparer.Compare(sourceOrderKey, currentValue._orderKey) < 0)
{
currentValue._orderKey = sourceOrderKey;
}
}
else
{
currentValue = new GroupKeyData(sourceOrderKey, key.Value, _orderComparer);
hashLookup.Add(key, currentValue);
}
Contract.Assert(currentValue != null);
// Call to the base class to yield the current value.
currentValue._grouping.Add(_elementSelector((TSource)sourceElement.First), sourceOrderKey);
}
// Sort the elements within each group
for (int j = 0; j < hashLookup.Count; j++)
{
hashLookup[j].Value._grouping.DoneAdding();
}
return hashLookup;
}
}
//---------------------------------------------------------------------------------------
// This little type implements the IGrouping<K,T> interface, and exposes a single
// key-to-many-values mapping.
//
internal class GroupByGrouping<TGroupKey, TElement> : IGrouping<TGroupKey, TElement>
{
private KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> _keyValues; // A key value pair.
//---------------------------------------------------------------------------------------
// Constructs a new grouping out of the key value pair.
//
internal GroupByGrouping(KeyValuePair<Wrapper<TGroupKey>, ListChunk<TElement>> keyValues)
{
Contract.Assert(keyValues.Value != null);
_keyValues = keyValues;
}
//---------------------------------------------------------------------------------------
// The key this mapping represents.
//
TGroupKey IGrouping<TGroupKey, TElement>.Key
{
get
{
return _keyValues.Key.Value;
}
}
//---------------------------------------------------------------------------------------
// Access to value enumerators.
//
IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator()
{
Contract.Assert(_keyValues.Value != null);
return _keyValues.Value.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TElement>)this).GetEnumerator();
}
}
/// <summary>
/// An ordered version of the grouping data structure. Represents an ordered group of elements that
/// have the same grouping key.
/// </summary>
internal class OrderedGroupByGrouping<TGroupKey, TOrderKey, TElement> : IGrouping<TGroupKey, TElement>
{
private TGroupKey _groupKey; // The group key for this grouping
private GrowingArray<TElement> _values; // Values in this group
private GrowingArray<TOrderKey> _orderKeys; // Order keys that correspond to the values
private IComparer<TOrderKey> _orderComparer; // Comparer for order keys
private KeyAndValuesComparer _wrappedComparer; // Comparer that wraps the _orderComparer used for sorting key/value pairs
/// <summary>
/// Constructs a new grouping
/// </summary>
internal OrderedGroupByGrouping(
TGroupKey groupKey,
IComparer<TOrderKey> orderComparer)
{
_groupKey = groupKey;
_values = new GrowingArray<TElement>();
_orderKeys = new GrowingArray<TOrderKey>();
_orderComparer = orderComparer;
_wrappedComparer = new KeyAndValuesComparer(_orderComparer);
}
/// <summary>
/// The key this grouping represents.
/// </summary>
TGroupKey IGrouping<TGroupKey, TElement>.Key
{
get
{
return _groupKey;
}
}
IEnumerator<TElement> IEnumerable<TElement>.GetEnumerator()
{
Contract.Assert(_values != null);
int valueCount = _values.Count;
TElement[] valueArray = _values.InternalArray;
Contract.Assert(valueArray.Length >= valueCount); // valueArray.Length may be larger than valueCount
for (int i = 0; i < valueCount; i++)
{
yield return valueArray[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<TElement>)this).GetEnumerator();
}
/// <summary>
/// Add an element
/// </summary>
internal void Add(TElement value, TOrderKey orderKey)
{
Contract.Assert(_values != null);
Contract.Assert(_orderKeys != null);
_values.Add(value);
_orderKeys.Add(orderKey);
}
/// <summary>
/// No more elements will be added, so we can sort the group now.
/// </summary>
internal void DoneAdding()
{
Contract.Assert(_values != null);
Contract.Assert(_orderKeys != null);
// Create a map of key-value pair.
// We can't use a dictionary since the keys are not necessarily unique
List<KeyValuePair<TOrderKey, TElement>> sortedValues = new List<KeyValuePair<TOrderKey, TElement>>();
for (int i = 0; i < _orderKeys.InternalArray.Length; i++)
{
sortedValues.Add(new KeyValuePair<TOrderKey, TElement>(_orderKeys.InternalArray[i], _values.InternalArray[i]));
}
// Sort the values by using the _orderComparer wrapped in a Tuple comparer
sortedValues.Sort(0, _values.Count, _wrappedComparer);
// Un-pack the values from the list back into the 2 separate arrays
for (int i = 0; i < _values.InternalArray.Length; i++)
{
_orderKeys.InternalArray[i] = sortedValues[i].Key;
_values.InternalArray[i] = sortedValues[i].Value;
}
#if DEBUG
_orderKeys = null; // Any future calls to Add() or DoneAdding() will fail
#endif
}
private class KeyAndValuesComparer : IComparer<KeyValuePair<TOrderKey, TElement>>
{
private IComparer<TOrderKey> myComparer;
public KeyAndValuesComparer(IComparer<TOrderKey> comparer)
{
myComparer = comparer;
}
public int Compare(KeyValuePair<TOrderKey, TElement> x, KeyValuePair<TOrderKey, TElement> y)
{
return myComparer.Compare(x.Key, y.Key);
}
}
}
}
| |
// 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.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ChangeSignature
{
[ExportLanguageService(typeof(AbstractChangeSignatureService), LanguageNames.CSharp), Shared]
internal sealed class CSharpChangeSignatureService : AbstractChangeSignatureService
{
public override async Task<ISymbol> GetInvocationSymbolAsync(
Document document, int position, bool restrictToDeclarations, CancellationToken cancellationToken)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = tree.GetRoot(cancellationToken).FindToken(position != tree.Length ? position : Math.Max(0, position - 1));
var ancestorDeclarationKinds = restrictToDeclarations ? _invokableAncestorKinds.Add(SyntaxKind.Block) : _invokableAncestorKinds;
SyntaxNode matchingNode = token.Parent.AncestorsAndSelf().FirstOrDefault(n => ancestorDeclarationKinds.Contains(n.Kind()));
if (matchingNode == null || matchingNode.IsKind(SyntaxKind.Block))
{
return null;
}
ISymbol symbol;
var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
symbol = semanticModel.GetDeclaredSymbol(matchingNode, cancellationToken);
if (symbol != null)
{
return symbol;
}
if (matchingNode.IsKind(SyntaxKind.ObjectCreationExpression))
{
var objectCreation = matchingNode as ObjectCreationExpressionSyntax;
if (token.Parent.AncestorsAndSelf().Any(a => a == objectCreation.Type))
{
var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type, cancellationToken).Symbol;
if (typeSymbol != null && typeSymbol.IsKind(SymbolKind.NamedType) && (typeSymbol as ITypeSymbol).TypeKind == TypeKind.Delegate)
{
return typeSymbol;
}
}
}
var symbolInfo = semanticModel.GetSymbolInfo(matchingNode, cancellationToken);
return symbolInfo.Symbol ?? symbolInfo.CandidateSymbols.FirstOrDefault();
}
private ImmutableArray<SyntaxKind> _invokableAncestorKinds = new[]
{
SyntaxKind.MethodDeclaration,
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.NameMemberCref,
SyntaxKind.SimpleLambdaExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.DelegateDeclaration
}.ToImmutableArray();
private ImmutableArray<SyntaxKind> _updatableAncestorKinds = new[]
{
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.DelegateDeclaration,
SyntaxKind.SimpleLambdaExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.NameMemberCref
}.ToImmutableArray();
private ImmutableArray<SyntaxKind> _updatableNodeKinds = new[]
{
SyntaxKind.MethodDeclaration,
SyntaxKind.ConstructorDeclaration,
SyntaxKind.IndexerDeclaration,
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.ThisConstructorInitializer,
SyntaxKind.BaseConstructorInitializer,
SyntaxKind.ObjectCreationExpression,
SyntaxKind.Attribute,
SyntaxKind.DelegateDeclaration,
SyntaxKind.NameMemberCref,
SyntaxKind.AnonymousMethodExpression,
SyntaxKind.ParenthesizedLambdaExpression,
SyntaxKind.SimpleLambdaExpression
}.ToImmutableArray();
public override SyntaxNode FindNodeToUpdate(Document document, SyntaxNode node)
{
if (_updatableNodeKinds.Contains(node.Kind()))
{
return node;
}
// TODO: file bug about this: var invocation = csnode.Ancestors().FirstOrDefault(a => a.Kind == SyntaxKind.InvocationExpression);
var matchingNode = node.AncestorsAndSelf().FirstOrDefault(n => _updatableAncestorKinds.Contains(n.Kind()));
if (matchingNode == null)
{
return null;
}
var nodeContainingOriginal = GetNodeContainingTargetNode(matchingNode);
if (nodeContainingOriginal == null)
{
return null;
}
return node.AncestorsAndSelf().Any(n => n == nodeContainingOriginal) ? matchingNode : null;
}
private SyntaxNode GetNodeContainingTargetNode(SyntaxNode matchingNode)
{
switch (matchingNode.Kind())
{
case SyntaxKind.InvocationExpression:
return (matchingNode as InvocationExpressionSyntax).Expression;
case SyntaxKind.ElementAccessExpression:
return (matchingNode as ElementAccessExpressionSyntax).ArgumentList;
case SyntaxKind.ObjectCreationExpression:
return (matchingNode as ObjectCreationExpressionSyntax).Type;
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.IndexerDeclaration:
case SyntaxKind.ThisConstructorInitializer:
case SyntaxKind.BaseConstructorInitializer:
case SyntaxKind.Attribute:
case SyntaxKind.DelegateDeclaration:
case SyntaxKind.NameMemberCref:
return matchingNode;
default:
return null;
}
}
public override SyntaxNode ChangeSignature(
Document document,
ISymbol declarationSymbol,
SyntaxNode potentiallyUpdatedNode,
SyntaxNode originalNode,
SignatureChange signaturePermutation,
CancellationToken cancellationToken)
{
var updatedNode = potentiallyUpdatedNode as CSharpSyntaxNode;
// Update <param> tags.
if (updatedNode.IsKind(SyntaxKind.MethodDeclaration) ||
updatedNode.IsKind(SyntaxKind.ConstructorDeclaration) ||
updatedNode.IsKind(SyntaxKind.IndexerDeclaration) ||
updatedNode.IsKind(SyntaxKind.DelegateDeclaration))
{
var updatedLeadingTrivia = UpdateParamTagsInLeadingTrivia(updatedNode, declarationSymbol, signaturePermutation);
if (updatedLeadingTrivia != null)
{
updatedNode = updatedNode.WithLeadingTrivia(updatedLeadingTrivia);
}
}
// Update declarations parameter lists
if (updatedNode.IsKind(SyntaxKind.MethodDeclaration))
{
var method = updatedNode as MethodDeclarationSyntax;
var updatedParameters = PermuteDeclaration(method.ParameterList.Parameters, signaturePermutation);
return method.WithParameterList(method.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.ConstructorDeclaration))
{
var constructor = updatedNode as ConstructorDeclarationSyntax;
var updatedParameters = PermuteDeclaration(constructor.ParameterList.Parameters, signaturePermutation);
return constructor.WithParameterList(constructor.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.IndexerDeclaration))
{
var indexer = updatedNode as IndexerDeclarationSyntax;
var updatedParameters = PermuteDeclaration(indexer.ParameterList.Parameters, signaturePermutation);
return indexer.WithParameterList(indexer.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.DelegateDeclaration))
{
var delegateDeclaration = updatedNode as DelegateDeclarationSyntax;
var updatedParameters = PermuteDeclaration(delegateDeclaration.ParameterList.Parameters, signaturePermutation);
return delegateDeclaration.WithParameterList(delegateDeclaration.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.AnonymousMethodExpression))
{
var anonymousMethod = updatedNode as AnonymousMethodExpressionSyntax;
// Delegates may omit parameters in C#
if (anonymousMethod.ParameterList == null)
{
return anonymousMethod;
}
var updatedParameters = PermuteDeclaration(anonymousMethod.ParameterList.Parameters, signaturePermutation);
return anonymousMethod.WithParameterList(anonymousMethod.ParameterList.WithParameters(updatedParameters).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.SimpleLambdaExpression))
{
var lambda = updatedNode as SimpleLambdaExpressionSyntax;
if (signaturePermutation.UpdatedConfiguration.ToListOfParameters().Any())
{
Debug.Assert(false, "Updating a simple lambda expression without removing its parameter");
}
else
{
// No parameters. Change to a parenthesized lambda expression
var emptyParameterList = SyntaxFactory.ParameterList()
.WithLeadingTrivia(lambda.Parameter.GetLeadingTrivia())
.WithTrailingTrivia(lambda.Parameter.GetTrailingTrivia());
return SyntaxFactory.ParenthesizedLambdaExpression(lambda.AsyncKeyword, emptyParameterList, lambda.ArrowToken, lambda.Body);
}
}
if (updatedNode.IsKind(SyntaxKind.ParenthesizedLambdaExpression))
{
var lambda = updatedNode as ParenthesizedLambdaExpressionSyntax;
var updatedParameters = PermuteDeclaration(lambda.ParameterList.Parameters, signaturePermutation);
return lambda.WithParameterList(lambda.ParameterList.WithParameters(updatedParameters));
}
// Update reference site argument lists
if (updatedNode.IsKind(SyntaxKind.InvocationExpression))
{
var invocation = updatedNode as InvocationExpressionSyntax;
var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolInfo = semanticModel.GetSymbolInfo(originalNode as InvocationExpressionSyntax, cancellationToken);
var methodSymbol = symbolInfo.Symbol as IMethodSymbol;
var isReducedExtensionMethod = false;
if (methodSymbol != null && methodSymbol.MethodKind == MethodKind.ReducedExtension)
{
isReducedExtensionMethod = true;
}
var newArguments = PermuteArgumentList(document, declarationSymbol, invocation.ArgumentList.Arguments, signaturePermutation, isReducedExtensionMethod);
return invocation.WithArgumentList(invocation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.ObjectCreationExpression))
{
var objCreation = updatedNode as ObjectCreationExpressionSyntax;
var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation);
return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.ThisConstructorInitializer) ||
updatedNode.IsKind(SyntaxKind.BaseConstructorInitializer))
{
var objCreation = updatedNode as ConstructorInitializerSyntax;
var newArguments = PermuteArgumentList(document, declarationSymbol, objCreation.ArgumentList.Arguments, signaturePermutation);
return objCreation.WithArgumentList(objCreation.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.ElementAccessExpression))
{
var elementAccess = updatedNode as ElementAccessExpressionSyntax;
var newArguments = PermuteArgumentList(document, declarationSymbol, elementAccess.ArgumentList.Arguments, signaturePermutation);
return elementAccess.WithArgumentList(elementAccess.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
if (updatedNode.IsKind(SyntaxKind.Attribute))
{
var attribute = updatedNode as AttributeSyntax;
var newArguments = PermuteAttributeArgumentList(document, declarationSymbol, attribute.ArgumentList.Arguments, signaturePermutation);
return attribute.WithArgumentList(attribute.ArgumentList.WithArguments(newArguments).WithAdditionalAnnotations(changeSignatureFormattingAnnotation));
}
// Handle references in crefs
if (updatedNode.IsKind(SyntaxKind.NameMemberCref))
{
var nameMemberCref = updatedNode as NameMemberCrefSyntax;
if (nameMemberCref.Parameters == null ||
!nameMemberCref.Parameters.Parameters.Any())
{
return nameMemberCref;
}
var newParameters = PermuteDeclaration(nameMemberCref.Parameters.Parameters, signaturePermutation);
var newCrefParameterList = nameMemberCref.Parameters.WithParameters(newParameters);
return nameMemberCref.WithParameters(newCrefParameterList);
}
Debug.Assert(false, "Unknown reference location");
return null;
}
private SeparatedSyntaxList<T> PermuteDeclaration<T>(SeparatedSyntaxList<T> list, SignatureChange updatedSignature) where T : SyntaxNode
{
var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var newParameters = new List<T>();
foreach (var newParam in reorderedParameters)
{
var pos = originalParameters.IndexOf(newParam);
var param = list[pos];
newParameters.Add(param);
}
var numSeparatorsToSkip = originalParameters.Count - reorderedParameters.Count;
return SyntaxFactory.SeparatedList(newParameters, GetSeparators(list, numSeparatorsToSkip));
}
private static SeparatedSyntaxList<AttributeArgumentSyntax> PermuteAttributeArgumentList(
Document document,
ISymbol declarationSymbol,
SeparatedSyntaxList<AttributeArgumentSyntax> arguments,
SignatureChange updatedSignature)
{
var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature);
var numSeparatorsToSkip = arguments.Count - newArguments.Count;
return SyntaxFactory.SeparatedList(newArguments.Select(a => (AttributeArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip));
}
private static SeparatedSyntaxList<ArgumentSyntax> PermuteArgumentList(
Document document,
ISymbol declarationSymbol,
SeparatedSyntaxList<ArgumentSyntax> arguments,
SignatureChange updatedSignature,
bool isReducedExtensionMethod = false)
{
var newArguments = PermuteArguments(document, declarationSymbol, arguments.Select(a => UnifiedArgumentSyntax.Create(a)).ToList(), updatedSignature, isReducedExtensionMethod);
var numSeparatorsToSkip = arguments.Count - newArguments.Count;
return SyntaxFactory.SeparatedList(newArguments.Select(a => (ArgumentSyntax)(UnifiedArgumentSyntax)a), GetSeparators(arguments, numSeparatorsToSkip));
}
private List<SyntaxTrivia> UpdateParamTagsInLeadingTrivia(CSharpSyntaxNode node, ISymbol declarationSymbol, SignatureChange updatedSignature)
{
if (!node.HasLeadingTrivia)
{
return null;
}
var paramNodes = node
.DescendantNodes(descendIntoTrivia: true)
.OfType<XmlElementSyntax>()
.Where(e => e.StartTag.Name.ToString() == DocumentationCommentXmlNames.ParameterElementName);
var permutedParamNodes = VerifyAndPermuteParamNodes(paramNodes, declarationSymbol, updatedSignature);
if (permutedParamNodes == null)
{
return null;
}
return GetPermutedTrivia(node, permutedParamNodes);
}
private List<XmlElementSyntax> VerifyAndPermuteParamNodes(IEnumerable<XmlElementSyntax> paramNodes, ISymbol declarationSymbol, SignatureChange updatedSignature)
{
// Only reorder if count and order match originally.
var originalParameters = updatedSignature.OriginalConfiguration.ToListOfParameters();
var reorderedParameters = updatedSignature.UpdatedConfiguration.ToListOfParameters();
var declaredParameters = declarationSymbol.GetParameters();
if (paramNodes.Count() != declaredParameters.Count())
{
return null;
}
var dictionary = new Dictionary<string, XmlElementSyntax>();
int i = 0;
foreach (var paramNode in paramNodes)
{
var nameAttribute = paramNode.StartTag.Attributes.FirstOrDefault(a => a.Name.ToString().Equals("name", StringComparison.OrdinalIgnoreCase));
if (nameAttribute == null)
{
return null;
}
var identifier = nameAttribute.DescendantNodes(descendIntoTrivia: true).OfType<IdentifierNameSyntax>().FirstOrDefault();
if (identifier == null || identifier.ToString() != declaredParameters.ElementAt(i).Name)
{
return null;
}
dictionary.Add(originalParameters[i].Name.ToString(), paramNode);
i++;
}
// Everything lines up, so permute them.
var permutedParams = new List<XmlElementSyntax>();
foreach (var parameter in reorderedParameters)
{
permutedParams.Add(dictionary[parameter.Name]);
}
return permutedParams;
}
private List<SyntaxTrivia> GetPermutedTrivia(CSharpSyntaxNode node, List<XmlElementSyntax> permutedParamNodes)
{
var updatedLeadingTrivia = new List<SyntaxTrivia>();
var index = 0;
foreach (var trivia in node.GetLeadingTrivia())
{
if (!trivia.HasStructure)
{
updatedLeadingTrivia.Add(trivia);
continue;
}
var structuredTrivia = trivia.GetStructure() as DocumentationCommentTriviaSyntax;
if (structuredTrivia == null)
{
updatedLeadingTrivia.Add(trivia);
continue;
}
var updatedNodeList = new List<XmlNodeSyntax>();
var structuredContent = structuredTrivia.Content.ToList();
for (int i = 0; i < structuredContent.Count; i++)
{
var content = structuredContent[i];
if (!content.IsKind(SyntaxKind.XmlElement))
{
updatedNodeList.Add(content);
continue;
}
var xmlElement = content as XmlElementSyntax;
if (xmlElement.StartTag.Name.ToString() != DocumentationCommentXmlNames.ParameterElementName)
{
updatedNodeList.Add(content);
continue;
}
// Found a param tag, so insert the next one from the reordered list
if (index < permutedParamNodes.Count)
{
updatedNodeList.Add(permutedParamNodes[index].WithLeadingTrivia(content.GetLeadingTrivia()).WithTrailingTrivia(content.GetTrailingTrivia()));
index++;
}
else
{
// Inspecting a param element that we are deleting but not replacing.
}
}
var newDocComments = SyntaxFactory.DocumentationCommentTrivia(structuredTrivia.Kind(), SyntaxFactory.List(updatedNodeList.AsEnumerable()));
newDocComments = newDocComments.WithEndOfComment(structuredTrivia.EndOfComment);
newDocComments = newDocComments.WithLeadingTrivia(structuredTrivia.GetLeadingTrivia()).WithTrailingTrivia(structuredTrivia.GetTrailingTrivia());
var newTrivia = SyntaxFactory.Trivia(newDocComments);
updatedLeadingTrivia.Add(newTrivia);
}
return updatedLeadingTrivia;
}
private static List<SyntaxToken> GetSeparators<T>(SeparatedSyntaxList<T> arguments, int numSeparatorsToSkip = 0) where T : SyntaxNode
{
var separators = new List<SyntaxToken>();
for (int i = 0; i < arguments.SeparatorCount - numSeparatorsToSkip; i++)
{
separators.Add(arguments.GetSeparator(i));
}
return separators;
}
public override async Task<IEnumerable<ISymbol>> DetermineCascadedSymbolsFromDelegateInvoke(IMethodSymbol symbol, Document document, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var nodes = root.DescendantNodes();
var convertedMethodGroups = nodes
.Where(
n =>
{
if (!n.IsKind(SyntaxKind.IdentifierName) ||
!semanticModel.GetMemberGroup(n, cancellationToken).Any())
{
return false;
}
ISymbol convertedType = semanticModel.GetTypeInfo(n, cancellationToken).ConvertedType;
if (convertedType != null)
{
convertedType = convertedType.OriginalDefinition;
}
if (convertedType != null)
{
convertedType = SymbolFinder.FindSourceDefinitionAsync(convertedType, document.Project.Solution, cancellationToken).WaitAndGetResult(cancellationToken) ?? convertedType;
}
return convertedType == symbol.ContainingType;
})
.Select(n => semanticModel.GetSymbolInfo(n, cancellationToken).Symbol);
return convertedMethodGroups;
}
protected override IEnumerable<IFormattingRule> GetFormattingRules(Document document)
{
return new[] { new ChangeSignatureFormattingRule() }.Concat(Formatter.GetDefaultFormattingRules(document));
}
}
}
| |
using NetApp.Tests.Helpers;
using Microsoft.Azure.Management.NetApp.Models;
using Microsoft.Azure.Management.NetApp;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using Xunit;
using System;
using System.Collections.Generic;
using System.Threading;
using System.ComponentModel;
using Microsoft.Rest.Azure;
namespace NetApp.Tests.ResourceTests
{
public class VolumeTests : TestBase
{
private const int delay = 10000;
public static ExportPolicyRule exportPolicyRule = new ExportPolicyRule()
{
RuleIndex = 1,
UnixReadOnly = false,
UnixReadWrite = true,
Cifs = false,
Nfsv3 = true,
Nfsv41 = false,
AllowedClients = "1.2.3.0/24"
};
public static IList<ExportPolicyRule> exportPolicyRuleList = new List<ExportPolicyRule>()
{
exportPolicyRule
};
public static VolumePropertiesExportPolicy exportPolicy = new VolumePropertiesExportPolicy()
{
Rules = exportPolicyRuleList
};
public static VolumePatchPropertiesExportPolicy exportPatchPolicy = new VolumePatchPropertiesExportPolicy()
{
Rules = exportPolicyRuleList
};
[Fact]
public void CreateDeleteVolume()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create a volume, get all and check
var resource = ResourceUtils.CreateVolume(netAppMgmtClient);
Assert.Equal(ResourceUtils.defaultExportPolicy.ToString(), resource.ExportPolicy.ToString());
// check DP properties exist but unassigned because
// dataprotection volume was not created
Assert.Null(resource.VolumeType);
Assert.Null(resource.DataProtection);
var volumesBefore = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
Assert.Single(volumesBefore);
// delete the volume and check again
netAppMgmtClient.Volumes.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1);
var volumesAfter = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
Assert.Empty(volumesAfter);
// cleanup
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void CreateVolumeWithProperties()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create a volume with tags and export policy
var dict = new Dictionary<string, string>();
dict.Add("Tag2", "Value2");
var protocolTypes = new List<string>() { "NFSv3" };
var resource = ResourceUtils.CreateVolume(netAppMgmtClient, protocolTypes: protocolTypes, tags: dict, exportPolicy: exportPolicy);
Assert.Equal(exportPolicy.ToString(), resource.ExportPolicy.ToString());
Assert.Equal(protocolTypes, resource.ProtocolTypes);
Assert.True(resource.Tags.ContainsKey("Tag2"));
Assert.Equal("Value2", resource.Tags["Tag2"]);
var volumesBefore = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
Assert.Single(volumesBefore);
// delete the volume and check again
netAppMgmtClient.Volumes.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1);
var volumesAfter = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
Assert.Empty(volumesAfter);
// cleanup
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void ListVolumes()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create two volumes under same pool
ResourceUtils.CreateVolume(netAppMgmtClient);
ResourceUtils.CreateVolume(netAppMgmtClient, ResourceUtils.volumeName2, volumeOnly: true);
// get the account list and check
var volumes = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
//Assert.Equal(volumes.ElementAt(1).Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName1);
//Assert.Equal(volumes.ElementAt(0).Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName2);
Assert.Contains(volumes, item => item.Name == $"{ResourceUtils.accountName1}/{ResourceUtils.poolName1}/{ResourceUtils.volumeName1}");
Assert.Contains(volumes, item => item.Name == $"{ResourceUtils.accountName1}/{ResourceUtils.poolName1}/{ResourceUtils.volumeName2}");
Assert.Equal(2, volumes.Count());
// clean up - delete the two volumes, the pool and the account
ResourceUtils.DeleteVolume(netAppMgmtClient);
ResourceUtils.DeleteVolume(netAppMgmtClient, ResourceUtils.volumeName2);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void GetVolumeByName()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the volume
ResourceUtils.CreateVolume(netAppMgmtClient);
// retrieve it
var volume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1);
Assert.Equal(volume.Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName1);
// clean up - delete the volume, pool and account
ResourceUtils.DeleteVolume(netAppMgmtClient);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void GetVolumeByNameNotFound()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create volume
ResourceUtils.CreatePool(netAppMgmtClient);
// try and get a volume in the pool - none have been created yet
try
{
var volume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1);
Assert.True(false); // expecting exception
}
catch (Exception ex)
{
Assert.Contains("was not found", ex.Message);
}
// cleanup
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void GetVolumeByNamePoolNotFound()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
ResourceUtils.CreateAccount(netAppMgmtClient);
// try and create a volume before the pool exist
try
{
var volume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1);
Assert.True(false); // expecting exception
}
catch (Exception ex)
{
Assert.Contains("not found", ex.Message);
}
// cleanup - remove the account
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void CreateVolumePoolNotFound()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
ResourceUtils.CreateAccount(netAppMgmtClient);
// try and create a volume before the pool exist
try
{
ResourceUtils.CreateVolume(netAppMgmtClient, volumeOnly: true);
Assert.True(false); // expecting exception
}
catch (Exception ex)
{
Assert.Contains("not found", ex.Message);
}
// cleanup - remove the account
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void DeletePoolWithVolumePresent()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the account and pool
ResourceUtils.CreateVolume(netAppMgmtClient);
var poolsBefore = netAppMgmtClient.Pools.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1);
Assert.Single(poolsBefore);
// try and delete the pool
try
{
netAppMgmtClient.Pools.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
Assert.True(false); // expecting exception
}
catch (Exception ex)
{
Assert.Contains("Can not delete resource before nested resources are deleted", ex.Message);
}
// clean up
ResourceUtils.DeleteVolume(netAppMgmtClient);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void CheckAvailability()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// check account resource name - should be available
var response = netAppMgmtClient.NetAppResource.CheckNameAvailability(ResourceUtils.location, ResourceUtils.accountName1, CheckNameResourceTypes.MicrosoftNetAppNetAppAccounts, ResourceUtils.resourceGroup);
Assert.True(response.IsAvailable);
// now check file path availability
response = netAppMgmtClient.NetAppResource.CheckFilePathAvailability(ResourceUtils.location, ResourceUtils.volumeName1, ResourceUtils.subnetId);
Assert.True(response.IsAvailable);
// create the volume
var volume = ResourceUtils.CreateVolume(netAppMgmtClient);
// check volume resource name - should be unavailable after its creation
var resourceName = ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName1;
response = netAppMgmtClient.NetAppResource.CheckNameAvailability(ResourceUtils.location, resourceName, CheckNameResourceTypes.MicrosoftNetAppNetAppAccountsCapacityPoolsVolumes, ResourceUtils.resourceGroup);
Assert.False(response.IsAvailable);
// now check file path availability again
response = netAppMgmtClient.NetAppResource.CheckFilePathAvailability(ResourceUtils.location, ResourceUtils.volumeName1, ResourceUtils.subnetId);
Assert.False(response.IsAvailable);
// clean up
ResourceUtils.DeleteVolume(netAppMgmtClient);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void CheckAvailabilityPre2021_04()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// check account resource name - should be available
var response = netAppMgmtClient.NetAppResource.CheckNameAvailability(ResourceUtils.location, ResourceUtils.accountName1, CheckNameResourceTypes.MicrosoftNetAppNetAppAccounts, ResourceUtils.resourceGroup);
Assert.True(response.IsAvailable);
// now check file path availability
response = netAppMgmtClient.NetAppResource.CheckFilePathAvailability(ResourceUtils.location, ResourceUtils.volumeName1, CheckNameResourceTypes.MicrosoftNetAppNetAppAccountsCapacityPoolsVolumes, ResourceUtils.resourceGroup);
Assert.True(response.IsAvailable);
// create the volume
var volume = ResourceUtils.CreateVolume(netAppMgmtClient);
// check volume resource name - should be unavailable after its creation
var resourceName = ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName1;
response = netAppMgmtClient.NetAppResource.CheckNameAvailability(ResourceUtils.location, resourceName, CheckNameResourceTypes.MicrosoftNetAppNetAppAccountsCapacityPoolsVolumes, ResourceUtils.resourceGroup);
Assert.False(response.IsAvailable);
// now check file path availability again
response = netAppMgmtClient.NetAppResource.CheckFilePathAvailability(ResourceUtils.location, ResourceUtils.volumeName1, CheckNameResourceTypes.MicrosoftNetAppNetAppAccountsCapacityPoolsVolumes, ResourceUtils.resourceGroup);
Assert.False(response.IsAvailable);
// clean up
ResourceUtils.DeleteVolume(netAppMgmtClient);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void UpdateVolume()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the volume
var oldVolume = ResourceUtils.CreateVolume(netAppMgmtClient);
Assert.Equal("Premium", oldVolume.ServiceLevel);
Assert.Equal(100 * ResourceUtils.gibibyte, oldVolume.UsageThreshold);
// The returned volume contains some items which cnanot be part of the payload, such as baremetaltenant, therefore create a new object selectively from the old one
var volume = new Volume
{
Location = oldVolume.Location,
ServiceLevel = oldVolume.ServiceLevel,
CreationToken = oldVolume.CreationToken,
SubnetId = oldVolume.SubnetId,
};
// update
volume.UsageThreshold = 2 * oldVolume.UsageThreshold;
var updatedVolume = netAppMgmtClient.Volumes.CreateOrUpdate(volume, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1);
Assert.Equal("Premium", updatedVolume.ServiceLevel); // didn't attempt to change - it would be rejected
Assert.Equal(100 * ResourceUtils.gibibyte * 2, updatedVolume.UsageThreshold);
// cleanup
ResourceUtils.DeleteVolume(netAppMgmtClient);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void PatchVolume()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the volume
var volume = ResourceUtils.CreateVolume(netAppMgmtClient);
Assert.Equal("Premium", volume.ServiceLevel);
Assert.Equal(100 * ResourceUtils.gibibyte, volume.UsageThreshold);
Assert.Equal(ResourceUtils.defaultExportPolicy.ToString(), volume.ExportPolicy.ToString());
// create a volume with tags and export policy
var dict = new Dictionary<string, string>();
dict.Add("Tag2", "Value2");
// Now try and modify it
var volumePatch = new VolumePatch()
{
UsageThreshold = 2 * volume.UsageThreshold,
Tags = dict,
ExportPolicy = exportPatchPolicy
};
// patch
var updatedVolume = netAppMgmtClient.Volumes.Update(volumePatch, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1);
Assert.Equal("Premium", updatedVolume.ServiceLevel); // didn't attempt to change - it would be rejected
Assert.Equal(200 * ResourceUtils.gibibyte, updatedVolume.UsageThreshold);
Assert.Equal(exportPolicy.ToString(), updatedVolume.ExportPolicy.ToString());
Assert.True(updatedVolume.Tags.ContainsKey("Tag2"));
Assert.Equal("Value2", updatedVolume.Tags["Tag2"]);
// cleanup
ResourceUtils.DeleteVolume(netAppMgmtClient);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
private void WaitForReplicationStatus(AzureNetAppFilesManagementClient netAppMgmtClient, string targetState)
{
ReplicationStatus replicationStatus = new ReplicationStatus {Healthy=false, MirrorState = "Uninitialized" };
int attempts = 0;
do
{
try
{
replicationStatus = netAppMgmtClient.Volumes.ReplicationStatusMethod(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest);
}
catch(CloudException ex)
{
if (!ex.Message.Contains("the volume replication is: 'Creating'"))
{
throw;
}
}
Thread.Sleep(1);
} while (replicationStatus.MirrorState != targetState);
//sometimes they dont sync up right away
if (!replicationStatus.Healthy.Value)
{
do
{
replicationStatus = netAppMgmtClient.Volumes.ReplicationStatusMethod(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest);
attempts++;
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(1000);
}
} while (replicationStatus.Healthy.Value || attempts == 10);
}
Assert.True(replicationStatus.Healthy);
}
private void WaitForSucceeded(AzureNetAppFilesManagementClient netAppMgmtClient, string accountName = ResourceUtils.accountName1, string poolName = ResourceUtils.poolName1, string volumeName = ResourceUtils.volumeName1)
{
Volume sourceVolume;
Volume dpVolume;
do
{
sourceVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.repResourceGroup, accountName, poolName, volumeName);
dpVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest);
Thread.Sleep(1);
} while ((sourceVolume.ProvisioningState != "Succeeded") || (dpVolume.ProvisioningState != "Succeeded"));
}
[Fact]
public void CreateDpVolume()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the source volume
var sourceVolume = ResourceUtils.CreateVolume(netAppMgmtClient, resourceGroup: ResourceUtils.repResourceGroup, vnet: ResourceUtils.repVnet, volumeName: ResourceUtils.volumeName1ReplSource,
accountName: ResourceUtils.accountName1Repl, poolName: ResourceUtils.poolName1Repl);
sourceVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.repResourceGroup, ResourceUtils.accountName1Repl, ResourceUtils.poolName1Repl, ResourceUtils.volumeName1ReplSource);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(delay); // some robustness against ARM caching
}
// create the data protection volume from the source
var dpVolume = ResourceUtils.CreateDpVolume(netAppMgmtClient, sourceVolume);
Assert.Equal(ResourceUtils.volumeName1ReplDest, dpVolume.Name.Substring(dpVolume.Name.LastIndexOf('/') + 1));
Assert.NotNull(dpVolume.DataProtection);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
var getDPVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest);
var authorizeRequest = new AuthorizeRequest
{
RemoteVolumeResourceId = dpVolume.Id
};
netAppMgmtClient.Volumes.AuthorizeReplication(ResourceUtils.repResourceGroup, ResourceUtils.accountName1Repl, ResourceUtils.poolName1Repl, ResourceUtils.volumeName1ReplSource, authorizeRequest);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
WaitForSucceeded(netAppMgmtClient, accountName: ResourceUtils.accountName1Repl, poolName: ResourceUtils.poolName1Repl, volumeName: ResourceUtils.volumeName1ReplSource);
WaitForReplicationStatus(netAppMgmtClient, "Mirrored");
netAppMgmtClient.Volumes.BreakReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest);
WaitForReplicationStatus(netAppMgmtClient, "Broken");
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
// sync to the test
WaitForSucceeded(netAppMgmtClient, accountName: ResourceUtils.accountName1Repl, poolName: ResourceUtils.poolName1Repl, volumeName: ResourceUtils.volumeName1ReplSource);
// resync
netAppMgmtClient.Volumes.ResyncReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest);
WaitForReplicationStatus(netAppMgmtClient, "Mirrored");
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
// break again
netAppMgmtClient.Volumes.BreakReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest);
WaitForReplicationStatus(netAppMgmtClient, "Broken");
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
// delete the data protection object
// - initiate delete replication on destination, this then releases on source, both resulting in object deletion
netAppMgmtClient.Volumes.DeleteReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest);
var replicationFound = true; // because it was previously present
while (replicationFound)
{
try
{
var replicationStatus = netAppMgmtClient.Volumes.ReplicationStatusMethod(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest);
}
catch
{
// an exception means the replication was not found
// i.e. it has been deleted
// ok without checking it could have been for another reason
// but then the delete below will fail
replicationFound = false;
}
Thread.Sleep(1);
}
// seems the volumes are not always in a terminal state here so check again
// and ensure the replication objects are removed
do
{
sourceVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.repResourceGroup, ResourceUtils.accountName1Repl, ResourceUtils.poolName1Repl, ResourceUtils.volumeName1ReplSource);
dpVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest);
Thread.Sleep(1);
} while ((sourceVolume.ProvisioningState != "Succeeded") || (dpVolume.ProvisioningState != "Succeeded") || (sourceVolume.DataProtection.Replication != null) || (dpVolume.DataProtection.Replication != null));
// now proceed with the delete of the volumes
netAppMgmtClient.Volumes.Delete(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest);
netAppMgmtClient.Volumes.Delete(ResourceUtils.repResourceGroup, ResourceUtils.accountName1Repl, ResourceUtils.poolName1Repl, ResourceUtils.volumeName1ReplSource);
// cleanup pool and account
ResourceUtils.DeletePool(netAppMgmtClient, resourceGroup: ResourceUtils.repResourceGroup, accountName: ResourceUtils.accountName1Repl, poolName: ResourceUtils.poolName1Repl);
ResourceUtils.DeletePool(netAppMgmtClient, ResourceUtils.remotePoolName1, ResourceUtils.remoteAccountName1, ResourceUtils.remoteResourceGroup);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.accountName1Repl, resourceGroup: ResourceUtils.repResourceGroup);
ResourceUtils.DeleteAccount(netAppMgmtClient, ResourceUtils.remoteAccountName1, ResourceUtils.remoteResourceGroup);
}
}
[Fact]
public void ChangePoolForVolume()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// create the volume
var volume = ResourceUtils.CreateVolume(netAppMgmtClient);
// create the other pool
var secondPool = ResourceUtils.CreatePool(netAppMgmtClient, ResourceUtils.poolName2, accountName: ResourceUtils.accountName1, resourceGroup: ResourceUtils.resourceGroup, location: ResourceUtils.location, poolOnly: true, serviceLevel: ServiceLevel.Standard);
Assert.Equal("Premium", volume.ServiceLevel);
Assert.Equal(100 * ResourceUtils.gibibyte, volume.UsageThreshold);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
var poolChangeRequest = new PoolChangeRequest() { NewPoolResourceId = secondPool.Id };
//Change pools
netAppMgmtClient.Volumes.PoolChange(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1, poolChangeRequest);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
// retrieve the volume and check
var volume2 = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName2, ResourceUtils.volumeName1);
Assert.Equal(volume2.Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName2 + '/' + ResourceUtils.volumeName1);
// cleanup
ResourceUtils.DeleteVolume(netAppMgmtClient, volumeName: ResourceUtils.volumeName1, accountName: ResourceUtils.accountName1, poolName: ResourceUtils.poolName2);
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeletePool(netAppMgmtClient, poolName: ResourceUtils.poolName2);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
[Fact]
public void LongListVolumes()
{
HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
using (MockContext context = MockContext.Start(this.GetType()))
{
var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
//Create 100 volumes
var createdVolumes = new List<string>();
int length = 103;
try
{
long setPoolSize = 11*ResourceUtils.tebibyte;
ResourceUtils.CreateVolume(netAppMgmtClient, poolSize: setPoolSize);
createdVolumes.Add(ResourceUtils.volumeName1);
for (int i = 0; i < length-1; i++)
{
ResourceUtils.CreateVolume(netAppMgmtClient, $"{ResourceUtils.volumeName1}-{i}", volumeOnly: true);
createdVolumes.Add($"{ResourceUtils.volumeName1}-{i}");
}
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
//get list of volumnes
var volumesPage = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
// Get all resources by polling on next page link
var volumeResponseList = ListNextLink<Volume>.GetAllResourcesByPollingNextLink(volumesPage, netAppMgmtClient.Volumes.ListNext);
Assert.Equal(length, volumeResponseList.Count);
// cleanup
foreach(var volumeName in createdVolumes)
{
ResourceUtils.DeleteVolume(netAppMgmtClient, volumeName: volumeName);
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(10000);
}
}
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
}
catch (CloudException cex)
{
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
string ble = cex.Message;
//get list of volumnes
var volumesPage = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
// Get all resources by polling on next page link
var volumeResponseList = ListNextLink<Volume>.GetAllResourcesByPollingNextLink(volumesPage, netAppMgmtClient.Volumes.ListNext);
foreach (var volume in volumeResponseList)
{
string volumeName = volume.Name.Split(@"/").Last();
try
{
ResourceUtils.DeleteVolume(netAppMgmtClient, volumeName: volumeName);
}
catch
{
}
}
}
if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record")
{
Thread.Sleep(30000);
}
ResourceUtils.DeletePool(netAppMgmtClient);
ResourceUtils.DeleteAccount(netAppMgmtClient);
}
}
//[Fact]
//public void CleanLongListVolumes()
//{
// HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath();
// using (MockContext context = MockContext.Start(this.GetType()))
// {
// var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK });
// //get list of volumes
// var volumesPage = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1);
// // Get all resources by polling on next page link
// var volumeResponseList = ListNextLink<Volume>.GetAllResourcesByPollingNextLink(volumesPage, netAppMgmtClient.Volumes.ListNext);
// foreach (var volume in volumeResponseList)
// {
// var volumeName = volume.Name.Split('/').Last();
// ResourceUtils.DeleteVolume(netAppMgmtClient, resourceGroup: ResourceUtils.resourceGroup, accountName: ResourceUtils.accountName1, poolName: ResourceUtils.poolName1, volumeName: volumeName);
// }
// ResourceUtils.DeletePool(netAppMgmtClient);
// ResourceUtils.DeleteAccount(netAppMgmtClient);
// }
//}
private static string GetSessionsDirectoryPath()
{
string executingAssemblyPath = typeof(NetApp.Tests.ResourceTests.VolumeTests).GetTypeInfo().Assembly.Location;
return Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Internal;
namespace System.Reflection.Metadata.Ecma335
{
/// <summary>
/// Provides extension methods for working with certain raw elements of the ECMA-335 metadata tables and heaps.
/// </summary>
public static class MetadataReaderExtensions
{
/// <summary>
/// Returns the number of rows in the specified table.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception>
public static int GetTableRowCount(this MetadataReader reader, TableIndex tableIndex)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
if ((int)tableIndex >= MetadataTokens.TableCount)
{
Throw.TableIndexOutOfRange();
}
return reader.TableRowCounts[(int)tableIndex];
}
/// <summary>
/// Returns the size of a row in the specified table.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception>
public static int GetTableRowSize(this MetadataReader reader, TableIndex tableIndex)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
switch (tableIndex)
{
case TableIndex.Module: return reader.ModuleTable.RowSize;
case TableIndex.TypeRef: return reader.TypeRefTable.RowSize;
case TableIndex.TypeDef: return reader.TypeDefTable.RowSize;
case TableIndex.FieldPtr: return reader.FieldPtrTable.RowSize;
case TableIndex.Field: return reader.FieldTable.RowSize;
case TableIndex.MethodPtr: return reader.MethodPtrTable.RowSize;
case TableIndex.MethodDef: return reader.MethodDefTable.RowSize;
case TableIndex.ParamPtr: return reader.ParamPtrTable.RowSize;
case TableIndex.Param: return reader.ParamTable.RowSize;
case TableIndex.InterfaceImpl: return reader.InterfaceImplTable.RowSize;
case TableIndex.MemberRef: return reader.MemberRefTable.RowSize;
case TableIndex.Constant: return reader.ConstantTable.RowSize;
case TableIndex.CustomAttribute: return reader.CustomAttributeTable.RowSize;
case TableIndex.FieldMarshal: return reader.FieldMarshalTable.RowSize;
case TableIndex.DeclSecurity: return reader.DeclSecurityTable.RowSize;
case TableIndex.ClassLayout: return reader.ClassLayoutTable.RowSize;
case TableIndex.FieldLayout: return reader.FieldLayoutTable.RowSize;
case TableIndex.StandAloneSig: return reader.StandAloneSigTable.RowSize;
case TableIndex.EventMap: return reader.EventMapTable.RowSize;
case TableIndex.EventPtr: return reader.EventPtrTable.RowSize;
case TableIndex.Event: return reader.EventTable.RowSize;
case TableIndex.PropertyMap: return reader.PropertyMapTable.RowSize;
case TableIndex.PropertyPtr: return reader.PropertyPtrTable.RowSize;
case TableIndex.Property: return reader.PropertyTable.RowSize;
case TableIndex.MethodSemantics: return reader.MethodSemanticsTable.RowSize;
case TableIndex.MethodImpl: return reader.MethodImplTable.RowSize;
case TableIndex.ModuleRef: return reader.ModuleRefTable.RowSize;
case TableIndex.TypeSpec: return reader.TypeSpecTable.RowSize;
case TableIndex.ImplMap: return reader.ImplMapTable.RowSize;
case TableIndex.FieldRva: return reader.FieldRvaTable.RowSize;
case TableIndex.EncLog: return reader.EncLogTable.RowSize;
case TableIndex.EncMap: return reader.EncMapTable.RowSize;
case TableIndex.Assembly: return reader.AssemblyTable.RowSize;
case TableIndex.AssemblyProcessor: return reader.AssemblyProcessorTable.RowSize;
case TableIndex.AssemblyOS: return reader.AssemblyOSTable.RowSize;
case TableIndex.AssemblyRef: return reader.AssemblyRefTable.RowSize;
case TableIndex.AssemblyRefProcessor: return reader.AssemblyRefProcessorTable.RowSize;
case TableIndex.AssemblyRefOS: return reader.AssemblyRefOSTable.RowSize;
case TableIndex.File: return reader.FileTable.RowSize;
case TableIndex.ExportedType: return reader.ExportedTypeTable.RowSize;
case TableIndex.ManifestResource: return reader.ManifestResourceTable.RowSize;
case TableIndex.NestedClass: return reader.NestedClassTable.RowSize;
case TableIndex.GenericParam: return reader.GenericParamTable.RowSize;
case TableIndex.MethodSpec: return reader.MethodSpecTable.RowSize;
case TableIndex.GenericParamConstraint: return reader.GenericParamConstraintTable.RowSize;
// debug tables
case TableIndex.Document: return reader.DocumentTable.RowSize;
case TableIndex.MethodDebugInformation: return reader.MethodDebugInformationTable.RowSize;
case TableIndex.LocalScope: return reader.LocalScopeTable.RowSize;
case TableIndex.LocalVariable: return reader.LocalVariableTable.RowSize;
case TableIndex.LocalConstant: return reader.LocalConstantTable.RowSize;
case TableIndex.ImportScope: return reader.ImportScopeTable.RowSize;
case TableIndex.StateMachineMethod: return reader.StateMachineMethodTable.RowSize;
case TableIndex.CustomDebugInformation: return reader.CustomDebugInformationTable.RowSize;
default:
throw new ArgumentOutOfRangeException(nameof(tableIndex));
}
}
/// <summary>
/// Returns the offset from the start of metadata to the specified table.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="tableIndex"/> is not a valid table index.</exception>
public static unsafe int GetTableMetadataOffset(this MetadataReader reader, TableIndex tableIndex)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return (int)(reader.GetTableMetadataBlock(tableIndex).Pointer - reader.Block.Pointer);
}
private static MemoryBlock GetTableMetadataBlock(this MetadataReader reader, TableIndex tableIndex)
{
Debug.Assert(reader != null);
switch (tableIndex)
{
case TableIndex.Module: return reader.ModuleTable.Block;
case TableIndex.TypeRef: return reader.TypeRefTable.Block;
case TableIndex.TypeDef: return reader.TypeDefTable.Block;
case TableIndex.FieldPtr: return reader.FieldPtrTable.Block;
case TableIndex.Field: return reader.FieldTable.Block;
case TableIndex.MethodPtr: return reader.MethodPtrTable.Block;
case TableIndex.MethodDef: return reader.MethodDefTable.Block;
case TableIndex.ParamPtr: return reader.ParamPtrTable.Block;
case TableIndex.Param: return reader.ParamTable.Block;
case TableIndex.InterfaceImpl: return reader.InterfaceImplTable.Block;
case TableIndex.MemberRef: return reader.MemberRefTable.Block;
case TableIndex.Constant: return reader.ConstantTable.Block;
case TableIndex.CustomAttribute: return reader.CustomAttributeTable.Block;
case TableIndex.FieldMarshal: return reader.FieldMarshalTable.Block;
case TableIndex.DeclSecurity: return reader.DeclSecurityTable.Block;
case TableIndex.ClassLayout: return reader.ClassLayoutTable.Block;
case TableIndex.FieldLayout: return reader.FieldLayoutTable.Block;
case TableIndex.StandAloneSig: return reader.StandAloneSigTable.Block;
case TableIndex.EventMap: return reader.EventMapTable.Block;
case TableIndex.EventPtr: return reader.EventPtrTable.Block;
case TableIndex.Event: return reader.EventTable.Block;
case TableIndex.PropertyMap: return reader.PropertyMapTable.Block;
case TableIndex.PropertyPtr: return reader.PropertyPtrTable.Block;
case TableIndex.Property: return reader.PropertyTable.Block;
case TableIndex.MethodSemantics: return reader.MethodSemanticsTable.Block;
case TableIndex.MethodImpl: return reader.MethodImplTable.Block;
case TableIndex.ModuleRef: return reader.ModuleRefTable.Block;
case TableIndex.TypeSpec: return reader.TypeSpecTable.Block;
case TableIndex.ImplMap: return reader.ImplMapTable.Block;
case TableIndex.FieldRva: return reader.FieldRvaTable.Block;
case TableIndex.EncLog: return reader.EncLogTable.Block;
case TableIndex.EncMap: return reader.EncMapTable.Block;
case TableIndex.Assembly: return reader.AssemblyTable.Block;
case TableIndex.AssemblyProcessor: return reader.AssemblyProcessorTable.Block;
case TableIndex.AssemblyOS: return reader.AssemblyOSTable.Block;
case TableIndex.AssemblyRef: return reader.AssemblyRefTable.Block;
case TableIndex.AssemblyRefProcessor: return reader.AssemblyRefProcessorTable.Block;
case TableIndex.AssemblyRefOS: return reader.AssemblyRefOSTable.Block;
case TableIndex.File: return reader.FileTable.Block;
case TableIndex.ExportedType: return reader.ExportedTypeTable.Block;
case TableIndex.ManifestResource: return reader.ManifestResourceTable.Block;
case TableIndex.NestedClass: return reader.NestedClassTable.Block;
case TableIndex.GenericParam: return reader.GenericParamTable.Block;
case TableIndex.MethodSpec: return reader.MethodSpecTable.Block;
case TableIndex.GenericParamConstraint: return reader.GenericParamConstraintTable.Block;
// debug tables
case TableIndex.Document: return reader.DocumentTable.Block;
case TableIndex.MethodDebugInformation: return reader.MethodDebugInformationTable.Block;
case TableIndex.LocalScope: return reader.LocalScopeTable.Block;
case TableIndex.LocalVariable: return reader.LocalVariableTable.Block;
case TableIndex.LocalConstant: return reader.LocalConstantTable.Block;
case TableIndex.ImportScope: return reader.ImportScopeTable.Block;
case TableIndex.StateMachineMethod: return reader.StateMachineMethodTable.Block;
case TableIndex.CustomDebugInformation: return reader.CustomDebugInformationTable.Block;
default:
throw new ArgumentOutOfRangeException(nameof(tableIndex));
}
}
/// <summary>
/// Returns the size of the specified heap.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception>
public static int GetHeapSize(this MetadataReader reader, HeapIndex heapIndex)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return reader.GetMetadataBlock(heapIndex).Length;
}
/// <summary>
/// Returns the offset from the start of metadata to the specified heap.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception>
public static unsafe int GetHeapMetadataOffset(this MetadataReader reader, HeapIndex heapIndex)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return (int)(reader.GetMetadataBlock(heapIndex).Pointer - reader.Block.Pointer);
}
/// <summary>
/// Returns the size of the specified heap.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="heapIndex"/> is not a valid heap index.</exception>
private static MemoryBlock GetMetadataBlock(this MetadataReader reader, HeapIndex heapIndex)
{
Debug.Assert(reader != null);
switch (heapIndex)
{
case HeapIndex.UserString:
return reader.UserStringHeap.Block;
case HeapIndex.String:
return reader.StringHeap.Block;
case HeapIndex.Blob:
return reader.BlobHeap.Block;
case HeapIndex.Guid:
return reader.GuidHeap.Block;
default:
throw new ArgumentOutOfRangeException(nameof(heapIndex));
}
}
/// <summary>
/// Returns the a handle to the UserString that follows the given one in the UserString heap or a nil handle if it is the last one.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
public static UserStringHandle GetNextHandle(this MetadataReader reader, UserStringHandle handle)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return reader.UserStringHeap.GetNextHandle(handle);
}
/// <summary>
/// Returns the a handle to the Blob that follows the given one in the Blob heap or a nil handle if it is the last one.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
public static BlobHandle GetNextHandle(this MetadataReader reader, BlobHandle handle)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return reader.BlobHeap.GetNextHandle(handle);
}
/// <summary>
/// Returns the a handle to the String that follows the given one in the String heap or a nil handle if it is the last one.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
public static StringHandle GetNextHandle(this MetadataReader reader, StringHandle handle)
{
if (reader == null)
{
Throw.ArgumentNull(nameof(reader));
}
return reader.StringHeap.GetNextHandle(handle);
}
/// <summary>
/// Enumerates entries of EnC log.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
public static IEnumerable<EditAndContinueLogEntry> GetEditAndContinueLogEntries(this MetadataReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
for (int rid = 1; rid <= reader.EncLogTable.NumberOfRows; rid++)
{
yield return new EditAndContinueLogEntry(
new EntityHandle(reader.EncLogTable.GetToken(rid)),
reader.EncLogTable.GetFuncCode(rid));
}
}
/// <summary>
/// Enumerates entries of EnC map.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="reader"/> is null.</exception>
public static IEnumerable<EntityHandle> GetEditAndContinueMapEntries(this MetadataReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
for (int rid = 1; rid <= reader.EncMapTable.NumberOfRows; rid++)
{
yield return new EntityHandle(reader.EncMapTable.GetToken(rid));
}
}
/// <summary>
/// Enumerate types that define one or more properties.
/// </summary>
/// <returns>
/// The resulting sequence corresponds exactly to entries in PropertyMap table,
/// i.e. n-th returned <see cref="TypeDefinitionHandle"/> is stored in n-th row of PropertyMap.
/// </returns>
public static IEnumerable<TypeDefinitionHandle> GetTypesWithProperties(this MetadataReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
for (int rid = 1; rid <= reader.PropertyMapTable.NumberOfRows; rid++)
{
yield return reader.PropertyMapTable.GetParentType(rid);
}
}
/// <summary>
/// Enumerate types that define one or more events.
/// </summary>
/// <returns>
/// The resulting sequence corresponds exactly to entries in EventMap table,
/// i.e. n-th returned <see cref="TypeDefinitionHandle"/> is stored in n-th row of EventMap.
/// </returns>
public static IEnumerable<TypeDefinitionHandle> GetTypesWithEvents(this MetadataReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
for (int rid = 1; rid <= reader.EventMapTable.NumberOfRows; rid++)
{
yield return reader.EventMapTable.GetParentType(rid);
}
}
/// <summary>
/// Given a type handle and a raw type kind found in a signature blob determines whether the target type is a value type or a reference type.
/// </summary>
public static SignatureTypeKind ResolveSignatureTypeKind(this MetadataReader reader, EntityHandle typeHandle, byte rawTypeKind)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
var typeKind = (SignatureTypeKind)rawTypeKind;
switch (typeKind)
{
case SignatureTypeKind.Unknown:
return SignatureTypeKind.Unknown;
case SignatureTypeKind.Class:
case SignatureTypeKind.ValueType:
break;
default:
// If read from metadata by the decoder the value would have been checked already.
// So it is the callers error to pass in an invalid value, not bad metadata.
throw new ArgumentOutOfRangeException(nameof(rawTypeKind));
}
switch (typeHandle.Kind)
{
case HandleKind.TypeDefinition:
// WinRT projections don't apply to TypeDefs
return typeKind;
case HandleKind.TypeReference:
var treatment = reader.GetTypeReference((TypeReferenceHandle)typeHandle).SignatureTreatment;
switch (treatment)
{
case TypeRefSignatureTreatment.ProjectedToClass:
return SignatureTypeKind.Class;
case TypeRefSignatureTreatment.ProjectedToValueType:
return SignatureTypeKind.ValueType;
case TypeRefSignatureTreatment.None:
return typeKind;
default:
throw ExceptionUtilities.UnexpectedValue(treatment);
}
case HandleKind.TypeSpecification:
// TODO: https://github.com/dotnet/corefx/issues/8139
// We need more work here in differentiating case because instantiations can project class
// to value type as in IReference<T> -> Nullable<T>. Unblocking Roslyn work where the differentiation
// feature is not used. Note that the use-case of custom-mods will not hit this because there is no
// CLASS | VALUETYPE before the modifier token and so it always comes in unresolved.
return SignatureTypeKind.Unknown;
default:
throw new ArgumentOutOfRangeException(nameof(typeHandle), SR.Format(SR.UnexpectedHandleKind, typeHandle.Kind));
}
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using Adaptive.SimpleBinaryEncoding;
namespace Adaptive.SimpleBinaryEncoding.PerfTests.Bench.SBE.FIX
{
public class MarketDataIncrementalRefresh
{
public const ushort TemplateId = (ushort)88;
public const byte TemplateVersion = (byte)0;
public const ushort BlockLength = (ushort)2;
public const string SematicType = "X";
private readonly MarketDataIncrementalRefresh _parentMessage;
private DirectBuffer _buffer;
private int _offset;
private int _limit;
private int _actingBlockLength;
private int _actingVersion;
public int Offset { get { return _offset; } }
public MarketDataIncrementalRefresh()
{
_parentMessage = this;
}
public void WrapForEncode(DirectBuffer buffer, int offset)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = BlockLength;
_actingVersion = TemplateVersion;
Limit = offset + _actingBlockLength;
}
public void WrapForDecode(DirectBuffer buffer, int offset,
int actingBlockLength, int actingVersion)
{
_buffer = buffer;
_offset = offset;
_actingBlockLength = actingBlockLength;
_actingVersion = actingVersion;
Limit = offset + _actingBlockLength;
}
public int Size
{
get
{
return _limit - _offset;
}
}
public int Limit
{
get
{
return _limit;
}
set
{
_buffer.CheckLimit(_limit);
_limit = value;
}
}
public const int TradeDateSchemaId = 75;
public static string TradeDateMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ushort TradeDateNullValue = (ushort)65535;
public const ushort TradeDateMinValue = (ushort)0;
public const ushort TradeDateMaxValue = (ushort)65534;
public ushort TradeDate
{
get
{
return _buffer.Uint16GetLittleEndian(_offset + 0);
}
set
{
_buffer.Uint16PutLittleEndian(_offset + 0, value);
}
}
private readonly EntriesGroup _entries = new EntriesGroup();
public const long EntriesSchemaId = 268;
public EntriesGroup Entries
{
get
{
_entries.WrapForDecode(_parentMessage, _buffer, _actingVersion);
return _entries;
}
}
public EntriesGroup EntriesCount(int count)
{
_entries.WrapForEncode(_parentMessage, _buffer, count);
return _entries;
}
public class EntriesGroup
{
private readonly GroupSizeEncoding _dimensions = new GroupSizeEncoding();
private MarketDataIncrementalRefresh _parentMessage;
private DirectBuffer _buffer;
private int _blockLength;
private int _actingVersion;
private int _count;
private int _index;
private int _offset;
public void WrapForDecode(MarketDataIncrementalRefresh parentMessage, DirectBuffer buffer, int actingVersion)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, actingVersion);
_count = _dimensions.NumInGroup;
_blockLength = _dimensions.BlockLength;
_actingVersion = actingVersion;
_index = -1;
_parentMessage.Limit = parentMessage.Limit + 3;
}
public void WrapForEncode(MarketDataIncrementalRefresh parentMessage, DirectBuffer buffer, int count)
{
_parentMessage = parentMessage;
_buffer = buffer;
_dimensions.Wrap(buffer, parentMessage.Limit, _actingVersion);
_dimensions.NumInGroup = (byte)count;
_dimensions.BlockLength = (ushort)82;
_index = -1;
_count = count;
_blockLength = 82;
parentMessage.Limit = parentMessage.Limit + 3;
}
public int Count { get { return _count; } }
public bool HasNext { get { return _index + 1 < _count; } }
public EntriesGroup Next()
{
if (_index + 1 >= _count)
{
throw new InvalidOperationException();
}
_offset = _parentMessage.Limit;
_parentMessage.Limit = _offset + _blockLength;
++_index;
return this;
}
public const int MdUpdateActionSchemaId = 279;
public static string MdUpdateActionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public MDUpdateAction MdUpdateAction
{
get
{
return (MDUpdateAction)_buffer.Uint8Get(_offset + 0);
}
set
{
_buffer.Uint8Put(_offset + 0, (byte)value);
}
}
public const int MdPriceLevelSchemaId = 1023;
public static string MdPriceLevelMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "MDPriceLevel";
}
return "";
}
public const byte MdPriceLevelNullValue = (byte)255;
public const byte MdPriceLevelMinValue = (byte)0;
public const byte MdPriceLevelMaxValue = (byte)254;
public byte MdPriceLevel
{
get
{
return _buffer.Uint8Get(_offset + 1);
}
set
{
_buffer.Uint8Put(_offset + 1, value);
}
}
public const int MdEntryTypeSchemaId = 269;
public static string MdEntryTypeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public MDEntryType MdEntryType
{
get
{
return (MDEntryType)_buffer.CharGet(_offset + 2);
}
set
{
_buffer.CharPut(_offset + 2, (byte)value);
}
}
public const int SecurityIdSourceSchemaId = 22;
public static string SecurityIdSourceMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "SecurityID";
}
return "";
}
public const byte SecurityIdSourceNullValue = (byte)0;
public const byte SecurityIdSourceMinValue = (byte)32;
public const byte SecurityIdSourceMaxValue = (byte)126;
public byte SecurityIdSource
{
get
{
return _buffer.CharGet(_offset + 3);
}
set
{
_buffer.CharPut(_offset + 3, value);
}
}
public const int SecurityIdSchemaId = 48;
public static string SecurityIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "InstrumentID";
}
return "";
}
public const ulong SecurityIdNullValue = 0x8000000000000000UL;
public const ulong SecurityIdMinValue = 0x0UL;
public const ulong SecurityIdMaxValue = 0x7fffffffffffffffUL;
public ulong SecurityId
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 4);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 4, value);
}
}
public const int RptSeqSchemaId = 83;
public static string RptSeqMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "SequenceNumber";
}
return "";
}
public const byte RptSeqNullValue = (byte)255;
public const byte RptSeqMinValue = (byte)0;
public const byte RptSeqMaxValue = (byte)254;
public byte RptSeq
{
get
{
return _buffer.Uint8Get(_offset + 12);
}
set
{
_buffer.Uint8Put(_offset + 12, value);
}
}
public const int QuoteConditionSchemaId = 276;
public static string QuoteConditionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public QuoteCondition QuoteCondition
{
get
{
return (QuoteCondition)_buffer.Uint8Get(_offset + 13);
}
set
{
_buffer.Uint8Put(_offset + 13, (byte)value);
}
}
public const int MdEntryPxSchemaId = 270;
public static string MdEntryPxMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "Price";
}
return "";
}
private readonly Decimal64 _mdEntryPx = new Decimal64();
public Decimal64 MdEntryPx
{
get
{
_mdEntryPx.Wrap(_buffer, _offset + 14, _actingVersion);
return _mdEntryPx;
}
}
public const int NumberOfOrdersSchemaId = 346;
public static string NumberOfOrdersMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "NumberOfOrders";
}
return "";
}
public const uint NumberOfOrdersNullValue = 4294967294U;
public const uint NumberOfOrdersMinValue = 0U;
public const uint NumberOfOrdersMaxValue = 4294967293U;
public uint NumberOfOrders
{
get
{
return _buffer.Uint32GetLittleEndian(_offset + 22);
}
set
{
_buffer.Uint32PutLittleEndian(_offset + 22, value);
}
}
public const int MdEntryTimeSchemaId = 273;
public static string MdEntryTimeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ulong MdEntryTimeNullValue = 0x8000000000000000UL;
public const ulong MdEntryTimeMinValue = 0x0UL;
public const ulong MdEntryTimeMaxValue = 0x7fffffffffffffffUL;
public ulong MdEntryTime
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 26);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 26, value);
}
}
public const int MdEntrySizeSchemaId = 271;
public static string MdEntrySizeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
private readonly IntQty32 _mdEntrySize = new IntQty32();
public IntQty32 MdEntrySize
{
get
{
_mdEntrySize.Wrap(_buffer, _offset + 34, _actingVersion);
return _mdEntrySize;
}
}
public const int TradingSessionIdSchemaId = 336;
public static string TradingSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public MarketStateIdentifier TradingSessionId
{
get
{
return (MarketStateIdentifier)_buffer.Uint8Get(_offset + 38);
}
set
{
_buffer.Uint8Put(_offset + 38, (byte)value);
}
}
public const int NetChgPrevDaySchemaId = 451;
public static string NetChgPrevDayMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
private readonly Decimal64 _netChgPrevDay = new Decimal64();
public Decimal64 NetChgPrevDay
{
get
{
_netChgPrevDay.Wrap(_buffer, _offset + 39, _actingVersion);
return _netChgPrevDay;
}
}
public const int TickDirectionSchemaId = 274;
public static string TickDirectionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public TickDirection TickDirection
{
get
{
return (TickDirection)_buffer.Uint8Get(_offset + 47);
}
set
{
_buffer.Uint8Put(_offset + 47, (byte)value);
}
}
public const int OpenCloseSettleFlagSchemaId = 286;
public static string OpenCloseSettleFlagMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public OpenCloseSettleFlag OpenCloseSettleFlag
{
get
{
return (OpenCloseSettleFlag)_buffer.Uint16GetLittleEndian(_offset + 48);
}
set
{
_buffer.Uint16PutLittleEndian(_offset + 48, (ushort)value);
}
}
public const int SettleDateSchemaId = 64;
public static string SettleDateMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ulong SettleDateNullValue = 0x8000000000000000UL;
public const ulong SettleDateMinValue = 0x0UL;
public const ulong SettleDateMaxValue = 0x7fffffffffffffffUL;
public ulong SettleDate
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 50);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 50, value);
}
}
public const int TradeConditionSchemaId = 277;
public static string TradeConditionMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public TradeCondition TradeCondition
{
get
{
return (TradeCondition)_buffer.Uint8Get(_offset + 58);
}
set
{
_buffer.Uint8Put(_offset + 58, (byte)value);
}
}
public const int TradeVolumeSchemaId = 1020;
public static string TradeVolumeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
private readonly IntQty32 _tradeVolume = new IntQty32();
public IntQty32 TradeVolume
{
get
{
_tradeVolume.Wrap(_buffer, _offset + 59, _actingVersion);
return _tradeVolume;
}
}
public const int MdQuoteTypeSchemaId = 1070;
public static string MdQuoteTypeMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public MDQuoteType MdQuoteType
{
get
{
return (MDQuoteType)_buffer.Uint8Get(_offset + 63);
}
set
{
_buffer.Uint8Put(_offset + 63, (byte)value);
}
}
public const int FixingBracketSchemaId = 5790;
public static string FixingBracketMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public const ulong FixingBracketNullValue = 0x8000000000000000UL;
public const ulong FixingBracketMinValue = 0x0UL;
public const ulong FixingBracketMaxValue = 0x7fffffffffffffffUL;
public ulong FixingBracket
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 64);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 64, value);
}
}
public const int AggressorSideSchemaId = 5797;
public static string AggressorSideMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public Side AggressorSide
{
get
{
return (Side)_buffer.CharGet(_offset + 72);
}
set
{
_buffer.CharPut(_offset + 72, (byte)value);
}
}
public const int MatchEventIndicatorSchemaId = 5799;
public static string MatchEventIndicatorMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "";
}
return "";
}
public MatchEventIndicator MatchEventIndicator
{
get
{
return (MatchEventIndicator)_buffer.CharGet(_offset + 73);
}
set
{
_buffer.CharPut(_offset + 73, (byte)value);
}
}
public const int TradeIdSchemaId = 1003;
public static string TradeIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.Epoch: return "unix";
case MetaAttribute.TimeUnit: return "nanosecond";
case MetaAttribute.SemanticType: return "ExecID";
}
return "";
}
public const ulong TradeIdNullValue = 0x8000000000000000UL;
public const ulong TradeIdMinValue = 0x0UL;
public const ulong TradeIdMaxValue = 0x7fffffffffffffffUL;
public ulong TradeId
{
get
{
return _buffer.Uint64GetLittleEndian(_offset + 74);
}
set
{
_buffer.Uint64PutLittleEndian(_offset + 74, value);
}
}
}
}
}
| |
using System;
using System.Xml;
using System.IO;
using System.Net;
using System.Text;
using System.Security;
namespace Hydra.Framework.XmlSerialization.XInclude
{
//
//**********************************************************************
/// <summary>
/// Custom <c>XmlReader</c>, handler for parse="text" case.
/// </summary>
//**********************************************************************
//
internal class TextIncludingReader : XmlReader
{
#region private fields
private string _encoding;
private ReadState _state;
private string _value;
private Uri _includeLocation;
private string _accept, _acceptLanguage;
private string _href;
private bool _exposeCDATA;
#endregion
#region constructors
public TextIncludingReader(Uri includeLocation, string encoding,
string accept, string acceptLanguage, bool exposeCDATA)
{
_includeLocation = includeLocation;
_href = includeLocation.AbsoluteUri;
_encoding = encoding;
_state = ReadState.Initial;
_accept = accept;
_acceptLanguage = acceptLanguage;
_exposeCDATA = exposeCDATA;
}
public TextIncludingReader(string value, bool exposeCDATA)
{
_state = ReadState.Initial;
_exposeCDATA = exposeCDATA;
_value = value;
}
#endregion
#region XmlReader overrides
public override int AttributeCount
{
get { return 0; }
}
public override string BaseURI
{
get { return _href; }
}
public override int Depth
{
get { return _state == ReadState.Interactive ? 1 : 0; }
}
public override bool EOF
{
get { return _state == ReadState.EndOfFile ? true : false; }
}
public override bool HasValue
{
get { return _state == ReadState.Interactive ? true : false; }
}
public override bool IsDefault
{
get { return false; }
}
public override bool IsEmptyElement
{
get { return false; }
}
public override string this[int index]
{
get { return String.Empty; }
}
public override string this[string qname]
{
get { return String.Empty; }
}
public override string this[string localname, string nsuri]
{
get { return String.Empty; }
}
public override string LocalName
{
get { return String.Empty; }
}
public override string Name
{
get { return String.Empty; }
}
public override string NamespaceURI
{
get { return String.Empty; }
}
public override XmlNameTable NameTable
{
get { return null; }
}
public override XmlNodeType NodeType
{
get
{
return _state == ReadState.Interactive ?
_exposeCDATA ? XmlNodeType.CDATA : XmlNodeType.Text
: XmlNodeType.None;
}
}
public override string Prefix
{
get { return String.Empty; }
}
public override char QuoteChar
{
get { return '"'; }
}
public override ReadState ReadState
{
get { return _state; }
}
public override string Value
{
get { return _state == ReadState.Interactive ? _value : String.Empty; }
}
public override string XmlLang
{
get { return String.Empty; }
}
public override XmlSpace XmlSpace
{
get { return XmlSpace.None; }
}
public override void Close()
{
_state = ReadState.Closed;
}
public override string GetAttribute(int index)
{
throw new ArgumentOutOfRangeException("index", index, "No attributes exposed");
}
public override string GetAttribute(string qname)
{
return null;
}
public override string GetAttribute(string localname, string nsuri)
{
return null;
}
public override string LookupNamespace(string prefix)
{
return null;
}
public override void MoveToAttribute(int index) { }
public override bool MoveToAttribute(string qname)
{
return false;
}
public override bool MoveToAttribute(string localname, string nsuri)
{
return false;
}
public override bool MoveToElement()
{
return false;
}
public override bool MoveToFirstAttribute()
{
return false;
}
public override bool MoveToNextAttribute()
{
return false;
}
public override bool ReadAttributeValue()
{
return false;
}
public override string ReadInnerXml()
{
return _state == ReadState.Interactive ? _value : String.Empty;
}
public override string ReadOuterXml()
{
return _state == ReadState.Interactive ? _value : String.Empty;
}
public override string ReadString()
{
return _state == ReadState.Interactive ? _value : String.Empty;
}
public override void ResolveEntity() { }
public override bool Read()
{
switch (_state)
{
case ReadState.Initial:
if (_value == null)
{
WebResponse wRes;
Stream stream = XIncludingReader.GetResource(_includeLocation.AbsoluteUri,
_accept, _acceptLanguage, out wRes);
StreamReader reader;
/* According to the spec, encoding should be determined as follows:
* external encoding information, if available, otherwise
* if the media type of the resource is text/xml, application/xml,
or matches the conventions text/*+xml or application/*+xml as
described in XML Media Types [IETF RFC 3023], the encoding is
recognized as specified in XML 1.0, otherwise
* the value of the encoding attribute if one exists, otherwise
* UTF-8.
*/
try
{
//TODO: try to get "content-encoding" from wRes.Headers collection?
//If mime type is xml-aware, get resource encoding as per XML 1.0
string contentType = wRes.ContentType.ToLower();
if (contentType == "text/xml" ||
contentType == "application/xml" ||
contentType.StartsWith("text/") && contentType.EndsWith("+xml") ||
contentType.StartsWith("application/") && contentType.EndsWith("+xml"))
{
//Yes, that's xml, let's read encoding from the xml declaration
reader = new StreamReader(stream, GetEncodingFromXMLDecl(_href));
}
else if (_encoding != null)
{
//Try to use user-specified encoding
Encoding enc;
try
{
enc = Encoding.GetEncoding(_encoding);
}
catch (Exception e)
{
throw new ResourceException(SR.GetString("NotSupportedEncoding",
_encoding), e);
}
reader = new StreamReader(stream, enc);
}
else
//Fallback to UTF-8
reader = new StreamReader(stream, Encoding.UTF8);
_value = reader.ReadToEnd();
TextUtils.CheckForNonXmlChars(_value);
}
catch (ResourceException re)
{
throw re;
}
catch (OutOfMemoryException oome)
{
//Crazy include - memory is out
//TODO: what about reading by chunks?
throw new ResourceException(SR.GetString("OutOfMemoryWhileFetchingResource", _href), oome);
}
catch (IOException ioe)
{
throw new ResourceException(SR.GetString("IOErrorWhileFetchingResource", _href), ioe);
}
}
_state = ReadState.Interactive;
return true;
case ReadState.Interactive:
//No more input
_state = ReadState.EndOfFile;
return false;
default:
return false;
}
} // Read()
#endregion
#region private methods
//
//**********************************************************************
/// <summary>
/// Reads encoding from the XML declarartion.
/// </summary>
/// <param name="href">URI reference indicating the location
/// of the resource to inlclude.</param>
/// <returns>The document encoding as per XML declaration.</returns>
/// <exception cref="ResourceException">Resource error.</exception>
//**********************************************************************
//
private Encoding GetEncodingFromXMLDecl(string href)
{
XmlTextReader tmpReader = new XmlTextReader(href);
tmpReader.ProhibitDtd = false;
tmpReader.WhitespaceHandling = WhitespaceHandling.None;
try
{
while (tmpReader.Read() && tmpReader.Encoding == null) { }
Encoding enc = tmpReader.Encoding;
return enc == null ? Encoding.UTF8 : enc;
}
finally
{
tmpReader.Close();
}
}
#endregion
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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 ASC.Core;
using ASC.Notify.Model;
using ASC.Notify.Recipients;
using ASC.Web.Community.Modules.News.Resources;
using ASC.Web.Community.News.Code.DAO;
using ASC.Web.Core.Subscriptions;
namespace ASC.Web.Community.News.Code.Module
{
public class SubscriptionManager : ISubscriptionManager
{
private Guid _newsSubscriptionTypeID = new Guid("{C27F9ADE-81C9-4103-B617-607811897C17}");
private static Guid SubscribeToNewsCommentsTypeID = Guid.NewGuid();
private bool IsEmptySubscriptionType(Guid productID, Guid moduleID, Guid typeID)
{
var type = GetSubscriptionTypes().Find(t => t.ID.Equals(typeID));
var objIDs = SubscriptionProvider.GetSubscriptions(type.NotifyAction, new DirectRecipient(SecurityContext.CurrentAccount.ID.ToString(), ""), false);
if (objIDs != null && objIDs.Length > 0)
return false;
return true;
}
private static INotifyAction GetNotifyActionBySubscriptionType(FeedSubscriptionType subscriptionType)
{
switch (subscriptionType)
{
case FeedSubscriptionType.NewFeed: return NewsConst.NewFeed;
}
return null;
}
#region ISubscriptionManager Members
public ISubscriptionProvider SubscriptionProvider
{
get
{
return NewsNotifySource.Instance.GetSubscriptionProvider();
}
}
#region Subscription Objects
private List<SubscriptionObject> GetNewFeedSubscriptionObjects(Guid productID, Guid moduleOrGroupID, Guid typeID)
{
return GetSubscriptionObjects(true, false);
}
private List<SubscriptionObject> GetNewCommentSubscriptionObjects(Guid productID, Guid moduleOrGroupID, Guid typeID)
{
return GetSubscriptionObjects(false, true);
}
private List<SubscriptionObject> GetSubscriptionObjects(bool includeFeed, bool includeComments)
{
List<SubscriptionObject> subscriptionObjects = new List<SubscriptionObject>();
IList<string> list = new List<string>();
var currentAccount = SecurityContext.CurrentAccount;
if (includeFeed)
{
list = new List<string>(
SubscriptionProvider.GetSubscriptions(
NewsConst.NewFeed,
new DirectRecipient(currentAccount.ID.ToString(), currentAccount.Name), false)
);
if (list.Count > 0)
{
foreach (string id in list)
{
if (!string.IsNullOrEmpty(id))
{
subscriptionObjects.Add(new SubscriptionObject()
{
ID = id,
Name = NewsResource.NotifyOnNewFeed,
URL = string.Empty,
SubscriptionType = GetSubscriptionTypes()[0]
});
}
}
}
}
if (includeComments)
{
list = new List<string>(
SubscriptionProvider.GetSubscriptions(
NewsConst.NewComment,
new DirectRecipient(currentAccount.ID.ToString(), currentAccount.Name), false)
);
if (list.Count > 0)
{
var storage = FeedStorageFactory.Create();
foreach (string id in list)
{
if (!string.IsNullOrEmpty(id))
{
try
{
var feedID = Int32.Parse(id);
var feed = storage.GetFeed(feedID);
subscriptionObjects.Add(new SubscriptionObject()
{
ID = id,
Name = feed.Caption,
URL = FeedUrls.GetFeedAbsolutePath(feed.Id),
SubscriptionType = GetSubscriptionTypes()[1]
});
}
catch { }
}
}
}
}
return subscriptionObjects;
}
public List<SubscriptionObject> GetSubscriptionObjects(Guid subItem)
{
return GetSubscriptionObjects(true, true);
}
#endregion
public List<SubscriptionType> GetSubscriptionTypes()
{
var subscriptionTypes = new List<SubscriptionType>();
subscriptionTypes.Add(new SubscriptionType()
{
ID = _newsSubscriptionTypeID,
Name = NewsResource.NotifyOnNewFeed,
NotifyAction = GetNotifyActionBySubscriptionType(FeedSubscriptionType.NewFeed),
Single = true,
IsEmptySubscriptionType = new IsEmptySubscriptionTypeDelegate(IsEmptySubscriptionType),
GetSubscriptionObjects = GetNewFeedSubscriptionObjects,
CanSubscribe = true
});
subscriptionTypes.Add(new SubscriptionType()
{
ID = SubscribeToNewsCommentsTypeID,
Name = NewsResource.NotificationOnNewComments,
NotifyAction = NewsConst.NewComment,
Single = false,
IsEmptySubscriptionType = new IsEmptySubscriptionTypeDelegate(IsEmptySubscriptionType),
GetSubscriptionObjects = GetNewCommentSubscriptionObjects
});
return subscriptionTypes;
}
public void UnsubscribeForObject(Guid subscriptionTypeId)
{
ISubscriptionProvider subscriptionProvider = NewsNotifySource.Instance.GetSubscriptionProvider();
if (subscriptionTypeId == _newsSubscriptionTypeID)
{
subscriptionProvider.UnSubscribe(
NewsConst.NewFeed,
null,
NewsNotifySource.Instance.GetRecipientsProvider().
GetRecipient(SecurityContext.CurrentAccount.
ID.ToString())
);
}
}
#endregion
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Utility.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.PowerShell.Utility\Select-String command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class SelectString : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public SelectString()
{
this.DisplayName = "Select-String";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.PowerShell.Utility\\Select-String"; } }
// Arguments
/// <summary>
/// Provides access to the InputObject parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSObject> InputObject { get; set; }
/// <summary>
/// Provides access to the Pattern parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> Pattern { get; set; }
/// <summary>
/// Provides access to the Path parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> Path { get; set; }
/// <summary>
/// Provides access to the LiteralPath parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> LiteralPath { get; set; }
/// <summary>
/// Provides access to the SimpleMatch parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> SimpleMatch { get; set; }
/// <summary>
/// Provides access to the CaseSensitive parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> CaseSensitive { get; set; }
/// <summary>
/// Provides access to the Quiet parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Quiet { get; set; }
/// <summary>
/// Provides access to the List parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> List { get; set; }
/// <summary>
/// Provides access to the Include parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> Include { get; set; }
/// <summary>
/// Provides access to the Exclude parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String[]> Exclude { get; set; }
/// <summary>
/// Provides access to the NotMatch parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> NotMatch { get; set; }
/// <summary>
/// Provides access to the AllMatches parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> AllMatches { get; set; }
/// <summary>
/// Provides access to the Encoding parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Encoding { get; set; }
/// <summary>
/// Provides access to the Context parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int32[]> Context { get; set; }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(InputObject.Expression != null)
{
targetCommand.AddParameter("InputObject", InputObject.Get(context));
}
if(Pattern.Expression != null)
{
targetCommand.AddParameter("Pattern", Pattern.Get(context));
}
if(Path.Expression != null)
{
targetCommand.AddParameter("Path", Path.Get(context));
}
if(LiteralPath.Expression != null)
{
targetCommand.AddParameter("LiteralPath", LiteralPath.Get(context));
}
if(SimpleMatch.Expression != null)
{
targetCommand.AddParameter("SimpleMatch", SimpleMatch.Get(context));
}
if(CaseSensitive.Expression != null)
{
targetCommand.AddParameter("CaseSensitive", CaseSensitive.Get(context));
}
if(Quiet.Expression != null)
{
targetCommand.AddParameter("Quiet", Quiet.Get(context));
}
if(List.Expression != null)
{
targetCommand.AddParameter("List", List.Get(context));
}
if(Include.Expression != null)
{
targetCommand.AddParameter("Include", Include.Get(context));
}
if(Exclude.Expression != null)
{
targetCommand.AddParameter("Exclude", Exclude.Get(context));
}
if(NotMatch.Expression != null)
{
targetCommand.AddParameter("NotMatch", NotMatch.Get(context));
}
if(AllMatches.Expression != null)
{
targetCommand.AddParameter("AllMatches", AllMatches.Get(context));
}
if(Encoding.Expression != null)
{
targetCommand.AddParameter("Encoding", Encoding.Get(context));
}
if(Context.Expression != null)
{
targetCommand.AddParameter("Context", Context.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Documents;
using Lucene.Net.Search;
using Lucene.Net.Support;
namespace Lucene.Net.Index.Memory
{
/// <summary>
/// High-performance single-document main memory Apache Lucene fulltext search index.
///
/// <h4>Overview</h4>
///
/// This class is a replacement/substitute for a large subset of
/// {@link RAMDirectory} functionality. It is designed to
/// enable maximum efficiency for on-the-fly matchmaking combining structured and
/// fuzzy fulltext search in realtime streaming applications such as Nux XQuery based XML
/// message queues, publish-subscribe systems for Blogs/newsfeeds, text chat, data acquisition and
/// distribution systems, application level routers, firewalls, classifiers, etc.
/// Rather than targeting fulltext search of infrequent queries over huge persistent
/// data archives (historic search), this class targets fulltext search of huge
/// numbers of queries over comparatively small transient realtime data (prospective
/// search).
/// For example as in
/// <pre>
/// float score = search(String text, Query query)
/// </pre>
/// <p/>
/// Each instance can hold at most one Lucene "document", with a document containing
/// zero or more "fields", each field having a name and a fulltext value. The
/// fulltext value is tokenized (split and transformed) into zero or more index terms
/// (aka words) on <c>addField()</c>, according to the policy implemented by an
/// Analyzer. For example, Lucene analyzers can split on whitespace, normalize to lower case
/// for case insensitivity, ignore common terms with little discriminatory value such as "he", "in", "and" (stop
/// words), reduce the terms to their natural linguistic root form such as "fishing"
/// being reduced to "fish" (stemming), resolve synonyms/inflexions/thesauri
/// (upon indexing and/or querying), etc. For details, see
/// <a target="_blank" href="http://today.java.net/pub/a/today/2003/07/30/LuceneIntro.html">Lucene Analyzer Intro</a>.
/// <p/>
/// Arbitrary Lucene queries can be run against this class - see <a target="_blank"
/// href="../../../../../../../queryparsersyntax.html">Lucene Query Syntax</a>
/// as well as <a target="_blank"
/// href="http://today.java.net/pub/a/today/2003/11/07/QueryParserRules.html">Query Parser Rules</a>.
/// Note that a Lucene query selects on the field names and associated (indexed)
/// tokenized terms, not on the original fulltext(s) - the latter are not stored
/// but rather thrown away immediately after tokenization.
/// <p/>
/// For some interesting background information on search technology, see Bob Wyman's
/// <a target="_blank"
/// href="http://bobwyman.pubsub.com/main/2005/05/mary_hodder_poi.html">Prospective Search</a>,
/// Jim Gray's
/// <a target="_blank" href="http://www.acmqueue.org/modules.php?name=Content&pa=showpage&pid=293&page=4">
/// A Call to Arms - Custom subscriptions</a>, and Tim Bray's
/// <a target="_blank"
/// href="http://www.tbray.org/ongoing/When/200x/2003/07/30/OnSearchTOC">On Search, the Series</a>.
///
///
/// <h4>Example Usage</h4>
///
/// <pre>
/// Analyzer analyzer = PatternAnalyzer.DEFAULT_ANALYZER;
/// //Analyzer analyzer = new SimpleAnalyzer();
/// MemoryIndex index = new MemoryIndex();
/// index.addField("content", "Readings about Salmons and other select Alaska fishing Manuals", analyzer);
/// index.addField("author", "Tales of James", analyzer);
/// QueryParser parser = new QueryParser("content", analyzer);
/// float score = index.search(parser.parse("+author:james +salmon~ +fish/// manual~"));
/// if (score > 0.0f) {
/// System.out.println("it's a match");
/// } else {
/// System.out.println("no match found");
/// }
/// System.out.println("indexData=" + index.toString());
/// </pre>
///
///
/// <h4>Example XQuery Usage</h4>
///
/// <pre>
/// (: An XQuery that finds all books authored by James that have something to do with "salmon fishing manuals", sorted by relevance :)
/// declare namespace lucene = "java:nux.xom.pool.FullTextUtil";
/// declare variable $query := "+salmon~ +fish/// manual~"; (: any arbitrary Lucene query can go here :)
///
/// for $book in /books/book[author="James" and lucene:match(abstract, $query) > 0.0]
/// let $score := lucene:match($book/abstract, $query)
/// order by $score descending
/// return $book
/// </pre>
///
///
/// <h4>No thread safety guarantees</h4>
///
/// An instance can be queried multiple times with the same or different queries,
/// but an instance is not thread-safe. If desired use idioms such as:
/// <pre>
/// MemoryIndex index = ...
/// synchronized (index) {
/// // read and/or write index (i.e. add fields and/or query)
/// }
/// </pre>
///
///
/// <h4>Performance Notes</h4>
///
/// Internally there's a new data structure geared towards efficient indexing
/// and searching, plus the necessary support code to seamlessly plug into the Lucene
/// framework.
/// <p/>
/// This class performs very well for very small texts (e.g. 10 chars)
/// as well as for large texts (e.g. 10 MB) and everything in between.
/// Typically, it is about 10-100 times faster than <c>RAMDirectory</c>.
/// Note that <c>RAMDirectory</c> has particularly
/// large efficiency overheads for small to medium sized texts, both in time and space.
/// Indexing a field with N tokens takes O(N) in the best case, and O(N logN) in the worst
/// case. Memory consumption is probably larger than for <c>RAMDirectory</c>.
/// <p/>
/// Example throughput of many simple term queries over a single MemoryIndex:
/// ~500000 queries/sec on a MacBook Pro, jdk 1.5.0_06, server VM.
/// As always, your mileage may vary.
/// <p/>
/// If you're curious about
/// the whereabouts of bottlenecks, run java 1.5 with the non-perturbing '-server
/// -agentlib:hprof=cpu=samples,depth=10' flags, then study the trace log and
/// correlate its hotspot trailer with its call stack headers (see <a
/// target="_blank" href="http://java.sun.com/developer/technicalArticles/Programming/HPROF.html">
/// hprof tracing </a>).
///
///</summary>
[Serializable]
public partial class MemoryIndex
{
/* info for each field: Map<String fieldName, Info field> */
private HashMap<String, Info> fields = new HashMap<String, Info>();
/* fields sorted ascending by fieldName; lazily computed on demand */
[NonSerialized] private KeyValuePair<String, Info>[] sortedFields;
/* pos: positions[3*i], startOffset: positions[3*i +1], endOffset: positions[3*i +2] */
private int stride;
/* Could be made configurable; See {@link Document#setBoost(float)} */
private static float docBoost = 1.0f;
private static long serialVersionUID = 2782195016849084649L;
private static bool DEBUG = false;
/*
* Constructs an empty instance.
*/
public MemoryIndex()
: this(false)
{
}
/*
* Constructs an empty instance that can optionally store the start and end
* character offset of each token term in the text. This can be useful for
* highlighting of hit locations with the Lucene highlighter package.
* Private until the highlighter package matures, so that this can actually
* be meaningfully integrated.
*
* @param storeOffsets
* whether or not to store the start and end character offset of
* each token term in the text
*/
private MemoryIndex(bool storeOffsets)
{
this.stride = storeOffsets ? 3 : 1;
}
/*
* Convenience method; Tokenizes the given field text and adds the resulting
* terms to the index; Equivalent to adding an indexed non-keyword Lucene
* {@link org.apache.lucene.document.Field} that is
* {@link org.apache.lucene.document.Field.Index#ANALYZED tokenized},
* {@link org.apache.lucene.document.Field.Store#NO not stored},
* {@link org.apache.lucene.document.Field.TermVector#WITH_POSITIONS termVectorStored with positions} (or
* {@link org.apache.lucene.document.Field.TermVector#WITH_POSITIONS termVectorStored with positions and offsets}),
*
* @param fieldName
* a name to be associated with the text
* @param text
* the text to tokenize and index.
* @param analyzer
* the analyzer to use for tokenization
*/
public void AddField(String fieldName, String text, Analyzer analyzer)
{
if (fieldName == null)
throw new ArgumentException("fieldName must not be null");
if (text == null)
throw new ArgumentException("text must not be null");
if (analyzer == null)
throw new ArgumentException("analyzer must not be null");
TokenStream stream = analyzer.TokenStream(fieldName, new StringReader(text));
AddField(fieldName, stream);
}
/*
* Convenience method; Creates and returns a token stream that generates a
* token for each keyword in the given collection, "as is", without any
* transforming text analysis. The resulting token stream can be fed into
* {@link #addField(String, TokenStream)}, perhaps wrapped into another
* {@link org.apache.lucene.analysis.TokenFilter}, as desired.
*
* @param keywords
* the keywords to generate tokens for
* @return the corresponding token stream
*/
public TokenStream CreateKeywordTokenStream<T>(ICollection<T> keywords)
{
// TODO: deprecate & move this method into AnalyzerUtil?
if (keywords == null)
throw new ArgumentException("keywords must not be null");
return new KeywordTokenStream<T>(keywords);
}
/*
* Equivalent to <c>addField(fieldName, stream, 1.0f)</c>.
*
* @param fieldName
* a name to be associated with the text
* @param stream
* the token stream to retrieve tokens from
*/
public void AddField(String fieldName, TokenStream stream)
{
AddField(fieldName, stream, 1.0f);
}
/*
* Iterates over the given token stream and adds the resulting terms to the index;
* Equivalent to adding a tokenized, indexed, termVectorStored, unstored,
* Lucene {@link org.apache.lucene.document.Field}.
* Finally closes the token stream. Note that untokenized keywords can be added with this method via
* {@link #CreateKeywordTokenStream(Collection)}, the Lucene contrib <c>KeywordTokenizer</c> or similar utilities.
*
* @param fieldName
* a name to be associated with the text
* @param stream
* the token stream to retrieve tokens from.
* @param boost
* the boost factor for hits for this field
* @see org.apache.lucene.document.Field#setBoost(float)
*/
public void AddField(String fieldName, TokenStream stream, float boost)
{
try
{
if (fieldName == null)
throw new ArgumentException("fieldName must not be null");
if (stream == null)
throw new ArgumentException("token stream must not be null");
if (boost <= 0.0f)
throw new ArgumentException("boost factor must be greater than 0.0");
if (fields[fieldName] != null)
throw new ArgumentException("field must not be added more than once");
var terms = new HashMap<String, ArrayIntList>();
int numTokens = 0;
int numOverlapTokens = 0;
int pos = -1;
var termAtt = stream.AddAttribute<ITermAttribute>();
var posIncrAttribute = stream.AddAttribute<IPositionIncrementAttribute>();
var offsetAtt = stream.AddAttribute<IOffsetAttribute>();
stream.Reset();
while (stream.IncrementToken())
{
String term = termAtt.Term;
if (term.Length == 0) continue; // nothing to do
// if (DEBUG) System.Diagnostics.Debug.WriteLine("token='" + term + "'");
numTokens++;
int posIncr = posIncrAttribute.PositionIncrement;
if (posIncr == 0)
numOverlapTokens++;
pos += posIncr;
ArrayIntList positions = terms[term];
if (positions == null)
{
// term not seen before
positions = new ArrayIntList(stride);
terms[term] = positions;
}
if (stride == 1)
{
positions.Add(pos);
}
else
{
positions.Add(pos, offsetAtt.StartOffset, offsetAtt.EndOffset);
}
}
stream.End();
// ensure infos.numTokens > 0 invariant; needed for correct operation of terms()
if (numTokens > 0)
{
boost = boost*docBoost; // see DocumentWriter.addDocument(...)
fields[fieldName] = new Info(terms, numTokens, numOverlapTokens, boost);
sortedFields = null; // invalidate sorted view, if any
}
}
catch (IOException e)
{
// can never happen
throw new SystemException(string.Empty, e);
}
finally
{
try
{
if (stream != null) stream.Close();
}
catch (IOException e2)
{
throw new SystemException(string.Empty, e2);
}
}
}
/*
* Creates and returns a searcher that can be used to execute arbitrary
* Lucene queries and to collect the resulting query results as hits.
*
* @return a searcher
*/
public IndexSearcher CreateSearcher()
{
MemoryIndexReader reader = new MemoryIndexReader(this);
IndexSearcher searcher = new IndexSearcher(reader); // ensures no auto-close !!
reader.SetSearcher(searcher); // to later get hold of searcher.getSimilarity()
return searcher;
}
/*
* Convenience method that efficiently returns the relevance score by
* matching this index against the given Lucene query expression.
*
* @param query
* an arbitrary Lucene query to run against this index
* @return the relevance score of the matchmaking; A number in the range
* [0.0 .. 1.0], with 0.0 indicating no match. The higher the number
* the better the match.
*
*/
public float Search(Query query)
{
if (query == null)
throw new ArgumentException("query must not be null");
Searcher searcher = CreateSearcher();
try
{
float[] scores = new float[1]; // inits to 0.0f (no match)
searcher.Search(query, new FillingCollector(scores));
float score = scores[0];
return score;
}
catch (IOException e)
{
// can never happen (RAMDirectory)
throw new SystemException(string.Empty, e);
}
finally
{
// searcher.close();
/*
* Note that it is harmless and important for good performance to
* NOT close the index reader!!! This avoids all sorts of
* unnecessary baggage and locking in the Lucene IndexReader
* superclass, all of which is completely unnecessary for this main
* memory index data structure without thread-safety claims.
*
* Wishing IndexReader would be an interface...
*
* Actually with the new tight createSearcher() API auto-closing is now
* made impossible, hence searcher.close() would be harmless and also
* would not degrade performance...
*/
}
}
/*
* Returns a reasonable approximation of the main memory [bytes] consumed by
* this instance. Useful for smart memory sensititive caches/pools. Assumes
* fieldNames are interned, whereas tokenized terms are memory-overlaid.
*
* @return the main memory consumption
*/
public int GetMemorySize()
{
// for example usage in a smart cache see nux.xom.pool.Pool
int PTR = VM.PTR;
int INT = VM.INT;
int size = 0;
size += VM.SizeOfObject(2*PTR + INT); // memory index
if (sortedFields != null) size += VM.SizeOfObjectArray(sortedFields.Length);
size += VM.SizeOfHashMap(fields.Count);
foreach (var entry in fields)
{
// for each Field Info
Info info = entry.Value;
size += VM.SizeOfObject(2*INT + 3*PTR); // Info instance vars
if (info.SortedTerms != null) size += VM.SizeOfObjectArray(info.SortedTerms.Length);
int len = info.Terms.Count;
size += VM.SizeOfHashMap(len);
var iter2 = info.Terms.GetEnumerator();
while (--len >= 0)
{
iter2.MoveNext();
// for each term
KeyValuePair<String, ArrayIntList> e = iter2.Current;
size += VM.SizeOfObject(PTR + 3*INT); // assumes substring() memory overlay
// size += STR + 2 * ((String) e.getKey()).length();
ArrayIntList positions = e.Value;
size += VM.SizeOfArrayIntList(positions.Size());
}
}
return size;
}
private int NumPositions(ArrayIntList positions)
{
return positions.Size()/stride;
}
/* sorts into ascending order (on demand), reusing memory along the way */
private void SortFields()
{
if (sortedFields == null) sortedFields = Sort(fields);
}
/* returns a view of the given map's entries, sorted ascending by key */
private static KeyValuePair<TKey, TValue>[] Sort<TKey, TValue>(HashMap<TKey, TValue> map)
where TKey : class, IComparable<TKey>
{
int size = map.Count;
var entries = map.ToArray();
if (size > 1) Array.Sort(entries, TermComparer.KeyComparer);
return entries;
}
/*
* Returns a String representation of the index data for debugging purposes.
*
* @return the string representation
*/
public override String ToString()
{
StringBuilder result = new StringBuilder(256);
SortFields();
int sumChars = 0;
int sumPositions = 0;
int sumTerms = 0;
for (int i = 0; i < sortedFields.Length; i++)
{
KeyValuePair<String, Info> entry = sortedFields[i];
String fieldName = entry.Key;
Info info = entry.Value;
info.SortTerms();
result.Append(fieldName + ":\n");
int numChars = 0;
int numPos = 0;
for (int j = 0; j < info.SortedTerms.Length; j++)
{
KeyValuePair<String, ArrayIntList> e = info.SortedTerms[j];
String term = e.Key;
ArrayIntList positions = e.Value;
result.Append("\t'" + term + "':" + NumPositions(positions) + ":");
result.Append(positions.ToString(stride)); // ignore offsets
result.Append("\n");
numPos += NumPositions(positions);
numChars += term.Length;
}
result.Append("\tterms=" + info.SortedTerms.Length);
result.Append(", positions=" + numPos);
result.Append(", Kchars=" + (numChars/1000.0f));
result.Append("\n");
sumPositions += numPos;
sumChars += numChars;
sumTerms += info.SortedTerms.Length;
}
result.Append("\nfields=" + sortedFields.Length);
result.Append(", terms=" + sumTerms);
result.Append(", positions=" + sumPositions);
result.Append(", Kchars=" + (sumChars/1000.0f));
return result.ToString();
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
/*
* Index data structure for a field; Contains the tokenized term texts and
* their positions.
*/
[Serializable]
private sealed class Info
{
public static readonly IComparer<KeyValuePair<string, Info>> InfoComparer = new TermComparer<Info>();
public static readonly IComparer<KeyValuePair<string, ArrayIntList>> ArrayIntListComparer = new TermComparer<ArrayIntList>();
/*
* Term strings and their positions for this field: Map <String
* termText, ArrayIntList positions>
*/
private HashMap<String, ArrayIntList> terms;
/* Terms sorted ascending by term text; computed on demand */
[NonSerialized] private KeyValuePair<String, ArrayIntList>[] sortedTerms;
/* Number of added tokens for this field */
private int numTokens;
/* Number of overlapping tokens for this field */
private int numOverlapTokens;
/* Boost factor for hits for this field */
private float boost;
/* Term for this field's fieldName, lazily computed on demand */
[NonSerialized] public Term template;
private static long serialVersionUID = 2882195016849084649L;
public Info(HashMap<String, ArrayIntList> terms, int numTokens, int numOverlapTokens, float boost)
{
this.terms = terms;
this.numTokens = numTokens;
this.NumOverlapTokens = numOverlapTokens;
this.boost = boost;
}
public HashMap<string, ArrayIntList> Terms
{
get { return terms; }
}
public int NumTokens
{
get { return numTokens; }
}
public int NumOverlapTokens
{
get { return numOverlapTokens; }
set { numOverlapTokens = value; }
}
public float Boost
{
get { return boost; }
}
public KeyValuePair<string, ArrayIntList>[] SortedTerms
{
get { return sortedTerms; }
}
/*
* Sorts hashed terms into ascending order, reusing memory along the
* way. Note that sorting is lazily delayed until required (often it's
* not required at all). If a sorted view is required then hashing +
* sort + binary search is still faster and smaller than TreeMap usage
* (which would be an alternative and somewhat more elegant approach,
* apart from more sophisticated Tries / prefix trees).
*/
public void SortTerms()
{
if (SortedTerms == null) sortedTerms = Sort(Terms);
}
/* note that the frequency can be calculated as numPosition(getPositions(x)) */
public ArrayIntList GetPositions(String term)
{
return Terms[term];
}
/* note that the frequency can be calculated as numPosition(getPositions(x)) */
public ArrayIntList GetPositions(int pos)
{
return SortedTerms[pos].Value;
}
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
/*
* Efficient resizable auto-expanding list holding <c>int</c> elements;
* implemented with arrays.
*/
[Serializable]
private sealed class ArrayIntList
{
private int[] elements;
private int size = 0;
private static long serialVersionUID = 2282195016849084649L;
private ArrayIntList()
: this(10)
{
}
public ArrayIntList(int initialCapacity)
{
elements = new int[initialCapacity];
}
public void Add(int elem)
{
if (size == elements.Length) EnsureCapacity(size + 1);
elements[size++] = elem;
}
public void Add(int pos, int start, int end)
{
if (size + 3 > elements.Length) EnsureCapacity(size + 3);
elements[size] = pos;
elements[size + 1] = start;
elements[size + 2] = end;
size += 3;
}
public int Get(int index)
{
if (index >= size) ThrowIndex(index);
return elements[index];
}
public int Size()
{
return size;
}
public int[] ToArray(int stride)
{
int[] arr = new int[Size()/stride];
if (stride == 1)
{
Array.Copy(elements, 0, arr, 0, size);
}
else
{
for (int i = 0, j = 0; j < size; i++, j += stride) arr[i] = elements[j];
}
return arr;
}
private void EnsureCapacity(int minCapacity)
{
int newCapacity = Math.Max(minCapacity, (elements.Length*3)/2 + 1);
int[] newElements = new int[newCapacity];
Array.Copy(elements, 0, newElements, 0, size);
elements = newElements;
}
private void ThrowIndex(int index)
{
throw new IndexOutOfRangeException("index: " + index
+ ", size: " + size);
}
/* returns the first few positions (without offsets); debug only */
public string ToString(int stride)
{
int s = Size()/stride;
int len = Math.Min(10, s); // avoid printing huge lists
StringBuilder buf = new StringBuilder(4*len);
buf.Append("[");
for (int i = 0; i < len; i++)
{
buf.Append(Get(i*stride));
if (i < len - 1) buf.Append(", ");
}
if (len != s) buf.Append(", ..."); // and some more...
buf.Append("]");
return buf.ToString();
}
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
private static readonly Term MATCH_ALL_TERM = new Term("");
/*
* Search support for Lucene framework integration; implements all methods
* required by the Lucene IndexReader contracts.
*/
private sealed partial class MemoryIndexReader : IndexReader
{
private readonly MemoryIndex _index;
private Searcher searcher; // needed to find searcher.getSimilarity()
internal MemoryIndexReader(MemoryIndex index)
{
_index = index;
}
private Info GetInfo(String fieldName)
{
return _index.fields[fieldName];
}
private Info GetInfo(int pos)
{
return _index.sortedFields[pos].Value;
}
public override int DocFreq(Term term)
{
Info info = GetInfo(term.Field);
int freq = 0;
if (info != null) freq = info.GetPositions(term.Text) != null ? 1 : 0;
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.docFreq: " + term + ", freq:" + freq);
return freq;
}
public override TermEnum Terms()
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.terms()");
return Terms(MATCH_ALL_TERM);
}
public override TermEnum Terms(Term term)
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.terms: " + term);
int i; // index into info.sortedTerms
int j; // index into sortedFields
_index.SortFields();
if (_index.sortedFields.Length == 1 && _index.sortedFields[0].Key == term.Field)
{
j = 0; // fast path
}
else
{
j = Array.BinarySearch(_index.sortedFields, new KeyValuePair<string, Info>(term.Field, null), Info.InfoComparer);
}
if (j < 0)
{
// not found; choose successor
j = -j - 1;
i = 0;
if (j < _index.sortedFields.Length) GetInfo(j).SortTerms();
}
else
{
// found
Info info = GetInfo(j);
info.SortTerms();
i = Array.BinarySearch(info.SortedTerms, new KeyValuePair<string, ArrayIntList>(term.Text, null), Info.ArrayIntListComparer);
if (i < 0)
{
// not found; choose successor
i = -i - 1;
if (i >= info.SortedTerms.Length)
{
// move to next successor
j++;
i = 0;
if (j < _index.sortedFields.Length) GetInfo(j).SortTerms();
}
}
}
int ix = i;
int jx = j;
return new MemoryTermEnum(_index, this, ix, jx);
}
public override TermPositions TermPositions()
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.termPositions");
return new MemoryTermPositions(_index, this);
}
public override TermDocs TermDocs()
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.termDocs");
return TermPositions();
}
public override ITermFreqVector[] GetTermFreqVectors(int docNumber)
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.getTermFreqVectors");
// This is okay, ToArray() is as optimized as writing it by hand
return _index.fields.Keys.Select(k => GetTermFreqVector(docNumber, k)).ToArray();
}
public override void GetTermFreqVector(int docNumber, TermVectorMapper mapper)
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.getTermFreqVectors");
// if (vectors.length == 0) return null;
foreach (String fieldName in _index.fields.Keys)
{
GetTermFreqVector(docNumber, fieldName, mapper);
}
}
public override void GetTermFreqVector(int docNumber, String field, TermVectorMapper mapper)
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.getTermFreqVector");
Info info = GetInfo(field);
if (info == null)
{
return;
}
info.SortTerms();
mapper.SetExpectations(field, info.SortedTerms.Length, _index.stride != 1, true);
for (int i = info.SortedTerms.Length; --i >= 0;)
{
ArrayIntList positions = info.SortedTerms[i].Value;
int size = positions.Size();
var offsets = new TermVectorOffsetInfo[size/_index.stride];
for (int k = 0, j = 1; j < size; k++, j += _index.stride)
{
int start = positions.Get(j);
int end = positions.Get(j + 1);
offsets[k] = new TermVectorOffsetInfo(start, end);
}
mapper.Map(info.SortedTerms[i].Key, _index.NumPositions(info.SortedTerms[i].Value), offsets,
(info.SortedTerms[i].Value).ToArray(_index.stride));
}
}
public override ITermFreqVector GetTermFreqVector(int docNumber, String fieldName)
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.getTermFreqVector");
Info info = GetInfo(fieldName);
if (info == null) return null; // TODO: or return empty vector impl???
info.SortTerms();
return new MemoryTermPositionVector(_index, info, fieldName);
}
private Similarity GetSimilarity()
{
if (searcher != null) return searcher.Similarity;
return Similarity.Default;
}
internal void SetSearcher(Searcher searcher)
{
this.searcher = searcher;
}
/* performance hack: cache norms to avoid repeated expensive calculations */
private byte[] cachedNorms;
private String cachedFieldName;
private Similarity cachedSimilarity;
public override byte[] Norms(String fieldName)
{
byte[] norms = cachedNorms;
Similarity sim = GetSimilarity();
if (fieldName != cachedFieldName || sim != cachedSimilarity)
{
// not cached?
Info info = GetInfo(fieldName);
int numTokens = info != null ? info.NumTokens : 0;
int numOverlapTokens = info != null ? info.NumOverlapTokens : 0;
float boost = info != null ? info.Boost : 1.0f;
FieldInvertState invertState = new FieldInvertState(0, numTokens, numOverlapTokens, 0, boost);
float n = sim.ComputeNorm(fieldName, invertState);
byte norm = Similarity.EncodeNorm(n);
norms = new byte[] {norm};
// cache it for future reuse
cachedNorms = norms;
cachedFieldName = fieldName;
cachedSimilarity = sim;
if (DEBUG)
System.Diagnostics.Debug.WriteLine("MemoryIndexReader.norms: " + fieldName + ":" + n + ":" +
norm + ":" + numTokens);
}
return norms;
}
public override void Norms(String fieldName, byte[] bytes, int offset)
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.norms*: " + fieldName);
byte[] norms = Norms(fieldName);
Buffer.BlockCopy(norms, 0, bytes, offset, norms.Length);
}
protected override void DoSetNorm(int doc, String fieldName, byte value)
{
throw new NotSupportedException();
}
public override int NumDocs()
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.numDocs");
return _index.fields.Count > 0 ? 1 : 0;
}
public override int MaxDoc
{
get
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.maxDoc");
return 1;
}
}
public override Document Document(int n)
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.document");
return new Document(); // there are no stored fields
}
//When we convert to JDK 1.5 make this Set<String>
public override Document Document(int n, FieldSelector fieldSelector)
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.document");
return new Document(); // there are no stored fields
}
public override bool IsDeleted(int n)
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.isDeleted");
return false;
}
public override bool HasDeletions
{
get
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.hasDeletions");
return false;
}
}
protected override void DoDelete(int docNum)
{
throw new NotSupportedException();
}
protected override void DoUndeleteAll()
{
throw new NotSupportedException();
}
protected override void DoCommit(IDictionary<String, String> commitUserData)
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.doCommit");
}
protected override void DoClose()
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.doClose");
}
// lucene >= 1.9 (remove this method for lucene-1.4.3)
public override ICollection<String> GetFieldNames(FieldOption fieldOption)
{
if (DEBUG) System.Diagnostics.Debug.WriteLine("MemoryIndexReader.getFieldNamesOption");
if (fieldOption == FieldOption.UNINDEXED)
return CollectionsHelper<string>.EmptyList();
if (fieldOption == FieldOption.INDEXED_NO_TERMVECTOR)
return CollectionsHelper<string>.EmptyList();
if (fieldOption == FieldOption.TERMVECTOR_WITH_OFFSET && _index.stride == 1)
return CollectionsHelper<string>.EmptyList();
if (fieldOption == FieldOption.TERMVECTOR_WITH_POSITION_OFFSET && _index.stride == 1)
return CollectionsHelper<string>.EmptyList();
return _index.fields.Keys.AsReadOnly();
}
}
///////////////////////////////////////////////////////////////////////////////
// Nested classes:
///////////////////////////////////////////////////////////////////////////////
private static class VM
{
public static readonly int PTR = Is64BitVM() ? 8 : 4;
// bytes occupied by primitive data types
public static readonly int BOOLEAN = 1;
public static readonly int BYTE = 1;
public static readonly int CHAR = 2;
public static readonly int SHORT = 2;
public static readonly int INT = 4;
public static readonly int LONG = 8;
public static readonly int FLOAT = 4;
public static readonly int DOUBLE = 8;
private static readonly int LOG_PTR = (int) Math.Round(Log2(PTR));
/*
* Object header of any heap allocated Java object.
* ptr to class, info for monitor, gc, hash, etc.
*/
private static readonly int OBJECT_HEADER = 2*PTR;
// assumes n > 0
// 64 bit VM:
// 0 --> 0*PTR
// 1..8 --> 1*PTR
// 9..16 --> 2*PTR
private static int SizeOf(int n)
{
return (((n - 1) >> LOG_PTR) + 1) << LOG_PTR;
}
public static int SizeOfObject(int n)
{
return SizeOf(OBJECT_HEADER + n);
}
public static int SizeOfObjectArray(int len)
{
return SizeOfObject(INT + PTR*len);
}
public static int SizeOfCharArray(int len)
{
return SizeOfObject(INT + CHAR*len);
}
public static int SizeOfIntArray(int len)
{
return SizeOfObject(INT + INT*len);
}
public static int SizeOfString(int len)
{
return SizeOfObject(3*INT + PTR) + SizeOfCharArray(len);
}
public static int SizeOfHashMap(int len)
{
return SizeOfObject(4*PTR + 4*INT) + SizeOfObjectArray(len)
+ len*SizeOfObject(3*PTR + INT); // entries
}
// note: does not include referenced objects
public static int SizeOfArrayList(int len)
{
return SizeOfObject(PTR + 2*INT) + SizeOfObjectArray(len);
}
public static int SizeOfArrayIntList(int len)
{
return SizeOfObject(PTR + INT) + SizeOfIntArray(len);
}
private static bool Is64BitVM()
{
return IntPtr.Size == 8;
}
/* logarithm to the base 2. Example: log2(4) == 2, log2(8) == 3 */
private static double Log2(double value)
{
return Math.Log(value, 2);
//return Math.Log(value) / Math.Log(2);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
using Orleans;
using Orleans.CodeGeneration;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;
using Orleans.TestingHost.Legacy;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
using TestExtensions;
using TestVersionGrainInterfaces;
using TestVersionGrains;
using Xunit;
namespace Tester.HeterogeneousSilosTests.UpgradeTests
{
public abstract class UpgradeTestsBase : IDisposable
{
private readonly TimeSpan refreshInterval = TimeSpan.FromMilliseconds(200);
private TimeSpan waitDelay;
protected IClusterClient Client => this.cluster.Client;
protected IManagementGrain ManagementGrain => this.cluster.Client.GetGrain<IManagementGrain>(0);
#if DEBUG
private const string BuildConfiguration = "Debug";
#else
private const string BuildConfiguration = "Release";
#endif
private const string AssemblyGrainsV1Build = "TestVersionGrainsV1";
private const string AssemblyGrainsV2Build = "TestVersionGrainsV2";
private const string CommonParentDirectory = "test";
private const string BinDirectory = "bin";
private const string VersionsProjectDirectory = "Versions";
private const string GrainsV1ProjectName = "TestVersionGrains";
private const string GrainsV2ProjectName = "TestVersionGrains2";
private const string VersionTestBinaryName = "TestVersionGrains.dll";
private readonly DirectoryInfo assemblyGrainsV1Dir;
private readonly DirectoryInfo assemblyGrainsV2Dir;
private readonly List<SiloHandle> deployedSilos = new List<SiloHandle>();
private int siloIdx = 0;
private TestClusterBuilder builder;
private TestCluster cluster;
protected abstract VersionSelectorStrategy VersionSelectorStrategy { get; }
protected abstract CompatibilityStrategy CompatibilityStrategy { get; }
protected virtual short SiloCount => 2;
protected UpgradeTestsBase()
{
// Setup dll references
// If test run from old master cmd line with single output directory
if (Directory.Exists(AssemblyGrainsV1Build))
{
assemblyGrainsV1Dir = new DirectoryInfo(AssemblyGrainsV1Build);
assemblyGrainsV2Dir = new DirectoryInfo(AssemblyGrainsV2Build);
}
else
{
var testDirectory = new DirectoryInfo(GetType().Assembly.Location);
while (String.Compare(testDirectory.Name, CommonParentDirectory, StringComparison.OrdinalIgnoreCase) != 0 || testDirectory.Parent == null)
{
testDirectory = testDirectory.Parent;
}
if (testDirectory.Parent == null)
{
throw new InvalidOperationException($"Cannot locate 'test' directory starting from '{GetType().Assembly.Location}'");
}
assemblyGrainsV1Dir = GetVersionTestDirectory(testDirectory, GrainsV1ProjectName);
assemblyGrainsV2Dir = GetVersionTestDirectory(testDirectory, GrainsV2ProjectName);
}
}
private DirectoryInfo GetVersionTestDirectory(DirectoryInfo testDirectory, string directoryName)
{
var projectDirectory = Path.Combine(testDirectory.FullName, VersionsProjectDirectory, directoryName, BinDirectory);
var directories = Directory.GetDirectories(projectDirectory, BuildConfiguration, SearchOption.AllDirectories);
if (directories.Length != 1)
{
throw new InvalidOperationException($"Number of directories found for pattern: '{BuildConfiguration}' under {testDirectory.FullName}: {directories.Length}");
}
var files = Directory.GetFiles(directories[0], VersionTestBinaryName, SearchOption.AllDirectories);
if (files.Length != 1)
{
throw new InvalidOperationException($"Number of files found for pattern: '{VersionTestBinaryName}' under {testDirectory.FullName}: {files.Length}");
}
return new DirectoryInfo(Path.GetDirectoryName(files[0]));
}
protected async Task Step1_StartV1Silo_Step2_StartV2Silo_Step3_StopV2Silo(int step2Version)
{
const int numberOfGrains = 100;
await StartSiloV1();
// Only V1 exist for now
for (var i = 0; i < numberOfGrains; i++)
{
var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i);
Assert.Equal(1, await grain.GetVersion());
}
// Start a new silo with V2
var siloV2 = await StartSiloV2();
for (var i = 0; i < numberOfGrains; i++)
{
var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i);
Assert.Equal(1, await grain.GetVersion());
}
for (var i = numberOfGrains; i < numberOfGrains * 2; i++)
{
var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i);
Assert.Equal(step2Version, await grain.GetVersion());
}
// Stop the V2 silo
await StopSilo(siloV2);
// Now all activation should be V1
for (var i = 0; i < numberOfGrains * 3; i++)
{
var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i);
Assert.Equal(1, await grain.GetVersion());
}
}
protected async Task ProxyCallNoPendingRequest(int expectedVersion)
{
await StartSiloV1();
// Only V1 exist for now
var grain0 = Client.GetGrain<IVersionUpgradeTestGrain>(0);
Assert.Equal(1, await grain0.GetVersion());
await StartSiloV2();
// New activation should be V2
var grain1 = Client.GetGrain<IVersionUpgradeTestGrain>(1);
Assert.Equal(2, await grain1.GetVersion());
Assert.Equal(expectedVersion, await grain1.ProxyGetVersion(grain0));
Assert.Equal(expectedVersion, await grain0.GetVersion());
}
protected async Task ProxyCallWithPendingRequest(int expectedVersion)
{
await StartSiloV1();
// Only V1 exist for now
var grain0 = Client.GetGrain<IVersionUpgradeTestGrain>(0);
Assert.Equal(1, await grain0.GetVersion());
// Start a new silo with V2
await StartSiloV2();
// New activation should be V2
var grain1 = Client.GetGrain<IVersionUpgradeTestGrain>(1);
Assert.Equal(2, await grain1.GetVersion());
var waitingTask = grain0.LongRunningTask(TimeSpan.FromSeconds(5));
var callBeforeUpgrade = grain0.GetVersion();
await Task.Delay(100); // Make sure requests are not sent out of order
var callProvokingUpgrade = grain1.ProxyGetVersion(grain0);
await waitingTask;
Assert.Equal(1, await callBeforeUpgrade);
Assert.Equal(expectedVersion, await callProvokingUpgrade);
}
protected async Task<SiloHandle> StartSiloV1()
{
var handle = await StartSilo(assemblyGrainsV1Dir);
await Task.Delay(waitDelay);
return handle;
}
protected async Task<SiloHandle> StartSiloV2()
{
var handle = await StartSilo(assemblyGrainsV2Dir);
await Task.Delay(waitDelay);
return handle;
}
private async Task<SiloHandle> StartSilo(DirectoryInfo rootDir)
{
SiloHandle silo;
if (this.siloIdx == 0)
{
// Setup configuration
this.builder = new TestClusterBuilder(1)
{
CreateSilo = AppDomainSiloHandle.Create
};
TestDefaultConfiguration.ConfigureTestCluster(this.builder);
builder.Options.ApplicationBaseDirectory = rootDir.FullName;
builder.AddSiloBuilderConfigurator<VersionGrainsSiloBuilderConfigurator>();
builder.ConfigureLegacyConfiguration(legacy =>
{
legacy.ClusterConfiguration.Globals.ExpectedClusterSize = SiloCount;
legacy.ClusterConfiguration.Globals.AssumeHomogenousSilosForTesting = false;
legacy.ClusterConfiguration.Globals.TypeMapRefreshInterval = refreshInterval;
legacy.ClusterConfiguration.Globals.DefaultVersionSelectorStrategy = VersionSelectorStrategy;
legacy.ClusterConfiguration.Globals.DefaultCompatibilityStrategy = CompatibilityStrategy;
legacy.ClientConfiguration.Gateways = legacy.ClientConfiguration.Gateways.Take(1).ToList(); // Only use primary gw
waitDelay = TestClusterLegacyUtils.GetLivenessStabilizationTime(legacy.ClusterConfiguration.Globals, false);
});
this.cluster = builder.Build();
await this.cluster.DeployAsync();
silo = this.cluster.Primary;
}
else
{
var configBuilder = new ConfigurationBuilder();
foreach (var source in cluster.ConfigurationSources) configBuilder.Add(source);
var testClusterOptions = new TestClusterOptions();
configBuilder.Build().Bind(testClusterOptions);
// Override the root directory.
var sources = new IConfigurationSource[]
{
new MemoryConfigurationSource {InitialData = new TestClusterOptions {ApplicationBaseDirectory = rootDir.FullName}.ToDictionary()}
};
silo = TestCluster.StartOrleansSilo(cluster, siloIdx, testClusterOptions, sources);
}
this.deployedSilos.Add(silo);
this.siloIdx++;
return silo;
}
protected async Task StopSilo(SiloHandle handle)
{
handle?.StopSilo(true);
this.deployedSilos.Remove(handle);
await Task.Delay(waitDelay);
}
public void Dispose()
{
if (!deployedSilos.Any()) return;
var primarySilo = this.deployedSilos[0];
foreach (var silo in this.deployedSilos.Skip(1))
{
silo.Dispose();
}
primarySilo.Dispose();
this.Client?.Dispose();
}
}
}
| |
namespace AngleSharp.Core.Tests.Html
{
using AngleSharp.Dom;
using AngleSharp.Html.Dom;
using NUnit.Framework;
using System;
/// <summary>
/// Tests generated according to the W3C-Test.org page:
/// http://www.w3c-test.org/html/semantics/forms/constraints/form-validation-validity-rangeUnderflow.html
/// </summary>
[TestFixture]
public class ValidityRangeUnderflowTests
{
private static IDocument CreateTestDocument()
{
return String.Empty.ToHtmlDocument();
}
[Test]
public void TestRangeunderflowInputDatetime1()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "2000-01-01T12:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime2()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T12:00:00Z");
element.Value = "";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime3()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01-01 12:00:00Z");
element.Value = "2000-01-01T12:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime4()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T11:00:00Z");
element.Value = "2000-01-01T12:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime5()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01-01T23:59:59Z");
element.Value = "2000-01-01T24:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime6()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "1980-01-01T12:00Z");
element.Value = "79-01-01T12:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime7()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T13:00:00Z");
element.Value = "2000-01-01T12:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime8()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T12:00:00.2Z");
element.Value = "2000-01-01T12:00:00.1Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime9()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T12:00:00.02Z");
element.Value = "2000-01-01T12:00:00.01Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime10()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01T12:00:00.002Z");
element.Value = "2000-01-01T12:00:00.001Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime11()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "9999-01-01T12:00:00Z");
element.Value = "2000-01-01T12:00:00Z";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDatetime12()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "datetime";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "8593-01-01T02:09+02:09");
element.Value = "8592-01-01T02:09+02:09";
Assert.AreEqual("datetime", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate1()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "2000-01-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate2()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01");
element.Value = "";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate3()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001/01/01");
element.Value = "2000-01-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate4()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-02-02");
element.Value = "2000-1-1";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate5()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "988-01-01");
element.Value = "987-01-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate6()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01-01");
element.Value = "2000-13-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate7()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01-01");
element.Value = "2000-02-30";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate8()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01-01");
element.Value = "2000-12-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate9()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-12-01");
element.Value = "2000-01-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputDate10()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "date";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "9999-01-02");
element.Value = "9999-01-01";
Assert.AreEqual("date", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth1()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "2000-01";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth2()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01");
element.Value = "";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth3()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001/01");
element.Value = "2000-02";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth4()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-02");
element.Value = "2000-1";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth5()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "988-01");
element.Value = "987-01";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth6()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01");
element.Value = "2000-13";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth7()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-01");
element.Value = "2000-12";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth8()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-01");
element.Value = "2000-12";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputMonth9()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "month";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "9999-01");
element.Value = "2000-01";
Assert.AreEqual("month", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek1()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "2000-W01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek2()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-W01");
element.Value = "";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek3()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001/W02");
element.Value = "2000-W01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek4()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-W02");
element.Value = "2000-W1";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek5()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-W02");
element.Value = "2000-w01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek6()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "988-W01");
element.Value = "987-W01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek7()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2001-W01");
element.Value = "2000-W57";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek8()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-W01");
element.Value = "2000-W12";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek9()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "2000-W12");
element.Value = "2000-W01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputWeek10()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "week";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "9999-W01");
element.Value = "2000-W01";
Assert.AreEqual("week", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime1()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "12:00:00";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime2()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00");
element.Value = "";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime3()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12.00.01");
element.Value = "12:00:00";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime4()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:01");
element.Value = "12.00.00";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime5()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00");
element.Value = "13:00:00";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime6()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "13:00:00");
element.Value = "12";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime7()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:02");
element.Value = "12:00:00";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime8()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00.2");
element.Value = "12:00:00.1";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime9()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00.02");
element.Value = "12:00:00.01";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime10()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00.002");
element.Value = "12:00:00.001";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputTime11()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "time";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "12:00:00");
element.Value = "11:59";
Assert.AreEqual("time", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber1()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "");
element.Value = "10";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber2()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "5");
element.Value = "";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber3()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "4");
element.Value = "5";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber4()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "-5.6");
element.Value = "-5.5";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
[SetCulture("ru")]
public void TestRangeunderflowInputNumber4InRussia()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "-5.6");
element.Value = "-5.5";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber5()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "0");
element.Value = "-0";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber6()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "5");
element.Value = "6abc";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(false, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber7()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "6");
element.Value = "5";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber8()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "-5.4");
element.Value = "-5.5";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
[Test]
public void TestRangeunderflowInputNumber9()
{
var document = CreateTestDocument();
var element = document.CreateElement("input") as HtmlInputElement;
Assert.IsNotNull(element);
element.Type = "number";
element.RemoveAttribute("required");
element.RemoveAttribute("pattern");
element.RemoveAttribute("step");
element.RemoveAttribute("max");
element.RemoveAttribute("min");
element.RemoveAttribute("maxlength");
element.RemoveAttribute("value");
element.RemoveAttribute("multiple");
element.RemoveAttribute("checked");
element.RemoveAttribute("selected");
element.SetAttribute("min", "5e+2");
element.Value = "-5e-1";
Assert.AreEqual("number", element.Type);
Assert.AreEqual(true, element.Validity.IsRangeUnderflow);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/servicecontrol/v1/metric_value.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.Api.Servicecontrol.V1 {
/// <summary>Holder for reflection information generated from google/api/servicecontrol/v1/metric_value.proto</summary>
public static partial class MetricValueReflection {
#region Descriptor
/// <summary>File descriptor for google/api/servicecontrol/v1/metric_value.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static MetricValueReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ci9nb29nbGUvYXBpL3NlcnZpY2Vjb250cm9sL3YxL21ldHJpY192YWx1ZS5w",
"cm90bxIcZ29vZ2xlLmFwaS5zZXJ2aWNlY29udHJvbC52MRocZ29vZ2xlL2Fw",
"aS9hbm5vdGF0aW9ucy5wcm90bxovZ29vZ2xlL2FwaS9zZXJ2aWNlY29udHJv",
"bC92MS9kaXN0cmlidXRpb24ucHJvdG8aH2dvb2dsZS9wcm90b2J1Zi90aW1l",
"c3RhbXAucHJvdG8aF2dvb2dsZS90eXBlL21vbmV5LnByb3RvIpEDCgtNZXRy",
"aWNWYWx1ZRJFCgZsYWJlbHMYASADKAsyNS5nb29nbGUuYXBpLnNlcnZpY2Vj",
"b250cm9sLnYxLk1ldHJpY1ZhbHVlLkxhYmVsc0VudHJ5Ei4KCnN0YXJ0X3Rp",
"bWUYAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEiwKCGVuZF90",
"aW1lGAMgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIUCgpib29s",
"X3ZhbHVlGAQgASgISAASFQoLaW50NjRfdmFsdWUYBSABKANIABIWCgxkb3Vi",
"bGVfdmFsdWUYBiABKAFIABIWCgxzdHJpbmdfdmFsdWUYByABKAlIABJIChJk",
"aXN0cmlidXRpb25fdmFsdWUYCCABKAsyKi5nb29nbGUuYXBpLnNlcnZpY2Vj",
"b250cm9sLnYxLkRpc3RyaWJ1dGlvbkgAGi0KC0xhYmVsc0VudHJ5EgsKA2tl",
"eRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAFCBwoFdmFsdWUiZwoOTWV0cmlj",
"VmFsdWVTZXQSEwoLbWV0cmljX25hbWUYASABKAkSQAoNbWV0cmljX3ZhbHVl",
"cxgCIAMoCzIpLmdvb2dsZS5hcGkuc2VydmljZWNvbnRyb2wudjEuTWV0cmlj",
"VmFsdWVCiAEKIGNvbS5nb29nbGUuYXBpLnNlcnZpY2Vjb250cm9sLnYxQhNN",
"ZXRyaWNWYWx1ZVNldFByb3RvUAFaSmdvb2dsZS5nb2xhbmcub3JnL2dlbnBy",
"b3RvL2dvb2dsZWFwaXMvYXBpL3NlcnZpY2Vjb250cm9sL3YxO3NlcnZpY2Vj",
"b250cm9s+AEBYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Api.Servicecontrol.V1.DistributionReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::Google.Type.MoneyReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Servicecontrol.V1.MetricValue), global::Google.Api.Servicecontrol.V1.MetricValue.Parser, new[]{ "Labels", "StartTime", "EndTime", "BoolValue", "Int64Value", "DoubleValue", "StringValue", "DistributionValue" }, new[]{ "Value" }, null, new pbr::GeneratedClrTypeInfo[] { null, }),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Servicecontrol.V1.MetricValueSet), global::Google.Api.Servicecontrol.V1.MetricValueSet.Parser, new[]{ "MetricName", "MetricValues" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Represents a single metric value.
/// </summary>
public sealed partial class MetricValue : pb::IMessage<MetricValue> {
private static readonly pb::MessageParser<MetricValue> _parser = new pb::MessageParser<MetricValue>(() => new MetricValue());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<MetricValue> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.Servicecontrol.V1.MetricValueReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MetricValue() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MetricValue(MetricValue other) : this() {
labels_ = other.labels_.Clone();
StartTime = other.startTime_ != null ? other.StartTime.Clone() : null;
EndTime = other.endTime_ != null ? other.EndTime.Clone() : null;
switch (other.ValueCase) {
case ValueOneofCase.BoolValue:
BoolValue = other.BoolValue;
break;
case ValueOneofCase.Int64Value:
Int64Value = other.Int64Value;
break;
case ValueOneofCase.DoubleValue:
DoubleValue = other.DoubleValue;
break;
case ValueOneofCase.StringValue:
StringValue = other.StringValue;
break;
case ValueOneofCase.DistributionValue:
DistributionValue = other.DistributionValue.Clone();
break;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MetricValue Clone() {
return new MetricValue(this);
}
/// <summary>Field number for the "labels" field.</summary>
public const int LabelsFieldNumber = 1;
private static readonly pbc::MapField<string, string>.Codec _map_labels_codec
= new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForString(18), 10);
private readonly pbc::MapField<string, string> labels_ = new pbc::MapField<string, string>();
/// <summary>
/// The labels describing the metric value.
/// See comments on [google.api.servicecontrol.v1.Operation.labels][google.api.servicecontrol.v1.Operation.labels] for
/// the overriding relationship.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, string> Labels {
get { return labels_; }
}
/// <summary>Field number for the "start_time" field.</summary>
public const int StartTimeFieldNumber = 2;
private global::Google.Protobuf.WellKnownTypes.Timestamp startTime_;
/// <summary>
/// The start of the time period over which this metric value's measurement
/// applies. The time period has different semantics for different metric
/// types (cumulative, delta, and gauge). See the metric definition
/// documentation in the service configuration for details.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp StartTime {
get { return startTime_; }
set {
startTime_ = value;
}
}
/// <summary>Field number for the "end_time" field.</summary>
public const int EndTimeFieldNumber = 3;
private global::Google.Protobuf.WellKnownTypes.Timestamp endTime_;
/// <summary>
/// The end of the time period over which this metric value's measurement
/// applies.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp EndTime {
get { return endTime_; }
set {
endTime_ = value;
}
}
/// <summary>Field number for the "bool_value" field.</summary>
public const int BoolValueFieldNumber = 4;
/// <summary>
/// A boolean value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool BoolValue {
get { return valueCase_ == ValueOneofCase.BoolValue ? (bool) value_ : false; }
set {
value_ = value;
valueCase_ = ValueOneofCase.BoolValue;
}
}
/// <summary>Field number for the "int64_value" field.</summary>
public const int Int64ValueFieldNumber = 5;
/// <summary>
/// A signed 64-bit integer value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Int64Value {
get { return valueCase_ == ValueOneofCase.Int64Value ? (long) value_ : 0L; }
set {
value_ = value;
valueCase_ = ValueOneofCase.Int64Value;
}
}
/// <summary>Field number for the "double_value" field.</summary>
public const int DoubleValueFieldNumber = 6;
/// <summary>
/// A double precision floating point value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double DoubleValue {
get { return valueCase_ == ValueOneofCase.DoubleValue ? (double) value_ : 0D; }
set {
value_ = value;
valueCase_ = ValueOneofCase.DoubleValue;
}
}
/// <summary>Field number for the "string_value" field.</summary>
public const int StringValueFieldNumber = 7;
/// <summary>
/// A text string value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string StringValue {
get { return valueCase_ == ValueOneofCase.StringValue ? (string) value_ : ""; }
set {
value_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
valueCase_ = ValueOneofCase.StringValue;
}
}
/// <summary>Field number for the "distribution_value" field.</summary>
public const int DistributionValueFieldNumber = 8;
/// <summary>
/// A distribution value.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Api.Servicecontrol.V1.Distribution DistributionValue {
get { return valueCase_ == ValueOneofCase.DistributionValue ? (global::Google.Api.Servicecontrol.V1.Distribution) value_ : null; }
set {
value_ = value;
valueCase_ = value == null ? ValueOneofCase.None : ValueOneofCase.DistributionValue;
}
}
private object value_;
/// <summary>Enum of possible cases for the "value" oneof.</summary>
public enum ValueOneofCase {
None = 0,
BoolValue = 4,
Int64Value = 5,
DoubleValue = 6,
StringValue = 7,
DistributionValue = 8,
}
private ValueOneofCase valueCase_ = ValueOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ValueOneofCase ValueCase {
get { return valueCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void ClearValue() {
valueCase_ = ValueOneofCase.None;
value_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as MetricValue);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(MetricValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!Labels.Equals(other.Labels)) return false;
if (!object.Equals(StartTime, other.StartTime)) return false;
if (!object.Equals(EndTime, other.EndTime)) return false;
if (BoolValue != other.BoolValue) return false;
if (Int64Value != other.Int64Value) return false;
if (DoubleValue != other.DoubleValue) return false;
if (StringValue != other.StringValue) return false;
if (!object.Equals(DistributionValue, other.DistributionValue)) return false;
if (ValueCase != other.ValueCase) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= Labels.GetHashCode();
if (startTime_ != null) hash ^= StartTime.GetHashCode();
if (endTime_ != null) hash ^= EndTime.GetHashCode();
if (valueCase_ == ValueOneofCase.BoolValue) hash ^= BoolValue.GetHashCode();
if (valueCase_ == ValueOneofCase.Int64Value) hash ^= Int64Value.GetHashCode();
if (valueCase_ == ValueOneofCase.DoubleValue) hash ^= DoubleValue.GetHashCode();
if (valueCase_ == ValueOneofCase.StringValue) hash ^= StringValue.GetHashCode();
if (valueCase_ == ValueOneofCase.DistributionValue) hash ^= DistributionValue.GetHashCode();
hash ^= (int) valueCase_;
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) {
labels_.WriteTo(output, _map_labels_codec);
if (startTime_ != null) {
output.WriteRawTag(18);
output.WriteMessage(StartTime);
}
if (endTime_ != null) {
output.WriteRawTag(26);
output.WriteMessage(EndTime);
}
if (valueCase_ == ValueOneofCase.BoolValue) {
output.WriteRawTag(32);
output.WriteBool(BoolValue);
}
if (valueCase_ == ValueOneofCase.Int64Value) {
output.WriteRawTag(40);
output.WriteInt64(Int64Value);
}
if (valueCase_ == ValueOneofCase.DoubleValue) {
output.WriteRawTag(49);
output.WriteDouble(DoubleValue);
}
if (valueCase_ == ValueOneofCase.StringValue) {
output.WriteRawTag(58);
output.WriteString(StringValue);
}
if (valueCase_ == ValueOneofCase.DistributionValue) {
output.WriteRawTag(66);
output.WriteMessage(DistributionValue);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += labels_.CalculateSize(_map_labels_codec);
if (startTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime);
}
if (endTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndTime);
}
if (valueCase_ == ValueOneofCase.BoolValue) {
size += 1 + 1;
}
if (valueCase_ == ValueOneofCase.Int64Value) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Int64Value);
}
if (valueCase_ == ValueOneofCase.DoubleValue) {
size += 1 + 8;
}
if (valueCase_ == ValueOneofCase.StringValue) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(StringValue);
}
if (valueCase_ == ValueOneofCase.DistributionValue) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(DistributionValue);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(MetricValue other) {
if (other == null) {
return;
}
labels_.Add(other.labels_);
if (other.startTime_ != null) {
if (startTime_ == null) {
startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
StartTime.MergeFrom(other.StartTime);
}
if (other.endTime_ != null) {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
EndTime.MergeFrom(other.EndTime);
}
switch (other.ValueCase) {
case ValueOneofCase.BoolValue:
BoolValue = other.BoolValue;
break;
case ValueOneofCase.Int64Value:
Int64Value = other.Int64Value;
break;
case ValueOneofCase.DoubleValue:
DoubleValue = other.DoubleValue;
break;
case ValueOneofCase.StringValue:
StringValue = other.StringValue;
break;
case ValueOneofCase.DistributionValue:
DistributionValue = other.DistributionValue;
break;
}
}
[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: {
labels_.AddEntriesFrom(input, _map_labels_codec);
break;
}
case 18: {
if (startTime_ == null) {
startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(startTime_);
break;
}
case 26: {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(endTime_);
break;
}
case 32: {
BoolValue = input.ReadBool();
break;
}
case 40: {
Int64Value = input.ReadInt64();
break;
}
case 49: {
DoubleValue = input.ReadDouble();
break;
}
case 58: {
StringValue = input.ReadString();
break;
}
case 66: {
global::Google.Api.Servicecontrol.V1.Distribution subBuilder = new global::Google.Api.Servicecontrol.V1.Distribution();
if (valueCase_ == ValueOneofCase.DistributionValue) {
subBuilder.MergeFrom(DistributionValue);
}
input.ReadMessage(subBuilder);
DistributionValue = subBuilder;
break;
}
}
}
}
}
/// <summary>
/// Represents a set of metric values in the same metric.
/// Each metric value in the set should have a unique combination of start time,
/// end time, and label values.
/// </summary>
public sealed partial class MetricValueSet : pb::IMessage<MetricValueSet> {
private static readonly pb::MessageParser<MetricValueSet> _parser = new pb::MessageParser<MetricValueSet>(() => new MetricValueSet());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<MetricValueSet> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.Servicecontrol.V1.MetricValueReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MetricValueSet() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MetricValueSet(MetricValueSet other) : this() {
metricName_ = other.metricName_;
metricValues_ = other.metricValues_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public MetricValueSet Clone() {
return new MetricValueSet(this);
}
/// <summary>Field number for the "metric_name" field.</summary>
public const int MetricNameFieldNumber = 1;
private string metricName_ = "";
/// <summary>
/// The metric name defined in the service configuration.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string MetricName {
get { return metricName_; }
set {
metricName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "metric_values" field.</summary>
public const int MetricValuesFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Api.Servicecontrol.V1.MetricValue> _repeated_metricValues_codec
= pb::FieldCodec.ForMessage(18, global::Google.Api.Servicecontrol.V1.MetricValue.Parser);
private readonly pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.MetricValue> metricValues_ = new pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.MetricValue>();
/// <summary>
/// The values in this metric.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.Servicecontrol.V1.MetricValue> MetricValues {
get { return metricValues_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as MetricValueSet);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(MetricValueSet other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (MetricName != other.MetricName) return false;
if(!metricValues_.Equals(other.metricValues_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (MetricName.Length != 0) hash ^= MetricName.GetHashCode();
hash ^= metricValues_.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 (MetricName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(MetricName);
}
metricValues_.WriteTo(output, _repeated_metricValues_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (MetricName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(MetricName);
}
size += metricValues_.CalculateSize(_repeated_metricValues_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(MetricValueSet other) {
if (other == null) {
return;
}
if (other.MetricName.Length != 0) {
MetricName = other.MetricName;
}
metricValues_.Add(other.metricValues_);
}
[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: {
MetricName = input.ReadString();
break;
}
case 18: {
metricValues_.AddEntriesFrom(input, _repeated_metricValues_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// StrangeCRC.cs - computes a crc used in the bziplib
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace DodoNet.Checksums
{
/// <summary>
/// Bzip2 checksum algorithm
/// </summary>
public class StrangeCRC : IChecksum
{
readonly static uint[] crc32Table = {
0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9,
0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9,
0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011,
0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81,
0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49,
0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae,
0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066,
0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e,
0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686,
0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f,
0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47,
0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7,
0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f,
0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f,
0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30,
0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088,
0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0,
0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
};
int globalCrc;
/// <summary>
/// Initialise a default instance of <see cref="StrangeCRC"></see>
/// </summary>
public StrangeCRC()
{
Reset();
}
/// <summary>
/// Reset the state of Crc.
/// </summary>
public void Reset()
{
globalCrc = -1;
}
/// <summary>
/// Get the current Crc value.
/// </summary>
public long Value {
get {
return ~globalCrc;
}
}
/// <summary>
/// Update the Crc value.
/// </summary>
/// <param name="value">data update is based on</param>
public void Update(int value)
{
int temp = (globalCrc >> 24) ^ value;
if (temp < 0) {
temp = 256 + temp;
}
globalCrc = unchecked((int)((globalCrc << 8) ^ crc32Table[temp]));
}
/// <summary>
/// Update Crc based on a block of data
/// </summary>
/// <param name="buffer">The buffer containing data to update the crc with.</param>
public void Update(byte[] buffer)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
Update(buffer, 0, buffer.Length);
}
/// <summary>
/// Update Crc based on a portion of a block of data
/// </summary>
/// <param name="buffer">block of data</param>
/// <param name="offset">index of first byte to use</param>
/// <param name="count">number of bytes to use</param>
public void Update(byte[] buffer, int offset, int count)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if ( offset < 0 )
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("offset");
#else
throw new ArgumentOutOfRangeException("offset", "cannot be less than zero");
#endif
}
if ( count < 0 )
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("count");
#else
throw new ArgumentOutOfRangeException("count", "cannot be less than zero");
#endif
}
if ( offset + count > buffer.Length )
{
throw new ArgumentOutOfRangeException("count");
}
for (int i = 0; i < count; ++i) {
Update(buffer[offset++]);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//Testing simple math on local vars and fields - add
#pragma warning disable 0414
using System;
internal class lclfldadd
{
//user-defined class that overloads operator +
public class numHolder
{
private int _i_num;
private uint _ui_num;
private long _l_num;
private ulong _ul_num;
private float _f_num;
private double _d_num;
private decimal _m_num;
public numHolder(int i_num)
{
_i_num = Convert.ToInt32(i_num);
_ui_num = Convert.ToUInt32(i_num);
_l_num = Convert.ToInt64(i_num);
_ul_num = Convert.ToUInt64(i_num);
_f_num = Convert.ToSingle(i_num);
_d_num = Convert.ToDouble(i_num);
_m_num = Convert.ToDecimal(i_num);
}
public static int operator +(numHolder a, int b)
{
return a._i_num + b;
}
public numHolder(uint ui_num)
{
_i_num = Convert.ToInt32(ui_num);
_ui_num = Convert.ToUInt32(ui_num);
_l_num = Convert.ToInt64(ui_num);
_ul_num = Convert.ToUInt64(ui_num);
_f_num = Convert.ToSingle(ui_num);
_d_num = Convert.ToDouble(ui_num);
_m_num = Convert.ToDecimal(ui_num);
}
public static uint operator +(numHolder a, uint b)
{
return a._ui_num + b;
}
public numHolder(long l_num)
{
_i_num = Convert.ToInt32(l_num);
_ui_num = Convert.ToUInt32(l_num);
_l_num = Convert.ToInt64(l_num);
_ul_num = Convert.ToUInt64(l_num);
_f_num = Convert.ToSingle(l_num);
_d_num = Convert.ToDouble(l_num);
_m_num = Convert.ToDecimal(l_num);
}
public static long operator +(numHolder a, long b)
{
return a._l_num + b;
}
public numHolder(ulong ul_num)
{
_i_num = Convert.ToInt32(ul_num);
_ui_num = Convert.ToUInt32(ul_num);
_l_num = Convert.ToInt64(ul_num);
_ul_num = Convert.ToUInt64(ul_num);
_f_num = Convert.ToSingle(ul_num);
_d_num = Convert.ToDouble(ul_num);
_m_num = Convert.ToDecimal(ul_num);
}
public static long operator +(numHolder a, ulong b)
{
return (long)(a._ul_num + b);
}
public numHolder(float f_num)
{
_i_num = Convert.ToInt32(f_num);
_ui_num = Convert.ToUInt32(f_num);
_l_num = Convert.ToInt64(f_num);
_ul_num = Convert.ToUInt64(f_num);
_f_num = Convert.ToSingle(f_num);
_d_num = Convert.ToDouble(f_num);
_m_num = Convert.ToDecimal(f_num);
}
public static float operator +(numHolder a, float b)
{
return a._f_num + b;
}
public numHolder(double d_num)
{
_i_num = Convert.ToInt32(d_num);
_ui_num = Convert.ToUInt32(d_num);
_l_num = Convert.ToInt64(d_num);
_ul_num = Convert.ToUInt64(d_num);
_f_num = Convert.ToSingle(d_num);
_d_num = Convert.ToDouble(d_num);
_m_num = Convert.ToDecimal(d_num);
}
public static double operator +(numHolder a, double b)
{
return a._d_num + b;
}
public numHolder(decimal m_num)
{
_i_num = Convert.ToInt32(m_num);
_ui_num = Convert.ToUInt32(m_num);
_l_num = Convert.ToInt64(m_num);
_ul_num = Convert.ToUInt64(m_num);
_f_num = Convert.ToSingle(m_num);
_d_num = Convert.ToDouble(m_num);
_m_num = Convert.ToDecimal(m_num);
}
public static int operator +(numHolder a, decimal b)
{
return (int)(a._m_num + b);
}
public static int operator +(numHolder a, numHolder b)
{
return a._i_num + b._i_num;
}
}
private static int s_i_s_op1 = 1;
private static uint s_ui_s_op1 = 1;
private static long s_l_s_op1 = 1;
private static ulong s_ul_s_op1 = 1;
private static float s_f_s_op1 = 1;
private static double s_d_s_op1 = 1;
private static decimal s_m_s_op1 = 1;
private static int s_i_s_op2 = 8;
private static uint s_ui_s_op2 = 8;
private static long s_l_s_op2 = 8;
private static ulong s_ul_s_op2 = 8;
private static float s_f_s_op2 = 8;
private static double s_d_s_op2 = 8;
private static decimal s_m_s_op2 = 8;
private static numHolder s_nHldr_s_op2 = new numHolder(8);
public static int i_f(String s)
{
if (s == "op1")
return 1;
else
return 8;
}
public static uint ui_f(String s)
{
if (s == "op1")
return 1;
else
return 8;
}
public static long l_f(String s)
{
if (s == "op1")
return 1;
else
return 8;
}
public static ulong ul_f(String s)
{
if (s == "op1")
return 1;
else
return 8;
}
public static float f_f(String s)
{
if (s == "op1")
return 1;
else
return 8;
}
public static double d_f(String s)
{
if (s == "op1")
return 1;
else
return 8;
}
public static decimal m_f(String s)
{
if (s == "op1")
return 1;
else
return 8;
}
public static numHolder nHldr_f(String s)
{
if (s == "op1")
return new numHolder(1);
else
return new numHolder(8);
}
private class CL
{
public int i_cl_op1 = 1;
public uint ui_cl_op1 = 1;
public long l_cl_op1 = 1;
public ulong ul_cl_op1 = 1;
public float f_cl_op1 = 1;
public double d_cl_op1 = 1;
public decimal m_cl_op1 = 1;
public int i_cl_op2 = 8;
public uint ui_cl_op2 = 8;
public long l_cl_op2 = 8;
public ulong ul_cl_op2 = 8;
public float f_cl_op2 = 8;
public double d_cl_op2 = 8;
public decimal m_cl_op2 = 8;
public numHolder nHldr_cl_op2 = new numHolder(8);
}
private struct VT
{
public int i_vt_op1;
public uint ui_vt_op1;
public long l_vt_op1;
public ulong ul_vt_op1;
public float f_vt_op1;
public double d_vt_op1;
public decimal m_vt_op1;
public int i_vt_op2;
public uint ui_vt_op2;
public long l_vt_op2;
public ulong ul_vt_op2;
public float f_vt_op2;
public double d_vt_op2;
public decimal m_vt_op2;
public numHolder nHldr_vt_op2;
}
public static int Main()
{
bool passed = true;
//initialize class
CL cl1 = new CL();
//initialize struct
VT vt1;
vt1.i_vt_op1 = 1;
vt1.ui_vt_op1 = 1;
vt1.l_vt_op1 = 1;
vt1.ul_vt_op1 = 1;
vt1.f_vt_op1 = 1;
vt1.d_vt_op1 = 1;
vt1.m_vt_op1 = 1;
vt1.i_vt_op2 = 8;
vt1.ui_vt_op2 = 8;
vt1.l_vt_op2 = 8;
vt1.ul_vt_op2 = 8;
vt1.f_vt_op2 = 8;
vt1.d_vt_op2 = 8;
vt1.m_vt_op2 = 8;
vt1.nHldr_vt_op2 = new numHolder(8);
int[] i_arr1d_op1 = { 0, 1 };
int[,] i_arr2d_op1 = { { 0, 1 }, { 1, 1 } };
int[,,] i_arr3d_op1 = { { { 0, 1 }, { 1, 1 } } };
uint[] ui_arr1d_op1 = { 0, 1 };
uint[,] ui_arr2d_op1 = { { 0, 1 }, { 1, 1 } };
uint[,,] ui_arr3d_op1 = { { { 0, 1 }, { 1, 1 } } };
long[] l_arr1d_op1 = { 0, 1 };
long[,] l_arr2d_op1 = { { 0, 1 }, { 1, 1 } };
long[,,] l_arr3d_op1 = { { { 0, 1 }, { 1, 1 } } };
ulong[] ul_arr1d_op1 = { 0, 1 };
ulong[,] ul_arr2d_op1 = { { 0, 1 }, { 1, 1 } };
ulong[,,] ul_arr3d_op1 = { { { 0, 1 }, { 1, 1 } } };
float[] f_arr1d_op1 = { 0, 1 };
float[,] f_arr2d_op1 = { { 0, 1 }, { 1, 1 } };
float[,,] f_arr3d_op1 = { { { 0, 1 }, { 1, 1 } } };
double[] d_arr1d_op1 = { 0, 1 };
double[,] d_arr2d_op1 = { { 0, 1 }, { 1, 1 } };
double[,,] d_arr3d_op1 = { { { 0, 1 }, { 1, 1 } } };
decimal[] m_arr1d_op1 = { 0, 1 };
decimal[,] m_arr2d_op1 = { { 0, 1 }, { 1, 1 } };
decimal[,,] m_arr3d_op1 = { { { 0, 1 }, { 1, 1 } } };
int[] i_arr1d_op2 = { 8, 0, 1 };
int[,] i_arr2d_op2 = { { 0, 8 }, { 1, 1 } };
int[,,] i_arr3d_op2 = { { { 0, 8 }, { 1, 1 } } };
uint[] ui_arr1d_op2 = { 8, 0, 1 };
uint[,] ui_arr2d_op2 = { { 0, 8 }, { 1, 1 } };
uint[,,] ui_arr3d_op2 = { { { 0, 8 }, { 1, 1 } } };
long[] l_arr1d_op2 = { 8, 0, 1 };
long[,] l_arr2d_op2 = { { 0, 8 }, { 1, 1 } };
long[,,] l_arr3d_op2 = { { { 0, 8 }, { 1, 1 } } };
ulong[] ul_arr1d_op2 = { 8, 0, 1 };
ulong[,] ul_arr2d_op2 = { { 0, 8 }, { 1, 1 } };
ulong[,,] ul_arr3d_op2 = { { { 0, 8 }, { 1, 1 } } };
float[] f_arr1d_op2 = { 8, 0, 1 };
float[,] f_arr2d_op2 = { { 0, 8 }, { 1, 1 } };
float[,,] f_arr3d_op2 = { { { 0, 8 }, { 1, 1 } } };
double[] d_arr1d_op2 = { 8, 0, 1 };
double[,] d_arr2d_op2 = { { 0, 8 }, { 1, 1 } };
double[,,] d_arr3d_op2 = { { { 0, 8 }, { 1, 1 } } };
decimal[] m_arr1d_op2 = { 8, 0, 1 };
decimal[,] m_arr2d_op2 = { { 0, 8 }, { 1, 1 } };
decimal[,,] m_arr3d_op2 = { { { 0, 8 }, { 1, 1 } } };
numHolder[] nHldr_arr1d_op2 = { new numHolder(8), new numHolder(0), new numHolder(1) };
numHolder[,] nHldr_arr2d_op2 = { { new numHolder(0), new numHolder(8) }, { new numHolder(1), new numHolder(1) } };
numHolder[,,] nHldr_arr3d_op2 = { { { new numHolder(0), new numHolder(8) }, { new numHolder(1), new numHolder(1) } } };
int[,] index = { { 0, 0 }, { 1, 1 } };
{
int i_l_op1 = 1;
int i_l_op2 = 8;
uint ui_l_op2 = 8;
long l_l_op2 = 8;
ulong ul_l_op2 = 8;
float f_l_op2 = 8;
double d_l_op2 = 8;
decimal m_l_op2 = 8;
numHolder nHldr_l_op2 = new numHolder(8);
if ((i_l_op1 + i_l_op2 != i_l_op1 + ui_l_op2) || (i_l_op1 + ui_l_op2 != i_l_op1 + l_l_op2) || (i_l_op1 + l_l_op2 != i_l_op1 + (int)ul_l_op2) || (i_l_op1 + (int)ul_l_op2 != i_l_op1 + f_l_op2) || (i_l_op1 + f_l_op2 != i_l_op1 + d_l_op2) || ((decimal)(i_l_op1 + d_l_op2) != i_l_op1 + m_l_op2) || (i_l_op1 + m_l_op2 != i_l_op1 + i_l_op2) || (i_l_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 1 failed");
passed = false;
}
if ((i_l_op1 + s_i_s_op2 != i_l_op1 + s_ui_s_op2) || (i_l_op1 + s_ui_s_op2 != i_l_op1 + s_l_s_op2) || (i_l_op1 + s_l_s_op2 != i_l_op1 + (int)s_ul_s_op2) || (i_l_op1 + (int)s_ul_s_op2 != i_l_op1 + s_f_s_op2) || (i_l_op1 + s_f_s_op2 != i_l_op1 + s_d_s_op2) || ((decimal)(i_l_op1 + s_d_s_op2) != i_l_op1 + s_m_s_op2) || (i_l_op1 + s_m_s_op2 != i_l_op1 + s_i_s_op2) || (i_l_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 2 failed");
passed = false;
}
if ((s_i_s_op1 + i_l_op2 != s_i_s_op1 + ui_l_op2) || (s_i_s_op1 + ui_l_op2 != s_i_s_op1 + l_l_op2) || (s_i_s_op1 + l_l_op2 != s_i_s_op1 + (int)ul_l_op2) || (s_i_s_op1 + (int)ul_l_op2 != s_i_s_op1 + f_l_op2) || (s_i_s_op1 + f_l_op2 != s_i_s_op1 + d_l_op2) || ((decimal)(s_i_s_op1 + d_l_op2) != s_i_s_op1 + m_l_op2) || (s_i_s_op1 + m_l_op2 != s_i_s_op1 + i_l_op2) || (s_i_s_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 3 failed");
passed = false;
}
if ((s_i_s_op1 + s_i_s_op2 != s_i_s_op1 + s_ui_s_op2) || (s_i_s_op1 + s_ui_s_op2 != s_i_s_op1 + s_l_s_op2) || (s_i_s_op1 + s_l_s_op2 != s_i_s_op1 + (int)s_ul_s_op2) || (s_i_s_op1 + (int)s_ul_s_op2 != s_i_s_op1 + s_f_s_op2) || (s_i_s_op1 + s_f_s_op2 != s_i_s_op1 + s_d_s_op2) || ((decimal)(s_i_s_op1 + s_d_s_op2) != s_i_s_op1 + s_m_s_op2) || (s_i_s_op1 + s_m_s_op2 != s_i_s_op1 + s_i_s_op2) || (s_i_s_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 4 failed");
passed = false;
}
}
{
uint ui_l_op1 = 1;
int i_l_op2 = 8;
uint ui_l_op2 = 8;
long l_l_op2 = 8;
ulong ul_l_op2 = 8;
float f_l_op2 = 8;
double d_l_op2 = 8;
decimal m_l_op2 = 8;
numHolder nHldr_l_op2 = new numHolder(8);
if ((ui_l_op1 + i_l_op2 != ui_l_op1 + ui_l_op2) || (ui_l_op1 + ui_l_op2 != ui_l_op1 + l_l_op2) || ((ulong)(ui_l_op1 + l_l_op2) != ui_l_op1 + ul_l_op2) || (ui_l_op1 + ul_l_op2 != ui_l_op1 + f_l_op2) || (ui_l_op1 + f_l_op2 != ui_l_op1 + d_l_op2) || ((decimal)(ui_l_op1 + d_l_op2) != ui_l_op1 + m_l_op2) || (ui_l_op1 + m_l_op2 != ui_l_op1 + i_l_op2) || (ui_l_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 5 failed");
passed = false;
}
if ((ui_l_op1 + s_i_s_op2 != ui_l_op1 + s_ui_s_op2) || (ui_l_op1 + s_ui_s_op2 != ui_l_op1 + s_l_s_op2) || ((ulong)(ui_l_op1 + s_l_s_op2) != ui_l_op1 + s_ul_s_op2) || (ui_l_op1 + s_ul_s_op2 != ui_l_op1 + s_f_s_op2) || (ui_l_op1 + s_f_s_op2 != ui_l_op1 + s_d_s_op2) || ((decimal)(ui_l_op1 + s_d_s_op2) != ui_l_op1 + s_m_s_op2) || (ui_l_op1 + s_m_s_op2 != ui_l_op1 + s_i_s_op2) || (ui_l_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 6 failed");
passed = false;
}
if ((s_ui_s_op1 + i_l_op2 != s_ui_s_op1 + ui_l_op2) || (s_ui_s_op1 + ui_l_op2 != s_ui_s_op1 + l_l_op2) || ((ulong)(s_ui_s_op1 + l_l_op2) != s_ui_s_op1 + ul_l_op2) || (s_ui_s_op1 + ul_l_op2 != s_ui_s_op1 + f_l_op2) || (s_ui_s_op1 + f_l_op2 != s_ui_s_op1 + d_l_op2) || ((decimal)(s_ui_s_op1 + d_l_op2) != s_ui_s_op1 + m_l_op2) || (s_ui_s_op1 + m_l_op2 != s_ui_s_op1 + i_l_op2) || (s_ui_s_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 7 failed");
passed = false;
}
if ((s_ui_s_op1 + s_i_s_op2 != s_ui_s_op1 + s_ui_s_op2) || (s_ui_s_op1 + s_ui_s_op2 != s_ui_s_op1 + s_l_s_op2) || ((ulong)(s_ui_s_op1 + s_l_s_op2) != s_ui_s_op1 + s_ul_s_op2) || (s_ui_s_op1 + s_ul_s_op2 != s_ui_s_op1 + s_f_s_op2) || (s_ui_s_op1 + s_f_s_op2 != s_ui_s_op1 + s_d_s_op2) || ((decimal)(s_ui_s_op1 + s_d_s_op2) != s_ui_s_op1 + s_m_s_op2) || (s_ui_s_op1 + s_m_s_op2 != s_ui_s_op1 + s_i_s_op2) || (s_ui_s_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 8 failed");
passed = false;
}
}
{
long l_l_op1 = 1;
int i_l_op2 = 8;
uint ui_l_op2 = 8;
long l_l_op2 = 8;
ulong ul_l_op2 = 8;
float f_l_op2 = 8;
double d_l_op2 = 8;
decimal m_l_op2 = 8;
numHolder nHldr_l_op2 = new numHolder(8);
if ((l_l_op1 + i_l_op2 != l_l_op1 + ui_l_op2) || (l_l_op1 + ui_l_op2 != l_l_op1 + l_l_op2) || (l_l_op1 + l_l_op2 != l_l_op1 + (long)ul_l_op2) || (l_l_op1 + (long)ul_l_op2 != l_l_op1 + f_l_op2) || (l_l_op1 + f_l_op2 != l_l_op1 + d_l_op2) || ((decimal)(l_l_op1 + d_l_op2) != l_l_op1 + m_l_op2) || (l_l_op1 + m_l_op2 != l_l_op1 + i_l_op2) || (l_l_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 9 failed");
passed = false;
}
if ((l_l_op1 + s_i_s_op2 != l_l_op1 + s_ui_s_op2) || (l_l_op1 + s_ui_s_op2 != l_l_op1 + s_l_s_op2) || (l_l_op1 + s_l_s_op2 != l_l_op1 + (long)s_ul_s_op2) || (l_l_op1 + (long)s_ul_s_op2 != l_l_op1 + s_f_s_op2) || (l_l_op1 + s_f_s_op2 != l_l_op1 + s_d_s_op2) || ((decimal)(l_l_op1 + s_d_s_op2) != l_l_op1 + s_m_s_op2) || (l_l_op1 + s_m_s_op2 != l_l_op1 + s_i_s_op2) || (l_l_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 10 failed");
passed = false;
}
if ((s_l_s_op1 + i_l_op2 != s_l_s_op1 + ui_l_op2) || (s_l_s_op1 + ui_l_op2 != s_l_s_op1 + l_l_op2) || (s_l_s_op1 + l_l_op2 != s_l_s_op1 + (long)ul_l_op2) || (s_l_s_op1 + (long)ul_l_op2 != s_l_s_op1 + f_l_op2) || (s_l_s_op1 + f_l_op2 != s_l_s_op1 + d_l_op2) || ((decimal)(s_l_s_op1 + d_l_op2) != s_l_s_op1 + m_l_op2) || (s_l_s_op1 + m_l_op2 != s_l_s_op1 + i_l_op2) || (s_l_s_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 11 failed");
passed = false;
}
if ((s_l_s_op1 + s_i_s_op2 != s_l_s_op1 + s_ui_s_op2) || (s_l_s_op1 + s_ui_s_op2 != s_l_s_op1 + s_l_s_op2) || (s_l_s_op1 + s_l_s_op2 != s_l_s_op1 + (long)s_ul_s_op2) || (s_l_s_op1 + (long)s_ul_s_op2 != s_l_s_op1 + s_f_s_op2) || (s_l_s_op1 + s_f_s_op2 != s_l_s_op1 + s_d_s_op2) || ((decimal)(s_l_s_op1 + s_d_s_op2) != s_l_s_op1 + s_m_s_op2) || (s_l_s_op1 + s_m_s_op2 != s_l_s_op1 + s_i_s_op2) || (s_l_s_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 12 failed");
passed = false;
}
}
{
ulong ul_l_op1 = 1;
int i_l_op2 = 8;
uint ui_l_op2 = 8;
long l_l_op2 = 8;
ulong ul_l_op2 = 8;
float f_l_op2 = 8;
double d_l_op2 = 8;
decimal m_l_op2 = 8;
numHolder nHldr_l_op2 = new numHolder(8);
if ((ul_l_op1 + (ulong)i_l_op2 != ul_l_op1 + ui_l_op2) || (ul_l_op1 + ui_l_op2 != ul_l_op1 + (ulong)l_l_op2) || (ul_l_op1 + (ulong)l_l_op2 != ul_l_op1 + ul_l_op2) || (ul_l_op1 + ul_l_op2 != ul_l_op1 + f_l_op2) || (ul_l_op1 + f_l_op2 != ul_l_op1 + d_l_op2) || ((decimal)(ul_l_op1 + d_l_op2) != ul_l_op1 + m_l_op2) || (ul_l_op1 + m_l_op2 != ul_l_op1 + (ulong)i_l_op2) || (ul_l_op1 + (ulong)i_l_op2 != 9))
{
Console.WriteLine("testcase 13 failed");
passed = false;
}
if ((ul_l_op1 + (ulong)s_i_s_op2 != ul_l_op1 + s_ui_s_op2) || (ul_l_op1 + s_ui_s_op2 != ul_l_op1 + (ulong)s_l_s_op2) || (ul_l_op1 + (ulong)s_l_s_op2 != ul_l_op1 + s_ul_s_op2) || (ul_l_op1 + s_ul_s_op2 != ul_l_op1 + s_f_s_op2) || (ul_l_op1 + s_f_s_op2 != ul_l_op1 + s_d_s_op2) || ((decimal)(ul_l_op1 + s_d_s_op2) != ul_l_op1 + s_m_s_op2) || (ul_l_op1 + s_m_s_op2 != ul_l_op1 + (ulong)s_i_s_op2) || (ul_l_op1 + (ulong)s_i_s_op2 != 9))
{
Console.WriteLine("testcase 14 failed");
passed = false;
}
if ((s_ul_s_op1 + (ulong)i_l_op2 != s_ul_s_op1 + ui_l_op2) || (s_ul_s_op1 + ui_l_op2 != s_ul_s_op1 + (ulong)l_l_op2) || (s_ul_s_op1 + (ulong)l_l_op2 != s_ul_s_op1 + ul_l_op2) || (s_ul_s_op1 + ul_l_op2 != s_ul_s_op1 + f_l_op2) || (s_ul_s_op1 + f_l_op2 != s_ul_s_op1 + d_l_op2) || ((decimal)(s_ul_s_op1 + d_l_op2) != s_ul_s_op1 + m_l_op2) || (s_ul_s_op1 + m_l_op2 != s_ul_s_op1 + (ulong)i_l_op2) || (s_ul_s_op1 + (ulong)i_l_op2 != 9))
{
Console.WriteLine("testcase 15 failed");
passed = false;
}
if ((s_ul_s_op1 + (ulong)s_i_s_op2 != s_ul_s_op1 + s_ui_s_op2) || (s_ul_s_op1 + s_ui_s_op2 != s_ul_s_op1 + (ulong)s_l_s_op2) || (s_ul_s_op1 + (ulong)s_l_s_op2 != s_ul_s_op1 + s_ul_s_op2) || (s_ul_s_op1 + s_ul_s_op2 != s_ul_s_op1 + s_f_s_op2) || (s_ul_s_op1 + s_f_s_op2 != s_ul_s_op1 + s_d_s_op2) || ((decimal)(s_ul_s_op1 + s_d_s_op2) != s_ul_s_op1 + s_m_s_op2) || (s_ul_s_op1 + s_m_s_op2 != s_ul_s_op1 + (ulong)s_i_s_op2) || (s_ul_s_op1 + (ulong)s_i_s_op2 != 9))
{
Console.WriteLine("testcase 16 failed");
passed = false;
}
}
{
float f_l_op1 = 1;
int i_l_op2 = 8;
uint ui_l_op2 = 8;
long l_l_op2 = 8;
ulong ul_l_op2 = 8;
float f_l_op2 = 8;
double d_l_op2 = 8;
decimal m_l_op2 = 8;
numHolder nHldr_l_op2 = new numHolder(8);
if ((f_l_op1 + i_l_op2 != f_l_op1 + ui_l_op2) || (f_l_op1 + ui_l_op2 != f_l_op1 + l_l_op2) || (f_l_op1 + l_l_op2 != f_l_op1 + ul_l_op2) || (f_l_op1 + ul_l_op2 != f_l_op1 + f_l_op2) || (f_l_op1 + f_l_op2 != f_l_op1 + d_l_op2) || (f_l_op1 + d_l_op2 != f_l_op1 + (float)m_l_op2) || (f_l_op1 + (float)m_l_op2 != f_l_op1 + i_l_op2) || (f_l_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 17 failed");
passed = false;
}
if ((f_l_op1 + s_i_s_op2 != f_l_op1 + s_ui_s_op2) || (f_l_op1 + s_ui_s_op2 != f_l_op1 + s_l_s_op2) || (f_l_op1 + s_l_s_op2 != f_l_op1 + s_ul_s_op2) || (f_l_op1 + s_ul_s_op2 != f_l_op1 + s_f_s_op2) || (f_l_op1 + s_f_s_op2 != f_l_op1 + s_d_s_op2) || (f_l_op1 + s_d_s_op2 != f_l_op1 + (float)s_m_s_op2) || (f_l_op1 + (float)s_m_s_op2 != f_l_op1 + s_i_s_op2) || (f_l_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 18 failed");
passed = false;
}
if ((s_f_s_op1 + i_l_op2 != s_f_s_op1 + ui_l_op2) || (s_f_s_op1 + ui_l_op2 != s_f_s_op1 + l_l_op2) || (s_f_s_op1 + l_l_op2 != s_f_s_op1 + ul_l_op2) || (s_f_s_op1 + ul_l_op2 != s_f_s_op1 + f_l_op2) || (s_f_s_op1 + f_l_op2 != s_f_s_op1 + d_l_op2) || (s_f_s_op1 + d_l_op2 != s_f_s_op1 + (float)m_l_op2) || (s_f_s_op1 + (float)m_l_op2 != s_f_s_op1 + i_l_op2) || (s_f_s_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 19 failed");
passed = false;
}
if ((s_f_s_op1 + s_i_s_op2 != s_f_s_op1 + s_ui_s_op2) || (s_f_s_op1 + s_ui_s_op2 != s_f_s_op1 + s_l_s_op2) || (s_f_s_op1 + s_l_s_op2 != s_f_s_op1 + s_ul_s_op2) || (s_f_s_op1 + s_ul_s_op2 != s_f_s_op1 + s_f_s_op2) || (s_f_s_op1 + s_f_s_op2 != s_f_s_op1 + s_d_s_op2) || (s_f_s_op1 + s_d_s_op2 != s_f_s_op1 + (float)s_m_s_op2) || (s_f_s_op1 + (float)s_m_s_op2 != s_f_s_op1 + s_i_s_op2) || (s_f_s_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 20 failed");
passed = false;
}
}
{
double d_l_op1 = 1;
int i_l_op2 = 8;
uint ui_l_op2 = 8;
long l_l_op2 = 8;
ulong ul_l_op2 = 8;
float f_l_op2 = 8;
double d_l_op2 = 8;
decimal m_l_op2 = 8;
numHolder nHldr_l_op2 = new numHolder(8);
if ((d_l_op1 + i_l_op2 != d_l_op1 + ui_l_op2) || (d_l_op1 + ui_l_op2 != d_l_op1 + l_l_op2) || (d_l_op1 + l_l_op2 != d_l_op1 + ul_l_op2) || (d_l_op1 + ul_l_op2 != d_l_op1 + f_l_op2) || (d_l_op1 + f_l_op2 != d_l_op1 + d_l_op2) || (d_l_op1 + d_l_op2 != d_l_op1 + (double)m_l_op2) || (d_l_op1 + (double)m_l_op2 != d_l_op1 + i_l_op2) || (d_l_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 21 failed");
passed = false;
}
if ((d_l_op1 + s_i_s_op2 != d_l_op1 + s_ui_s_op2) || (d_l_op1 + s_ui_s_op2 != d_l_op1 + s_l_s_op2) || (d_l_op1 + s_l_s_op2 != d_l_op1 + s_ul_s_op2) || (d_l_op1 + s_ul_s_op2 != d_l_op1 + s_f_s_op2) || (d_l_op1 + s_f_s_op2 != d_l_op1 + s_d_s_op2) || (d_l_op1 + s_d_s_op2 != d_l_op1 + (double)s_m_s_op2) || (d_l_op1 + (double)s_m_s_op2 != d_l_op1 + s_i_s_op2) || (d_l_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 22 failed");
passed = false;
}
if ((s_d_s_op1 + i_l_op2 != s_d_s_op1 + ui_l_op2) || (s_d_s_op1 + ui_l_op2 != s_d_s_op1 + l_l_op2) || (s_d_s_op1 + l_l_op2 != s_d_s_op1 + ul_l_op2) || (s_d_s_op1 + ul_l_op2 != s_d_s_op1 + f_l_op2) || (s_d_s_op1 + f_l_op2 != s_d_s_op1 + d_l_op2) || (s_d_s_op1 + d_l_op2 != s_d_s_op1 + (double)m_l_op2) || (s_d_s_op1 + (double)m_l_op2 != s_d_s_op1 + i_l_op2) || (s_d_s_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 23 failed");
passed = false;
}
if ((s_d_s_op1 + s_i_s_op2 != s_d_s_op1 + s_ui_s_op2) || (s_d_s_op1 + s_ui_s_op2 != s_d_s_op1 + s_l_s_op2) || (s_d_s_op1 + s_l_s_op2 != s_d_s_op1 + s_ul_s_op2) || (s_d_s_op1 + s_ul_s_op2 != s_d_s_op1 + s_f_s_op2) || (s_d_s_op1 + s_f_s_op2 != s_d_s_op1 + s_d_s_op2) || (s_d_s_op1 + s_d_s_op2 != s_d_s_op1 + (double)s_m_s_op2) || (s_d_s_op1 + (double)s_m_s_op2 != s_d_s_op1 + s_i_s_op2) || (s_d_s_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 24 failed");
passed = false;
}
}
{
decimal m_l_op1 = 1;
int i_l_op2 = 8;
uint ui_l_op2 = 8;
long l_l_op2 = 8;
ulong ul_l_op2 = 8;
float f_l_op2 = 8;
double d_l_op2 = 8;
decimal m_l_op2 = 8;
numHolder nHldr_l_op2 = new numHolder(8);
if ((m_l_op1 + i_l_op2 != m_l_op1 + ui_l_op2) || (m_l_op1 + ui_l_op2 != m_l_op1 + l_l_op2) || (m_l_op1 + l_l_op2 != m_l_op1 + ul_l_op2) || (m_l_op1 + ul_l_op2 != m_l_op1 + (decimal)f_l_op2) || (m_l_op1 + (decimal)f_l_op2 != m_l_op1 + (decimal)d_l_op2) || (m_l_op1 + (decimal)d_l_op2 != m_l_op1 + m_l_op2) || (m_l_op1 + m_l_op2 != m_l_op1 + i_l_op2) || (m_l_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 25 failed");
passed = false;
}
if ((m_l_op1 + s_i_s_op2 != m_l_op1 + s_ui_s_op2) || (m_l_op1 + s_ui_s_op2 != m_l_op1 + s_l_s_op2) || (m_l_op1 + s_l_s_op2 != m_l_op1 + s_ul_s_op2) || (m_l_op1 + s_ul_s_op2 != m_l_op1 + (decimal)s_f_s_op2) || (m_l_op1 + (decimal)s_f_s_op2 != m_l_op1 + (decimal)s_d_s_op2) || (m_l_op1 + (decimal)s_d_s_op2 != m_l_op1 + s_m_s_op2) || (m_l_op1 + s_m_s_op2 != m_l_op1 + s_i_s_op2) || (m_l_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 26 failed");
passed = false;
}
if ((s_m_s_op1 + i_l_op2 != s_m_s_op1 + ui_l_op2) || (s_m_s_op1 + ui_l_op2 != s_m_s_op1 + l_l_op2) || (s_m_s_op1 + l_l_op2 != s_m_s_op1 + ul_l_op2) || (s_m_s_op1 + ul_l_op2 != s_m_s_op1 + (decimal)f_l_op2) || (s_m_s_op1 + (decimal)f_l_op2 != s_m_s_op1 + (decimal)d_l_op2) || (s_m_s_op1 + (decimal)d_l_op2 != s_m_s_op1 + m_l_op2) || (s_m_s_op1 + m_l_op2 != s_m_s_op1 + i_l_op2) || (s_m_s_op1 + i_l_op2 != 9))
{
Console.WriteLine("testcase 27 failed");
passed = false;
}
if ((s_m_s_op1 + s_i_s_op2 != s_m_s_op1 + s_ui_s_op2) || (s_m_s_op1 + s_ui_s_op2 != s_m_s_op1 + s_l_s_op2) || (s_m_s_op1 + s_l_s_op2 != s_m_s_op1 + s_ul_s_op2) || (s_m_s_op1 + s_ul_s_op2 != s_m_s_op1 + (decimal)s_f_s_op2) || (s_m_s_op1 + (decimal)s_f_s_op2 != s_m_s_op1 + (decimal)s_d_s_op2) || (s_m_s_op1 + (decimal)s_d_s_op2 != s_m_s_op1 + s_m_s_op2) || (s_m_s_op1 + s_m_s_op2 != s_m_s_op1 + s_i_s_op2) || (s_m_s_op1 + s_i_s_op2 != 9))
{
Console.WriteLine("testcase 28 failed");
passed = false;
}
}
if (!passed)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using FastQuant;
using FastQuant.Indicators;
using System.Linq;
using FastQuant.Optimization;
namespace Samples.SMACrossover
{
public class SMACrossover : InstrumentStrategy
{
private SMA sma1;
private SMA sma2;
private bool entryEnabled = true;
private int OCACount = 0;
private Order marketOrder;
private Order limitOrder;
private Order stopOrder;
private Group barsGroup;
private Group fillGroup;
private Group equityGroup;
private Group sma1Group;
private Group sma2Group;
private Group closeMonitorGroup;
private Group openMonitorGroup;
private Group positionMonitorGroup;
[Parameter]
public double MoneyForInstrument = 100000;
[Parameter]
double Qty = 100;
[Parameter]
public int Length1 = 14;
[Parameter]
public int Length2 = 50;
public double StopOCALevel = 0.98;
public double LimitOCALevel = 1.05;
public double StopLevel = 0.05;
public StopType StopType = StopType.Trailing;
public StopMode StopMode = StopMode.Percent;
public bool CrossoverExitEnabled = true;
public bool OCAExitEnabled = true;
public bool StopExitEnabled = true;
public SMACrossover(Framework framework, string name)
: base(framework, name)
{
}
protected override void OnStrategyStart()
{
// Add money for current trading instrument's portfolio.
Portfolio.Account.Deposit(Clock.DateTime, MoneyForInstrument, CurrencyId.USD, "Initial allocation");
// Set up indicators.
sma1 = new SMA(Bars, Length1);
sma2 = new SMA(Bars, Length2);
AddGroups();
}
protected override void OnBar(Instrument instrument, Bar bar)
{
Bars.Add(bar);
// Log open close and position info to Strategy Monitor.
Log(bar.DateTime, bar.Close, closeMonitorGroup);
Log(bar.DateTime, bar.Open, openMonitorGroup);
if (HasPosition(instrument))
Log(bar.DateTime, Position.Side.ToString(), positionMonitorGroup);
else
Log(bar.DateTime, "None", positionMonitorGroup);
// Log bars.
Log(bar, barsGroup);
if (sma1.Count == 0 || sma2.Count == 0)
return;
// Log sma.
Log(bar.DateTime, sma1.Last, sma1Group);
Log(bar.DateTime, sma2.Last, sma2Group);
// Update performance.
Portfolio.Performance.Update();
// Log equity.
Log(bar.DateTime, Portfolio.Value, equityGroup);
// Does the fast average cross over the slow average? If so, time to buy long.
Cross cross = sma1.Crosses(sma2, bar.DateTime);
// We only allow one active position at a time.
if (entryEnabled)
{
// If price trend is moving upward, open a long position using a market order, and send it in.
if (cross == Cross.Above)
{
marketOrder = BuyOrder(instrument, Qty, "Entry");
Send(marketOrder);
// If one cancels all exit method is desired, we
// also issue a limit (profit target) order, and
// a stop loss order in case the breakout fails.
// The OCA exit method uses a real stop loss order.
// The Stop exit method uses a stop indicator.
// Use either the OCA or Stop method, not both at once.
if (OCAExitEnabled)
{
// Create and send a profit limit order.
double profitTarget = LimitOCALevel * bar.Close;
limitOrder = SellLimitOrder(instrument, Qty, profitTarget, "Limit OCA " + OCACount);
limitOrder.OCA = "OCA " + Instrument.Symbol + " " + OCACount;
Send(limitOrder);
// Create and send a stop loss order.
double lossTarget = StopOCALevel * bar.Close;
stopOrder = SellStopOrder(instrument, Qty, lossTarget, "Stop OCA " + OCACount);
stopOrder.OCA = "OCA " + Instrument.Symbol + " " + OCACount;
Send(stopOrder);
// Bump the OCA count to make OCA group strings unique.
OCACount++;
}
entryEnabled = false;
}
}
// Else if entry is disabled on this bar, we have an open position.
else
{
// If we are using the crossover exit, and if the fast
// average just crossed below the slow average, issue a
// market order to close the existing position.
if (CrossoverExitEnabled)
{
if (cross == Cross.Below)
{
marketOrder = SellOrder(instrument, Qty, "Crossover Exit");
Send(marketOrder);
}
}
}
}
protected override void OnPositionOpened(Position position)
{
// If we want to exit trades using the Stop method, set a
// a trailing stop indicator when the position is
// first opened. The stop indicator is not a stop loss
// order that can be executed by a broker. Instead, the stop
// just fires the OnStopExecuted event when it it triggered.
if (StopExitEnabled)
AddStop(new Stop(this, position, StopLevel, StopType, StopMode));
}
protected override void OnPositionClosed(Position position)
{
// When a position is closed, cancel the limit and stop
// orders that might be associated with this position.
// But only cancel if the order has not been filled or
// not been cancelled already.
if (OCAExitEnabled && !(limitOrder.IsFilled || limitOrder.IsCancelled))
Cancel(limitOrder);
// Allow entries once again, since our position is closed.
entryEnabled = true;
}
protected override void OnFill(Fill fill)
{
// Add fill to group.
Log(fill, fillGroup);
}
protected override void OnStopExecuted(Stop stop)
{
// If our trailing stop indicator was executed,
// issue a market sell order to close the position.
marketOrder = SellOrder(Instrument, Qty, "Stop Exit");
Send(marketOrder);
}
private void AddGroups()
{
// Create bars group.
barsGroup = new Group("Bars");
barsGroup.Add("Pad", DataObjectType.String, 0);
barsGroup.Add("SelectorKey", Instrument.Symbol);
//// Create fills group.
fillGroup = new Group("Fills");
fillGroup.Add("Pad", 0);
fillGroup.Add("SelectorKey", Instrument.Symbol);
// Create equity group.
equityGroup = new Group("Equity");
equityGroup.Add("Pad", 1);
equityGroup.Add("SelectorKey", Instrument.Symbol);
// Create sma1 values group.
sma1Group = new Group("SMA1");
sma1Group.Add("Pad", 0);
sma1Group.Add("SelectorKey", Instrument.Symbol);
sma1Group.Add("Color", Color.Green);
// Create sma2 values group.
sma2Group = new Group("SMA2");
sma2Group.Add("Pad", 0);
sma2Group.Add("SelectorKey", Instrument.Symbol);
sma2Group.Add("Color", Color.Red);
// Create log monitor groups.
closeMonitorGroup = new Group("Close");
closeMonitorGroup.Add("LogName", "Close");
closeMonitorGroup.Add("StrategyName", "MyStrategy");
closeMonitorGroup.Add("Symbol", Instrument.Symbol);
openMonitorGroup = new Group("Open");
openMonitorGroup.Add("LogName", "Open");
openMonitorGroup.Add("StrategyName", "MyStrategy");
openMonitorGroup.Add("Symbol", Instrument.Symbol);
positionMonitorGroup = new Group("Position");
positionMonitorGroup.Add("LogName", "Position");
positionMonitorGroup.Add("StrategyName", "MyStrategy");
positionMonitorGroup.Add("Symbol", Instrument.Symbol);
// Add groups to manager.
GroupManager.Add(barsGroup);
GroupManager.Add(fillGroup);
GroupManager.Add(equityGroup);
GroupManager.Add(sma1Group);
GroupManager.Add(sma2Group);
GroupManager.Add(closeMonitorGroup);
GroupManager.Add(openMonitorGroup);
GroupManager.Add(positionMonitorGroup);
}
}
public class SMACrossoverLoadOnStart : InstrumentStrategy
{
private SMA fastSMA;
private SMA slowSMA;
private Group barsGroup;
private Group fillGroup;
private Group equityGroup;
private Group fastSmaGroup;
private Group slowSmaGroup;
public static bool SuspendTrading = false;
[Parameter]
public double AllocationPerInstrument = 100000;
[Parameter]
public double Qty = 100;
[Parameter]
public int FastSMALength = 8;
[Parameter]
public int SlowSMALength = 21;
public SMACrossoverLoadOnStart(Framework framework, string name)
: base(framework, name)
{
}
protected override void OnStrategyInit()
{
Portfolio.Account.Deposit(AllocationPerInstrument, CurrencyId.USD, "Initial allocation");
// Set up indicators.
fastSMA = new SMA(Bars, FastSMALength);
slowSMA = new SMA(Bars, SlowSMALength);
AddGroups();
}
protected override void OnStrategyStart()
{
Console.WriteLine("Starting strategy in {0} mode.", Mode);
}
protected override void OnBar(Instrument instrument, Bar bar)
{
// Add bar to bar series.
Bars.Add(bar);
Log(bar, barsGroup);
if (fastSMA.Count > 0)
Log(fastSMA.Last, fastSmaGroup);
if (slowSMA.Count > 0)
Log(slowSMA.Last, slowSmaGroup);
// Calculate performance.
Portfolio.Performance.Update();
Log(Portfolio.Value, equityGroup);
if (!SuspendTrading)
{
// Check strategy logic.
if (fastSMA.Count > 0 && slowSMA.Count > 0)
{
Cross cross = fastSMA.Crosses(slowSMA, bar.DateTime);
if (!HasPosition(instrument))
{
// Enter long/short.
if (cross == Cross.Above)
{
Order enterOrder = BuyOrder(Instrument, Qty, "Enter Long");
Send(enterOrder);
}
else if (cross == Cross.Below)
{
Order enterOrder = SellOrder(Instrument, Qty, "Enter Short");
Send(enterOrder);
}
}
else
{
// Reverse to long/short.
if (Position.Side == PositionSide.Long && cross == Cross.Below)
{
Order reverseOrder = SellOrder(Instrument, Math.Abs(Position.Amount) + Qty, "Reverse to Short");
Send(reverseOrder);
}
else if (Position.Side == PositionSide.Short && cross == Cross.Above)
{
Order reverseOrder = BuyOrder(Instrument, Math.Abs(Position.Amount) + Qty, "Reverse to Long");
Send(reverseOrder);
}
}
}
}
}
protected override void OnFill(Fill fill)
{
// Add fill to group.
Log(fill, fillGroup);
}
private void AddGroups()
{
// Create bars group.
barsGroup = new Group("Bars");
barsGroup.Add("Pad", DataObjectType.String, 0);
barsGroup.Add("SelectorKey", Instrument.Symbol);
// Create fills group.
fillGroup = new Group("Fills");
fillGroup.Add("Pad", 0);
fillGroup.Add("SelectorKey", Instrument.Symbol);
// Create equity group.
equityGroup = new Group("Equity");
equityGroup.Add("Pad", 1);
equityGroup.Add("SelectorKey", Instrument.Symbol);
// Create fast sma values group.
fastSmaGroup = new Group("FastSMA");
fastSmaGroup.Add("Pad", 0);
fastSmaGroup.Add("SelectorKey", Instrument.Symbol);
fastSmaGroup.Add("Color", Color.Green);
// Create slow sma values group.
slowSmaGroup = new Group("SlowSMA");
slowSmaGroup.Add("Pad", 0);
slowSmaGroup.Add("SelectorKey", Instrument.Symbol);
slowSmaGroup.Add("Color", Color.Red);
// Add groups to manager.
GroupManager.Add(barsGroup);
GroupManager.Add(fillGroup);
GroupManager.Add(equityGroup);
GroupManager.Add(fastSmaGroup);
GroupManager.Add(slowSmaGroup);
}
}
public class SMACrossoverWithEventFilter : InstrumentStrategy
{
class MyEventFilter : EventFilter
{
private TimeSpan filterStartTime;
private TimeSpan filterEndTime;
private Dictionary<int, Trade> goodTrades;
public MyEventFilter(Framework framework, TimeSpan filterStartTime, TimeSpan filterEndTime)
: base(framework)
{
this.filterStartTime = filterStartTime;
this.filterEndTime = filterEndTime;
goodTrades = new Dictionary<int, Trade>();
}
public override Event Filter(Event e)
{
// Filter if event is trade.
if (e.TypeId == EventType.Trade)
{
Trade trade = (Trade)e;
Trade lastGoodTrade = null;
// If filter has good trade.
if (goodTrades.TryGetValue(trade.InstrumentId, out lastGoodTrade))
{
// Check if trade falls in the +-7.5% interval from last good trade.
if (Math.Abs((1 - lastGoodTrade.Price / trade.Price) * 100) < 7.5)
{
// Save trade as good.
goodTrades[trade.InstrumentId] = trade;
// Check if trade falls in the filter time interval.
// If no return null, else return trade.
if (trade.DateTime.TimeOfDay < filterStartTime ||
trade.DateTime.TimeOfDay > filterEndTime)
return null;
else
return trade;
}
else
return null;
}
// If filter hasn't one trade.
else
{
// Save trade as good.
goodTrades[trade.InstrumentId] = trade;
// Check if trade falls in the filter time interval.
// If no return null, else return trade.
if (trade.DateTime.TimeOfDay < filterStartTime ||
trade.DateTime.TimeOfDay > filterEndTime)
return null;
else
return trade;
}
}
return e;
}
}
private SMA fastSMA;
private SMA slowSMA;
private Group barsGroup;
private Group fillGroup;
private Group equityGroup;
private Group fastSmaGroup;
private Group slowSmaGroup;
[Parameter]
public double AllocationPerInstrument = 100000;
[Parameter]
double Qty = 100;
[Parameter]
int FastSMALength = 8;
[Parameter]
int SlowSMALength = 21;
public SMACrossoverWithEventFilter(Framework framework, string name)
: base(framework, name)
{
}
protected override void OnStrategyStart()
{
Portfolio.Account.Deposit(AllocationPerInstrument, CurrencyId.USD, "Initial allocation");
// Set up indicators.
fastSMA = new SMA(Bars, FastSMALength);
slowSMA = new SMA(Bars, SlowSMALength);
AddGroups();
}
protected override void OnBar(Instrument instrument, Bar bar)
{
// Add bar to bar series.
Bars.Add(bar);
Log(bar, barsGroup);
if (fastSMA.Count > 0)
Log(fastSMA.Last, fastSmaGroup);
if (slowSMA.Count > 0)
Log(slowSMA.Last, slowSmaGroup);
// Calculate performance.
Portfolio.Performance.Update();
Log(Portfolio.Value, equityGroup);
// Check strategy logic.
if (fastSMA.Count > 0 && slowSMA.Count > 0)
{
Cross cross = fastSMA.Crosses(slowSMA, bar.DateTime);
if (!HasPosition(instrument))
{
// Enter long/short.
if (cross == Cross.Above)
{
Order enterOrder = BuyOrder(Instrument, Qty, "Enter Long");
Send(enterOrder);
}
else if (cross == Cross.Below)
{
Order enterOrder = SellOrder(Instrument, Qty, "Enter Short");
Send(enterOrder);
}
}
else
{
// Reverse to long/short.
if (Position.Side == PositionSide.Long && cross == Cross.Below)
{
Order reverseOrder = SellOrder(Instrument, Math.Abs(Position.Amount) + Qty, "Reverse to Short");
Send(reverseOrder);
}
else if (Position.Side == PositionSide.Short && cross == Cross.Above)
{
Order reverseOrder = BuyOrder(Instrument, Math.Abs(Position.Amount) + Qty, "Reverse to Long");
Send(reverseOrder);
}
}
}
}
protected override void OnFill(Fill fill)
{
Log(fill, fillGroup);
}
private void AddGroups()
{
// Create bars group.
barsGroup = new Group("Bars");
barsGroup.Add("Pad", DataObjectType.String, 0);
barsGroup.Add("SelectorKey", Instrument.Symbol);
// Create fills group.
fillGroup = new Group("Fills");
fillGroup.Add("Pad", 0);
fillGroup.Add("SelectorKey", Instrument.Symbol);
// Create equity group.
equityGroup = new Group("Equity");
equityGroup.Add("Pad", 1);
equityGroup.Add("SelectorKey", Instrument.Symbol);
// Create fast sma values group.
fastSmaGroup = new Group("FastSMA");
fastSmaGroup.Add("Pad", 0);
fastSmaGroup.Add("SelectorKey", Instrument.Symbol);
fastSmaGroup.Add("Color", Color.Green);
// Create slow sma values group.
slowSmaGroup = new Group("SlowSMA");
slowSmaGroup.Add("Pad", 0);
slowSmaGroup.Add("SelectorKey", Instrument.Symbol);
slowSmaGroup.Add("Color", Color.Red);
// Add groups to manager.
GroupManager.Add(barsGroup);
GroupManager.Add(fillGroup);
GroupManager.Add(equityGroup);
GroupManager.Add(fastSmaGroup);
GroupManager.Add(slowSmaGroup);
}
}
public class SMACrossoverWithTakeProfitAndStopLoss : InstrumentStrategy
{
private SMA fastSMA;
private SMA slowSMA;
private Order enterOrder;
private Order takeProfitOrder;
private Order stopLossOrder;
private Group barsGroup;
private Group fillGroup;
private Group equityGroup;
private Group fastSmaGroup;
private Group slowSmaGroup;
[Parameter]
public double AllocationPerInstrument = 100000;
[Parameter]
double Qty = 100;
[Parameter]
int FastSMALength = 8;
[Parameter]
int SlowSMALength = 21;
[Parameter]
double TakeProfit = 0.01;
[Parameter]
double StopLoss = 0.01;
public SMACrossoverWithTakeProfitAndStopLoss(Framework framework, string name)
: base(framework, name)
{
}
protected override void OnStrategyStart()
{
Portfolio.Account.Deposit(AllocationPerInstrument, CurrencyId.USD, "Initial allocation");
// Set up indicators.
fastSMA = new SMA(Bars, FastSMALength);
slowSMA = new SMA(Bars, SlowSMALength);
AddGroups();
}
protected override void OnBar(Instrument instrument, Bar bar)
{
// Add bar to bar series.
Bars.Add(bar);
Log(bar, barsGroup);
if (fastSMA.Count > 0)
Log(fastSMA.Last, fastSmaGroup);
if (slowSMA.Count > 0)
Log(slowSMA.Last, slowSmaGroup);
// Calculate performance.
Portfolio.Performance.Update();
// Add equity to group.
Log(Portfolio.Value, equityGroup);
// Check strategy logic.
if (fastSMA.Count > 0 && slowSMA.Count > 0)
{
Cross cross = fastSMA.Crosses(slowSMA, bar.DateTime);
// Enter long/short.
if (!HasPosition(instrument))
{
if (cross == Cross.Above)
{
enterOrder = BuyOrder(Instrument, Qty, "Enter Long");
Send(enterOrder);
}
else if (cross == Cross.Below)
{
enterOrder = SellOrder(Instrument, Qty, "Enter Short");
Send(enterOrder);
}
}
}
}
protected override void OnFill(Fill fill)
{
Log(fill, fillGroup);
}
protected override void OnOrderPartiallyFilled(Order order)
{
// Update take profit order.
if (order == stopLossOrder)
{
// Get take profit price and updated qty.
double takeProfitPrice = takeProfitOrder.Price;
double qty = Math.Abs(Position.Amount);
// Cancel existing take profit order.
Cancel(takeProfitOrder);
if (Position.Side == PositionSide.Long)
{
// Create updated order and send it.
takeProfitOrder = SellLimitOrder(Instrument, qty, takeProfitPrice, "TakeProfit");
Send(takeProfitOrder);
}
else
{
// Create updated order and send it.
takeProfitOrder = BuyLimitOrder(Instrument, qty, takeProfitPrice, "TakeProfit");
Send(takeProfitOrder);
}
}
// Update stop loss order.
else if (order == takeProfitOrder)
{
// Get take profit price and updated qty.
double stopLossPrice = stopLossOrder.Price;
double qty = Math.Abs(Position.Amount);
// Cancel existing stop loss order.
Cancel(stopLossOrder);
if (Position.Side == PositionSide.Long)
{
// Create updated order and send it.
stopLossOrder = SellStopOrder(Instrument, qty, stopLossPrice, "StopLoss");
Send(stopLossOrder);
}
else
{
// Create updated order and send it.
stopLossOrder = BuyStopOrder(Instrument, qty, stopLossPrice, "StopLoss");
Send(stopLossOrder);
}
}
}
protected override void OnOrderFilled(Order order)
{
if (order == enterOrder)
{
// Send take profit and stop loss orders.
if (Position.Side == PositionSide.Long)
{
// Calculate prices.
double takeProfitPrice = Position.EntryPrice * (1 + TakeProfit);
double stopLossPrice = Position.EntryPrice * (1 - StopLoss);
// Create orders.
takeProfitOrder = SellLimitOrder(Instrument, Qty, takeProfitPrice, "TakeProfit");
stopLossOrder = SellStopOrder(Instrument, Qty, stopLossPrice, "StopLoss");
// Send orders.
Send(stopLossOrder);
Send(takeProfitOrder);
}
else
{
// Calculate prices.
double takeProfitPrice = Position.EntryPrice * (1 - TakeProfit);
double stopLossPrice = Position.EntryPrice * (1 + StopLoss);
// Create orders.
takeProfitOrder = BuyLimitOrder(Instrument, Qty, takeProfitPrice, "TakeProfit");
stopLossOrder = BuyStopOrder(Instrument, Qty, stopLossPrice, "StopLoss");
// Send orders.
Send(stopLossOrder);
Send(takeProfitOrder);
}
}
else if (order == stopLossOrder)
{
// Cancel take profit order.
if (!takeProfitOrder.IsDone)
Cancel(takeProfitOrder);
}
else if (order == takeProfitOrder)
{
// Cancel stop loss order.
if (!stopLossOrder.IsDone)
Cancel(stopLossOrder);
}
}
private void AddGroups()
{
// Create bars group.
barsGroup = new Group("Bars");
barsGroup.Add("Pad", DataObjectType.String, 0);
barsGroup.Add("SelectorKey", Instrument.Symbol);
// Create fills group.
fillGroup = new Group("Fills");
fillGroup.Add("Pad", 0);
fillGroup.Add("SelectorKey", Instrument.Symbol);
// Create equity group.
equityGroup = new Group("Equity");
equityGroup.Add("Pad", 1);
equityGroup.Add("SelectorKey", Instrument.Symbol);
// Create fast sma values group.
fastSmaGroup = new Group("FastSMA");
fastSmaGroup.Add("Pad", 0);
fastSmaGroup.Add("SelectorKey", Instrument.Symbol);
fastSmaGroup.Add("Color", Color.Green);
// Create slow sma values group.
slowSmaGroup = new Group("SlowSMA");
slowSmaGroup.Add("Pad", 0);
slowSmaGroup.Add("SelectorKey", Instrument.Symbol);
slowSmaGroup.Add("Color", Color.Red);
// Add groups to manager.
GroupManager.Add(barsGroup);
GroupManager.Add(fillGroup);
GroupManager.Add(equityGroup);
GroupManager.Add(fastSmaGroup);
GroupManager.Add(slowSmaGroup);
}
}
public class Optimization : Scenario
{
public Optimization(Framework framework)
: base(framework)
{
}
public override void Run()
{
MulticoreOptimizer optimizer = new MulticoreOptimizer();
OptimizationUniverse universe = new OptimizationUniverse();
for (int length1 = 2; length1 < 14; length1++)
for (int length2 = length1 + 1; length2 < 28; length2++)
{
OptimizationParameterSet parameter = new OptimizationParameterSet();
parameter.Add("Length1", length1);
parameter.Add("Length2", length2);
parameter.Add("Bar", (long)60);
universe.Add(parameter);
}
strategy = new SMACrossover(framework, "strategy ");
Instrument instrument1 = InstrumentManager.Instruments["AAPL"];
Instrument instrument2 = InstrumentManager.Instruments["MSFT"];
InstrumentList instruments = new InstrumentList();
instruments.Add(instrument1);
instruments.Add(instrument2);
DataSimulator.DateTime1 = new DateTime(2013, 12, 01);
DataSimulator.DateTime2 = new DateTime(2013, 12, 31);
optimizer.Optimize(strategy, instruments, universe, 100);
}
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using ESRI.ArcLogistics.App.Geocode;
using ESRI.ArcLogistics.App.GridHelpers;
using ESRI.ArcLogistics.App.Mapping;
using ESRI.ArcLogistics.App.Tools;
using ESRI.ArcLogistics.DomainObjects;
using Xceed.Wpf.DataGrid;
namespace ESRI.ArcLogistics.App.Pages.Wizards
{
/// <summary>
/// Interaction logic for FleetSetupWizardUngeocodedOrdersPage.xaml
/// </summary>
internal partial class FleetSetupWizardUngeocodedOrdersPage : WizardPageBase,
ISupportNext, ISupportCancel, ISupportBack
{
#region Constructors
/// <summary>
/// Constructor.
/// </summary>
public FleetSetupWizardUngeocodedOrdersPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(_FleetSetupWizardUngeocodedOrdersPageLoaded);
Unloaded += new RoutedEventHandler(_FleetSetupWizardUngeocodedOrdersPageUnloaded);
}
/// <summary>
/// Constructor.
/// </summary>
public FleetSetupWizardUngeocodedOrdersPage(IList<Order> ungeocodedOrders)
: this()
{
_FillUngeocodedOrders(ungeocodedOrders);
}
#endregion
#region ISupportBack members
/// <summary>
/// Interface for event, which sygnalyze about "Back" button in page pressed.
/// </summary>
public event EventHandler BackRequired;
#endregion
#region ISupportNext members
/// <summary>
/// Interface for event, which sygnalyze about "Next" button in page pressed.
/// </summary>
public event EventHandler NextRequired;
#endregion
#region ISupportCancel members
/// <summary>
/// Interface for event, which sygnalyze about "Cancel" button in page pressed.
/// </summary>
public event EventHandler CancelRequired;
#endregion
#region Private properties
/// <summary>
/// Current selected order.
/// </summary>
private Order CurrentItem
{
get
{
return DataGridControl.SelectedItem as Order;
}
}
/// <summary>
/// Specialized context.
/// </summary>
private FleetSetupWizardDataContext DataKeeper
{
get
{
return DataContext as FleetSetupWizardDataContext;
}
}
#endregion
#region Private methods
/// <summary>
/// React on page loaded.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _FleetSetupWizardUngeocodedOrdersPageLoaded(object sender, RoutedEventArgs e)
{
// Init page if not inited yet.
if (!_inited)
{
_isParentFleetWizard = DataKeeper != null;
// Set row height.
ContentGrid.RowDefinitions[DATA_GRID_ROW_DEFINITION_INDEX].Height =
new System.Windows.GridLength(DEFAULT_ROW_HEIGHT * ROW_COUNT + DataGridControl.Margin.Top
+ DataGridControl.Margin.Bottom + ROW_COUNT);
// Create subpages.
string typeName = (string)App.Current.FindResource(ORDER_RESOURCE_NAME);
typeName = typeName.ToLower();
_matchFoundSubPage = new MatchFoundSubPage(typeName);
_candidatesNotFoundSubPage = new CandidatesNotFoundSubPage(typeName);
_candidatesFoundSubPage = new CandidatesFoundSubPage(typeName);
_SetSubPage(null);
// Init orders collection.
_collectionSource = (DataGridCollectionViewSource)LayoutRoot.FindResource(COLLECTION_SOURCE_KEY);
_CreateOrdersLayer();
// Create and init geocodable page.
_geocodablePage = new GeocodablePage(typeof(Order), mapCtrl, candidateSelect,
controlsGrid, DataGridControl, splitter, _ordersLayer);
_geocodablePage.MatchFound += new EventHandler(_MatchFound);
_geocodablePage.CandidatesFound += new EventHandler(_CandidatesFound);
_geocodablePage.CandidatesNotFound += new EventHandler(_CandidatesNotFound);
// Datakeeper is not null in fleetwizard.
_geocodablePage.ParentIsFleetWisard = _isParentFleetWizard;
mapCtrl.AddTool(new EditingTool(), null);
_collectionSource = (DataGridCollectionViewSource)LayoutRoot.FindResource(COLLECTION_SOURCE_KEY);
GridStructureInitializer structureInitializer = new GridStructureInitializer(GridSettingsProvider.FleetGeocodableGridStructure);
structureInitializer.BuildGridStructure(_collectionSource, DataGridControl);
CommonHelpers.HidePostalCode2Column(DataGridControl);
// Load grid layout.
GridLayoutLoader layoutLoader = new GridLayoutLoader(GridSettingsProvider.FleetLocationsSettingsRepositoryName,
_collectionSource.ItemProperties);
layoutLoader.LoadLayout(DataGridControl);
if (!_isParentFleetWizard)
_RemoveRedundantElements();
_inited = true;
}
// Get orders collection from datakeeper if it is not null. Otherwise - from current project.
if (_isParentFleetWizard)
{
// Fill ungeocoded orders list.
_FillUngeocodedOrders(DataKeeper.AddedOrders);
}
else
{
// Do nothing. Ungeocoded order already set by constructor.
}
_collectionSource.Source = _ungeocodedOrders;
_ordersLayer.Collection = _ungeocodedOrders;
_selectionBinding.UnregisterAllCollections();
_selectionBinding.RegisterCollection(DataGridControl);
_selectionBinding.RegisterCollection(mapCtrl.SelectedItems);
ButtonFinish.IsEnabled = _IsFinishButtonEnabled(_ungeocodedOrders);
}
/// <summary>
/// If orders page called by optimize and edit page - hide redundant.
/// </summary>
private void _RemoveRedundantElements()
{
AllOrdersMustBeGeocodedText.Visibility = Visibility.Collapsed;
ButtonBack.Visibility = Visibility.Collapsed;
ButtonCancel.Visibility = Visibility.Collapsed;
GeocodeResultText.Visibility = Visibility.Collapsed;
GeocodeHelperPanel.Visibility = Visibility.Collapsed;
// Hide column container for Geocode helper panel.
ContentGrid.ColumnDefinitions[1].MaxWidth = 0;
// Remove tooltip because we can finish with ungeocoded orders.
ButtonFinish.ToolTip = null;
}
/// <summary>
/// Create layer for showing ungeocoded orders.
/// </summary>
private void _CreateOrdersLayer()
{
_ordersLayer = new ObjectLayer(new List<Order>(), typeof(Order), false);
_ordersLayer.EnableToolTip();
_ordersLayer.Selectable = false;
mapCtrl.AddLayer(_ordersLayer);
}
/// <summary>
/// React on page unloaded.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _FleetSetupWizardUngeocodedOrdersPageUnloaded(object sender, RoutedEventArgs e)
{
foreach (Order order in _ungeocodedOrders)
{
order.PropertyChanged -= new PropertyChangedEventHandler(_OrderPropertyChanged);
}
}
/// <summary>
/// React on order property changed.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _OrderPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var order = (Order)sender;
_UpdateOrdersProperties(order);
ButtonFinish.IsEnabled = _IsFinishButtonEnabled(_ungeocodedOrders);
}
/// <summary>
/// Updates properties for all orders with the same name as the specified one.
/// </summary>
/// <param name="sourceOrder">The reference to an
/// <see cref="ESRI.ArcLogistics.DomainObjects.Order"/> object to read property values
/// from.</param>
private void _UpdateOrdersProperties(Order sourceOrder)
{
Debug.Assert(sourceOrder != null);
var orders = _orderGroups[sourceOrder].Where(order => order != sourceOrder);
foreach (var order in orders)
{
sourceOrder.CopyTo(order);
}
}
/// <summary>
/// Button "Finish" click handler.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _ButtonFinishClick(object sender, RoutedEventArgs e)
{
if (null != NextRequired)
NextRequired(this, EventArgs.Empty);
}
/// <summary>
/// Fill orders collection.
/// </summary>
private void _FillUngeocodedOrders(IEnumerable<Order> unassignedOrders)
{
Debug.Assert(unassignedOrders != null);
Debug.Assert(unassignedOrders.All(order => order != null));
Debug.Assert(unassignedOrders.All(order => !string.IsNullOrEmpty(order.Name)));
var orderGroups = unassignedOrders
.Where(order => !order.IsGeocoded)
.GroupBy(order => new OrderKey(order))
.ToDictionary(group => group.First(), group => group.ToList());
_ungeocodedOrders.Clear();
foreach (var order in orderGroups.Keys)
{
_ungeocodedOrders.Add(order);
order.PropertyChanged += new PropertyChangedEventHandler(_OrderPropertyChanged);
}
_orderGroups = orderGroups;
}
/// <summary>
/// React on candidates not found.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _CandidatesNotFound(object sender, EventArgs e)
{
_SetSubPage(_candidatesNotFoundSubPage);
}
/// <summary>
/// React on candidates found.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _CandidatesFound(object sender, EventArgs e)
{
_SetSubPage(_candidatesFoundSubPage);
}
/// <summary>
/// React on match found.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _MatchFound(object sender, EventArgs e)
{
_SetSubPage(_matchFoundSubPage);
mapCtrl.map.UpdateLayout();
// Current item must have geolocation.
Debug.Assert(CurrentItem.GeoLocation != null);
// Remeber the current oreder, it can changed before invoke executes.
Geometry.Point geoLocatedPoint = CurrentItem.GeoLocation.Value;
// Zooming to current item suspended because zooming should go after suspended zoom
// restoring in mapextentmanager. Suspended zoom restoring invoked in case of saved
// old extent(zoom was changed by mouse) and because of map control size changed
// after showing subpage.
Dispatcher.BeginInvoke(new Action(delegate()
{
_ZoomOnCurrentItem(geoLocatedPoint);
}
),
DispatcherPriority.Background);
// Do not need to finish editing there if match was found by tool.
if (_skipStartGeocoding)
{
// Do nothing.
}
else
{
_skipStartGeocoding = true;
try
{
DataGridControl.EndEdit();
}
catch
{
// Exception in cycle end editing.
}
_skipStartGeocoding = false;
}
}
/// <summary>
/// Check is finish button enabled: parent page is optimize and edit or ungeocoded orders is absent.
/// </summary>
/// <param name="orders">Orders collection.</param>
/// <returns>Is finish button enabled.</returns>
private bool _IsFinishButtonEnabled(IList<Order> orders)
{
bool isFinishButtonEnabled = true;
if (DataKeeper != null)
{
foreach (Order order in orders)
{
if (!order.IsGeocoded)
{
isFinishButtonEnabled = false;
break;
}
}
}
return isFinishButtonEnabled;
}
/// <summary>
/// Set subpage.
/// </summary>
/// <param name="subPage">Subpage to set. Null if disable subpages.</param>
private void _SetSubPage(IGeocodeSubPage subPage)
{
// Do not need to set subpages if page was not called from fleet wizard.
if (!_isParentFleetWizard)
return;
GeocodeHelperPanel.Children.Clear();
if (subPage != null)
{
GeocodeHelperPanel.Children.Add(subPage as Grid);
Grid.SetColumnSpan(controlsGrid, 1);
// Set subpage text.
GeocodeResultText.Text = subPage.GetGeocodeResultString(CurrentItem, _geocodablePage.CandidatesToZoom);
GeocodeResultText.Visibility = Visibility.Visible;
}
else
{
Grid.SetColumnSpan(controlsGrid, 2);
// Remove subpage text.
GeocodeResultText.Text = string.Empty;
GeocodeResultText.Visibility = Visibility.Collapsed;
}
}
/// <summary>
/// React on delete button click.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _ButtonDeleteClick(object sender, RoutedEventArgs e)
{
// Cancel to prevent crash in case of item is not valid.
if (DataGridControl.IsBeingEdited)
{
DataGridControl.CancelEdit();
}
Order orderToDelete = CurrentItem;
orderToDelete.PropertyChanged -= _OrderPropertyChanged;
IList<Order> orders = (IList<Order>)_collectionSource.Source;
orders.Remove(orderToDelete);
Debug.Assert(_orderGroups.ContainsKey(orderToDelete));
foreach (var order in _orderGroups[orderToDelete])
{
// If datakeeper is not null - remove order from it.
if (DataKeeper != null)
{
DataKeeper.AddedOrders.Remove(order);
}
// Remove order from current project.
App.Current.Project.Orders.Remove(order);
}
App.Current.Project.Save();
// If all remaining orders geocoded - make finish button enabled.
ButtonFinish.IsEnabled = _IsFinishButtonEnabled(_ungeocodedOrders);
}
/// <summary>
/// React on locate button click.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _ButtonLocateClick(object sender, RoutedEventArgs e)
{
bool editingWasEndedSuccessfully = false;
// Remove history items.
try
{
// Endedit can lead to exception if name is empty and not commited yet.
DataGridControl.EndEdit();
editingWasEndedSuccessfully = true;
}
catch { }
_ProcessLocateOrder(editingWasEndedSuccessfully);
}
/// <summary>
/// React on cancel button click.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _ButtonCancelClick(object sender, RoutedEventArgs e)
{
if (null != CancelRequired)
CancelRequired(this, EventArgs.Empty);
}
/// <summary>
/// React on back button click.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _ButtonBackClick(object sender, RoutedEventArgs e)
{
DataGridControl.CancelEdit();
if (null != CancelRequired)
CancelRequired(this, EventArgs.Empty);
if (null != BackRequired)
BackRequired(this, EventArgs.Empty);
}
/// <summary>
/// Zoom on order if geocoded or start geocoding otherwise.
/// </summary>
/// <param name="editingWasEndedSuccessfully">Is Locate button was pressed and endedit was successful.</param>
private void _ProcessLocateOrder(bool editingWasEndedSuccessfully)
{
if (CurrentItem.IsGeocoded)
{
_ZoomOnCurrentItem(CurrentItem.GeoLocation.Value);
}
else
{
// Geocoding possibly already started by endedit.
if (!editingWasEndedSuccessfully)
{
// Geocode order.
_geocodablePage.StartGeocoding(CurrentItem);
}
if (_geocodablePage.CandidatesToZoom != null)
{
MapExtentHelpers.ZoomToCandidates(mapCtrl, _geocodablePage.CandidatesToZoom);
}
}
}
/// <summary>
/// Zoom on point.
/// </summary>
/// <param name="point">Point to zoom at</param>
private void _ZoomOnCurrentItem(Geometry.Point point)
{
// Current item can be null because zooming suspended.
//if (CurrentItem != null)
//{
// Zoom on order.
List<ESRI.ArcLogistics.Geometry.Point> points = new List<ESRI.ArcLogistics.Geometry.Point>();
points.Add(point);
MapExtentHelpers.SetExtentOnCollection(mapCtrl, points);
//}
}
/// <summary>
/// Set "Locate" button availability.
/// </summary>
private void _ProcessLocateState()
{
ButtonsPanel.IsEnabled = false;
if (CurrentItem == null)
{
// If item is not selected - hide button.
ButtonsPanel.Visibility = Visibility.Hidden;
}
else
{
if (GeocodeHelpers.IsActiveAddressFieldsEmpty(CurrentItem))
{
// If address fields are empty - disable button.
ButtonsPanel.IsEnabled = false;
}
else
{
_ShowLocateButton();
ButtonsPanel.IsEnabled = true;
}
}
}
/// <summary>
/// React on selection change.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _SelectionChanged(object sender, DataGridSelectionChangedEventArgs e)
{
if (_inited)
{
if (_isSelectedByInternalGridLogic)
{
DataGridControl.SelectedItems.Clear();
_isSelectedByInternalGridLogic = false;
}
else
{
_geocodablePage.OnSelectionChanged(DataGridControl.SelectedItems);
_SetSubPage(null);
_ProcessLocateState();
if (CurrentItem != null)
{
_ProcessLocateOrder(false);
}
}
}
}
/// <summary>
/// React on beginning edit.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Event args.</param>
private void _BeginningEdit(object sender, DataGridItemCancelEventArgs e)
{
_ShowLocateButton();
if (GeocodeHelpers.IsActiveAddressFieldsEmpty(CurrentItem))
{
ButtonsPanel.IsEnabled = false;
}
else
{
ButtonsPanel.IsEnabled = true;
}
_geocodablePage.OnBeginningEdit(e);
e.Handled = true;
CurrentItem.Address.PropertyChanged += new PropertyChangedEventHandler(_AddressPropertyChanged);
CurrentItem.PropertyChanged += new PropertyChangedEventHandler(_CurrentItemPropertyChanged);
}
/// <summary>
/// React on committing edit.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Event args.</param>
private void _CommittingEdit(object sender, DataGridItemCancelEventArgs e)
{
_geocodablePage.OnCommittingEdit(e, !_skipStartGeocoding);
e.Handled = true;
CurrentItem.Address.PropertyChanged -= new PropertyChangedEventHandler(_AddressPropertyChanged);
CurrentItem.PropertyChanged -= new PropertyChangedEventHandler(_CurrentItemPropertyChanged);
}
/// <summary>
/// React on cancelling edit.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Event args.</param>
private void _CancelingEdit(object sender, DataGridItemHandledEventArgs e)
{
_geocodablePage.OnEditCanceled(e);
e.Handled = true;
CurrentItem.Address.PropertyChanged -= new PropertyChangedEventHandler(_AddressPropertyChanged);
CurrentItem.PropertyChanged -= new PropertyChangedEventHandler(_CurrentItemPropertyChanged);
}
/// <summary>
/// React on edit canceled.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Event args.</param>
private void _EditCanceled(object sender, DataGridItemEventArgs e)
{
_geocodablePage.OnEditCanceled(e);
}
/// <summary>
/// React on current item address property changed.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Ignored.</param>
private void _AddressPropertyChanged(object sender, PropertyChangedEventArgs e)
{
_ProcessLocateState();
}
/// <summary>
/// React on selected item property changed.
/// </summary>
/// <param name="sender">Ignored.</param>
/// <param name="e">Property changed event args.</param>
private void _CurrentItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName.Equals(Location.PropertyNameName, StringComparison.OrdinalIgnoreCase))
{
_ProcessLocateState();
}
}
/// <summary>
/// Show locate button with corrected margin.
/// </summary>
private void _ShowLocateButton()
{
ButtonsPanel.Visibility = Visibility.Visible;
// Call margin setter suspended because container is not correct after scrolling.
Dispatcher.BeginInvoke(
new Action(delegate()
{
ButtonsPanel.Margin = CommonHelpers.GetItemContainerMargin(CurrentItem, DataGridControl, DEFAULT_ROW_HEIGHT);
}
),
DispatcherPriority.Background);
}
#endregion // Event handlers
#region Private constants
/// <summary>
/// Collection source resource key name.
/// </summary>
private const string COLLECTION_SOURCE_KEY = "DataGridSource";
/// <summary>
/// Datagrid control default row height.
/// </summary>
private readonly double DEFAULT_ROW_HEIGHT = (double)App.Current.FindResource("XceedRowDefaultHeight");
/// <summary>
/// Index of row in definions, which contains datagrid.
/// </summary>
private const int DATA_GRID_ROW_DEFINITION_INDEX = 3;
/// <summary>
/// Datagrid control default row count.
/// </summary>
private readonly int ROW_COUNT = 5;
/// <summary>
/// Order resource name.
/// </summary>
private const string ORDER_RESOURCE_NAME = "Order";
/// <summary>
/// Name string.
/// </summary>
private const string NAME_PROPERTY_STRING = "Name";
#endregion
#region Private fields
/// <summary>
/// Is page inited.
/// </summary>
private bool _inited;
/// <summary>
/// Match found subpage.
/// </summary>
private MatchFoundSubPage _matchFoundSubPage;
/// <summary>
/// Candidate not found subpage.
/// </summary>
private CandidatesNotFoundSubPage _candidatesNotFoundSubPage;
/// <summary>
/// Candidate found subpage.
/// </summary>
private CandidatesFoundSubPage _candidatesFoundSubPage;
/// <summary>
/// Geocodable page.
/// </summary>
private GeocodablePage _geocodablePage;
/// <summary>
/// Collection view source.
/// </summary>
private DataGridCollectionViewSource _collectionSource;
/// <summary>
/// Layer for showing orders.
/// </summary>
private ObjectLayer _ordersLayer;
/// <summary>
/// Flag for clearing selection after selecting first element by internal datagrid control internal logic.
/// </summary>
private bool _isSelectedByInternalGridLogic = true;
/// <summary>
/// Helper for synchronization selection between map layer and datagrid control.
/// </summary>
private MultiCollectionBinding _selectionBinding = new MultiCollectionBinding();
/// <summary>
/// Collection of ungeocoded orders.
/// </summary>
private ObservableCollection<Order> _ungeocodedOrders = new ObservableCollection<Order>();
/// <summary>
/// Flag to prevent cycle calling start geocoding after match found.
/// </summary>
private bool _skipStartGeocoding;
/// <summary>
/// Is parent fleet wizard. It depends on is data keeper not null.
/// </summary>
private bool _isParentFleetWizard;
/// <summary>
/// Groups orders with the same name but with different planned dates.
/// </summary>
private Dictionary<Order, List<Order>> _orderGroups;
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
using UnityEngine;
using Object = UnityEngine.Object;
namespace Thinksquirrel.Fluvio.Internal
{
using Threading;
// This class sets up implementations of certain platform-specific features.
[ExecuteInEditMode]
[AddComponentMenu("")]
class FluvioRuntimeHelper : MonoBehaviour
{
#if UNITY_EDITOR
static int s_ProcessId = -1;
#endif
#if !UNITY_WEBGL && !UNITY_WINRT
IThreadFactory m_ThreadFactory;
IThreadHandler m_ThreadHandler;
IInterlocked m_Interlocked;
#endif
void OnEnable()
{
// Inject platform-specific dependencies
#if UNITY_EDITOR
if (s_ProcessId < 0) s_ProcessId = System.Diagnostics.Process.GetCurrentProcess().Id;
// Create settings object in the editor
var serializedInstance = Resources.Load("FluvioManager", typeof(FluvioSettings)) as FluvioSettings;
if (!serializedInstance)
{
var instance = FluvioSettings.GetFluvioSettingsObject();
serializedInstance = CreateProjectSettingsAsset(instance, "Resources", "FluvioManager.asset");
}
FluvioSettings.SetFluvioSettingsObject(serializedInstance);
FluvioComputeShader.SetIncludeParser(new ComputeIncludeParser());
UnityEditor.EditorApplication.update += EditorUpdate;
#endif
// OpenCL support
#if UNITY_STANDALONE// || UNITY_ANDROID // TODO - Android support for OpenCL is WIP
Cloo.Bindings.CLInterface.SetInterface(new Cloo.Bindings.CL12());
#endif
// Multithreading
#if !UNITY_WEBGL && !UNITY_WINRT
m_ThreadFactory = new ThreadFactory();
m_ThreadHandler = new ThreadHandler();
m_Interlocked = new Interlocked();
FluidBase.onFluidEnabled += OnFluidEnabled;
FluidBase.onFluidDisabled += OnFluidDisabled;
OnFluidEnabled(null);
#endif
}
#if UNITY_EDITOR
void EditorUpdate()
{
if (!(Application.isPlaying && Application.runInBackground))
{
CheckApplicationFocus();
}
}
#endif
void OnFluidEnabled(FluidBase fluid)
{
#if !UNITY_WEBGL && !UNITY_WINRT
if (FluidBase.fluidCount > 0 && !Parallel.isInitialized)
{
Parallel.Initialize(m_ThreadFactory, m_ThreadHandler, m_Interlocked);
}
#endif
}
static void OnFluidDisabled(FluidBase fluid)
{
#if !UNITY_WEBGL && !UNITY_WINRT
if (FluidBase.fluidCount == 0)
{
Parallel.Reset();
}
#endif
}
#if !UNITY_WEBGL && !UNITY_WINRT
void OnApplicationPause(bool isPaused)
{
if (!Application.isEditor) UpdateThreads(!isPaused);
}
void OnApplicationFocus(bool isFocused)
{
if (!Application.isEditor) UpdateThreads(isFocused);
}
void UpdateThreads(bool isFocused)
{
if (isFocused && FluidBase.fluidCount > 0 && !Parallel.isInitialized)
{
Parallel.Initialize(m_ThreadFactory, m_ThreadHandler, m_Interlocked);
}
else if (!isFocused)
{
Parallel.Reset();
}
}
#endif
#if UNITY_EDITOR_WIN
void CheckApplicationFocus()
{
var activatedHandle = GetForegroundWindow();
if (activatedHandle == IntPtr.Zero)
return;
int activeProcId;
GetWindowThreadProcessId(activatedHandle, out activeProcId);
UpdateThreads(activeProcId == s_ProcessId);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
#elif UNITY_EDITOR_OSX
#if !UNITY_WEBPLAYER
System.Diagnostics.Process m_FocusProcess;
bool m_IsActive = true;
const string kAppleScript =
"-e \"global frontApp, frontAppId\" "+
"-e \"tell application \\\"System Events\\\"\" "+
"-e \"set frontApp to first application process whose frontmost is true\" " +
"-e \"set frontAppId to unix id of frontApp\" " +
"-e \"end tell\" " +
"-e \"return {frontAppId}\"";
#endif
void CheckApplicationFocus()
{
#if !UNITY_WEBPLAYER // No support for this when in Web Player mode
try
{
if (m_IsActive) UpdateThreads(true);
if (m_FocusProcess != null && !m_FocusProcess.HasExited) return;
var file = new System.IO.FileInfo(System.IO.Path.GetTempPath() + "/fluvio-active-window.sh");
if (!file.Exists)
{
System.IO.File.WriteAllText(file.FullName, "#!/bin/sh\necho `osascript " + kAppleScript + "`");
var procChmod = new System.Diagnostics.Process
{
StartInfo =
{
UseShellExecute = false,
FileName = "chmod",
Arguments = "+x \"" + file.FullName + "\""
}
};
procChmod.Start();
procChmod.WaitForExit();
}
var proc = new System.Diagnostics.Process
{
StartInfo =
{
UseShellExecute = false,
FileName = file.FullName,
RedirectStandardOutput = true
}
};
proc.OutputDataReceived += (sender, args) =>
{
if (args.Data == null) return;
var activeProcId = int.Parse(args.Data);
m_IsActive = activeProcId == s_ProcessId;
if (!m_IsActive) UpdateThreads(false);
};
m_FocusProcess = proc;
proc.Start();
proc.BeginOutputReadLine();
}
catch {}
#endif
}
#elif UNITY_EDITOR_LINUX
// TODO: Support for pausing Linux editor
void CheckApplicationFocus() {}
#endif
void OnDisable()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.update -= EditorUpdate;
#endif
FluidBase.onFluidEnabled -= OnFluidEnabled;
FluidBase.onFluidDisabled -= OnFluidDisabled;
}
#if UNITY_EDITOR
static T CreateProjectSettingsAsset<T>(T obj, string folder, string fileName) where T : Object
{
string path;
if (Application.platform == RuntimePlatform.WindowsEditor)
{
path = Application.dataPath.Replace("/", "\\") + "\\Fluvio-ProjectSettings\\" + folder;
}
else
{
path = Application.dataPath + "/Fluvio-ProjectSettings/" + folder;
}
System.IO.Directory.CreateDirectory(path);
var path2 = "Assets/Fluvio-ProjectSettings/" + folder + "/" + fileName;
var currentObj = UnityEditor.AssetDatabase.LoadAssetAtPath(path2, typeof(T)) as T;
if (currentObj)
{
UnityEditor.EditorUtility.CopySerialized(obj, currentObj);
UnityEditor.AssetDatabase.Refresh();
}
else
{
UnityEditor.AssetDatabase.CreateAsset(obj, path2);
UnityEditor.AssetDatabase.Refresh();
currentObj = obj;
}
return currentObj;
}
#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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.ComponentModel
{
public partial interface ISynchronizeInvoke
{
bool InvokeRequired { get; }
System.IAsyncResult BeginInvoke(System.Delegate method, object[] args);
object EndInvoke(System.IAsyncResult result);
object Invoke(System.Delegate method, object[] args);
}
public sealed partial class BrowsableAttribute : System.Attribute
{
public static readonly System.ComponentModel.BrowsableAttribute Default;
public static readonly System.ComponentModel.BrowsableAttribute No;
public static readonly System.ComponentModel.BrowsableAttribute Yes;
public BrowsableAttribute(bool browsable) { }
public bool Browsable { get; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
public partial class CategoryAttribute : System.Attribute
{
public CategoryAttribute() { }
public CategoryAttribute(string category) { }
public static System.ComponentModel.CategoryAttribute Action { get; }
public static System.ComponentModel.CategoryAttribute Appearance { get; }
public static System.ComponentModel.CategoryAttribute Asynchronous { get; }
public static System.ComponentModel.CategoryAttribute Behavior { get; }
public string Category { get; }
public static System.ComponentModel.CategoryAttribute Data { get; }
public static System.ComponentModel.CategoryAttribute Default { get; }
public static System.ComponentModel.CategoryAttribute Design { get; }
public static System.ComponentModel.CategoryAttribute DragDrop { get; }
public static System.ComponentModel.CategoryAttribute Focus { get; }
public static System.ComponentModel.CategoryAttribute Format { get; }
public static System.ComponentModel.CategoryAttribute Key { get; }
public static System.ComponentModel.CategoryAttribute Layout { get; }
public static System.ComponentModel.CategoryAttribute Mouse { get; }
public static System.ComponentModel.CategoryAttribute WindowStyle { get; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
protected virtual string GetLocalizedString(string value) { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
[System.ComponentModel.DesignerCategoryAttribute("Component")]
public partial class Component : System.MarshalByRefObject, System.ComponentModel.IComponent, System.IDisposable
{
public Component() { }
protected virtual bool CanRaiseEvents { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))]
public System.ComponentModel.IContainer Container { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))]
protected bool DesignMode { get { throw null; } }
protected System.ComponentModel.EventHandlerList Events { get { throw null; } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.DesignerSerializationVisibilityAttribute((System.ComponentModel.DesignerSerializationVisibility)(0))]
public virtual System.ComponentModel.ISite Site { get { throw null; } set { } }
[System.ComponentModel.BrowsableAttribute(false)]
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(2))]
public event System.EventHandler Disposed { add { } remove { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
~Component() { }
protected virtual object GetService(System.Type service) { throw null; }
public override string ToString() { throw null; }
}
public partial class ComponentCollection : System.Collections.ReadOnlyCollectionBase
{
internal ComponentCollection() { }
public ComponentCollection(System.ComponentModel.IComponent[] components) { }
public virtual System.ComponentModel.IComponent this[int index] { get { throw null; } }
public virtual System.ComponentModel.IComponent this[string name] { get { throw null; } }
public void CopyTo(System.ComponentModel.IComponent[] array, int index) { }
}
public partial class DescriptionAttribute : System.Attribute
{
public static readonly System.ComponentModel.DescriptionAttribute Default;
public DescriptionAttribute() { }
public DescriptionAttribute(string description) { }
public virtual string Description { get; }
protected string DescriptionValue { get; set; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
public sealed partial class DesignerCategoryAttribute : Attribute
{
public static readonly DesignerCategoryAttribute Component;
public static readonly DesignerCategoryAttribute Default;
public static readonly DesignerCategoryAttribute Form;
public static readonly DesignerCategoryAttribute Generic;
public DesignerCategoryAttribute() { }
public DesignerCategoryAttribute(string category) { }
public string Category { get; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
public override object TypeId { get { throw null; } }
}
public enum DesignerSerializationVisibility
{
Content = 2,
Hidden = 0,
Visible = 1,
}
public sealed partial class DesignerSerializationVisibilityAttribute : System.Attribute
{
public static readonly System.ComponentModel.DesignerSerializationVisibilityAttribute Content;
public static readonly System.ComponentModel.DesignerSerializationVisibilityAttribute Default;
public static readonly System.ComponentModel.DesignerSerializationVisibilityAttribute Hidden;
public static readonly System.ComponentModel.DesignerSerializationVisibilityAttribute Visible;
public DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility visibility) { }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public System.ComponentModel.DesignerSerializationVisibility Visibility { get; }
public override bool IsDefaultAttribute() { throw null; }
}
public sealed partial class DesignOnlyAttribute : System.Attribute
{
public static readonly DesignOnlyAttribute Default;
public static readonly DesignOnlyAttribute No;
public static readonly DesignOnlyAttribute Yes;
public DesignOnlyAttribute(bool isDesignOnly) { }
public bool IsDesignOnly { get; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
public partial class DisplayNameAttribute : System.Attribute
{
public static readonly System.ComponentModel.DisplayNameAttribute Default;
public DisplayNameAttribute() { }
public DisplayNameAttribute(string displayName) { }
public virtual string DisplayName { get; }
protected string DisplayNameValue { get; set; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
public sealed partial class EventHandlerList : System.IDisposable
{
public EventHandlerList() { }
public System.Delegate this[object key] { get { throw null; } set { } }
public void AddHandler(object key, System.Delegate value) { }
public void AddHandlers(System.ComponentModel.EventHandlerList listToAddFrom) { }
public void Dispose() { }
public void RemoveHandler(object key, System.Delegate value) { }
}
public partial interface IComponent : System.IDisposable
{
System.ComponentModel.ISite Site { get; set; }
event System.EventHandler Disposed;
}
public partial interface IContainer : System.IDisposable
{
System.ComponentModel.ComponentCollection Components { get; }
void Add(System.ComponentModel.IComponent component);
void Add(System.ComponentModel.IComponent component, string name);
void Remove(System.ComponentModel.IComponent component);
}
public sealed partial class ImmutableObjectAttribute : System.Attribute
{
public static readonly System.ComponentModel.ImmutableObjectAttribute Default;
public static readonly System.ComponentModel.ImmutableObjectAttribute No;
public static readonly System.ComponentModel.ImmutableObjectAttribute Yes;
public ImmutableObjectAttribute(bool immutable) { }
public bool Immutable { get; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
public sealed partial class InitializationEventAttribute : System.Attribute
{
public InitializationEventAttribute(string eventName) { }
public string EventName { get; }
}
public partial interface ISite : System.IServiceProvider
{
System.ComponentModel.IComponent Component { get; }
System.ComponentModel.IContainer Container { get; }
bool DesignMode { get; }
string Name { get; set; }
}
public partial interface ISupportInitialize
{
void BeginInit();
void EndInit();
}
public sealed partial class LocalizableAttribute : System.Attribute
{
public static readonly System.ComponentModel.LocalizableAttribute Default;
public static readonly System.ComponentModel.LocalizableAttribute No;
public static readonly System.ComponentModel.LocalizableAttribute Yes;
public LocalizableAttribute(bool isLocalizable) { }
public bool IsLocalizable { get; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
public sealed partial class MergablePropertyAttribute : System.Attribute
{
public static readonly System.ComponentModel.MergablePropertyAttribute Default;
public static readonly System.ComponentModel.MergablePropertyAttribute No;
public static readonly System.ComponentModel.MergablePropertyAttribute Yes;
public MergablePropertyAttribute(bool allowMerge) { }
public bool AllowMerge { get; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
public sealed partial class NotifyParentPropertyAttribute : System.Attribute
{
public static readonly System.ComponentModel.NotifyParentPropertyAttribute Default;
public static readonly System.ComponentModel.NotifyParentPropertyAttribute No;
public static readonly System.ComponentModel.NotifyParentPropertyAttribute Yes;
public NotifyParentPropertyAttribute(bool notifyParent) { }
public bool NotifyParent { get; }
public override bool Equals(object obj) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
public sealed partial class ParenthesizePropertyNameAttribute : System.Attribute
{
public static readonly System.ComponentModel.ParenthesizePropertyNameAttribute Default;
public ParenthesizePropertyNameAttribute() { }
public ParenthesizePropertyNameAttribute(bool needParenthesis) { }
public bool NeedParenthesis { get; }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
public sealed partial class ReadOnlyAttribute : System.Attribute
{
public static readonly System.ComponentModel.ReadOnlyAttribute Default;
public static readonly System.ComponentModel.ReadOnlyAttribute No;
public static readonly System.ComponentModel.ReadOnlyAttribute Yes;
public ReadOnlyAttribute(bool isReadOnly) { }
public bool IsReadOnly { get; }
public override bool Equals(object value) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
public enum RefreshProperties
{
All = 1,
None = 0,
Repaint = 2,
}
public sealed partial class RefreshPropertiesAttribute : System.Attribute
{
public static readonly System.ComponentModel.RefreshPropertiesAttribute All;
public static readonly System.ComponentModel.RefreshPropertiesAttribute Default;
public static readonly System.ComponentModel.RefreshPropertiesAttribute Repaint;
public RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties refresh) { }
public System.ComponentModel.RefreshProperties RefreshProperties { get; }
public override bool Equals(object value) { throw null; }
public override int GetHashCode() { throw null; }
public override bool IsDefaultAttribute() { throw null; }
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// EncoderExceptionFallback.cs
namespace System.Text
{
using System;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
[Serializable]
public sealed class EncoderExceptionFallback : EncoderFallback
{
// Construction
public EncoderExceptionFallback()
{
}
public override EncoderFallbackBuffer CreateFallbackBuffer()
{
return new EncoderExceptionFallbackBuffer();
}
// Maximum number of characters that this instance of this fallback could return
public override int MaxCharCount
{
get
{
return 0;
}
}
public override bool Equals(Object value)
{
EncoderExceptionFallback that = value as EncoderExceptionFallback;
if (that != null)
{
return (true);
}
return (false);
}
public override int GetHashCode()
{
return 654;
}
}
public sealed class EncoderExceptionFallbackBuffer : EncoderFallbackBuffer
{
public EncoderExceptionFallbackBuffer(){}
public override bool Fallback(char charUnknown, int index)
{
// Fall back our char
throw new EncoderFallbackException(
Environment.GetResourceString("Argument_InvalidCodePageConversionIndex",
(int)charUnknown, index), charUnknown, index);
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
{
if (!Char.IsHighSurrogate(charUnknownHigh))
{
throw new ArgumentOutOfRangeException("charUnknownHigh",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
}
if (!Char.IsLowSurrogate(charUnknownLow))
{
throw new ArgumentOutOfRangeException("CharUnknownLow",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xDC00, 0xDFFF));
}
Contract.EndContractBlock();
int iTemp = Char.ConvertToUtf32(charUnknownHigh, charUnknownLow);
// Fall back our char
throw new EncoderFallbackException(
Environment.GetResourceString("Argument_InvalidCodePageConversionIndex",
iTemp, index), charUnknownHigh, charUnknownLow, index);
}
public override char GetNextChar()
{
return (char)0;
}
public override bool MovePrevious()
{
// Exception fallback doesn't have anywhere to back up to.
return false;
}
// Exceptions are always empty
public override int Remaining
{
get
{
return 0;
}
}
}
[Serializable]
public sealed class EncoderFallbackException : ArgumentException
{
char charUnknown;
char charUnknownHigh;
char charUnknownLow;
int index;
public EncoderFallbackException()
: base(Environment.GetResourceString("Arg_ArgumentException"))
{
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
public EncoderFallbackException(String message)
: base(message)
{
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
public EncoderFallbackException(String message, Exception innerException)
: base(message, innerException)
{
SetErrorCode(__HResults.COR_E_ARGUMENT);
}
internal EncoderFallbackException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
internal EncoderFallbackException(
String message, char charUnknown, int index) : base(message)
{
this.charUnknown = charUnknown;
this.index = index;
}
internal EncoderFallbackException(
String message, char charUnknownHigh, char charUnknownLow, int index) : base(message)
{
if (!Char.IsHighSurrogate(charUnknownHigh))
{
throw new ArgumentOutOfRangeException("charUnknownHigh",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xD800, 0xDBFF));
}
if (!Char.IsLowSurrogate(charUnknownLow))
{
throw new ArgumentOutOfRangeException("CharUnknownLow",
Environment.GetResourceString("ArgumentOutOfRange_Range",
0xDC00, 0xDFFF));
}
Contract.EndContractBlock();
this.charUnknownHigh = charUnknownHigh;
this.charUnknownLow = charUnknownLow;
this.index = index;
}
public char CharUnknown
{
get
{
return (charUnknown);
}
}
public char CharUnknownHigh
{
get
{
return (charUnknownHigh);
}
}
public char CharUnknownLow
{
get
{
return (charUnknownLow);
}
}
public int Index
{
get
{
return index;
}
}
// Return true if the unknown character is a surrogate pair.
public bool IsUnknownSurrogate()
{
return (this.charUnknownHigh != '\0');
}
}
}
| |
//
// ListView_Header.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
namespace Hyena.Data.Gui
{
public partial class ListView<T> : ListViewBase
{
internal struct CachedColumn
{
public static readonly CachedColumn Zero;
public Column Column;
public int X1;
public int X2;
public int Width;
public int MinWidth;
public int MaxWidth;
public int ResizeX1;
public int ResizeX2;
public int Index;
public double ElasticWidth;
public double ElasticPercent;
}
private static Gdk.Cursor resize_x_cursor = new Gdk.Cursor (Gdk.CursorType.SbHDoubleArrow);
private static Gdk.Cursor drag_cursor = new Gdk.Cursor (Gdk.CursorType.Fleur);
private bool resizable;
private int header_width;
private double list_width, max_width;
private int sort_column_index = -1;
private int resizing_column_index = -1;
private int pressed_column_index = -1;
private int pressed_column_x = -1;
private int pressed_column_x_start = -1;
private int pressed_column_x_offset = -1;
private int pressed_column_x_drag = -1;
private int pressed_column_x_start_hadjustment = -1;
private bool pressed_column_is_dragging = false;
private bool pressed_column_drag_started = false;
private Pango.Layout column_layout;
private CachedColumn [] column_cache;
private List<int> elastic_columns;
public int Width {
get { return (int)list_width; }
}
public int MaxWidth {
get { return (int)max_width + Theme.TotalBorderWidth*2; }
}
#region Columns
private void InvalidateColumnCache ()
{
column_cache = null;
}
private void GenerateColumnCache ()
{
column_cache = new CachedColumn[column_controller.Count];
int i = 0;
double total = 0.0;
foreach (Column column in column_controller) {
if (!column.Visible) {
continue;
}
// If we don't already have a MinWidth set, use the width of our Title text
column.CalculateWidths (column_layout, HeaderVisible, HeaderHeight);
column_cache[i] = new CachedColumn ();
column_cache[i].Column = column;
column_cache[i].Index = i;
total += column.Width;
i++;
}
Array.Resize (ref column_cache, i);
double scale_factor = 1.0 / total;
for (i = 0; i < column_cache.Length; i++) {
column_cache[i].Column.Width *= scale_factor;
if (column_cache[i].Column.Width <= 0) {
Hyena.Log.Warning ("Overriding 0-computed column cache width");
column_cache[i].Column.Width = 0.01;
}
}
RecalculateColumnSizes ();
}
private void RegenerateColumnCache ()
{
if (column_controller == null) {
return;
}
if (column_cache == null) {
GenerateColumnCache ();
}
for (int i = 0; i < column_cache.Length; i++) {
// Calculate this column's proportional share of the width, and set positions (X1/X2)
column_cache[i].Width = (int)Math.Round (((double)header_width * column_cache[i].Column.Width));
column_cache[i].X1 = i == 0 ? 0 : column_cache[i - 1].X2;
column_cache[i].X2 = column_cache[i].X1 + column_cache[i].Width;
column_cache[i].ResizeX1 = column_cache[i].X2;
column_cache[i].ResizeX2 = column_cache[i].ResizeX1 + 2;
}
// TODO handle max width
int index = column_cache.Length - 1;
if (index >= 0) {
column_cache[index].X2 = header_width;
column_cache[index].Width = column_cache[index].X2 - column_cache[index].X1;
}
}
private void RecalculateColumnSizes ()
{
if (column_cache == null) {
return;
}
ISortable sortable = Model as ISortable;
sort_column_index = -1;
int min_header_width = 0;
for (int i = 0; i < column_cache.Length; i++) {
if (sortable != null) {
ColumnHeaderCellText column_cell = column_cache[i].Column.HeaderCell as ColumnHeaderCellText;
if (column_cell != null) {
ISortableColumn sort_column = column_cache[i].Column as ISortableColumn;
column_cell.HasSort = sort_column != null && sortable.SortColumn == sort_column;
if (column_cell.HasSort) {
sort_column_index = i;
}
}
}
column_cache[i].Column.CalculateWidths (column_layout, HeaderVisible, HeaderHeight);
column_cache[i].MaxWidth = column_cache[i].Column.MaxWidth;
column_cache[i].MinWidth = column_cache[i].Column.MinWidth;
min_header_width += column_cache[i].MinWidth;
}
if (column_cache.Length == 1) {
column_cache[0].Column.Width = 1.0;
} else if (min_header_width >= header_interaction_alloc.Width) {
header_width = min_header_width;
resizable = false;
for (int i = 0; i < column_cache.Length; i++) {
column_cache[i].Column.Width = (double)column_cache[i].MinWidth / (double)header_width;
}
} else {
header_width = header_interaction_alloc.Width;
resizable = true;
if (elastic_columns == null) {
elastic_columns = new List<int> (column_cache.Length);
}
elastic_columns.Clear ();
for (int i = 0; i < column_cache.Length; i++) {
elastic_columns.Add (i);
column_cache[i].ElasticWidth = 0.0;
column_cache[i].ElasticPercent = column_cache[i].Column.Width * header_width;
}
double remaining_width = RecalculateColumnSizes (header_width, header_width);
while (Math.Round (remaining_width) != 0.0 && elastic_columns.Count > 0) {
double total_elastic_width = 0.0;
foreach (int i in elastic_columns) {
total_elastic_width += column_cache[i].ElasticWidth;
}
remaining_width = RecalculateColumnSizes (remaining_width, total_elastic_width);
}
for (int i = 0; i < column_cache.Length; i++) {
column_cache[i].Column.Width = column_cache[i].ElasticWidth / (double)header_width;
}
}
double tmp_width = 0.0;
double tmp_max = 0.0;
foreach (var col in column_cache) {
tmp_width += col.ElasticWidth;
tmp_max += col.MaxWidth == Int32.MaxValue ? col.MinWidth : col.MaxWidth;
}
list_width = tmp_width;
max_width = tmp_max;
}
private double RecalculateColumnSizes (double total_width, double total_elastic_width)
{
double remaining_width = total_width;
for (int index = 0; index < elastic_columns.Count; index++) {
int i = elastic_columns[index];
double percent = column_cache[i].ElasticPercent / total_elastic_width;
double delta = total_width * percent;
// TODO handle max widths
double width = column_cache[i].ElasticWidth + delta;
if (width < column_cache[i].MinWidth) {
delta = column_cache[i].MinWidth - column_cache[i].ElasticWidth;
elastic_columns.RemoveAt (index);
index--;
} else if (width > column_cache[i].MaxWidth) {
delta = column_cache[i].MaxWidth - column_cache[i].ElasticWidth;
elastic_columns.RemoveAt (index);
index--;
}
remaining_width -= delta;
column_cache[i].ElasticWidth += delta;
}
if (Math.Abs (total_width - remaining_width) < 1.0 || remaining_width == Double.NaN) {
Hyena.Log.Warning ("Forcefully breaking out of RCS loop b/c change in total_width less than 1.0");
return 0;
}
return Math.Round (remaining_width);
}
protected virtual void OnColumnControllerUpdated ()
{
InvalidateColumnCache ();
RegenerateColumnCache ();
UpdateAdjustments ();
QueueDirtyRegion ();
}
protected virtual void OnColumnLeftClicked (Column clickedColumn)
{
if (Model is ISortable && clickedColumn is ISortableColumn) {
ISortableColumn sort_column = clickedColumn as ISortableColumn;
ISortable sortable = Model as ISortable;
// Change the sort-type with every click
if (sort_column == ColumnController.SortColumn) {
switch (sort_column.SortType) {
case SortType.Ascending: sort_column.SortType = SortType.Descending; break;
case SortType.Descending: sort_column.SortType = SortType.None; break;
case SortType.None: sort_column.SortType = SortType.Ascending; break;
}
}
// If we're switching from a different column, or we aren't reorderable, make sure sort type isn't None
if ((sort_column != ColumnController.SortColumn || !IsEverReorderable) && sort_column.SortType == SortType.None) {
sort_column.SortType = SortType.Ascending;
}
sortable.Sort (sort_column);
ColumnController.SortColumn = sort_column;
IsReorderable = sortable.SortColumn == null || sortable.SortColumn.SortType == SortType.None;
Model.Reload ();
CenterOnSelection ();
RecalculateColumnSizes ();
RegenerateColumnCache ();
InvalidateHeader ();
}
}
protected virtual void OnColumnRightClicked (Column clickedColumn, int x, int y)
{
Column [] columns = ColumnController.ToArray ();
Array.Sort (columns, delegate (Column a, Column b) {
// Fully qualified type name to avoid Mono 1.2.4 bug
return System.String.Compare (a.Title, b.Title);
});
uint items = 0;
for (int i = 0; i < columns.Length; i++) {
if (columns[i].Id != null) {
items++;
}
}
uint max_items_per_column = 15;
if (items >= max_items_per_column * 2) {
max_items_per_column = (uint)Math.Ceiling (items / 3.0);
} else if (items >= max_items_per_column) {
max_items_per_column = (uint)Math.Ceiling (items / 2.0);
}
uint column_count = (uint)Math.Ceiling (items / (double)max_items_per_column);
Menu menu = new Menu ();
uint row_offset = 2;
if (clickedColumn.Id != null) { // FIXME: Also restrict if the column vis can't be changed
menu.Attach (new ColumnHideMenuItem (clickedColumn), 0, column_count, 0, 1);
menu.Attach (new SeparatorMenuItem (), 0, column_count, 1, 2);
}
items = 0;
for (uint i = 0, n = (uint)columns.Length, column = 0, row = 0; i < n; i++) {
if (columns[i].Id == null) {
continue;
}
row = items++ % max_items_per_column;
menu.Attach (new ColumnToggleMenuItem (columns[i]),
column, column + 1, row + row_offset, row + 1 + row_offset);
if (row == max_items_per_column - 1) {
column++;
}
}
menu.ShowAll ();
menu.Popup (null, null, delegate (Menu popup, out int pos_x, out int pos_y, out bool push_in) {
int win_x, win_y;
Window.GetOrigin (out win_x, out win_y);
pos_x = win_x + x;
pos_y = win_y + y;
push_in = true;
}, 3, Gtk.Global.CurrentEventTime);
}
private void ResizeColumn (double x)
{
CachedColumn resizing_column = column_cache[resizing_column_index];
double resize_delta = x - resizing_column.ResizeX2;
// If this column cannot be resized, check the columns to the left.
int real_resizing_column_index = resizing_column_index;
while (resizing_column.MinWidth == resizing_column.MaxWidth) {
if (real_resizing_column_index == 0) {
return;
}
resizing_column = column_cache[--real_resizing_column_index];
}
// Make sure the resize_delta won't make us smaller than the min
if (resizing_column.Width + resize_delta < resizing_column.MinWidth) {
resize_delta = resizing_column.MinWidth - resizing_column.Width;
}
// Make sure the resize_delta won't make us bigger than the max
if (resizing_column.Width + resize_delta > resizing_column.MaxWidth) {
resize_delta = resizing_column.MaxWidth - resizing_column.Width;
}
if (resize_delta == 0) {
return;
}
int sign = Math.Sign (resize_delta);
resize_delta = Math.Abs (resize_delta);
double total_elastic_width = 0.0;
for (int i = real_resizing_column_index + 1; i < column_cache.Length; i++) {
total_elastic_width += column_cache[i].ElasticWidth = sign == 1
? column_cache[i].Width - column_cache[i].MinWidth
: column_cache[i].MaxWidth - column_cache[i].Width;
}
if (total_elastic_width == 0) {
return;
}
if (resize_delta > total_elastic_width) {
resize_delta = total_elastic_width;
}
// Convert to a proprotional width
resize_delta = sign * resize_delta / (double)header_width;
for (int i = real_resizing_column_index + 1; i < column_cache.Length; i++) {
column_cache[i].Column.Width += -resize_delta * (column_cache[i].ElasticWidth / total_elastic_width);
}
resizing_column.Column.Width += resize_delta;
RegenerateColumnCache ();
QueueDraw ();
}
private Column GetColumnForResizeHandle (int x)
{
if (column_cache == null || !resizable) {
return null;
}
x += HadjustmentValue;
for (int i = 0; i < column_cache.Length - 1; i++) {
if (x < column_cache[i].ResizeX1 - 2) {
// No point in checking other columns since their ResizeX1 are even larger
break;
} else if (x <= column_cache[i].ResizeX2 + 2 && CanResizeColumn (i)) {
return column_cache[i].Column;
}
}
return null;
}
protected int GetColumnWidth (int column_index)
{
CachedColumn cached_column = column_cache[column_index];
return cached_column.Width;
}
private bool CanResizeColumn (int column_index)
{
// At least one column to the left (including the one being resized) should be resizable.
bool found = false;
for (int i = column_index; i >= 0 ; i--) {
if (column_cache[i].Column.MaxWidth != column_cache[i].Column.MinWidth) {
found = true;
break;
}
}
if (!found) {
return false;
}
// At least one column to the right should be resizable as well.
for (int i = column_index + 1; i < column_cache.Length; i++) {
if (column_cache[i].Column.MaxWidth != column_cache[i].Column.MinWidth) {
return true;
}
}
return false;
}
private Column GetColumnAt (int x)
{
if (column_cache == null) {
return null;
}
x += HadjustmentValue;
foreach (CachedColumn column in column_cache) {
if (x >= column.X1 && x <= column.X2) {
return column.Column;
}
}
return null;
}
private CachedColumn GetCachedColumnForColumn (Column col)
{
foreach (CachedColumn ca_col in column_cache) {
if (ca_col.Column == col) {
return ca_col;
}
}
return CachedColumn.Zero;
}
private ColumnController column_controller;
public ColumnController ColumnController {
get { return column_controller; }
set {
if (column_controller == value) {
return;
}
if (column_controller != null) {
column_controller.Updated -= OnColumnControllerUpdatedHandler;
}
column_controller = value;
OnColumnControllerUpdated ();
if (column_controller != null) {
column_controller.Updated += OnColumnControllerUpdatedHandler;
}
}
}
#endregion
#region Header
private int header_height = 0;
private int HeaderHeight {
get {
// FIXME: ViewLayout should have the header info and never be null
if (!header_visible || ViewLayout != null) {
return 0;
}
if (header_height == 0) {
int w;
int h;
column_layout.SetText ("W");
column_layout.GetPixelSize (out w, out h);
header_height = h;
header_height += 10;
}
return header_height;
}
}
private bool header_visible = true;
public bool HeaderVisible {
get { return header_visible; }
set {
header_visible = value;
MoveResize (Allocation);
}
}
#endregion
#region Gtk.MenuItem Wrappers for the column context menu
private class ColumnToggleMenuItem : CheckMenuItem
{
private Column column;
private bool ready = false;
private Label label;
public ColumnToggleMenuItem (Column column) : base ()
{
this.column = column;
Active = column.Visible;
ready = true;
label = new Label ();
label.Xalign = 0.0f;
label.Text = column.LongTitle ?? String.Empty;
label.Show ();
Add (label);
}
protected override void OnStyleUpdated ()
{
base.OnStyleUpdated ();
Gdk.RGBA rgba = StyleContext.GetColor (StateFlags.Selected);
label.OverrideColor (StateFlags.Prelight, rgba);
}
protected override void OnActivated ()
{
base.OnActivated ();
if (!ready) {
return;
}
column.Visible = Active;
}
}
private class ColumnHideMenuItem : ImageMenuItem
{
private Column column;
private Label label;
public ColumnHideMenuItem (Column column) : base ()
{
this.column = column;
this.Image = new Image (Stock.Remove, IconSize.Menu);
label = new Label ();
label.Xalign = 0.0f;
label.Markup = String.Format (Catalog.GetString ("Hide <i>{0}</i>"),
GLib.Markup.EscapeText (column.LongTitle));
label.Show ();
Add (label);
}
protected override void OnStyleUpdated ()
{
base.OnStyleUpdated ();
Gdk.RGBA rgba = StyleContext.GetColor (StateFlags.Selected);
label.OverrideColor (StateFlags.Prelight, rgba);
}
protected override void OnActivated ()
{
column.Visible = false;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using MS.Internal.Xml.XPath;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Xml.Schema;
namespace System.Xml.XPath
{
// Provides a navigation interface API using XPath data model.
[DebuggerDisplay("{debuggerDisplayProxy}")]
public abstract class XPathNavigator : XPathItem, IXPathNavigable, IXmlNamespaceResolver
{
internal static readonly XPathNavigatorKeyComparer comparer = new XPathNavigatorKeyComparer();
//-----------------------------------------------
// Object
//-----------------------------------------------
public override string ToString()
{
return Value;
}
//-----------------------------------------------
// XPathItem
//-----------------------------------------------
public override sealed bool IsNode
{
get { return true; }
}
public virtual void SetValue(string value)
{
throw new NotSupportedException();
}
public override object TypedValue
{
get
{
return Value;
}
}
public virtual void SetTypedValue(object typedValue)
{
if (typedValue == null)
{
throw new ArgumentNullException("typedValue");
}
switch (NodeType)
{
case XPathNodeType.Element:
case XPathNodeType.Attribute:
break;
default:
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
SetValue(XmlUntypedConverter.ToString(typedValue, this));
}
public override Type ValueType
{
get
{
return typeof(string);
}
}
public override bool ValueAsBoolean
{
get
{
return XmlUntypedConverter.ToBoolean(Value);
}
}
public override DateTime ValueAsDateTime
{
get
{
return XmlUntypedConverter.ToDateTime(Value);
}
}
public override double ValueAsDouble
{
get
{
return XmlUntypedConverter.ToDouble(Value);
}
}
public override int ValueAsInt
{
get
{
return XmlUntypedConverter.ToInt32(Value);
}
}
public override long ValueAsLong
{
get
{
return XmlUntypedConverter.ToInt64(Value);
}
}
public override object ValueAs(Type returnType, IXmlNamespaceResolver nsResolver)
{
if (nsResolver == null)
{
nsResolver = this;
}
return XmlUntypedConverter.ChangeType(Value, returnType, nsResolver);
}
//-----------------------------------------------
// IXPathNavigable
//-----------------------------------------------
public virtual XPathNavigator CreateNavigator()
{
return Clone();
}
//-----------------------------------------------
// IXmlNamespaceResolver
//-----------------------------------------------
public abstract XmlNameTable NameTable { get; }
public virtual string LookupNamespace(string prefix)
{
if (prefix == null)
return null;
if (NodeType != XPathNodeType.Element)
{
XPathNavigator navSave = Clone();
// If current item is not an element, then try parent
if (navSave.MoveToParent())
return navSave.LookupNamespace(prefix);
}
else if (MoveToNamespace(prefix))
{
string namespaceURI = Value;
MoveToParent();
return namespaceURI;
}
// Check for "", "xml", and "xmlns" prefixes
if (prefix.Length == 0)
return string.Empty;
else if (prefix == "xml")
return XmlConst.ReservedNsXml;
else if (prefix == "xmlns")
return XmlConst.ReservedNsXmlNs;
return null;
}
public virtual string LookupPrefix(string namespaceURI)
{
if (namespaceURI == null)
return null;
XPathNavigator navClone = Clone();
if (NodeType != XPathNodeType.Element)
{
// If current item is not an element, then try parent
if (navClone.MoveToParent())
return navClone.LookupPrefix(namespaceURI);
}
else
{
if (navClone.MoveToFirstNamespace(XPathNamespaceScope.All))
{
// Loop until a matching namespace is found
do
{
if (namespaceURI == navClone.Value)
return navClone.LocalName;
}
while (navClone.MoveToNextNamespace(XPathNamespaceScope.All));
}
}
// Check for default, "xml", and "xmlns" namespaces
if (namespaceURI == LookupNamespace(string.Empty))
return string.Empty;
else if (namespaceURI == XmlConst.ReservedNsXml)
return "xml";
else if (namespaceURI == XmlConst.ReservedNsXmlNs)
return "xmlns";
return null;
}
public virtual IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
XPathNodeType nt = NodeType;
if ((nt != XPathNodeType.Element && scope != XmlNamespaceScope.Local) || nt == XPathNodeType.Attribute || nt == XPathNodeType.Namespace)
{
XPathNavigator navSave = Clone();
// If current item is not an element, then try parent
if (navSave.MoveToParent())
return navSave.GetNamespacesInScope(scope);
}
Dictionary<string, string> dict = new Dictionary<string, string>();
// "xml" prefix always in scope
if (scope == XmlNamespaceScope.All)
dict["xml"] = XmlConst.ReservedNsXml;
// Now add all in-scope namespaces
if (MoveToFirstNamespace((XPathNamespaceScope)scope))
{
do
{
string prefix = LocalName;
string ns = Value;
// Exclude xmlns="" declarations unless scope = Local
if (prefix.Length != 0 || ns.Length != 0 || scope == XmlNamespaceScope.Local)
dict[prefix] = ns;
}
while (MoveToNextNamespace((XPathNamespaceScope)scope));
MoveToParent();
}
return dict;
}
//-----------------------------------------------
// XPathNavigator
//-----------------------------------------------
// Returns an object of type IKeyComparer. Using this the navigators can be hashed
// on the basis of actual position it represents rather than the clr reference of
// the navigator object.
public static IEqualityComparer NavigatorComparer
{
get { return comparer; }
}
public abstract XPathNavigator Clone();
public abstract XPathNodeType NodeType { get; }
public abstract string LocalName { get; }
public abstract string Name { get; }
public abstract string NamespaceURI { get; }
public abstract string Prefix { get; }
public abstract string BaseURI { get; }
public abstract bool IsEmptyElement { get; }
public virtual string XmlLang
{
get
{
XPathNavigator navClone = Clone();
do
{
if (navClone.MoveToAttribute("lang", XmlConst.ReservedNsXml))
return navClone.Value;
}
while (navClone.MoveToParent());
return string.Empty;
}
}
public virtual XmlReader ReadSubtree()
{
switch (NodeType)
{
case XPathNodeType.Root:
case XPathNodeType.Element:
break;
default:
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
return CreateReader();
}
public virtual void WriteSubtree(XmlWriter writer)
{
if (null == writer)
throw new ArgumentNullException("writer");
writer.WriteNode(this, true);
}
public virtual object UnderlyingObject
{
get { return null; }
}
public virtual bool HasAttributes
{
get
{
if (!MoveToFirstAttribute())
return false;
MoveToParent();
return true;
}
}
public virtual string GetAttribute(string localName, string namespaceURI)
{
string value;
if (!MoveToAttribute(localName, namespaceURI))
return "";
value = Value;
MoveToParent();
return value;
}
public virtual bool MoveToAttribute(string localName, string namespaceURI)
{
if (MoveToFirstAttribute())
{
do
{
if (localName == LocalName && namespaceURI == NamespaceURI)
return true;
}
while (MoveToNextAttribute());
MoveToParent();
}
return false;
}
public abstract bool MoveToFirstAttribute();
public abstract bool MoveToNextAttribute();
public virtual string GetNamespace(string name)
{
string value;
if (!MoveToNamespace(name))
{
if (name == "xml")
return XmlConst.ReservedNsXml;
if (name == "xmlns")
return XmlConst.ReservedNsXmlNs;
return string.Empty;
}
value = Value;
MoveToParent();
return value;
}
public virtual bool MoveToNamespace(string name)
{
if (MoveToFirstNamespace(XPathNamespaceScope.All))
{
do
{
if (name == LocalName)
return true;
}
while (MoveToNextNamespace(XPathNamespaceScope.All));
MoveToParent();
}
return false;
}
public abstract bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope);
public abstract bool MoveToNextNamespace(XPathNamespaceScope namespaceScope);
public bool MoveToFirstNamespace() { return MoveToFirstNamespace(XPathNamespaceScope.All); }
public bool MoveToNextNamespace() { return MoveToNextNamespace(XPathNamespaceScope.All); }
public abstract bool MoveToNext();
public abstract bool MoveToPrevious();
public virtual bool MoveToFirst()
{
switch (NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
// MoveToFirst should only succeed for content-typed nodes
return false;
}
if (!MoveToParent())
return false;
return MoveToFirstChild();
}
public abstract bool MoveToFirstChild();
public abstract bool MoveToParent();
public virtual void MoveToRoot()
{
while (MoveToParent())
;
}
public abstract bool MoveTo(XPathNavigator other);
public abstract bool MoveToId(string id);
public virtual bool MoveToChild(string localName, string namespaceURI)
{
if (MoveToFirstChild())
{
do
{
if (NodeType == XPathNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI)
return true;
}
while (MoveToNext());
MoveToParent();
}
return false;
}
public virtual bool MoveToChild(XPathNodeType type)
{
if (MoveToFirstChild())
{
int mask = XPathNavigatorEx.GetContentKindMask(type);
do
{
if (((1 << (int)NodeType) & mask) != 0)
return true;
}
while (MoveToNext());
MoveToParent();
}
return false;
}
public virtual bool MoveToFollowing(string localName, string namespaceURI)
{
return MoveToFollowing(localName, namespaceURI, null);
}
public virtual bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end)
{
XPathNavigator navSave = Clone();
if (end != null)
{
switch (end.NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
// Scan until we come to the next content-typed node
// after the attribute or namespace node
end = end.Clone();
end.MoveToNonDescendant();
break;
}
}
switch (NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
if (!MoveToParent())
{
return false;
}
break;
}
do
{
if (!MoveToFirstChild())
{
// Look for next sibling
while (true)
{
if (MoveToNext())
break;
if (!MoveToParent())
{
// Restore previous position and return false
MoveTo(navSave);
return false;
}
}
}
// Have we reached the end of the scan?
if (end != null && IsSamePosition(end))
{
// Restore previous position and return false
MoveTo(navSave);
return false;
}
}
while (NodeType != XPathNodeType.Element
|| localName != LocalName
|| namespaceURI != NamespaceURI);
return true;
}
public virtual bool MoveToFollowing(XPathNodeType type)
{
return MoveToFollowing(type, null);
}
public virtual bool MoveToFollowing(XPathNodeType type, XPathNavigator end)
{
XPathNavigator navSave = Clone();
int mask = XPathNavigatorEx.GetContentKindMask(type);
if (end != null)
{
switch (end.NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
// Scan until we come to the next content-typed node
// after the attribute or namespace node
end = end.Clone();
end.MoveToNonDescendant();
break;
}
}
switch (NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
if (!MoveToParent())
{
return false;
}
break;
}
do
{
if (!MoveToFirstChild())
{
// Look for next sibling
while (true)
{
if (MoveToNext())
break;
if (!MoveToParent())
{
// Restore previous position and return false
MoveTo(navSave);
return false;
}
}
}
// Have we reached the end of the scan?
if (end != null && IsSamePosition(end))
{
// Restore previous position and return false
MoveTo(navSave);
return false;
}
}
while (((1 << (int)NodeType) & mask) == 0);
return true;
}
public virtual bool MoveToNext(string localName, string namespaceURI)
{
XPathNavigator navClone = Clone();
while (MoveToNext())
{
if (NodeType == XPathNodeType.Element && localName == LocalName && namespaceURI == NamespaceURI)
return true;
}
MoveTo(navClone);
return false;
}
public virtual bool MoveToNext(XPathNodeType type)
{
XPathNavigator navClone = Clone();
int mask = XPathNavigatorEx.GetContentKindMask(type);
while (MoveToNext())
{
if (((1 << (int)NodeType) & mask) != 0)
return true;
}
MoveTo(navClone);
return false;
}
public virtual bool HasChildren
{
get
{
if (MoveToFirstChild())
{
MoveToParent();
return true;
}
return false;
}
}
public abstract bool IsSamePosition(XPathNavigator other);
public virtual bool IsDescendant(XPathNavigator nav)
{
if (nav != null)
{
nav = nav.Clone();
while (nav.MoveToParent())
if (nav.IsSamePosition(this))
return true;
}
return false;
}
public virtual XmlNodeOrder ComparePosition(XPathNavigator nav)
{
if (nav == null)
{
return XmlNodeOrder.Unknown;
}
if (IsSamePosition(nav))
return XmlNodeOrder.Same;
XPathNavigator n1 = this.Clone();
XPathNavigator n2 = nav.Clone();
int depth1 = GetDepth(n1.Clone());
int depth2 = GetDepth(n2.Clone());
if (depth1 > depth2)
{
while (depth1 > depth2)
{
n1.MoveToParent();
depth1--;
}
if (n1.IsSamePosition(n2))
return XmlNodeOrder.After;
}
if (depth2 > depth1)
{
while (depth2 > depth1)
{
n2.MoveToParent();
depth2--;
}
if (n1.IsSamePosition(n2))
return XmlNodeOrder.Before;
}
XPathNavigator parent1 = n1.Clone();
XPathNavigator parent2 = n2.Clone();
while (true)
{
if (!parent1.MoveToParent() || !parent2.MoveToParent())
return XmlNodeOrder.Unknown;
if (parent1.IsSamePosition(parent2))
{
if (n1.GetType().ToString() != "Microsoft.VisualStudio.Modeling.StoreNavigator")
{
Debug.Assert(CompareSiblings(n1.Clone(), n2.Clone()) != CompareSiblings(n2.Clone(), n1.Clone()), "IsSamePosition() on custom navigator returns inconsistent results");
}
return CompareSiblings(n1, n2);
}
n1.MoveToParent();
n2.MoveToParent();
}
}
public virtual XPathExpression Compile(string xpath)
{
return XPathExpression.Compile(xpath);
}
public virtual XPathNavigator SelectSingleNode(string xpath)
{
return SelectSingleNode(XPathExpression.Compile(xpath));
}
public virtual XPathNavigator SelectSingleNode(string xpath, IXmlNamespaceResolver resolver)
{
return SelectSingleNode(XPathExpression.Compile(xpath, resolver));
}
public virtual XPathNavigator SelectSingleNode(XPathExpression expression)
{
XPathNodeIterator iter = this.Select(expression);
if (iter.MoveNext())
{
return iter.Current;
}
return null;
}
public virtual XPathNodeIterator Select(string xpath)
{
Contract.Ensures(Contract.Result<XPathNodeIterator>() != null);
return this.Select(XPathExpression.Compile(xpath));
}
public virtual XPathNodeIterator Select(string xpath, IXmlNamespaceResolver resolver)
{
Contract.Ensures(Contract.Result<XPathNodeIterator>() != null);
return this.Select(XPathExpression.Compile(xpath, resolver));
}
public virtual XPathNodeIterator Select(XPathExpression expr)
{
Contract.Ensures(Contract.Result<XPathNodeIterator>() != null);
XPathNodeIterator result = Evaluate(expr) as XPathNodeIterator;
if (result == null)
{
throw XPathException.Create(SR.Xp_NodeSetExpected);
}
return result;
}
public virtual object Evaluate(string xpath)
{
return Evaluate(XPathExpression.Compile(xpath), null);
}
public virtual object Evaluate(string xpath, IXmlNamespaceResolver resolver)
{
return this.Evaluate(XPathExpression.Compile(xpath, resolver));
}
public virtual object Evaluate(XPathExpression expr)
{
return Evaluate(expr, null);
}
public virtual object Evaluate(XPathExpression expr, XPathNodeIterator context)
{
CompiledXpathExpr cexpr = expr as CompiledXpathExpr;
if (cexpr == null)
{
throw XPathException.Create(SR.Xp_BadQueryObject);
}
Query query = Query.Clone(cexpr.QueryTree);
query.Reset();
if (context == null)
{
context = new XPathSingletonIterator(this.Clone(), /*moved:*/true);
}
object result = query.Evaluate(context);
if (result is XPathNodeIterator)
{
return new XPathSelectionIterator(context.Current, query);
}
return result;
}
public virtual bool Matches(XPathExpression expr)
{
CompiledXpathExpr cexpr = expr as CompiledXpathExpr;
if (cexpr == null)
throw XPathException.Create(SR.Xp_BadQueryObject);
// We should clone query because some Query.MatchNode() alter expression state and this may brake
// SelectionIterators that are running using this Query
// Example of MatchNode() that alret the state is FilterQuery.MatchNode()
Query query = Query.Clone(cexpr.QueryTree);
try
{
return query.MatchNode(this) != null;
}
catch (XPathException)
{
throw XPathException.Create(SR.Xp_InvalidPattern, cexpr.Expression);
}
}
public virtual bool Matches(string xpath)
{
return Matches(CompileMatchPattern(xpath));
}
public virtual XPathNodeIterator SelectChildren(XPathNodeType type)
{
return new XPathChildIterator(this.Clone(), type);
}
public virtual XPathNodeIterator SelectChildren(string name, string namespaceURI)
{
return new XPathChildIterator(this.Clone(), name, namespaceURI);
}
public virtual XPathNodeIterator SelectAncestors(XPathNodeType type, bool matchSelf)
{
return new XPathAncestorIterator(this.Clone(), type, matchSelf);
}
public virtual XPathNodeIterator SelectAncestors(string name, string namespaceURI, bool matchSelf)
{
return new XPathAncestorIterator(this.Clone(), name, namespaceURI, matchSelf);
}
public virtual XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf)
{
return new XPathDescendantIterator(this.Clone(), type, matchSelf);
}
public virtual XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf)
{
return new XPathDescendantIterator(this.Clone(), name, namespaceURI, matchSelf);
}
public virtual bool CanEdit
{
get
{
return false;
}
}
public virtual XmlWriter PrependChild()
{
throw new NotSupportedException();
}
public virtual XmlWriter AppendChild()
{
throw new NotSupportedException();
}
public virtual XmlWriter InsertAfter()
{
throw new NotSupportedException();
}
public virtual XmlWriter InsertBefore()
{
throw new NotSupportedException();
}
public virtual XmlWriter CreateAttributes()
{
throw new NotSupportedException();
}
public virtual XmlWriter ReplaceRange(XPathNavigator lastSiblingToReplace)
{
throw new NotSupportedException();
}
public virtual void ReplaceSelf(string newNode)
{
XmlReader reader = CreateContextReader(newNode, false);
ReplaceSelf(reader);
}
public virtual void ReplaceSelf(XmlReader newNode)
{
if (newNode == null)
{
throw new ArgumentNullException("newNode");
}
XPathNodeType type = NodeType;
if (type == XPathNodeType.Root
|| type == XPathNodeType.Attribute
|| type == XPathNodeType.Namespace)
{
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
XmlWriter writer = ReplaceRange(this);
BuildSubtree(newNode, writer);
writer.Dispose();
}
public virtual void ReplaceSelf(XPathNavigator newNode)
{
if (newNode == null)
{
throw new ArgumentNullException("newNode");
}
XmlReader reader = newNode.CreateReader();
ReplaceSelf(reader);
}
// Returns the markup representing the current node and all of its children.
public virtual string OuterXml
{
get
{
StringWriter stringWriter;
XmlWriterSettings writerSettings;
// Attributes and namespaces are not allowed at the top-level by the well-formed writer
if (NodeType == XPathNodeType.Attribute)
{
return string.Concat(Name, "=\"", Value, "\"");
}
else if (NodeType == XPathNodeType.Namespace)
{
if (LocalName.Length == 0)
return string.Concat("xmlns=\"", Value, "\"");
else
return string.Concat("xmlns:", LocalName, "=\"", Value, "\"");
}
stringWriter = new StringWriter(CultureInfo.InvariantCulture);
writerSettings = new XmlWriterSettings();
writerSettings.Indent = true;
writerSettings.OmitXmlDeclaration = true;
writerSettings.ConformanceLevel = ConformanceLevel.Auto;
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
{
xmlWriter.WriteNode(this, true);
}
return stringWriter.ToString();
}
set
{
ReplaceSelf(value);
}
}
// Returns the markup representing just the children of the current node.
public virtual string InnerXml
{
get
{
switch (NodeType)
{
case XPathNodeType.Root:
case XPathNodeType.Element:
StringWriter stringWriter;
XmlWriterSettings writerSettings;
XmlWriter xmlWriter;
stringWriter = new StringWriter(CultureInfo.InvariantCulture);
writerSettings = new XmlWriterSettings();
writerSettings.Indent = true;
writerSettings.OmitXmlDeclaration = true;
writerSettings.ConformanceLevel = ConformanceLevel.Auto;
xmlWriter = XmlWriter.Create(stringWriter, writerSettings);
try
{
if (MoveToFirstChild())
{
do
{
xmlWriter.WriteNode(this, true);
}
while (MoveToNext());
// Restore position
MoveToParent();
}
}
finally
{
xmlWriter.Dispose();
}
return stringWriter.ToString();
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
return Value;
default:
return string.Empty;
}
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
switch (NodeType)
{
case XPathNodeType.Root:
case XPathNodeType.Element:
XPathNavigator edit = CreateNavigator();
while (edit.MoveToFirstChild())
{
edit.DeleteSelf();
}
if (value.Length != 0)
{
edit.AppendChild(value);
}
break;
case XPathNodeType.Attribute:
SetValue(value);
break;
default:
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
}
}
public virtual void AppendChild(string newChild)
{
XmlReader reader = CreateContextReader(newChild, true);
AppendChild(reader);
}
public virtual void AppendChild(XmlReader newChild)
{
if (newChild == null)
{
throw new ArgumentNullException("newChild");
}
XmlWriter writer = AppendChild();
BuildSubtree(newChild, writer);
writer.Dispose();
}
public virtual void AppendChild(XPathNavigator newChild)
{
if (newChild == null)
{
throw new ArgumentNullException("newChild");
}
if (!IsValidChildType(newChild.NodeType))
{
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
XmlReader reader = newChild.CreateReader();
AppendChild(reader);
}
public virtual void PrependChild(string newChild)
{
XmlReader reader = CreateContextReader(newChild, true);
PrependChild(reader);
}
public virtual void PrependChild(XmlReader newChild)
{
if (newChild == null)
{
throw new ArgumentNullException("newChild");
}
XmlWriter writer = PrependChild();
BuildSubtree(newChild, writer);
writer.Dispose();
}
public virtual void PrependChild(XPathNavigator newChild)
{
if (newChild == null)
{
throw new ArgumentNullException("newChild");
}
if (!IsValidChildType(newChild.NodeType))
{
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
XmlReader reader = newChild.CreateReader();
PrependChild(reader);
}
public virtual void InsertBefore(string newSibling)
{
XmlReader reader = CreateContextReader(newSibling, false);
InsertBefore(reader);
}
public virtual void InsertBefore(XmlReader newSibling)
{
if (newSibling == null)
{
throw new ArgumentNullException("newSibling");
}
XmlWriter writer = InsertBefore();
BuildSubtree(newSibling, writer);
writer.Dispose();
}
public virtual void InsertBefore(XPathNavigator newSibling)
{
if (newSibling == null)
{
throw new ArgumentNullException("newSibling");
}
if (!IsValidSiblingType(newSibling.NodeType))
{
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
XmlReader reader = newSibling.CreateReader();
InsertBefore(reader);
}
public virtual void InsertAfter(string newSibling)
{
XmlReader reader = CreateContextReader(newSibling, false);
InsertAfter(reader);
}
public virtual void InsertAfter(XmlReader newSibling)
{
if (newSibling == null)
{
throw new ArgumentNullException("newSibling");
}
XmlWriter writer = InsertAfter();
BuildSubtree(newSibling, writer);
writer.Dispose();
}
public virtual void InsertAfter(XPathNavigator newSibling)
{
if (newSibling == null)
{
throw new ArgumentNullException("newSibling");
}
if (!IsValidSiblingType(newSibling.NodeType))
{
throw new InvalidOperationException(SR.Xpn_BadPosition);
}
XmlReader reader = newSibling.CreateReader();
InsertAfter(reader);
}
public virtual void DeleteRange(XPathNavigator lastSiblingToDelete)
{
throw new NotSupportedException();
}
public virtual void DeleteSelf()
{
DeleteRange(this);
}
// base for following methods
private static void WriteElement(XmlWriter writer, string prefix, string localName, string namespaceURI, string value)
{
writer.WriteStartElement(prefix, localName, namespaceURI);
if (value != null)
{
writer.WriteString(value);
}
writer.WriteEndElement();
writer.Dispose();
}
public virtual void PrependChildElement(string prefix, string localName, string namespaceURI, string value)
{
WriteElement(PrependChild(), prefix, localName, namespaceURI, value);
}
public virtual void AppendChildElement(string prefix, string localName, string namespaceURI, string value)
{
WriteElement(AppendChild(), prefix, localName, namespaceURI, value);
}
public virtual void InsertElementBefore(string prefix, string localName, string namespaceURI, string value)
{
WriteElement(InsertBefore(), prefix, localName, namespaceURI, value);
}
public virtual void InsertElementAfter(string prefix, string localName, string namespaceURI, string value)
{
WriteElement(InsertAfter(), prefix, localName, namespaceURI, value);
}
public virtual void CreateAttribute(string prefix, string localName, string namespaceURI, string value)
{
XmlWriter writer = CreateAttributes();
writer.WriteStartAttribute(prefix, localName, namespaceURI);
if (value != null)
{
writer.WriteString(value);
}
writer.WriteEndAttribute();
writer.Dispose();
}
//-----------------------------------------------
// Internal
//-----------------------------------------------
internal bool MoveToNonDescendant()
{
// If current node is document, there is no next non-descendant
if (NodeType == XPathNodeType.Root)
return false;
// If sibling exists, it is the next non-descendant
if (MoveToNext())
return true;
// The current node is either an attribute, namespace, or last child node
XPathNavigator navSave = Clone();
if (!MoveToParent())
return false;
switch (navSave.NodeType)
{
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
// Next node in document order is first content-child of parent
if (MoveToFirstChild())
return true;
break;
}
while (!MoveToNext())
{
if (!MoveToParent())
{
// Restore original position and return false
MoveTo(navSave);
return false;
}
}
return true;
}
/// <summary>
/// Returns ordinal number of attribute, namespace or child node within its parent.
/// Order is reversed for attributes and child nodes to avoid O(N**2) running time.
/// This property is useful for debugging, and also used in UniqueId implementation.
/// </summary>
internal uint IndexInParent
{
get
{
XPathNavigator nav = this.Clone();
uint idx = 0;
switch (NodeType)
{
case XPathNodeType.Attribute:
while (nav.MoveToNextAttribute())
{
idx++;
}
break;
case XPathNodeType.Namespace:
while (nav.MoveToNextNamespace())
{
idx++;
}
break;
default:
while (nav.MoveToNext())
{
idx++;
}
break;
}
return idx;
}
}
internal static readonly char[] NodeTypeLetter = new char[] {
'R', // Root
'E', // Element
'A', // Attribute
'N', // Namespace
'T', // Text
'S', // SignificantWhitespace
'W', // Whitespace
'P', // ProcessingInstruction
'C', // Comment
'X', // All
};
internal static readonly char[] UniqueIdTbl = new char[] {
'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', '1', '2', '3', '4',
'5', '6'
};
// Requirements for id:
// 1. must consist of alphanumeric characters only
// 2. must begin with an alphabetic character
// 3. same id is generated for the same node
// 4. ids are unique
//
// id = node type letter + reverse path to root in terms of encoded IndexInParent integers from node to root separated by 0's if needed
internal virtual string UniqueId
{
get
{
XPathNavigator nav = this.Clone();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
// Ensure distinguishing attributes, namespaces and child nodes
sb.Append(NodeTypeLetter[(int)NodeType]);
while (true)
{
uint idx = nav.IndexInParent;
if (!nav.MoveToParent())
{
break;
}
if (idx <= 0x1f)
{
sb.Append(UniqueIdTbl[idx]);
}
else
{
sb.Append('0');
do
{
sb.Append(UniqueIdTbl[idx & 0x1f]);
idx >>= 5;
} while (idx != 0);
sb.Append('0');
}
}
return sb.ToString();
}
}
private static XPathExpression CompileMatchPattern(string xpath)
{
bool hasPrefix;
Query query = new QueryBuilder().BuildPatternQuery(xpath, out hasPrefix);
return new CompiledXpathExpr(query, xpath, hasPrefix);
}
private static int GetDepth(XPathNavigator nav)
{
int depth = 0;
while (nav.MoveToParent())
{
depth++;
}
return depth;
}
// XPath based comparison for namespaces, attributes and other
// items with the same parent element.
//
// n2
// namespace(0) attribute(-1) other(-2)
// n1
// namespace(0) ?(0) before(-1) before(-2)
// attribute(1) after(1) ?(0) before(-1)
// other (2) after(2) after(1) ?(0)
private static XmlNodeOrder CompareSiblings(XPathNavigator n1, XPathNavigator n2)
{
int cmp = 0;
#if DEBUG
Debug.Assert(!n1.IsSamePosition(n2));
XPathNavigator p1 = n1.Clone(), p2 = n2.Clone();
Debug.Assert(p1.MoveToParent() && p2.MoveToParent() && p1.IsSamePosition(p2));
#endif
switch (n1.NodeType)
{
case XPathNodeType.Namespace:
break;
case XPathNodeType.Attribute:
cmp += 1;
break;
default:
cmp += 2;
break;
}
switch (n2.NodeType)
{
case XPathNodeType.Namespace:
if (cmp == 0)
{
while (n1.MoveToNextNamespace())
{
if (n1.IsSamePosition(n2))
{
return XmlNodeOrder.Before;
}
}
}
break;
case XPathNodeType.Attribute:
cmp -= 1;
if (cmp == 0)
{
while (n1.MoveToNextAttribute())
{
if (n1.IsSamePosition(n2))
{
return XmlNodeOrder.Before;
}
}
}
break;
default:
cmp -= 2;
if (cmp == 0)
{
while (n1.MoveToNext())
{
if (n1.IsSamePosition(n2))
{
return XmlNodeOrder.Before;
}
}
}
break;
}
return cmp < 0 ? XmlNodeOrder.Before : XmlNodeOrder.After;
}
internal static bool IsText(XPathNodeType type)
{
return (uint)(type - XPathNodeType.Text) <= (XPathNodeType.Whitespace - XPathNodeType.Text);
}
// Lax check for potential child item.
private bool IsValidChildType(XPathNodeType type)
{
switch (NodeType)
{
case XPathNodeType.Root:
switch (type)
{
case XPathNodeType.Element:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
return true;
}
break;
case XPathNodeType.Element:
switch (type)
{
case XPathNodeType.Element:
case XPathNodeType.Text:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
return true;
}
break;
}
return false;
}
// Lax check for potential sibling item.
private bool IsValidSiblingType(XPathNodeType type)
{
switch (NodeType)
{
case XPathNodeType.Element:
case XPathNodeType.Text:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
switch (type)
{
case XPathNodeType.Element:
case XPathNodeType.Text:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Whitespace:
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
return true;
}
break;
}
return false;
}
private XmlReader CreateReader()
{
return XPathNavigatorReader.Create(this);
}
private XmlReader CreateContextReader(string xml, bool fromCurrentNode)
{
if (xml == null)
{
throw new ArgumentNullException("xml");
}
// We have to set the namespace context for the reader.
XPathNavigator editor = CreateNavigator();
// scope starts from parent.
XmlNamespaceManager mgr = new XmlNamespaceManager(NameTable);
if (!fromCurrentNode)
{
editor.MoveToParent(); // should always succeed.
}
if (editor.MoveToFirstNamespace(XPathNamespaceScope.All))
{
do
{
mgr.AddNamespace(editor.LocalName, editor.Value);
}
while (editor.MoveToNextNamespace(XPathNamespaceScope.All));
}
XmlParserContext context = new XmlParserContext(NameTable, mgr, null, XmlSpace.Default);
return XmlReader.Create(new StringReader(xml), new XmlReaderSettings(), context);
}
internal static void BuildSubtree(XmlReader reader, XmlWriter writer)
{
// important (perf) string literal...
string xmlnsUri = XmlConst.ReservedNsXmlNs; // http://www.w3.org/2000/xmlns/
ReadState readState = reader.ReadState;
if (readState != ReadState.Initial
&& readState != ReadState.Interactive)
{
throw new ArgumentException(SR.Xml_InvalidOperation, "reader");
}
int level = 0;
if (readState == ReadState.Initial)
{
if (!reader.Read())
return;
level++; // if start in initial, read everything (not just first)
}
do
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
bool isEmptyElement = reader.IsEmptyElement;
while (reader.MoveToNextAttribute())
{
if ((object)reader.NamespaceURI == (object)xmlnsUri)
{
if (reader.Prefix.Length == 0)
{
// Default namespace declaration "xmlns"
Debug.Assert(reader.LocalName == "xmlns");
writer.WriteAttributeString("", "xmlns", xmlnsUri, reader.Value);
}
else
{
Debug.Assert(reader.Prefix == "xmlns");
writer.WriteAttributeString("xmlns", reader.LocalName, xmlnsUri, reader.Value);
}
}
else
{
writer.WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteString(reader.Value);
writer.WriteEndAttribute();
}
}
reader.MoveToElement();
if (isEmptyElement)
{
// there might still be a value, if there is a default value specified in the schema
writer.WriteEndElement();
}
else
{
level++;
}
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
//should not read beyond the level of the reader's original position.
level--;
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
writer.WriteString(reader.Value);
break;
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
writer.WriteString(reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.LocalName, reader.Value);
break;
case XmlNodeType.EntityReference:
reader.ResolveEntity();
break;
case XmlNodeType.EndEntity:
case XmlNodeType.None:
case XmlNodeType.DocumentType:
case XmlNodeType.XmlDeclaration:
break;
case XmlNodeType.Attribute:
if ((object)reader.NamespaceURI == (object)xmlnsUri)
{
if (reader.Prefix.Length == 0)
{
// Default namespace declaration "xmlns"
Debug.Assert(reader.LocalName == "xmlns");
writer.WriteAttributeString("", "xmlns", xmlnsUri, reader.Value);
}
else
{
Debug.Assert(reader.Prefix == "xmlns");
writer.WriteAttributeString("xmlns", reader.LocalName, xmlnsUri, reader.Value);
}
}
else
{
writer.WriteStartAttribute(reader.Prefix, reader.LocalName, reader.NamespaceURI);
writer.WriteString(reader.Value);
writer.WriteEndAttribute();
}
break;
}
}
while (reader.Read() && (level > 0));
}
private object debuggerDisplayProxy { get { return new DebuggerDisplayProxy(this); } }
[DebuggerDisplay("{ToString()}")]
internal struct DebuggerDisplayProxy
{
private XPathNavigator _nav;
public DebuggerDisplayProxy(XPathNavigator nav)
{
_nav = nav;
}
public override string ToString()
{
string result = _nav.NodeType.ToString();
switch (_nav.NodeType)
{
case XPathNodeType.Element:
result += ", Name=\"" + _nav.Name + '"';
break;
case XPathNodeType.Attribute:
case XPathNodeType.Namespace:
case XPathNodeType.ProcessingInstruction:
result += ", Name=\"" + _nav.Name + '"';
result += ", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(_nav.Value) + '"';
break;
case XPathNodeType.Text:
case XPathNodeType.Whitespace:
case XPathNodeType.SignificantWhitespace:
case XPathNodeType.Comment:
result += ", Value=\"" + XmlConvertEx.EscapeValueForDebuggerDisplay(_nav.Value) + '"';
break;
}
return result;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using LiveToLift.Web.Areas.HelpPage.ModelDescriptions;
using LiveToLift.Web.Areas.HelpPage.Models;
namespace LiveToLift.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//#define Debug
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace Aurora.Framework
{
public sealed class PacketPool
{
private static readonly PacketPool instance = new PacketPool();
private static readonly Dictionary<Type, Stack<Object>> DataBlocks =
new Dictionary<Type, Stack<Object>>();
private readonly object m_poolLock = new object();
private readonly Dictionary<int, Stack<Packet>> pool = new Dictionary<int, Stack<Packet>>();
private bool dataBlockPoolEnabled = true;
private bool packetPoolEnabled = true;
public static PacketPool Instance
{
get { return instance; }
}
public bool RecyclePackets
{
set { packetPoolEnabled = value; }
get { return packetPoolEnabled; }
}
public bool RecycleDataBlocks
{
set { dataBlockPoolEnabled = value; }
get { return dataBlockPoolEnabled; }
}
/// <summary>
/// For outgoing packets that just have the packet type
/// </summary>
/// <param name = "type"></param>
/// <returns></returns>
public Packet GetPacket(PacketType type)
{
int t = (int) type;
Packet packet;
if (!packetPoolEnabled)
return Packet.BuildPacket(type);
lock (m_poolLock)
{
if (!pool.ContainsKey(t) || (pool[t]).Count == 0)
{
// Creating a new packet if we cannot reuse an old package
packet = Packet.BuildPacket(type);
}
else
{
// Recycle old packages
#if Debug
MainConsole.Instance.Info("[PacketPool]: Using " + type);
#endif
packet = (pool[t]).Pop();
}
}
return packet;
}
private static PacketType GetType(byte[] bytes)
{
byte[] decoded_header = new byte[10 + 8];
ushort id;
PacketFrequency freq;
if ((bytes[0] & Helpers.MSG_ZEROCODED) != 0)
{
Helpers.ZeroDecode(bytes, 16, decoded_header);
}
else
{
Buffer.BlockCopy(bytes, 0, decoded_header, 0, 10);
}
if (decoded_header[6] == 0xFF)
{
if (decoded_header[7] == 0xFF)
{
id = (ushort) ((decoded_header[8] << 8) + decoded_header[9]);
freq = PacketFrequency.Low;
}
else
{
id = decoded_header[7];
freq = PacketFrequency.Medium;
}
}
else
{
id = decoded_header[6];
freq = PacketFrequency.High;
}
return Packet.GetType(id, freq);
}
/// <summary>
/// For incoming packets that are just types
/// </summary>
/// <param name = "bytes"></param>
/// <param name = "packetEnd"></param>
/// <param name = "zeroBuffer"></param>
/// <returns></returns>
public Packet GetPacket(byte[] bytes, ref int packetEnd, byte[] zeroBuffer)
{
PacketType type = GetType(bytes);
if (zeroBuffer != null)
Array.Clear(zeroBuffer, 0, zeroBuffer.Length);
int i = 0;
Packet packet = GetPacket(type);
if (packet == null)
MainConsole.Instance.WarnFormat("[PACKETPOOL]: Failed to get packet of type {0}", type);
else
packet.FromBytes(bytes, ref i, ref packetEnd, zeroBuffer);
return packet;
}
/// <summary>
/// Return a packet to the packet pool
/// </summary>
/// <param name = "packet"></param>
public bool ReturnPacket(Packet packet)
{
/*if (dataBlockPoolEnabled)
{
switch (packet.Type)
{
case PacketType.ObjectUpdate:
ObjectUpdatePacket oup = (ObjectUpdatePacket)packet;
foreach (ObjectUpdatePacket.ObjectDataBlock oupod in oup.ObjectData)
ReturnDataBlock<ObjectUpdatePacket.ObjectDataBlock>(oupod);
oup.ObjectData = null;
break;
case PacketType.ImprovedTerseObjectUpdate:
ImprovedTerseObjectUpdatePacket itoup =
(ImprovedTerseObjectUpdatePacket)packet;
foreach(ImprovedTerseObjectUpdatePacket.ObjectDataBlock itoupod in itoup.ObjectData)
ReturnDataBlock<ImprovedTerseObjectUpdatePacket.ObjectDataBlock>(itoupod);
itoup.ObjectData = null;
break;
}
}*/
if (packetPoolEnabled)
{
switch (packet.Type)
{
// List pooling packets here
case PacketType.ObjectUpdate:
lock (m_poolLock)
{
//Special case, this packet gets sent as a ObjectUpdate for both compressed and non compressed
int t = (int) packet.Type;
if (packet is ObjectUpdateCompressedPacket)
t = (int) PacketType.ObjectUpdateCompressed;
#if Debug
MainConsole.Instance.Info("[PacketPool]: Returning " + type);
#endif
if (!pool.ContainsKey(t))
pool[t] = new Stack<Packet>();
if ((pool[t]).Count < 50)
(pool[t]).Push(packet);
}
return true;
//Outgoing packets:
case PacketType.ObjectUpdateCompressed:
case PacketType.ObjectUpdateCached:
case PacketType.ImprovedTerseObjectUpdate:
case PacketType.ObjectDelete:
case PacketType.LayerData:
case PacketType.FetchInventoryReply:
case PacketType.PacketAck:
case PacketType.StartPingCheck:
case PacketType.CompletePingCheck:
case PacketType.InventoryDescendents:
//Incoming packets:
case PacketType.AgentUpdate:
case PacketType.AgentAnimation:
case PacketType.AvatarAnimation:
case PacketType.CoarseLocationUpdate:
case PacketType.ImageData:
case PacketType.ImagePacket:
case PacketType.MapBlockReply:
case PacketType.MapBlockRequest:
case PacketType.MapItemReply:
case PacketType.MapItemRequest:
case PacketType.SendXferPacket:
case PacketType.TransferPacket:
lock (m_poolLock)
{
int t = (int) packet.Type;
#if Debug
MainConsole.Instance.Info("[PacketPool]: Returning " + type);
#endif
if (!pool.ContainsKey(t))
pool[t] = new Stack<Packet>();
if ((pool[t]).Count < 50)
(pool[t]).Push(packet);
}
return true;
// Other packets wont pool
default:
break;
}
}
return false;
}
public static T GetDataBlock<T>() where T : new()
{
lock (DataBlocks)
{
Stack<Object> s;
if (DataBlocks.TryGetValue(typeof (T), out s))
{
if (s.Count > 0)
return (T) s.Pop();
}
else
{
DataBlocks[typeof (T)] = new Stack<Object>();
}
return new T();
}
}
public static void ReturnDataBlock<T>(T block) where T : new()
{
if (block == null)
return;
lock (DataBlocks)
{
if (!DataBlocks.ContainsKey(typeof (T)))
DataBlocks[typeof (T)] = new Stack<Object>();
if (DataBlocks[typeof (T)].Count < 50)
DataBlocks[typeof (T)].Push(block);
}
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime;
namespace Orleans
{
/// <summary>
/// Utility functions for dealing with Task's.
/// </summary>
public static class PublicOrleansTaskExtentions
{
private static readonly Task<object> CanceledTask;
private static readonly Task<object> CompletedTask = Task.FromResult(default(object));
static PublicOrleansTaskExtentions()
{
var completion = new TaskCompletionSource<object>();
completion.SetCanceled();
CanceledTask = completion.Task;
}
/// <summary>
/// Observes and ignores a potential exception on a given Task.
/// If a Task fails and throws an exception which is never observed, it will be caught by the .NET finalizer thread.
/// This function awaits the given task and if the exception is thrown, it observes this exception and simply ignores it.
/// This will prevent the escalation of this exception to the .NET finalizer thread.
/// </summary>
/// <param name="task">The task to be ignored.</param>
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "ignored")]
public static void Ignore(this Task task)
{
if (task.IsCompleted)
{
var ignored = task.Exception;
}
else
{
task.ContinueWith(
t => { var ignored = t.Exception; },
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
}
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task"/>.
/// </summary>
/// <param name="task">
/// The task.
/// </param>
/// <returns>
/// The response.
/// </returns>
public static Task<object> Box(this Task task)
{
switch (task.Status)
{
case TaskStatus.RanToCompletion:
return CompletedTask;
case TaskStatus.Faulted:
{
return TaskFromFaulted(task);
}
case TaskStatus.Canceled:
{
return CanceledTask;
}
default:
return BoxAwait(task);
}
}
/// <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>
/// <returns>
/// The response.
/// </returns>
public static Task<object> Box<T>(this Task<T> task)
{
switch (task.Status)
{
case TaskStatus.RanToCompletion:
return Task.FromResult((object)task.GetResult());
case TaskStatus.Faulted:
{
return TaskFromFaulted(task);
}
case TaskStatus.Canceled:
{
return CanceledTask;
}
default:
return BoxAwait(task);
}
}
/// <summary>
/// Returns a <see cref="Task{Object}"/> for the provided <see cref="Task{Object}"/>.
/// </summary>
/// <typeparam name="object">
/// The underlying type of <paramref name="task"/>.
/// </typeparam>
/// <param name="task">
/// The task.
/// </param>
/// <returns>
/// The response.
/// </returns>
public static Task<object> Box(this Task<object> task)
{
return task;
}
private static async Task<object> BoxAwait(Task task)
{
await task;
return default(object);
}
private static async Task<object> BoxAwait<T>(Task<T> task)
{
return await task;
}
private static Task<object> TaskFromFaulted(Task task)
{
var completion = new TaskCompletionSource<object>();
completion.SetException(task.Exception.InnerExceptions);
return completion.Task;
}
}
internal static class OrleansTaskExtentions
{
public static async Task LogException(this Task task, Logger logger, ErrorCode errorCode, string message)
{
try
{
await task;
}
catch (Exception exc)
{
var ignored = task.Exception; // Observe exception
logger.Error((int)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));
}
internal static void WaitWithThrow(this Task task, TimeSpan timeout)
{
if (!task.Wait(timeout))
{
throw new TimeoutException(String.Format("Task.WaitWithThrow has timed out after {0}.", timeout));
}
}
internal static T WaitForResultWithThrow<T>(this Task<T> task, TimeSpan timeout)
{
if (!task.Wait(timeout))
{
throw new TimeoutException(String.Format("Task<T>.WaitForResultWithThrow has timed out after {0}.", 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>
/// <exception cref="TimeoutException">If we time out we will get this exception</exception>
/// <returns>The completed task</returns>
internal static async Task WithTimeout(this Task taskToComplete, TimeSpan timeout)
{
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();
throw new TimeoutException(String.Format("WithTimeout has timed out after {0}.", timeout));
}
/// <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>
/// <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)
{
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();
throw new TimeoutException(String.Format("WithTimeout has timed out after {0}.", timeSpan));
}
internal static Task<T> FromException<T>(Exception exception)
{
var tcs = new TaskCompletionSource<T>(exception);
tcs.TrySetException(exception);
return tcs.Task;
}
internal static Task<T> ConvertTaskViaTcs<T>(Task<T> task)
{
if (task == null) return Task.FromResult(default(T));
var resolver = new TaskCompletionSource<T>();
if (task.Status == TaskStatus.RanToCompletion)
{
resolver.TrySetResult(task.Result);
}
else if (task.IsFaulted)
{
resolver.TrySetException(task.Exception);
}
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();
}
}
}
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
{
private static readonly Task<int> doneConstant = Task.FromResult(1);
/// <summary>
/// A special 'Done' Task that is already in the RunToCompletion state
/// </summary>
public static Task Done
{
get
{
return doneConstant;
}
}
}
}
| |
// Stubs for the namespace Microsoft.SqlServer.Management.Smo. Used for mocking in tests.
using System;
using System.Collections.Generic;
using System.Security;
using System.Runtime.InteropServices;
namespace Microsoft.SqlServer.Management.Smo
{
#region Public Enums
// TypeName: Microsoft.SqlServer.Management.Smo.LoginCreateOptions
// Used by:
// MSFT_xSQLServerLogin.Tests.ps1
public enum LoginCreateOptions
{
None = 0,
IsHashed = 1,
MustChange = 2
}
// TypeName: Microsoft.SqlServer.Management.Smo.LoginType
// BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase
// Used by:
// MSFT_xSQLServerLogin
public enum LoginType
{
AsymmetricKey = 4,
Certificate = 3,
ExternalGroup = 6,
ExternalUser = 5,
SqlLogin = 2,
WindowsGroup = 1,
WindowsUser = 0,
Unknown = -1 // Added for verification (mock) purposes, to verify that a login type is passed
}
// TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityReplicaFailoverMode
// Used by:
// MSFT_xSQLAOGroupEnsure.Tests
public enum AvailabilityReplicaFailoverMode
{
Automatic,
Manual,
Unknown
}
// TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityReplicaAvailabilityMode
// Used by:
// MSFT_xSQLAOGroupEnsure.Tests
public enum AvailabilityReplicaAvailabilityMode
{
AsynchronousCommit,
SynchronousCommit,
Unknown
}
// TypeName: Microsoft.SqlServer.Management.Smo.EndpointType
// Used by:
// xSQLServerEndpoint
public enum EndpointType
{
DatabaseMirroring,
ServiceBroker,
Soap,
TSql
}
// TypeName: Microsoft.SqlServer.Management.Smo.ProtocolType
// Used by:
// xSQLServerEndpoint
public enum ProtocolType
{
Http,
NamedPipes,
SharedMemory,
Tcp,
Via
}
// TypeName: Microsoft.SqlServer.Management.Smo.ServerMirroringRole
// Used by:
// xSQLServerEndpoint
public enum ServerMirroringRole
{
All,
None,
Partner,
Witness
}
// TypeName: Microsoft.SqlServer.Management.Smo.EndpointEncryption
// Used by:
// xSQLServerEndpoint
public enum EndpointEncryption
{
Disabled,
Required,
Supported
}
// TypeName: Microsoft.SqlServer.Management.Smo.EndpointEncryptionAlgorithm
// Used by:
// xSQLServerEndpoint
public enum EndpointEncryptionAlgorithm
{
Aes,
AesRC4,
None,
RC4,
RC4Aes
}
#endregion Public Enums
#region Public Classes
public class Globals
{
// Static property that is switched on or off by tests if data should be mocked (true) or not (false).
public static bool GenerateMockData = false;
}
// Typename: Microsoft.SqlServer.Management.Smo.ObjectPermissionSet
// BaseType: Microsoft.SqlServer.Management.Smo.PermissionSetBase
// Used by:
// xSQLServerEndpointPermission.Tests.ps1
public class ObjectPermissionSet
{
public ObjectPermissionSet(){}
public ObjectPermissionSet(
bool connect )
{
this.Connect = connect;
}
public bool Connect = false;
}
// TypeName: Microsoft.SqlServer.Management.Smo.ServerPermissionSet
// BaseType: Microsoft.SqlServer.Management.Smo.PermissionSetBase
// Used by:
// xSQLServerPermission.Tests.ps1
public class ServerPermissionSet
{
public ServerPermissionSet(){}
public ServerPermissionSet(
bool alterAnyAvailabilityGroup,
bool alterAnyEndpoint,
bool connectSql,
bool viewServerState )
{
this.AlterAnyAvailabilityGroup = alterAnyAvailabilityGroup;
this.AlterAnyEndpoint = alterAnyEndpoint;
this.ConnectSql = connectSql;
this.ViewServerState = viewServerState;
}
public bool AlterAnyAvailabilityGroup = false;
public bool AlterAnyEndpoint = false;
public bool ConnectSql = false;
public bool ViewServerState = false;
}
// TypeName: Microsoft.SqlServer.Management.Smo.ServerPermissionInfo
// BaseType: Microsoft.SqlServer.Management.Smo.PermissionInfo
// Used by:
// xSQLServerPermission.Tests.ps1
public class ServerPermissionInfo
{
public ServerPermissionInfo()
{
Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] permissionSet = { new Microsoft.SqlServer.Management.Smo.ServerPermissionSet() };
this.PermissionType = permissionSet;
}
public ServerPermissionInfo(
Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] permissionSet )
{
this.PermissionType = permissionSet;
}
public Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] PermissionType;
public string PermissionState = "Grant";
}
// TypeName: Microsoft.SqlServer.Management.Smo.DatabasePermissionSet
// BaseType: Microsoft.SqlServer.Management.Smo.PermissionSetBase
// Used by:
// xSQLServerDatabasePermission.Tests.ps1
public class DatabasePermissionSet
{
public DatabasePermissionSet(){}
public DatabasePermissionSet( bool connect, bool update )
{
this.Connect = connect;
this.Update = update;
}
public bool Connect = false;
public bool Update = false;
}
// TypeName: Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo
// BaseType: Microsoft.SqlServer.Management.Smo.PermissionInfo
// Used by:
// xSQLServerDatabasePermission.Tests.ps1
public class DatabasePermissionInfo
{
public DatabasePermissionInfo()
{
Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] permissionSet = { new Microsoft.SqlServer.Management.Smo.DatabasePermissionSet() };
this.PermissionType = permissionSet;
}
public DatabasePermissionInfo( Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] permissionSet )
{
this.PermissionType = permissionSet;
}
public Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] PermissionType;
public string PermissionState = "Grant";
}
// TypeName: Microsoft.SqlServer.Management.Smo.Server
// BaseType: Microsoft.SqlServer.Management.Smo.SqlSmoObject
// Used by:
// xSQLServerPermission
// MSFT_xSQLServerLogin
public class Server
{
public string MockGranteeName;
public string Name;
public string DisplayName;
public string InstanceName;
public string ServiceName;
public bool IsClustered = false;
public bool IsHadrEnabled = false;
public Server(){}
public Microsoft.SqlServer.Management.Smo.ServerPermissionInfo[] EnumServerPermissions( string principal, Microsoft.SqlServer.Management.Smo.ServerPermissionSet permissionSetQuery )
{
Microsoft.SqlServer.Management.Smo.ServerPermissionInfo[] permissionInfo = null;
List<Microsoft.SqlServer.Management.Smo.ServerPermissionInfo> listOfServerPermissionInfo = null;
if( Globals.GenerateMockData ) {
listOfServerPermissionInfo = new List<Microsoft.SqlServer.Management.Smo.ServerPermissionInfo>();
Microsoft.SqlServer.Management.Smo.ServerPermissionSet[] permissionSet = {
// AlterAnyEndpoint is set to false to test when permissions are missing.
// AlterAnyAvailabilityGroup is set to true.
new Microsoft.SqlServer.Management.Smo.ServerPermissionSet( true, false, false, false ),
// ConnectSql is set to true.
new Microsoft.SqlServer.Management.Smo.ServerPermissionSet( false, false, true, false ),
// ViewServerState is set to true.
new Microsoft.SqlServer.Management.Smo.ServerPermissionSet( false, false, false, true ) };
listOfServerPermissionInfo.Add( new Microsoft.SqlServer.Management.Smo.ServerPermissionInfo( permissionSet ) );
}
if( listOfServerPermissionInfo != null ) {
permissionInfo = listOfServerPermissionInfo.ToArray();
}
return permissionInfo;
}
public void Grant( Microsoft.SqlServer.Management.Smo.ServerPermissionSet permission, string granteeName )
{
if( granteeName != this.MockGranteeName )
{
string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'";
throw new System.ArgumentException(errorMessage, "granteeName");
}
}
public void Revoke( Microsoft.SqlServer.Management.Smo.ServerPermissionSet permission, string granteeName )
{
if( granteeName != this.MockGranteeName )
{
string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'";
throw new System.ArgumentException(errorMessage, "granteeName");
}
}
}
// TypeName: Microsoft.SqlServer.Management.Smo.Login
// BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase
// Used by:
// MSFT_xSQLServerLogin
public class Login
{
private bool _mockPasswordPassed = false;
public string Name;
public LoginType LoginType = LoginType.Unknown;
public bool MustChangePassword = false;
public bool PasswordPolicyEnforced = false;
public bool PasswordExpirationEnabled = false;
public bool IsDisabled = false;
public string MockName;
public LoginType MockLoginType;
public Login( Server server, string name )
{
this.Name = name;
}
public Login( Object server, string name )
{
this.Name = name;
}
public void Alter()
{
if( !( String.IsNullOrEmpty(this.MockName) ) )
{
if(this.MockName != this.Name)
{
throw new Exception();
}
}
if( !( String.IsNullOrEmpty(this.MockLoginType.ToString()) ) )
{
if( this.MockLoginType != this.LoginType )
{
throw new Exception(this.MockLoginType.ToString());
}
}
}
public void ChangePassword( SecureString secureString )
{
IntPtr valuePtr = IntPtr.Zero;
try
{
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(secureString);
if ( Marshal.PtrToStringUni(valuePtr) == "pw" )
{
throw new FailedOperationException (
"FailedOperationException",
new SmoException (
"SmoException",
new SqlServerManagementException (
"SqlServerManagementException",
new Exception (
"Password validation failed. The password does not meet Windows policy requirements because it is too short."
)
)
)
);
}
else if ( Marshal.PtrToStringUni(valuePtr) == "reused" )
{
throw new FailedOperationException ();
}
else if ( Marshal.PtrToStringUni(valuePtr) == "other" )
{
throw new Exception ();
}
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
public void Create()
{
if( this.LoginType == LoginType.Unknown ) {
throw new System.Exception( "Called Create() method without a value for LoginType." );
}
if( this.LoginType == LoginType.SqlLogin && _mockPasswordPassed != true ) {
throw new System.Exception( "Called Create() method for the LoginType 'SqlLogin' but called with the wrong overloaded method. Did not pass the password with the Create() method." );
}
if( !( String.IsNullOrEmpty(this.MockName) ) )
{
if(this.MockName != this.Name)
{
throw new Exception();
}
}
if( !( String.IsNullOrEmpty(this.MockLoginType.ToString()) ) )
{
if( this.MockLoginType != this.LoginType )
{
throw new Exception(this.MockLoginType.ToString());
}
}
}
public void Create( SecureString secureString )
{
_mockPasswordPassed = true;
this.Create();
}
public void Create( SecureString password, LoginCreateOptions options )
{
IntPtr valuePtr = IntPtr.Zero;
try
{
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(password);
if ( Marshal.PtrToStringUni(valuePtr) == "pw" )
{
throw new FailedOperationException (
"FailedOperationException",
new SmoException (
"SmoException",
new SqlServerManagementException (
"SqlServerManagementException",
new Exception (
"Password validation failed. The password does not meet Windows policy requirements because it is too short."
)
)
)
);
}
else if ( this.Name == "Existing" )
{
throw new FailedOperationException ( "The login already exists" );
}
else if ( this.Name == "Unknown" )
{
throw new Exception ();
}
else
{
_mockPasswordPassed = true;
this.Create();
}
}
finally
{
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
public void Drop()
{
if( !( String.IsNullOrEmpty(this.MockName) ) )
{
if(this.MockName != this.Name)
{
throw new Exception();
}
}
if( !( String.IsNullOrEmpty(this.MockLoginType.ToString()) ) )
{
if( this.MockLoginType != this.LoginType )
{
throw new Exception(this.MockLoginType.ToString());
}
}
}
}
// TypeName: Microsoft.SqlServer.Management.Smo.ServerRole
// BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase
// Used by:
// MSFT_xSQLServerRole
public class ServerRole
{
public ServerRole( Server server, string name ) {
this.Name = name;
}
public ServerRole( Object server, string name ) {
this.Name = name;
}
public string Name;
}
// TypeName: Microsoft.SqlServer.Management.Smo.Database
// BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase
// Used by:
// MSFT_xSQLServerDatabase
// MSFT_xSQLServerDatabasePermission
public class Database
{
public string MockGranteeName;
public Database( Server server, string name ) {
this.Name = name;
}
public Database( Object server, string name ) {
this.Name = name;
}
public string Name;
public void Create()
{
}
public void Drop()
{
}
public Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo[] EnumDatabasePermissions( string granteeName )
{
List<Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo> listOfDatabasePermissionInfo = new List<Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo>();
if( Globals.GenerateMockData ) {
Microsoft.SqlServer.Management.Smo.DatabasePermissionSet[] permissionSet = {
new Microsoft.SqlServer.Management.Smo.DatabasePermissionSet( true, false ),
new Microsoft.SqlServer.Management.Smo.DatabasePermissionSet( false, true )
};
listOfDatabasePermissionInfo.Add( new Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo( permissionSet ) );
} else {
listOfDatabasePermissionInfo.Add( new Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo() );
}
Microsoft.SqlServer.Management.Smo.DatabasePermissionInfo[] permissionInfo = listOfDatabasePermissionInfo.ToArray();
return permissionInfo;
}
public void Grant( Microsoft.SqlServer.Management.Smo.DatabasePermissionSet permission, string granteeName )
{
if( granteeName != this.MockGranteeName )
{
string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'";
throw new System.ArgumentException(errorMessage, "granteeName");
}
}
public void Deny( Microsoft.SqlServer.Management.Smo.DatabasePermissionSet permission, string granteeName )
{
if( granteeName != this.MockGranteeName )
{
string errorMessage = "Expected to get granteeName == '" + this.MockGranteeName + "'. But got '" + granteeName + "'";
throw new System.ArgumentException(errorMessage, "granteeName");
}
}
}
// TypeName: Microsoft.SqlServer.Management.Smo.User
// BaseType: Microsoft.SqlServer.Management.Smo.ScriptNameObjectBase
// Used by:
// xSQLServerDatabaseRole.Tests.ps1
public class User
{
public User( Server server, string name )
{
this.Name = name;
}
public User( Object server, string name )
{
this.Name = name;
}
public string Name;
public string Login;
public void Create()
{
}
public void Drop()
{
}
}
// TypeName: Microsoft.SqlServer.Management.Smo.SqlServerManagementException
// BaseType: System.Exception
// Used by:
// xSqlServerLogin.Tests.ps1
public class SqlServerManagementException : Exception
{
public SqlServerManagementException () : base () {}
public SqlServerManagementException (string message) : base (message) {}
public SqlServerManagementException (string message, Exception inner) : base (message, inner) {}
}
// TypeName: Microsoft.SqlServer.Management.Smo.SmoException
// BaseType: Microsoft.SqlServer.Management.Smo.SqlServerManagementException
// Used by:
// xSqlServerLogin.Tests.ps1
public class SmoException : SqlServerManagementException
{
public SmoException () : base () {}
public SmoException (string message) : base (message) {}
public SmoException (string message, SqlServerManagementException inner) : base (message, inner) {}
}
// TypeName: Microsoft.SqlServer.Management.Smo.FailedOperationException
// BaseType: Microsoft.SqlServer.Management.Smo.SmoException
// Used by:
// xSqlServerLogin.Tests.ps1
public class FailedOperationException : SmoException
{
public FailedOperationException () : base () {}
public FailedOperationException (string message) : base (message) {}
public FailedOperationException (string message, SmoException inner) : base (message, inner) {}
}
// TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityGroup
// BaseType: Microsoft.SqlServer.Management.Smo.NamedSmoObject
// Used by:
// xSQLServerAlwaysOnAvailabilityGroup
public class AvailabilityGroup
{
public AvailabilityGroup()
{}
public AvailabilityGroup( Server server, string name )
{}
public string AutomatedBackupPreference;
public string AvailabilityReplicas;
public bool BasicAvailabilityGroup;
public string FailureConditionLevel;
public string HealthCheckTimeout;
public string Name;
public string PrimaryReplicaServerName;
public string LocalReplicaRole;
public void Alter()
{
if ( this.Name == "AlterFailed" )
{
throw new System.Exception( "Alter Availability Group failed" );
}
}
}
// TypeName: Microsoft.SqlServer.Management.Smo.AvailabilityReplica
// BaseType: Microsoft.SqlServer.Management.Smo.NamedSmoObject
// Used by:
// xSQLServerAlwaysOnAvailabilityGroup
public class AvailabilityReplica
{
public AvailabilityReplica()
{}
public AvailabilityReplica( AvailabilityGroup availabilityGroup, string name )
{}
public string AvailabilityMode;
public string BackupPriority;
public string ConnectionModeInPrimaryRole;
public string ConnectionModeInSecondaryRole;
public string EndpointUrl;
public string FailoverMode;
public string Name;
public string ReadOnlyRoutingConnectionUrl;
public string[] ReadOnlyRoutingList;
public void Alter()
{
if ( this.Name == "AlterFailed" )
{
throw new System.Exception( "Alter Availability Group Replica failed" );
}
}
public void Create()
{}
}
#endregion Public Classes
}
| |
// 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 contains the classes necessary to represent the Transform processing model used in
// XMLDSIG. The basic idea is as follows. A Reference object contains within it a TransformChain, which
// is an ordered set of XMLDSIG transforms (represented by <Transform>...</Transform> clauses in the XML).
// A transform in XMLDSIG operates on an input of either an octet stream or a node set and produces
// either an octet stream or a node set. Conversion between the two types is performed by parsing (octet stream->
// node set) or C14N (node set->octet stream). We generalize this slightly to allow a transform to define an array of
// input and output types (because I believe in the future there will be perf gains by being smarter about what goes in & comes out)
// Each XMLDSIG transform is represented by a subclass of the abstract Transform class. We need to use CryptoConfig to
// associate Transform classes with URLs for transform extensibility, but that's a future concern for this code.
// Once the Transform chain is constructed, call TransformToOctetStream to convert some sort of input type to an octet
// stream. (We only bother implementing that much now since every use of transform chains in XmlDsig ultimately yields something to hash).
using System.Collections;
using System.IO;
using System.Xml;
namespace System.Security.Cryptography.Xml
{
// This class represents an ordered chain of transforms
public class TransformChain
{
private readonly ArrayList _transforms;
public TransformChain()
{
_transforms = new ArrayList();
}
public void Add(Transform transform)
{
if (transform != null)
_transforms.Add(transform);
}
public IEnumerator GetEnumerator()
{
return _transforms.GetEnumerator();
}
public int Count
{
get { return _transforms.Count; }
}
public Transform this[int index]
{
get
{
if (index >= _transforms.Count)
throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index));
return (Transform)_transforms[index];
}
}
// The goal behind this method is to pump the input stream through the transforms and get back something that
// can be hashed
internal Stream TransformToOctetStream(object inputObject, Type inputType, XmlResolver resolver, string baseUri)
{
object currentInput = inputObject;
foreach (Transform transform in _transforms)
{
if (currentInput == null || transform.AcceptsType(currentInput.GetType()))
{
//in this case, no translation necessary, pump it through
transform.Resolver = resolver;
transform.BaseURI = baseUri;
transform.LoadInput(currentInput);
currentInput = transform.GetOutput();
}
else
{
// We need translation
// For now, we just know about Stream->{XmlNodeList,XmlDocument} and {XmlNodeList,XmlDocument}->Stream
if (currentInput is Stream)
{
if (transform.AcceptsType(typeof(XmlDocument)))
{
Stream currentInputStream = currentInput as Stream;
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
XmlReader valReader = Utils.PreProcessStreamInput(currentInputStream, resolver, baseUri);
doc.Load(valReader);
transform.LoadInput(doc);
currentInputStream.Close();
currentInput = transform.GetOutput();
continue;
}
else
{
throw new CryptographicException(SR.Cryptography_Xml_TransformIncorrectInputType);
}
}
if (currentInput is XmlNodeList)
{
if (transform.AcceptsType(typeof(Stream)))
{
CanonicalXml c14n = new CanonicalXml((XmlNodeList)currentInput, resolver, false);
MemoryStream ms = new MemoryStream(c14n.GetBytes());
transform.LoadInput(ms);
currentInput = transform.GetOutput();
ms.Close();
continue;
}
else
{
throw new CryptographicException(SR.Cryptography_Xml_TransformIncorrectInputType);
}
}
if (currentInput is XmlDocument)
{
if (transform.AcceptsType(typeof(Stream)))
{
CanonicalXml c14n = new CanonicalXml((XmlDocument)currentInput, resolver);
MemoryStream ms = new MemoryStream(c14n.GetBytes());
transform.LoadInput(ms);
currentInput = transform.GetOutput();
ms.Close();
continue;
}
else
{
throw new CryptographicException(SR.Cryptography_Xml_TransformIncorrectInputType);
}
}
throw new CryptographicException(SR.Cryptography_Xml_TransformIncorrectInputType);
}
}
// Final processing, either we already have a stream or have to canonicalize
if (currentInput is Stream)
{
return currentInput as Stream;
}
if (currentInput is XmlNodeList)
{
CanonicalXml c14n = new CanonicalXml((XmlNodeList)currentInput, resolver, false);
MemoryStream ms = new MemoryStream(c14n.GetBytes());
return ms;
}
if (currentInput is XmlDocument)
{
CanonicalXml c14n = new CanonicalXml((XmlDocument)currentInput, resolver);
MemoryStream ms = new MemoryStream(c14n.GetBytes());
return ms;
}
throw new CryptographicException(SR.Cryptography_Xml_TransformIncorrectInputType);
}
internal Stream TransformToOctetStream(Stream input, XmlResolver resolver, string baseUri)
{
return TransformToOctetStream(input, typeof(Stream), resolver, baseUri);
}
internal Stream TransformToOctetStream(XmlDocument document, XmlResolver resolver, string baseUri)
{
return TransformToOctetStream(document, typeof(XmlDocument), resolver, baseUri);
}
internal XmlElement GetXml(XmlDocument document, string ns)
{
XmlElement transformsElement = document.CreateElement("Transforms", ns);
foreach (Transform transform in _transforms)
{
if (transform != null)
{
// Construct the individual transform element
XmlElement transformElement = transform.GetXml(document);
if (transformElement != null)
transformsElement.AppendChild(transformElement);
}
}
return transformsElement;
}
internal void LoadXml(XmlElement value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);
nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
XmlNodeList transformNodes = value.SelectNodes("ds:Transform", nsm);
if (transformNodes.Count == 0)
throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Transforms");
_transforms.Clear();
for (int i = 0; i < transformNodes.Count; ++i)
{
XmlElement transformElement = (XmlElement)transformNodes.Item(i);
string algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl);
Transform transform = CryptoHelpers.CreateFromName<Transform>(algorithm);
if (transform == null)
throw new CryptographicException(SR.Cryptography_Xml_UnknownTransform);
// let the transform read the children of the transformElement for data
transform.LoadInnerXml(transformElement.ChildNodes);
_transforms.Add(transform);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography.X509Certificates;
using System.Windows;
using Microsoft.Research.ClousotRegression;
namespace ReferenceAllOOBC
{
internal class TestMicrosoftVisualBasic
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 15, MethodILOffset = 0)]
public static void Test1(string str)
{
Contract.Assert(Microsoft.VisualBasic.Strings.Len(str) == str.Length);
}
}
internal class TestMscorlib
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference \'array\'", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 13, MethodILOffset = 0)]
public static void Test1(Array array)
{
Contract.Assert(array.Rank >= 0);
//Contract.Assert(((System.Collections.ICollection)array).Count == array.Length);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference 'e'", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 13, MethodILOffset = 0)]
public static void TestExceptionGetType(Exception e)
{
Contract.Assert(e.GetType() != null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 12, MethodILOffset = 0)]
public static void Test2()
{
Contract.Assert(System.Collections.Generic.EqualityComparer<string>.Default != null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 18, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 28, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 38, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 51, MethodILOffset = 0)]
public static void TestPureLookup(Dictionary<int, string> dict, int key)
{
Contract.Requires(dict != null);
string result1;
var found1 = dict.TryGetValue(key, out result1);
string result2;
var found2 = dict.TryGetValue(key, out result2);
Contract.Assert(found1 == found2);
Contract.Assert(result1 == result2);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 18, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 34, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 54, MethodILOffset = 0)]
public static void TestOutByRef()
{
var d = new Dictionary<string, object>();
d[""] = new object();
object o = null;
d.TryGetValue("", out o);
Contract.Assume(o != null);
Contract.Assert(true); // make sure this is reachable
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 29, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 53, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 59, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 13, MethodILOffset = 29)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 13, MethodILOffset = 59)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 36, MethodILOffset = 59)]
public static string TryGetTail(string value, string divider)
{
Contract.Requires(value != null);
Contract.Requires(divider != null);
var p = value.IndexOf(divider);
if (p == -1) return null;
return value.Substring(p + divider.Length);
}
#if NETFRAMEWORK_4_0 && NETFRAMEWORK_4_0_CONTRACTS || SILVERLIGHT_4_0 && SILVERLIGHT_4_0_CONTRACTS
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 22, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 15, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 43, MethodILOffset = 0)]
public static void TestTuple(int x)
{
var p = Tuple.Create(x);
Contract.Assert(p != null);
Contract.Assert(object.Equals(p.Item1, x));
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 22, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 15, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 43, MethodILOffset = 0)]
public static void TestTuple2(int x)
{
var p = new Tuple<int>(x);
Contract.Assert(p != null);
Contract.Assert(object.Equals(p.Item1, x));
}
#endif
private class CollectionWrapper<T> : ICollection<T>
{
private readonly ICollection<T> mBackend = new List<T>();
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 6, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 12, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 20, MethodILOffset = 35)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 13, MethodILOffset = 35)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 38, MethodILOffset = 35)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 28, MethodILOffset = 35)]
public CollectionWrapper()
{
Contract.Ensures(((ICollection<T>)this).Count == 0);
}
[ContractInvariantMethod]
private void Invariant()
{
Contract.Invariant(mBackend != null);
Contract.Invariant(mBackend.Count == this.Count);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 14)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 13, MethodILOffset = 14)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 38, MethodILOffset = 14)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 28, MethodILOffset = 14)]
void ICollection<T>.Add(T item)
{
mBackend.Add(item); // performs mod of mBackend.Count and implictly this.Count
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 7, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 13)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 13, MethodILOffset = 13)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 38, MethodILOffset = 13)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 15, MethodILOffset = 13)]
void ICollection<T>.Clear()
{
mBackend.Clear();
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 11, MethodILOffset = 17)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 31, MethodILOffset = 17)]
bool ICollection<T>.Contains(T item)
{
return mBackend.Contains(item);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 38, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 41, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 9, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 13, MethodILOffset = 9)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 31, MethodILOffset = 9)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 58, MethodILOffset = 9)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 13, MethodILOffset = 15)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 38, MethodILOffset = 15)]
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
mBackend.CopyTo(array, arrayIndex);
}
public int Count
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 26, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 31, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 7, MethodILOffset = 40)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 12, MethodILOffset = 40)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 17, MethodILOffset = 40)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 19, MethodILOffset = 40)]
get
{
Contract.Ensures(Contract.Result<int>() == mBackend.Count);
return mBackend.Count;
}
}
bool ICollection<T>.IsReadOnly
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 7, MethodILOffset = 0)]
get
{
return mBackend.IsReadOnly;
}
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 13, MethodILOffset = 17)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 38, MethodILOffset = 17)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 1, MethodILOffset = 17)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 44, MethodILOffset = 17)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 28, MethodILOffset = 17)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 79, MethodILOffset = 17)]
bool ICollection<T>.Remove(T item)
{
return mBackend.Remove(item);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 7, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 17, MethodILOffset = 16)]
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return mBackend.GetEnumerator();
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as field receiver)", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 7, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 17, MethodILOffset = 16)]
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return mBackend.GetEnumerator();
}
}
private class MyCollection : ReadOnlyCollection<object>
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 7, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "Array creation : ok", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 19, MethodILOffset = 7)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"No overflow (caused by a negative array size)", PrimaryILOffset = 2, MethodILOffset = 0)]
public MyCollection() : base(new object[0]) { }
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 3, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.False, Message = "requires is false: index >= 0", PrimaryILOffset = 13, MethodILOffset = 3)]
[RegressionOutcome(Outcome = ProofOutcome.Bottom, Message = "requires unreachable", PrimaryILOffset = 33, MethodILOffset = 3)]
public object GetItem()
{
return this[-1];
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 16, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.False, Message = "requires is false: index >= 0", PrimaryILOffset = 13, MethodILOffset = 16)]
[RegressionOutcome(Outcome = ProofOutcome.Bottom, Message = "requires unreachable", PrimaryILOffset = 33, MethodILOffset = 16)]
public static T Test<T>(ReadOnlyCollection<T> x)
{
Contract.Requires(x != null);
return x[-1];
}
}
}
internal class TestSystem
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 12, MethodILOffset = 0)]
public static void Test1()
{
Contract.Assert(System.Diagnostics.Process.GetCurrentProcess() != null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 15, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 35, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 60, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 28, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 48, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 13, MethodILOffset = 60)]
[RegressionOutcome(Outcome = ProofOutcome.False, Message = "requires is false: value <= 0xFFFF", PrimaryILOffset = 35, MethodILOffset = 60)]
public static void Test2(SmtpClient mailClient)
{
Contract.Requires(mailClient != null);
X509CertificateCollection certs = mailClient.ClientCertificates;
Contract.Assert(certs != null);
ServicePoint sp = mailClient.ServicePoint;
Contract.Assert(sp != null);
mailClient.Port = 0x10000;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 28, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 35, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 16, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 43, MethodILOffset = 0)]
public static void Test3()
{
var l = new LinkedList<int>();
Contract.Assert(l.Count == 0);
l.AddFirst(1111);
Contract.Assert(l.Count == 1);
}
}
internal class TestSystemConfiguration
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference \'elem\'", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 13, MethodILOffset = 0)]
public static void Test1(System.Configuration.ConfigurationElement elem)
{
Contract.Assert(elem.ElementInformation != null);
}
}
internal class TestSystemConfigurationInstall
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference \'installer\'", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 13, MethodILOffset = 0)]
public static void Test1(System.Configuration.Install.Installer installer)
{
Contract.Assert(installer.Installers != null);
}
}
internal class TestSystemCore
{
[ClousotRegressionTest] // CCI2 is not seeing Requires of Cast
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = "requires unproven: source != null", PrimaryILOffset = 13, MethodILOffset = 2)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 13, MethodILOffset = 0)]
public static void Test1(System.Collections.IEnumerable coll)
{
Contract.Assert(coll.Cast<string>() != null);
}
}
internal class TestSystemData
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference \'constraint\'", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 13, MethodILOffset = 0)]
public static void Test1(System.Data.Constraint constraint)
{
Contract.Assert(constraint.ExtendedProperties != null);
}
}
internal class TestSystemDrawing
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 13, MethodILOffset = 0)]
public static void Test1(IntPtr ptr)
{
Contract.Assert(System.Drawing.Bitmap.FromHicon(ptr) != null);
}
}
internal class TestSystemSecurity
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = "requires unproven: userData != null", PrimaryILOffset = 13, MethodILOffset = 4)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 17, MethodILOffset = 0)]
public static void Test1(byte[] userData, byte[] entropy, System.Security.Cryptography.DataProtectionScope scope)
{
var result = System.Security.Cryptography.ProtectedData.Protect(userData, entropy, scope);
Contract.Assert(result != null);
}
}
internal class TestSystemWeb
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 26, MethodILOffset = 0)]
public static void Test1(string s)
{
Contract.Requires(s != null);
Contract.Assert(System.Web.HttpUtility.HtmlAttributeEncode(s) != null);
}
}
internal class TestSystemWindows
{
//requires silverlight
}
internal class TestSystemWindowsBrowser
{
//requires silverlight
}
internal class TestSystemWindowsForms
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 12, MethodILOffset = 0)]
public static void Test1()
{
Contract.Assert(System.Windows.Forms.Application.OpenForms != null);
}
}
internal class TestSystemXml
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference \'doc\'", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 13, MethodILOffset = 0)]
public static void Test1(System.Xml.XmlDocument doc)
{
Contract.Assert(doc.Schemas != null);
}
}
internal class TestSystemXmlLinq
{
[ClousotRegressionTest] // CCI2 is not seeing contracts on Annotations
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = "Possibly calling a method on a null reference 'doc'", PrimaryILOffset = 16, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 13, MethodILOffset = 16)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 27, MethodILOffset = 0)]
private static void Test1(System.Xml.Linq.XDocument doc, System.Type type)
{
Contract.Requires(type != null);
Contract.Assert(doc.Annotations(type) != null);
}
[ClousotRegressionTest] // CCI2 is lacking requires of XName implicit converter
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 15, MethodILOffset = 6)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 19, MethodILOffset = 0)]
private static void Test2(IEnumerable<string> elements)
{
System.Xml.Linq.XName xname1 = "hello";
Contract.Assert(xname1 != null);
}
[ClousotRegressionTest] // CCI2 is not seeing some requires contracts
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 118, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as array)", PrimaryILOffset = 60, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 80, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 88, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 100, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 141, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 154, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 166, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "Lower bound access ok", PrimaryILOffset = 60, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "Upper bound access ok", PrimaryILOffset = 60, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 15, MethodILOffset = 133)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 19, MethodILOffset = 146)]
private void WriteContractElementToSummary(System.Xml.Linq.XElement summaryElement, string contractElement, params string[] info)
{
Contract.Requires(summaryElement != null);
Contract.Requires(contractElement != null);
Contract.Requires(info != null);
System.Text.StringBuilder infoBuilder = new System.Text.StringBuilder(contractElement);
foreach (string infoString in info)
{
if (infoString != null)
{
infoBuilder.Append(" (");
infoBuilder.Append(infoString);
infoBuilder.Append(")");
}
}
System.Xml.Linq.XName xname = "para";
System.Xml.Linq.XElement contractXElement = new System.Xml.Linq.XElement(xname, infoBuilder.ToString());
summaryElement.Add(contractXElement);
Console.WriteLine("\t\t" + infoBuilder.ToString());
}
}
internal class TestWindowsBase
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 5, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 13, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 29, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 21, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 37, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possible precision mismatch for the arguments of ==", PrimaryILOffset = 19, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possible precision mismatch for the arguments of ==", PrimaryILOffset = 35, MethodILOffset = 0)]
public static void Test1(double x, double y)
{
var p = new Point(x, y);
Contract.Assert(p.X == x);
Contract.Assert(p.Y == y);
}
}
internal class TestMicrosoftVisualBasicCompatibility
{
[ClousotRegressionTest]// CCI2 is lacking some contracts
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "valid non-null reference (as receiver)", PrimaryILOffset = 15, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 26, MethodILOffset = 0)]
public static void Test1(Microsoft.VisualBasic.Compatibility.VB6.BaseControlArray bca)
{
Contract.Requires(bca != null);
Contract.Assert(bca.Count() >= 0);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.